id
int64 1
2k
| content
stringlengths 272
88.9k
| title
stringlengths 3
77
| title_slug
stringlengths 3
79
| question_content
stringlengths 230
5k
| question_hints
stringclasses 695
values | tag
stringclasses 618
values | level
stringclasses 3
values | similar_question_ids
stringclasses 822
values |
---|---|---|---|---|---|---|---|---|
1,752 |
hey everybody this is larry this is me going over q1 of the weekly contest 227. check if array is sorted and rotated hit the like button hit the subscribe button join me on discord let me know what you think about this problem um this one i think this i think there's actually a easier uh clever way of doing it in n square or maybe even um yeah uh or some sort of uh thing but i for this part of my solution my contest code is really racky because i um i didn't say this because you know i'm trying to optimize for time right and i did this in about one minute 15 seconds so yeah so time is of the essence um and basically what i did was i sort i get you know i get the way i sorted it and then i just try every combination of like slicing and rotation if you will um to get the answer um so yeah so i think you can actually check the monetization part the sorted part and of end time so you can actually do this in n square but the way that i did it um and you can do an n square of extra or one extra space that'll be the optimal solution and i would recommend that for an interview but for me i you know i do a sword so that's the end again that's not actually that important because it gets dominated by this part which is n square anyway but it takes an extra of n extra space so yeah so quadratic time um you can probably do some funky things with um sliding windows and stuff like that to kind of check maybe i don't know but let me know what you think let me know what you did and you can watch me stop the car tell this poem during the contest next you hey uh yeah thanks for watching hit the like button to subscribe and join me in discord um let me know what you think about this problem and this solution this explanation um and yeah do have a good day and a good weekend stay good stay healthy to a good mental health and i will see you next problem bye
|
Check if Array Is Sorted and Rotated
|
arithmetic-subarrays
|
Given an array `nums`, return `true` _if the array was originally sorted in non-decreasing order, then rotated **some** number of positions (including zero)_. Otherwise, return `false`.
There may be **duplicates** in the original array.
**Note:** An array `A` rotated by `x` positions results in an array `B` of the same length such that `A[i] == B[(i+x) % A.length]`, where `%` is the modulo operation.
**Example 1:**
**Input:** nums = \[3,4,5,1,2\]
**Output:** true
**Explanation:** \[1,2,3,4,5\] is the original sorted array.
You can rotate the array by x = 3 positions to begin on the the element of value 3: \[3,4,5,1,2\].
**Example 2:**
**Input:** nums = \[2,1,3,4\]
**Output:** false
**Explanation:** There is no sorted array once rotated that can make nums.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** true
**Explanation:** \[1,2,3\] is the original sorted array.
You can rotate the array by x = 0 positions (i.e. no rotation) to make nums.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 100`
|
To check if a given sequence is arithmetic, just check that the difference between every two consecutive elements is the same. If and only if a set of numbers can make an arithmetic sequence, then its sorted version makes an arithmetic sequence. So to check a set of numbers, sort it, and check if that sequence is arithmetic. For each query, get the corresponding set of numbers which will be the sub-array represented by the query, sort it, and check if the result sequence is arithmetic.
|
Array,Sorting
|
Medium
|
413,1626
|
63 |
hey everybody this is larry this is day 28 of the april eco daily challenge hit the like button hit the subscribe button join me on discord uh today is the 28th the last day of week four and we're almost done with april hope y'all enjoying so far in today's promise unique paths too um so this problem you know i usually start with livestreams a little bit slow just fast forward or whatever you need to do always need that disclaimer because if you keep on telling me that i don't explain the problem well enough i'm like yeah that's not the point but uh okay so to this form you start the top left you want to move down or right uh and now the obstacles i'm a unique path there so if there's no obstacles you could actually look up binomial formula and it's actually kind of an interesting proof if you want to play around with that but this one is actually i don't know what unique path 1 is but this is a relatively straightforward uh dynamic programming problem the first thing to notice is that i mean the first thing i noticed to be honest is that i've done this problem or a similar e problem good e problems many times many a times so to me i just knew it was going to be dynamic programming unless the dimensions are too big that we have to figure out a different strategy and given that m and n is less than 100 uh that should be fast enough because this dynamic programming should be linear in the size of the input but maybe we're jumping ahead a little bit the other thing to notice is that you know so what separates this problem with another grid problem right well in this case this graph or um this implicit graph or you know with respect to uh you know let's say you draw an edge a directed edge from where a robot is or each cell that a robot can be and then you know the next location that the robot can be at um well in that case if we look at that graph it is uh a dag right and that you know it's directly directed and it's asynchronous right so there's no psychos and because there's no cycles dynamic programming is a very good um you know like it's uh it's a good question to ask whether that could be true and in this case uh so there are a couple of variations in this form uh this the minimization or maximization or something like that depending on what you do like picking up apples or something i don't know um but and just based on that just changes the function um but the transition is roughly mostly the same uh the only thing that you have to consider is that there are obstacles and well you know you shouldn't be an obstacle uh or you shouldn't be in a path that has an obstacle in it um so yeah uh okay and to be honest this kind of problem i usually go bottoms up and there's a very uh you know it's a good transition but i recommend just doing it up both top down and bottoms up and then you know the one with the space compression or um the space optimization as i would call it um to get it down to all of uh maybe m or n space or something like that um yeah uh and with that you know i have a link some i have a like a walkthrough of how to do that so you know i have a link below but um but cool let's get started i'm going to do it just uh top down version and then you know we'll see where it goes uh depending how tired i am but yeah but that's you know let's say count from any x and y right so that said rose is equal to length of obstacle grid i'm gonna rename this to something shorter to type though for interview purposes or whatever maybe i would not um i might you know long and descript if it's okay but uh make sure that this is at least one so i don't have to check okay um yeah so yeah for an actual interview i recommend just keeping it long because descriptive names are better um but you know for now i'm just going to do this but yeah so let's see so if m of x y well we have to keep check track area we have to keep track of the bounds first i'm just trying to see if one is a okay so one is there's an obstacle so we have to return zero here because there's no path that goes through if this is if there's an obstacle um so we're just going for the base case if um what is that one uh a couple of ways to do it as well uh oh depending how you want to define uh certain things but yeah i'm gonna play around and this is probably not the way that i usually do it but if x is greater than or you go to rows or y is greater than or equal to columns we return zero for the same reason that you know the desire bound so there are no paths and then if these constraints are good then if x is equal to rows minus one and y is equal to columns minus one we return one because um we've got already at the end point so let's step back a second so what is this function right count the number of ways to reach x of to reach uh the lower right corner from x y right so if we're already there then that's by default one way of getting there from you know from itself almost like a mathematical uh identity e thing so then now we can think about the transition right well raise is equal to zero we and i would also say that this is awkward though because this can overflow so you just have to trust that um because i'm looking at the constraints here because i'm not like okay um the math can overflow that was like maybe i forgot something and that it cannot overflow but no i'm pretty sure this couldn't overflow so um i think maybe for this problem maybe it's an older problem or something like that where you just have to trust that wrong overflow um and python wouldn't worry that much about it anyway for that reason but it is a little bit awkward so if you're in the java c plus you'll be like okay um because what i was going to say is if m and n is less than 30 say or something like that 30 or 25 or whatever um because of the binomial uh um formula um you can kind of work it out so that like maybe the constraints are such in a way that it doesn't overflow uh that's not the case here though so yeah anyway um so that's what i was thinking about when i get here and then now we have two paths right one is go right so how many ways are there if we run right if we went away right then we just requested we say okay we went right so the number of ways to reach the lower right corner is from is at our current spot going left or sorry going right or going down right so that they both create um a distinct way from this branching point and then at the end we just return ways um and then we can just return count from zero and we'll yeah let's just say mostly done not uh not actually done um because again this is going to take um take a long time just on the fact that you know uh let's see oh okay so this is the other one the only two test cases okay fine um yeah so this looks good um but it is going to be too slow and we can kind of show that in a bit i'm just gonna was it a hundred i don't know what this is but this looks like it's good now because i didn't count uh and this should time out because okay maybe not wow did i not do that much to do that many i don't just look like a lot but um did i cash by accident huh that's remarkably fa oh i guess it's only 107 paths uh what i need to do is actually this bit but with zero so then the more paths i mean i was just lazy so i was just copying and pasting um and this in theory should time out maybe not who knows anymore wow yeah i'm really bad at this clearly uh but my point is that it should time out with big enough uh you know this is a hundred by hundred it should definitely time out i was just a little bit lazy about it counting okay well mistakes were made but unless i cashed by accident now uh okay well my bad attempt to show you that it'll time out aside um just you know this should time out for a hundred times a hundred because there's just way too many paths uh maybe i uh now i'm annoyed that i didn't show it so i'm gonna show it so let's actually count that's ten that's a hundred okay this is 50 by 100 i think that should be big enough unless i miscounted then i would just be sad okay so now you can see that it is time timing out as i as predicted but um but yeah uh so what are you going to do right well you know and if you're affirmative dynamic programming you're probably already ahead of what i'm going to say and know that what i'm going to say which is that you know this function for every input we know that it's going to be this give us the same output right and so we do this the something called memorization which is just that we memorize that this is a function meaning that for every same input we get the same output so why did i just save it somewhere next time right so that's let's do that paradigm uh i usually write it out so that it's easier to see and explain but uh yeah let's say has cash as you go to this times i'm my laptop keyboard today so i'm a little bit awkward but yeah so now we have this cache and then now we can just check it a little bit um yeah we will check it after the bounce it doesn't really matter as long as you know because they're both lookups but it has cache of x y then we return cache of x y and then at the very end we just save it down i know that is obviously easier if you're familiar with um with i don't know llu cash or whatever in general um it is this is well i mean we knew that it was just gonna be big though i mean is there a mod that i forgot maybe i forgot a mod uh it just may be that this is not a valid input and data or that's not in their input i mean it is definitely valid input right but in any case uh yeah i mean that seems right um yeah as you can see i know that people talk about like hey is it okay to ask um use are you cash or something like that in interviews but you can see that like i did this in four five lines of six lines of code i guess and i did it in about 30 seconds right so do you need it i mean i do it on contests or into or yeah i do it in contests because you know i want to focus on other stuff and sometimes you do make typos and stuff like that and but you know but in the context you're not trying to explain someone how your code works necessarily um so yeah so i would definitely recommend just doing this because then now you can explain the complexity also in the easier way um so you know this is going to be straightforward we just count the number of inputs right the number of possible inputs uh x could be from zero to two rows um like it could be from zero to columns so the total number of possible inputs is all of those times columns yeah fair enough right because this is well there are row numbers of the row numbers here the column numbers here so it's going to be row times columns uh let's see what's the other thing so that's time oh sorry so that's the number of possible input so that's also going to be also uh space complexity because for each one you're storing all of one object which is you know just the hash cache object and also just the cache raised object and then the other thing is what's the time complexity right well if you look at this function everything will have an o of 1 because we can assume that at this point this is all one everything has an all one complexity so then your total time complexity is just the number of possible inputs times the num the amount of time you spend on each um each car so it's going to be also all of our times columns for time complexity um okay so what does this mean right this means that this is linear in this in the size of the input because the input is rows times columns as we know um so yeah linear in time and space um that's all i have for this problem uh for an additional like making sure you understand this um try to do it bottoms up as well i find that this problem is very relatively straightforward to do bottoms up um and then do the space optimization after that i think this problem is also relatively easy to do space optimization um so yeah because these are skills that you have to practice on the easier problems because it only gets harder for that kind of stuff um but yeah hopefully this logic makes sense um yeah that's all i have for this problem oh did i submit it i think once i actually did finish a problem but then i forgot to submit it and then it i just almost missed a day because of it uh like killed my streak or whatever but yeah so this looks good uh got accepted in case you didn't see and that's all i have for this farm uh hit the like button in the subscriber and join me on discord i hope y'all have a great rest of the month and just like you know stay cool stay good stay healthy and to good mental health and i will see you later bye
|
Unique Paths II
|
unique-paths-ii
|
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time.
An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle.
Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The testcases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\]
**Output:** 2
**Explanation:** There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
**Example 2:**
**Input:** obstacleGrid = \[\[0,1\],\[0,0\]\]
**Output:** 1
**Constraints:**
* `m == obstacleGrid.length`
* `n == obstacleGrid[i].length`
* `1 <= m, n <= 100`
* `obstacleGrid[i][j]` is `0` or `1`.
|
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1]
else
obstacleGrid[i,j] = 0
You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem.
if obstacleGrid[i][j] is not an obstacle
obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j]
else
obstacleGrid[i,j] = 0
|
Array,Dynamic Programming,Matrix
|
Medium
|
62,1022
|
322 |
foreign once again we are going to solve some very classic problems in dynamic programming so um the problem that we are going to solve now this is very well known as Point change and once again uh you know each problem in BP can be thought of as a concept now in interview you might not directly be asked that concept you'd be asked a question a totally unseen question where you have to figure out how to apply that concept okay so for that our understanding of the concept should be Rock Solid okay so uh this question goes as follows it says that we have been given coins of several denominations so what is the meaning of denomination like in India if you take a look uh the coin denominations are one rupee coin two rupee coin you don't have a three rupee coin you don't have a four rupee coin but then you have a five rupee coin and then you have a 10 rupee coin and then I think you also have a 20 rupee coin so that's how the denominations work in uh different countries so there are different denominations and they are given to you in form of an array so let's say the name of the array is points the size of the array is M it means there are M denominations okay and those denominations are let's say c0 c one till CM minus 1. okay now we have been given this array as an input and we have also been given an integer n as an input right now you can assume one thing you can assume that we have infinite Supply of each denomination when I say infinite supply of each denomination let's say there is a denomination of three rupee coin then there are infinite coins of three rupee okay you can assume that now what we have to do is given this integer n we want to find minimum number of points needed to make n what is the minimum number of points needed to make n as in what is the amino number of points which you can collect such that their sum is equals to n and this array has been given to you which represents the denominations that you have and for each denomination in finite coins are there so from each denomination you can take as many coins as possible is the question making sense to everyone how many of you get that okay want an example so let's take some example let's say uh the denominations array that we have has 1 5 and 7. okay so we have got infinite coins of one rupee 5 rupee and seven rupee and now the value of n is nine so tell me what is the minimum number of points that you need to make nine okay so a lot of you are saying three can you also tell me what are those three coins which you're taking to make nine yeah seven one so you can take a seven rupee coin and you can take two units of one rupee coin and if you sum them up you will get nine okay so you know this problem is so classic that it is used by certain uh cash vending machines also for example you go to an ATM and let's say you want to withdraw some amount then the ATM might try to dispense as lash node as less notes as possible okay so the ATM might try to dispense as less nodes as possible and also the sum of those nodes should be equal to the amount that you have entered so um this can be modeled as a real life problem let's say this is a very important point to understand now okay so one of you is saying we have two options for each coin those two options if those two options let's say we assume are either take a coin or do not take a coin then does it make sense let's say you talk about one rupee coin when you talk about one rupee coin either I can leave it completely or I can take it once or I can take it twice or I can take it Thrice or I can take it four times why because there are infinite supply of each denomination it's not like you have got one unit coin of each denomination no it's not like that there are infinite supply of each denomination so whenever you are scanning this array and let's say you are considering this element then there are several choices for this element First Choice could be do not take it at all and then move on second choice could be take it once third choice could be take it twice uh okay so there is a very well known approach to this problem which lot of people come up with okay let's take a look you want to make nine okay now assume that this array is sorted for now let's make that assumption so start from the end when I say start from the end try to take the largest denomination because when you take the largest denomination then n decreases very fast right and that is what you want that by taking fewest possible points the N should have decreased to zero that is what you want facing first take this seven so okay I took this seven when I took this seven the remaining amount becomes 9 minus 7 which is 2. now you cannot take this 7 again so you can move back to this five when you come to this 5 can you take this 5 for n equals to 2 does it make sense yes or no the answer is no so again you will move back now you come to this one and you want to make two rupee so you have to take one rupee coin twice that is what you do and now it becomes zero so this is the approach that a lot of people come up with it starts from the end and take the current coin as many times as it is possible to take and then reduce your n and then again take as many times as possible this is how you keep going on now lot of you are saying it'll fail so lot of you are saying it'll fail for other kinds of input like n equals to 10. so tell me clearly whatever algorithm I told just now if I run it for n equals to 10 then how many coins would be taken four coins and what are those four coins seven triple one exactly so again you start from the end you see that this 7 can be taken so you take this 7. right and now the value of n becomes 3 can you take it again no so you will move back how about this five can you take this 5 again or can you take this 5 at all the answer is no because this is three already so again you move back now you are here so you will take that one for three times so you have gathered four coins but think and say what is the fewest number of coins that can make n equals to ten given this denomination it is 2 I can just take 5 followed by another five so the algorithm that we just discussed which is greedy in nature which always takes the highest denomination and then moves back that is not going to work so let's move on and scrap this approach and come up with a smarter approach so tell me what can be done how do we think so don't think about DP don't think about uh anything which is very Herculean to think of uh think of a simple recursive way see uh whenever you see questions like find a minimum find maximum then automatically that question uh has a high probability of being solved using DP right I mean certain times DP might not be necessary certain times it can be solved using simple logic like greedy certain times it can be solved using binary search which will teach you uh but chances are very high that it is DP if it is DP the first step is recursion so think recursively you know here if you focus on this problem here you don't have to tell me which coins did you pick like for n equals to nine you don't have to tell me hey I picked one seven rupee coin and two one rupee coin you don't have to tell me that you just have to tell me the answer three that three is the minimum number of coins that I picked so if you focus on this and work your way out you might be able to come up with a very easy recursive relation and let us understand that so let's keep looking see um let's say you want to make n rupees okay and this is the array that you have okay let me write a new array this is the array that you have of size m so that's your array starting from I equals to 0 to M minus 1 and then there are certain elements in this tell me uh like if you want to make n rupees then in how many different ways can you choose your first point if there are M options over here in how many different ways you can choose your first point tell me in M different ways right see you have got one rupee coin five rupee coin seven rupee coin so what is the for how in how many different ways can you pick your first coin it could either be one or five or seven so it depends upon the size of the array so there are M options that I have for my very first coin now just think of it if you have taken your first coin as this which is array zero so you wanted to make NRP coin and if you take your first coin as array zero then how much amount will be left you want you wanted to make n and you took array zero so now the amount left will be n minus array 0 let me just write it as in okay but you could have taken other decision also that other decision could have been to take this as your first coin if you would have taken this as your first coin which is A1 then the remaining amount would have been n minus A1 similarly you can see there would be so many options the final option would have been to take the last element if you would have taken the last element which is a of M minus 1 then the remaining amount would have been n minus a of n minus 1. so these are the transitions that are possible so you can think that this is a state and you move from this state to this state if you pick this as your first coin but if you pick this as your first coin you move from here to here similarly if you pick this as the first point you move from here to there now tell me one thing so when you have made a decision to pick this coin or that coin or whatever as your first coin then you have already picked one coin because you have already picked one coin you should do one plus something now the question is what should that something be so think of it in this manner you wanted to make n rupees and after picking one coin you want to make n minus a0 rupees now if somebody tells you what is the minimum number of coins that is required to make this much rupees and then that much rupees and looks like your job is done now who is going to tell you let's say some magician tells you that hey the fewest number of coins that you need to make this much Rupees is X the fewest number of points that you need to make this much Rupees is y and the fewest number of coins that you need to make this means Rupees is Z then using those you can very easily solve for the fewest number of coins used to make n rupees we can even take a very quick example here which corresponds to all that I have said let's say uh your array is three four seven and your n is 10. so there is a function that you call for the current value of n now tell me how many transitions will happen from here look at the size of the Oriental how many choices do you have for the first find three choices and what are those three choices your first coin could either be a three rupee coin if that's your first coin you will move from F of 10 to F of ten minus 3 which is seven if your first coin is this you will move from F of 10 to F of 10 minus 4 which is six and if your first point is this you will move to F of n minus 7 that is 3. you understand these transitions how they are happening right now when you made this Choice then the first coin that you picked was a three rupee coin when you made this Choice then the first point that you picked was a four rupee coin when you made this choice in the first coin that you picked was a seven rupee coin now all that I am trying to tell you is let's say there is a magician and he tells you the fewest number of points required to make remaining amount that is seven so tell me what is the fewest number of coins that you need to make seven rupees given that denomination one only one you can pick that coin any job will be done so two coins are needed right and what is the fewest number of coins needed to make six rupees given that denomination 2 right and what is that you can pick 3 followed by 3 and what is the fewest number of points required to make three just one take that three all that I am saying you is you realize that for this the answer is one because you just need one coin to make seven rupees given this denomination similarly for this the answer is 2 you just need two points for this the answer is one so if somebody tells you this is one this is two this is one then you can tell me the answer for this what is the fewest number of coins need to make 10 Rupees tell me now what is the fewest number of coins needed to make 10 Rupees it is two and how did you get that too you got that too by doing one plus why did you do one plus because the moment you have made first transition that means you have taken some point which coin I don't care but you have taken some coin now whatever is the minimum of this and that I can add it so whatever is the minimum of F7 F6 F3 that can be added to one and that will be the value of f of n so uh does it look like uh forget about magician why did I say magician say there is a function f of 10 I mean hey somebody tells you that what is the minimum number of points that you need to make seven rupees somebody tells you that now somebody tells you what is the minimum number of coins you have to make six rupees what is the minimum number of points you need to make three rupees somebody tells you that okay here it is one here it is two here it is one so what will be the minimum number of coins need to make 10 Rupees it will be one plus minimum of one comma two comma 1 you see you if you are making seven rupees by one coin then you can add three to eight as another coin and now you have just two coins using which you can make ten rupees okay so do you see that uh it is purely a recurrence relation okay and if you want you can even draw this recursion tree and see how the values are being returned so let's say F of 10 from here you will call F of 7 F of six and F of three this diagram is copy paste of that okay so now what is the meaning of f of x is it will return me fewest number of coins to make X that is what f of x is that clear so I am saying fewest number of points needed to make 10 Rupees is equals to 1 plus minimum of this that why I am doing one plus because the moment I made my first choice I already took one coin it was either three rupee coin or four rupee coin or seven rupee coin now these are remaining amount so if somebody tells me what is the minimum number of coins to make those amount I can take Min of those add one to eight and that will be my answer okay so again you can go on from here at F of seven again there can be three transitions because at every stage you can pick any of these three coins why because they are in infinite Supply so again F of seven can you tell me what will be the functions which will be called by F of seven very easy to say right because once again I can say that my current coin could either be a 3 rupee or 4 rupee or 7 rupee so if my current coin is a three rupee coin seven minus three will be four if it is a four rupee coin it will be this and if it is a seven rupee coin it will be zero that's how things are happening now again I hope you remembered the definition of f of x if you really remember the definition of f of x can you tell me what should F of 0 return what is the fewest number of coins that I need to make zero rupees so when n is equals to zero just return 0. so this can be your termination condition of the code that you will write uh now again like I can draw more so you can again see that here again there are three choices so at each node there are three choices or to generalize it at each node there are M choices where m is the size of your array where m is the number of denominations that you have so once again at F of four what will be the calls that you will make 4 minus 3 which is one and four minus 4 which is zero and four minus 7 which is minus three interestingly this looks a bit itchy right where the remaining amount is negative what to do in this case when the remaining amount is negative but you realize it that this can happen right certain times the remaining amount can become negative why it can become negative because you never know what this value is and when you subtract an element from this it can become negative so you have to handle this thing in a proper manner I'll come to that but before that I'll give you a very quick example to solve so let's say we have denominations of 246 and we want to make five rupees uh what is the fewest number of coins that I need to make five rupees here is it possible to make five rupees here not possible right so this is very important thing to realize now guys let me tell you one thing see if you look at these edges these are like your DC's and arrows so in this particular Arrow you took a three rupee coin that is the reason you move from 10 to 7 so and right here three rupee point in this Arrow again you took a three rupee coin that is the reason you move from seven to four in this Arrow what did you take you moved from 4 to minus three so you took a seven rupee line you know I would say that this particular decision path is not a correct decision path because if you are moving along this path you cannot create the desired amount which is 10. and furthermore I can say there is no way I can create negative amount from positive denominations so this is impossible thing so let me erase these for now you know in recursion what you do is you solve every sub problem one by one so at F of 4 what you are trying to solve forget about this big tree just focus your attention on this small tree at F of 4 you are trying to find fewest number of points to make four fewest number of coins to make four is dependent upon fewest number of points to make one zero and minus three now uh think what should this return what should F of one ideally return from here when you look at F of 1 you realize that hey given this denomination one cannot be made when you look at F of 0 you can say that because of this termination condition I can return 0 from here now these are the impossible things so whenever you encounter impossible things what should ideally be returned forget about this for now let's focus on this some of you those who are saying return infinite you are saying totally correct why you are saying totally correct because whatever is returned from here you want to discard that why you want to discard that because it is not possible to make infinite amount correct now if you are taking Min of certain things let's say mean of 5 comma Infinity it will always be five mean of minus 5 comma Infinity it will always be minus five so when you are taking Min of certain things out of those things if something is infinite it'll automatically be discarded so what we can do is if my function has ever been called on a negative amount then I'll immediately return infinite from there because returning infinite will ensure that for the computation of this thing when Min will be taken then whatever is returned from here will automatically be kicked out so this is very important point to understand certain times you write this kind of relationship certain times you might write a relationship which says 1 plus Max of something and in that if you realize that uh you end up on a state which is impossible State and if you are taking Max maybe you can return minus infinite because Max of X comma minus infinite will always be x correct so this is again another trick that I want you guys to understand so you know this is how it happens so uh our first termination condition is that if the remaining amount is 0 return 0 and it makes sense because if I go by this definition this makes sense similarly if my remaining amount is negative then return infinite correct okay now look at this F of one what will happen at this F of 1 when you look at this F of one again from here you will make all those three calls which is f of 1 minus 3 which is minus 2 F of 1 minus 4 which is minus 3 F of 1 minus six one minus seven which is minus six now all these things will return in finite infinite all these things will return infinite and now again from here you can make sure to return another infinite because you can just write your code in a way I'll come to the coding part you can write your code in a way that one plus uh integer infinite is also an infinite value that is returned to the top So eventually what will happen from here is when you take mean off this and that it will turn out to be 0 and F of 4 will be 1 plus 0 which is one so you'll return 1 from here and returning one makes sense because if somebody asks you a question that what is the fewest number of coins need to make four you would say one just take this thing similarly in this manner calls will go down and values will be returned and that is how you can now imagine something will be written from here and F of 10 what it will do is it will find mean of those add 1 to it and that will be the answer of 10. okay let's look at the regards the code for this let's say there is a function called as main coins this function returns something what does it return it Returns the minimum amount you need to make uh n rupees okay so you pass here n correct now tell me what is the first line of code that I should have base case right and what is the base case here there are two base cases here first when n is 0 we return 0. and there is one more base case we just learned if remaining amount is negative then in order to discard the contribution of that because we are taking Min we will return in finite which depending on your language you have to see like you can see C plus there is a provision of internal score Max which is the largest value that an integer data type possesses okay otherwise what to do so now comes the logic which should be as simple as this so whenever you are at a particular function call let's say you are at F of n you should be making all these calls and how do you how many calls will be there tell me the number of calls will be equal to M because that is the number of denominations that you have so do I need a for Loop here I need a for Loop then only I can make those M calls right so I'll iterate on my points array so for I equals to 0 I smaller than m i plus see what this for Loop is doing is if this is my coins array then my I is moving on from 0 to M minus 1. so let's say currently if my I is here then I want to take this coin as my current coin so when you take this coin as your current coin and present amount was this then what will be the leftover amount you take a of I and the present amount is n then the leftover amount will be n minus a of I had shown it to you right so I can say the remaining amount will be n minus a i correct and you will make a function call on this so you will call Min coins method on this correct and also because you have taken this AI currently so you have to add plus 1 to it you add this plus one before after it does not really matter okay and you want to do this thing for all the values of IE that is the reason you have written this for Loop you want to do this for all the values of I and for whichever value of I you are getting the minimum possible value of this uh that will lead to your answer so what I can do is before starting this for loop I can have an answer variable and I can initialize this answer to Infinity let's say it is n underscore Max to start with and now every time what I'll do is I'll update my answer I'll write answer equals to uh minimum of this expression comma answer so all that is happening is think of it in this manner you made this call okay you made this call and it returned you let's say x it returned you X so you have 1 plus x with you and your answer was initially Infinity so you update your answer to mean off this comma that and then you make this call and then whatever is returned using that again you update your answer so this is just like you know uh scanning 10 different values or M different values and finding out their minimum so I have initialized answer to integral score Max and every time I'm making the call adding one to it and updating my answer if possible okay now once this for Loop would have been over then think of it in this way from this function you would have made all these calls and you would have gotten your actual answer so what are you waiting for you can just return this answer okay now there is one very good question that a lot of you are asking see I had told you in situations like these like at F of 1 you might it might happen that all the children are returning in finite infinite in finite so if you compute one plus Min off uh in timate and store it in an integer let's say x what will happen how will your computer respond to this theoretically you will say hey one plus infinity is infinity but your computer will not agree to it because if you add one to maximum integer value sorry uh minimum integer value it's not maximum sorry it's Max min so if you add 1 to the maximum integer value it'll lead to overflow so there is an overflow scenario that can happen over here so how to handle that all that you can do is you can change the types to Long so if you change the types to long one plus n tender score Max whatever it will be it'll still be greater than integer Infinity but it can be accumulated in a long so in questions like this is also another point of care that you have to take in your mind cool anyways so tell me one thing now this is the code that we have and this is the recursion tree diagram that we have so here n is something which defines our state and what is n it is the remaining amount now tell me something uh do you see overlapping sub problems over here yeah three so you can say you can easily see that this F of 3 is present here also and here also overlap overlapping is a problem is happening so how do we counter overlapping for problem memorization very good the first step you guys have figured out so uh yeah the first thing I'll do is I'll create a memorization array now what should be the dimension of this is this a one-dimensional problem or a is this a one-dimensional problem or a is this a one-dimensional problem or a two dimensional problem it's one dimensional problem only y because the problem is being denoted only by one integer the remaining amount is just one integer it is not two or three or four integers okay so I need a one-dimensional memorization array and one-dimensional memorization array and one-dimensional memorization array and what should be the size of that array so if you take a look the value n will keep on reducing only why because you are always subtracting something from it so the different values of remaining amounts that you will see in this tree are the different values of this integer that you will see at the nodes of this tree will be smaller than or equals to n now from 0 to n there are n plus 1 integers so it's good to initialize it to that right and you can initialize all of them to some value like minus 1. why because I know for sure that the fewest number of coins will never be minus one can it ever happen that number of points is minus one no so I can initialize everything to minus 1 and now you just need to write your memorization logic over here which is I think super easy thing to do what is the first step of memorization base case remains as it is no one is going to touch that okay now after base case the first thing that you will do is you will check in the memorization array whether answer for n is present or not so after this line you can write if I hope this part is visible you can write if mem of n not equals to minus 1. okay so what I have written is if memo of n not equals to minus 1 then you can just return mem of n right otherwise what you can do is you have computed actual answer in this case because if let's say you had not solved for the amount n then you have solved for it and after solving for it first store that answer in memo of n and then go ahead and return that answer so everything is still the same the first part is mem check the second part is solve and then store and then return but do you somehow realize inside that this code will be much more optimal than the previous code because uh if you have solved for f of 3 here if you have created a gigantic tree for f of three here you will not create that here again it will for sure be more optimal
|
Coin Change
|
coin-change
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104`
| null |
Array,Dynamic Programming,Breadth-First Search
|
Medium
|
1025,1393,2345
|
1,513 |
hi my name is Ray and today I'll be explaining question 2 from the codes weekly competition 197 question 2 is number of sub strings with only ones and the question gives you an input binary string of zeros and ones and it expects you to return all sub strings with all characters ones so that may seem like that may seem a little bit confusing but let's just dive straight into example one so we have this binary string 0 1 and we need to find the number of sub strings with only ones as characters so an example one single digit one occurs 5 times 1 occurs three times and 1 occurs once so we would return line so how do we do this how do we find the number of time the number of sub strings with only one character with only 1 as its character well the first thing we need to do or the first thing I did was I created a string array and I split um the binary string split binary string based on the occurrence of 0 so that seems a little bit confusing but all that is every time there is a 0 I split the array so I would have 1 as the first element and I would have 1 as a second element because I split the string based on this 0 and there's a function in Java which is string dot split which will automatically do that for you so the next thing I did is I did if I added a for each loop to loop through the string array and for each element I determine the number of common combinations of ones and then added this to a count variable and finally I just return the count so that's the entire solution and if this doesn't make sense I'll quickly walk through this solution in example one so as I said we had split the string array with 1 and 1 so you have to find the number of combinations of ones so you can have two ones and you can have one 11 for this first element right here you try to highlight that for this first element right here so that equals 3 so the second element 1 we can have 3 ones we can have 2 11s and we can have 1 111 so that equals 6 so we says 3 plus 6 equals 9 so we would just return line and if there were more elements we would just keep on adding and finally we would just return whatever the final numbers so yep that's the entire solution to this question it initially may seem a little bit confusing but once you figure out that you need to split the array based on the occurrences of 0 the question becomes extremely straightforward if you're still confused just leave a comments down below and I'll do my best to explain it and as always if this video helped you in any way please like and subscribe and I will leave the link to my code down below thanks and I'll see you in the next video
|
Number of Substrings With Only 1s
|
find-all-good-strings
|
Given a binary string `s`, return _the number of substrings with all characters_ `1`_'s_. Since the answer may be too large, return it modulo `109 + 7`.
**Example 1:**
**Input:** s = "0110111 "
**Output:** 9
**Explanation:** There are 9 substring in total with only 1's characters.
"1 " -> 5 times.
"11 " -> 3 times.
"111 " -> 1 time.
**Example 2:**
**Input:** s = "101 "
**Output:** 2
**Explanation:** Substring "1 " is shown 2 times in s.
**Example 3:**
**Input:** s = "111111 "
**Output:** 21
**Explanation:** Each substring contains only 1's characters.
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'0'` or `'1'`.
|
Use DP with 4 states (pos: Int, posEvil: Int, equalToS1: Bool, equalToS2: Bool) which compute the number of valid strings of size "pos" where the maximum common suffix with string "evil" has size "posEvil". When "equalToS1" is "true", the current valid string is equal to "S1" otherwise it is greater. In a similar way when equalToS2 is "true" the current valid string is equal to "S2" otherwise it is smaller. To update the maximum common suffix with string "evil" use KMP preprocessing.
|
String,Dynamic Programming,String Matching
|
Hard
| null |
1,652 |
Hua Tha Is Problem Tubes So You How Is The Time Of Luck Code Liye Baki Fritters Phone Number Like Example Military Plane Take Care Love You All Subscribe Plus 500 Hai Apne Real Romance And Also Actress Elements In The Field Of Fashion Kare Saunf 125 V4 Plus Seventh Class 5 Result Newly Made Locket in Operation Bigg Boss Wasted On This Look TVS Elements of the Year - This Look TVS Elements of the Year - This Look TVS Elements of the Year - 250 Laage To Previous 2002 Friends Riots After - 39 After - 39 After - 39 A Positive Attitude And She Din Kuch To Bol Hum Solution Basically Brute Force Solution Or You Can do something on the table at the time of duty of all of 4 but for it's okay difficult hero for fifty plus one two three two one two three idiots subscribe button subscribe The Channel Please subscribe and subscribe the negative numbers like share here and one two here But 642 A Love You Want To That Thing Nickel Two Minus One Okay So Two - Lee Position Shoulder Saturn Okay So Two - Lee Position Shoulder Saturn Okay So Two - Lee Position Shoulder Saturn So Simply Say The - Prepositions From To The So Simply Say The - Prepositions From To The So Simply Say The - Prepositions From To The Audible 108 End Background 248 So Every Place For International School Model Will Cry - Place For International School Model Will Cry - Place For International School Model Will Cry - Silencer Accounts Class 300 Plus 4 Bichhe Digest India Element Position 543 Loot Witch Nothing But That Laxman Position Speech Sorry That Jab Supreme Power To Do That Plus Form But You Can Live With Example It Will Not Be Born In A Small Village Till Time Complete That Aapke Khand Like This SAARC 1000 simple things more than 200 all videos have minimum relation to make spring balance ok very nice problem ok but that tweet a are you want to make the stranger format of ego that BB all that which is the format you need to achieve a hello How to achieve this power a 12v LED bulb is always b or inch location check what happened the party and work for change of partition done and what is the score not think it is a partition The Amazing Me Hai To Lakshmi Dubey Ne Naitik Share Good Example that in your let's imagine partition is in all ok navda do you want to participate in partition in fire what will be the cost of converted into oils for loved by all the soul in 700 what is the cost will be nothing but deleted all December Partition According to Right Side Connect Over All What Will Be More Conscious at Least One and So Right Side Connect 121 Likes in More School System Minimum Partition Point to Partition Points Cost Determines 126 Number of GPS on the Right Side Number of Baroda Left Side OK Tips Of The Independence Day With Solution In Which Will Be The Position Of Do I Invented Simple Net C Partition Done And What Happens To Convert All Of The Thing To Be Easy And Even Into It's Okay Iftar Parties And What Happens To Convert Hadith 282 Rauniyar Digit Products Button In Partition On Whatsapp In Doing Right Side Is Left Side That I Costume And Tamil Whatsapp My Husband Daniel And You Too S Well S Math Does Not Come In The Night So In The Code In This A Prefix And Suffix Poking Sweater Return For this flash lights reduce voice male b muslim left all in this right that it onlight ok so fast benefits avoid all in this green manner good manner but 2000 clear a positive english simply feeling of this is normally your fix solid collect physical Tubelight anomaly all but IF YOU CURRENTLY ARAB RIGHT ISSUE CURRENTLY THANKS SUCCESSFUL AND CO TAX RIDES AT SPECIAL LAW TO NOTHING BUT ARE YOU WANTS TO ADD ONE TO THE PREVIOUS LEFT BETWEEN REDUCE NOBEL PRICE OF ANY INTERVIEW YOUTH AND PLANETS OK NFC OF THE FIRST WOMAN CHIEF Coach I do n't do Difference Between Left PlayStation 2 Right OK Digit Important End WhatsApp And Observe And Should Always Give That All To Have Been Sworn In What I Love You All Girls Are Also Chapter I Will Note From This Point Fit Condition Like You Love You To Front Part Ko Birthday Wish Karna Hai Ki Jis Question Of Who You For Watching This Of Soul In The Contest All My Products Like Decorating Sim Posted In Work So Instead Of Directing Road Dhairya Guru All Elements To Use This Element Ok Video then subscribe to the Page if you liked The Video then subscribe to the Page That And Passing Of Yours To Have Been Events To Show Good Contest Information 2all Setting This Tool Solution For Problem Screen To A
|
Defuse the Bomb
|
minimum-suffix-flips
|
You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`.
To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**.
* If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers.
* If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers.
* If `k == 0`, replace the `ith` number with `0`.
As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`.
Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_!
**Example 1:**
**Input:** code = \[5,7,1,4\], k = 3
**Output:** \[12,10,16,13\]
**Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is \[7+1+4, 1+4+5, 4+5+7, 5+7+1\]. Notice that the numbers wrap around.
**Example 2:**
**Input:** code = \[1,2,3,4\], k = 0
**Output:** \[0,0,0,0\]
**Explanation:** When k is zero, the numbers are replaced by 0.
**Example 3:**
**Input:** code = \[2,4,9,3\], k = -2
**Output:** \[12,5,6,13\]
**Explanation:** The decrypted code is \[3+9, 2+3, 4+2, 9+4\]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers.
**Constraints:**
* `n == code.length`
* `1 <= n <= 100`
* `1 <= code[i] <= 100`
* `-(n - 1) <= k <= n - 1`
|
Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.
|
String,Greedy
|
Medium
| null |
456 |
hi all welcome to learn code repeat so today we will be looking at day twenty three of the october lead code challenge the name of the problem is one three two pattern let us look into the problem so the problem states given an array of n integers norms a 132 pattern is a subsequence of three integers number five num of j and m of k such that i is less than j which is less than k and the nums of i is less than numbers of k is less than nums of j return true if there is a one three two pattern in nums otherwise written false follow up the o of n square is trivial could you come up with a o of n log n or o of n solution and they have given couple of examples so let us take the second example here so here it is three one four two and the output expected is either true or false so here if you see one is less than four and two is less than 4 but it is greater than 1 right so if this is i j and k right this is i this j and this k right so nums of i should be less than numbers of k and nums of k should be less than numbers of j so the in between should be higher so if it is a graph something like this right where the numbers are going up so this will be like going up and then it is going down so 4 is here 1 is here and 2 is here ok so we have to identify such patterns and this pattern need not be contiguous it is a subsequence so there can be a gap in between so it can be like 3 comma 1 comma 4 comma 5 and then 2. so here one four and two is correct even in this case ok so let us see how we can solve this first using a brute force approach and then we can optimize the solution so one of the example is minus one three two zero so we have to find three numbers right uh i j and k right such that nums of i is less than nums of k which is less than norms of j right and i is less than j is less than k ok so these are the condition right so the simple approach will be to use three for loops and go through i j and k nested loops and find out this condition right whether this condition is true then return two right and the algorithm will look something like this so we have three for loops one two and this is the third one and we can check inside the nested loop the innermost loop whether the conditions are met then return to this is a simple brute force approach right however for this since its nested three for loop the complexity will be of n cube right where n is the number of elements in the array okay and we are using no additional space here so the space complexity so this is the time complexity and space complexity will be o of one because there is no additional space here now can we improve this particular algorithm right so here right instead of having one for loop writers so we have nums of i numbs of k and nums of j right so one i can say one is the min value so this is the minimum value and then there is a middle value and then there is a max value right so i can identify min value and i can keep that mean value as is right so let us say this is the array right so i can check what is a min till that point and i can keep that mean value as is right because they are asking for any combination right if there is any combination that satisfy this condition then we are good we should return true right so if the minimum value till a given point right till a given index should be ok for us right so what we can do is we can remove this right this particular for loop we can remove this and within this j for loop right we can just check what is the minimum till that point and use that min of i right let us call that as min of i to replace this particular numbers of i right so the algorithm for that will look something like this we are using min of i which points to numbers of zero then for each j iteration we are checking what is the mean of it till that point so it is a mat dot mean of min of phi and nums of j the current element and then inside the for loop so we are checking the same condition right numbers of k is less than numbers of j and min alpha is less than numbers of so by doing that we have optimized the algorithm to o of n square ok now can we further optimize this right ah can we further optimize this to often and that is what they are asking in the question can we optimize this to o of n so the first thing that we can see here right we can have a separate for loop for this right to calculate the mean value right so let us say if i have a separate for loop to calculate a main value then in that case i need to store that mean value right one thing i can do is have a min nums array and at each index right we need to find out what is the minimum till that index right so if i am at this index what is the minimum till that index so here it is minus one if i am here it is again minus one right and for this particular case everything will be minus one because till each index the minimum is minus one right so that way i can form the min array right so i will need one for loop for the mean array so till now the time complexity is o of n right now i need to check whether that condition is satisfied what was the condition numbers of so the condition was nums of i is less than of k which is less than nums of j and i is less than j is less than k this was a condition right so let me highlight this here right so we will check how can we use one for loop for this condition right so one way we can do is we can go from right to left direction so let's see how it will help right so if i am using a for loop to go from right to left right let us say this is k equal to num let us say nums is n dot length minus 1 and k is greater than equal to zero k is minus ok so this is one for loop so we just need to use one for loop to solve this equation right or to solve this problem right so how can we use one for loop right so what we can check is since we have the minimums value right so min nums is nothing but this nums of y condition right that we are replacing with minus so here i can check whether my nums of k is greater than nums of i right which is min na so if my lets say n is the numbers of k right i am just using n here n of k if it is greater than minimums of k ok so what this means is i am going from here that means there is some min value which is less than my n of k my nums of k ok now we do not need what exactly is the mean value right we just want to check whether this condition is satisfied so any mean value is fine for us so here we can very well say that j is less than k right so we need one k and one either k minus one or two or three whatever is the value right that should be satisfying this particular case right so first we are checking for this nums of k is greater than numbers of j so we are taken care of this particular two condition right now how can we take care of this two condition ok so what we can do is first we can add the number that we are getting in a stack right so let us say this is a stack right i add this value 0 right now in the next iteration if this condition is satisfied that means my next number that is here 2 is greater than minimums of k is minus 1 which is true if that is satisfied so i can directly check in my stack and i can so here i can checks my stack is not is empty and i can check whether my stacks peak right that is the top of the stack if it is less than my min value if it is less than or equal to then pop it ok so stack dot peak is less than equal to min then i need to do abstract dot pop why i need to pop it because if it is less than equal to min right then it will never satisfy this condition even if i move forward right on the left side it will never satisfy this condition so i can very well pop that element from the stack okay and after that if there is still any element right so that means if stack is still not empty and i can check this condition right so this numbs of j is my current numbers of k right here in this case it is this is my current k value so this current k value is greater than my nums of k right which is the element in the stack dot peak ok so that means i am somewhere here 2 so this needs to be greater than this right that's what it is right so if k is greater than j so this k is this value right which was the value in the stack right and my current pointer is to this two pointer right or two index right which is nothing but the j value so j value is here since i am using one for loop so i am using the variable as k here but this is basically in this particular case it is the j value so i am checking that condition number of j is greater than t dot peak which is the stack dot peak so stack dot peak has nums of k value which was this if that is the case then i can directly return true right because now it has satisfied this condition and this condition was satisfied in the if condition here if that is not the case right then we can very well use this nums of k for the next iteration so i can directly do a stack dot push my nums of k ok so using this one for loop now i can solve this problem right so let's say what will happen in this case so in this case anyway it was only zero so it will be popped up right so let me remove this and add another condition so let us say the input is one two three 4 right this is the input so the min array will be 1 comma 1 right because 1 is the minimum value and when i am going to this for loop right initially my stack right my stack will be something like so initially it will be 4 right 4 will be added this 4 will be added into the stack then my pointer will be here it will check whether this current pointer is greater than min value yes the mean value is this yes and is it greater that is nums of k is it greater than the value in my s t dot peak right so this my stack will not be popped okay so it will check whether this is a my current pointer value is less than min value yes so if condition is satisfied now it will check in the while loop whether stack dot peak is less than min so stack dot peak is 4 is not less than min so this file condition will not be executed in the if condition it will check whether nums of k which is 3 is greater than stack dot peak 3 is greater than 4 no so it will go to this it will push my this number 3 into the stack okay now my pointer will be here it will check whether this is greater than min value yes it will again check whether this is greater than my stack no so this will be added here and similarly one it will check whether one is greater than min no so it won't even go in this if condition so final value in the stack will be two three four and at the end the for loop will exit so at the end if the for loop exits we can directly written false here because we know there won't be any condition that satisfies this particular case right so let us code this and see whether it works fine so here i have written the same algorithm so first i am checking whether the length is less than three then i can directly written false because i cannot check the three conditions so that will be my base case then i am creating a min array min nums array and i am showing the minimum value till that point using math dot min and then this is the one for loop that we are having in that first i am checking if my current j is greater than min nums of j only in that case i will enter in this particular if condition and then i am checking in the stack whether tax peak is less than min nums if that is the case then pop the stack and after doing the while loop of popping the stack i am checking if still there exist an element in the stack which is less than nums of j in that case the condition is satisfied so we have to return to else add the element into the stack okay and at the end we are returning false so let us run this code and see whether it works fine and the code is accepted so here the time complexity is o of n since we are using only two for loops it is not an estate for loop there are two for loops so it is o of n and the space complexity is also o of n because we are using a minums array and also a stack so both will take max o of n space so space complexity is also o of n so that's it for this video thank you
|
132 Pattern
|
132-pattern
|
Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109`
| null |
Array,Binary Search,Stack,Monotonic Stack,Ordered Set
|
Medium
| null |
213 |
all right let's talk about hospital 2 and house robert 2 is almost exactly to the same as house rubber one the only thing is different is how swap 2 is arranged in a circle so the last element can go back to the first and you will definitely understand that two cannot go to the last right but two can go to the second last so for example the first one cannot go to the last one but you can actually as actually visit the second last element which is three and two can go to the last right when you go on the cycle you'll meet yourself again like when you add one right the neighbor of two is one and three so you're not you're gonna access the first element if you are on the second so let's just uh talk about the code so if the length is equal to zero i mean you are not dropping anything right so you return zero if the length is equal to one then you just return itself right and let's talk about the length is greater than two could equal then two right so like i said if you're on the first you can add your traverse to the second last if you're on the second which is one you can actually traverse to the last element which is zero to the second last and one to the last element so this is the rubbing method so when you rub you need to have to a local value i mean which is including exclude so you will definitely record your current value and add in num add so and now i will store the previous uh element that you are adding for the including and excluding so let's just say when i equal to zero so including will say okay now add right now i was initially uh zero because it excludes you and you plus yourself and its clue is you don't want include value so you just add the previous one just compute the previous one which one is greater if i is greater than just return add nonlinear square to just written knowledge and then the next following loop a and now i will update it right so it's clue updated for the previous value and include will just keep adding itself and with no add because when you plus add right you'll just add yourself again so which is neighbor right so you are not actually allowed to do that and then you return the including exclude value that will be your answer and do look about two three four one right this is a cycle and uh two cannot be just three and one so you can actually visit four only so it's the second last how about three you cannot visit two and four but you can actually visit the one which is the last element that will be your answer and let's talk about the result okay pass all right it's pretty good so let's talk about time and space so you actually traverse the loop twice but it's separately right and for each rough jump you traverse to all of them because you're actually using every single node and then you just uh compute the value at the end right then the worst case for the time is relevant and then space is all the one you're not actually using any space and that will be your final solution and peace
|
House Robber II
|
house-robber-ii
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[2,3,2\]
**Output:** 3
**Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.
**Example 2:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 3:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 1000`
|
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
|
Array,Dynamic Programming
|
Medium
|
198,256,276,337,600,656
|
814 |
so hey there everyone welcome back so it was our today's problem of the day named as binary tree pruning so we are given with that root of a binary we have to return the same tree where every subtree of the given tree not containing a one has been removed right so obser sub tree of a node is a node plus every node that is descendant of a node so for example in this tree so we are given with this entry we simply have to remove that subtrees that are not containing one right means that our containing zeros we can remove it we have to remove it and we have to return our updated tree right so for example in this case it's left subtree is already null right it's already null so going on to its right sub tree so moving on we have zero here right but further we have to check its left and right child also so in its right subtree means it in its right part we have one right so we don't have to remove one we can't remove one we can remove a zero in the in every sub tree right if in subtree it is containing zero right then we have to remove it so in its left sub tree there is zero right so we will remove it so this will be our updated binary tree right so for example this is the second test case uh given so our root node is one right so we can't remove it we don't have to remove it so now moving on to its left sub tree so will check till end right until it's uh further its left and right child and nodes are not null right so we have to remove till and we have to check till end right so now we have zero right so in its left part so uh for its left sub tree we have root node as zero right so we can remove it but first we'll check its left hand right child is zero is one present or not right so we have to check one or not because we can't remove one right so now further moving on its left and right child both are zero right so it's whole left c subtree is containing only nodes node values with zero right so we can remove this whole sub tree right so in our updated tree here will be our null present in our left part right so now moving on to its right subtree so uh root node is one so we don't have to remove it so checking for its left hand right part so in the left part it's it has zero node right only zero node so we'll remove it and in our updated here is null right so in its right part we have one right we'll keep one as it is right so this will be our updated tree right very simple so now simply what we are doing here is we are doing our post photo traversal right we are doing post order traversal so i hope you know all the traversals we have in order preorder and post order so according to post auto traversal how we'll do how what we will do in this case first we visit left then uh write note then a root right i hope you know post order so in the given problem this is what we are doing post order traversal so uh let's see let me draw it again so we have this binary tree given in our second test case right so this was our binary tree right so now we are first checking let's see we are going to its left subtree first so now we will not check first root okay so first we are checking its left root left node then its right node then root value right so if left and right both are zero then they both will return all right so they both are returning null so in the case now our root is also zero then this whole sub tree will return null to the root value right this whole sub tree will turn all right so means then our updated tree is in its left part we have null value right similarly we are checking for the right subtree so now we'll visit first hits will visit for first hits uh left child so it is zero right it is zero uh you can check further also this is null right this is null so now for this its root is as root value is zero then uh it will return all right it will return null to further its root value right so checking for one it's red child it is not zero right so it will return one in this case right so it is as one as it is so our updated tree will be so now we are checking root node also right we are done with the left part right part now root node is one right will keep root node also right so now it is one in the here it has returned null right in the right part we have one so it will be as it is so right so simply we are doing the post rotate reversal right so here is a very simple code so first of all we are checking if root is not equal to null right so we are calling recursion on our left part roots left and we are calling on right part right so in the case if root's value is equal to zero right and our roots left is equal to null and roots right is equal to null right so in this case it is returning null value right so as we have already seen here so we have these three let me draw it again let's see once more so we have one zero one so we have code recursion on the left part right further we have code recursion on this left part so we are now here right so now you can check in its left part we have null in its right part we also have null so if our now roots left so this is our now root right this is our current root value now zero so uh we are checking for the up to last right till last we are going so we have now this root value this is root now right so further in its left and right child both are null right both are not so they are returning null to the root right they are returning null so further we are checking if root value is equal to zero yes is it is equal to zero then this whole part is returning answer null right answer null further we are checking for the right part right so similarly it is similar as we have checked for the left part so its left and right child are null right so they both are returning null further we are checking the root value if it is 0 or one if it is zero the whole tree will return value null right so now both its left and right part are returning null right further we are checking if root value is zero one it is zero now this whole part this whole left subtree this whole left shift subtree right all the values are coming zero then this whole sub tree is returning null to the main root value right similarly we are checking for the right subtree also right this is a very simple code so if root's value is equal to zero and also root left is equal to codonal and root right is equal to also null in the in that case we are returning null value otherwise we are returning the root value right otherwise we are returning the root value so in the case let's say we have one in this case right so this will return this left part is returning one to the root value then in this case will not return null right so okay right part is returning null because it is zero right but our left part having one right so this uh subtree will be as it is so our updated tree will be in the case we have one in the case here right in that case i am saying so in that case our answer will be like this right because we have one we have we don't have to remove one we only remove zero so yamaha 0 we are removing this 0 because it is returning null right so in the case if it is if a left and right part anyone is having value 1 then in that case will return our root value right we are returning our root value roots left is also one right so we are returning this whole thing right so we are returning root simply so this is the code so it's working code you can see so yeah we are getting the right answer so that's it for this video so if you still have any doubt please ask in the comment box and you can connect with me my linkedin handle is given in the description box so thank you so much
|
Binary Tree Pruning
|
smallest-rotation-with-highest-score
|
Given the `root` of a binary tree, return _the same tree where every subtree (of the given tree) not containing a_ `1` _has been removed_.
A subtree of a node `node` is `node` plus every node that is a descendant of `node`.
**Example 1:**
**Input:** root = \[1,null,0,0,1\]
**Output:** \[1,null,0,null,1\]
**Explanation:**
Only the red nodes satisfy the property "every subtree not containing a 1 ".
The diagram on the right represents the answer.
**Example 2:**
**Input:** root = \[1,0,1,0,0,0,1\]
**Output:** \[1,null,1,null,1\]
**Example 3:**
**Input:** root = \[1,1,0,1,1,0,1,0\]
**Output:** \[1,1,0,1,1,null,1\]
**Constraints:**
* The number of nodes in the tree is in the range `[1, 200]`.
* `Node.val` is either `0` or `1`.
| null |
Array,Prefix Sum
|
Hard
| null |
199 |
hey guys how's it going in this video i'm going to walk through this legal problem finally right side view so this problem was asked by facebook for 59 times in the past six months so if you're going for an interview with facebook you do not want to miss this video so let's take a look at this problem to see what's asking given the root of a binary tree imagine yourself standing on the right side return the value of the note that you can see from the order from the top to the bottom so if we're given the tree looks like this and what we need to return is uh one three and four basically if you're standing here on the right if you look at this look at the tree and that's the note that you will be seeing on the right side and also there are some other example so this problem looks intimidating at the first glance but actually it's not that bad actually we can solve this problem using the method that we use to solve the level order traversal so if you haven't solved that problem i recommend you to do that first and then come back to this one later because um we are basically applying a very similar methodology right here so let's dive in to the solution so first we have a queue basically we will use the breakfast search to traverse all the nodes um essentially what we're going to do is to have um let me show you what we're going to achieve i'm going to print this one i call it label order from left to right essentially what we're gonna get is um the level order uh the number from uh level order traversal for example the first level it's gonna be one which is on the top second level is two and three which is the second level from the left to the right that's why i call it uh level other left right and also the last level is going to be from the left and to the right again but it's the last level um yeah so this is what we're gonna uh get and as soon as we get this guy over here we should look up the uh the last number right this number and also this number and then that will be the uh the required answer if the on the question was asking to look at the tree from the left hand side we just get the first number okay so this number and this number so that would be a slight modification as you can see now it's one three and four and then we just change the first number run it again actually it's going to get um one two and five the other side okay so now the problem comes back comes to how do we get this level order traversal let's look at the code right now and we will use the bfs uh for bfs we need a queue right so the first element in the queue is going to be root and i have the level on the left right which i just show you so while there's an element at least one element in the queue and we initialize a empty list for the level and also i have the tam queue which collects the nodes for the next level and i'm going to swap it at the end so for all the nodes in the queue and i append the current nodes the value to the level list okay and if we have a left node so if the current node has a left child which appended to the tam queue which will serve for the next level uh calculation at the same time if there is a right trial which is appended to the temp queue as well so at the end and after we look through all the nodes in the queue on the current level and then we get all the nodes that we collect from the temp queue put it in the to the queue for the next calculation and then we empty the chem key list okay at the same time we collect the level which is the value we collected from the current level uh appended to the level order left right and then we empty the level list to search for the next uh next level um traversal so and then after that uh as i showed you before we're gonna get something else like this okay for each level all the numbers from the left to the right okay and after that um we just simply extract the number the last number on each of the sub-list sub-list sub-list let's submit that so for time complexity it's going to be big o of um it's going to be big of a number of nodes and same for space complexity so this is my solution to this problem i hope you find this helpful if it is please like and subscribe thank you so much for watching see you next month bye
|
Binary Tree Right Side View
|
binary-tree-right-side-view
|
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_.
**Example 1:**
**Input:** root = \[1,2,3,null,5,null,4\]
**Output:** \[1,3,4\]
**Example 2:**
**Input:** root = \[1,null,3\]
**Output:** \[1,3\]
**Example 3:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
116,545
|
1,514 |
hey everybody this is Larry this is cute three of the recent indeed contest half of a maximum probability hit the like button hit the subscribe button join me on disco and yeah going over this fall so this poem has a couple of components that you have to think about the thing that I had trouble with a little bit was when I was solving it live and you could watch me about I do that was that I wasn't sure when said I wasn't sure that greedy works right so I mean it looks like a shortest path and it smells like a surest path I knew that was maybe some variation in the shortest path there are a lot of shortest path algorithms though so the thing for me that I have to try to figure out was that they're multiplying two probabilities you always the greedy construct is that when you add a node your is one to get them to that node with the maximum probability and in this case they're no psychos in this case because which is kind of like negative edges well negative psychos matter there are psycho spin but you whenever you go back to you know the same place your probability will always go down because well I mean I guess it could remain the same of your entire path it's just 100% but effectively path it's just 100% but effectively path it's just 100% but effectively there's no way to gain probability so because of that Dijkstra works because whenever you reach a node you want to be there at the maximum probability and yeah and that's pretty much it that's the idea the input is a little bit weird I don't know why they separate out other than maybe to be a little bit misleading there's a poem statement they said well the probabilities but yeah I just wrote Dijkstra's algorithm where I reconstruct a graph I put it in adjacent seal is where we're you know for every you connected to we've with a probability of W and I just use W because they're rates and you we are both popular graph constructs yeah and that's how I constructed adjacency graph I said two the default value to zero meaning that the civil chance of getting to any of those places and in Python heaps men heaps so I and when I wanted was a max-heap so you see that I am I just max-heap so you see that I am I just max-heap so you see that I am I just inverted it by times it by negative one to kind of you know start off just you're at the store in position with a hundred percent probability you said there's a distance and then the rest is just standard Dijkstra heap where well we come right back to the positive amount so that I don't have to worry about it or think about it too much but basically you have this thing if we're at the end and we could just return the probability because of greeting we know that whenever we get to note is the best that we can get to this just make sure that if we put the same note in there keep multiple times we just get rid of it and then here is just for every edge that this node is connected to this vertex is connected to if we can get this shorter but and this is the current probability times the probability of this success so there is some probability theory that you have to know to sound this but I mean I sent that a new distance and then I push it on the heap and if I cannot get here then that means that I cannot get to the end I return to zero so yeah so that's cute Buie the complexity what is the complexity so this is let's see so this is at least o of n but over here adder oh yeah so we put each node and so this is gonna be the heap may will have at most o of ye elements so that means that heavy elevation will be large ye and because we only do roughly speaking we ish a number of relaxations it's gonna be real ugly and yeah and that's the time yeah that's time complexity the space complexity we well we store something for you to edge so it's Romeo 3 plus G per se so yeah so that's kind of the compact for this one digits I could totally see this one being on an interview so definitely practice for it because it is just a shortest path there is some greedy as well but it is based off things that in theory people should know so yeah that's why I have a disc problem stay tuned for the live portion nope I got it so quickly and then path for maximum probability I was so the short answer for this problem is that it is greedy slash Dijkstra's algorithm I mean thanks first album requires it you know it is a greedy algorithm way but for me I just I had to convince myself and that's what I was thinking in the beginning I'd convinced myself that I mean quit is the shortest fat form of some sort but German tation and whether we could do greedy Dijkstra wasn't super clear to me also the input was a little bit weird in that I don't know why they separated out the edges and their success probability and not putting them together maybe that maybe they try and not make it a hint or something but I also had did have some concerns about just in terms of possible mistakes and stuff like that I was definitely trying to be mindful but for this one I yeah and I just I think right now I'm just trying to convince myself that the greedy algorithm is ok cuz I was like hmm like into it intuition wise that's what I thought but I really wasn't sure so yeah so that's basically what I was doing and I was like ok I'm going to tie sure the base case would be zero so that's what I put there yeah and I was thinking whether like I think I was just thinking about data structure for a second of like where do I need to convert at na and update I end up converting it to an adjacency list but the success probability as the edge and yeah and then I was just like okay let's just do it tighter let's make put a heap yeah we start by and this might look a little bit odd but in Python the heaps main heaps so that's why I take the negative value so that I but what I do is check the base case is that the storing know has a 100% probability of storing know has a 100% probability of storing know has a 100% probability of starting so I put in a one-day yeah now starting so I put in a one-day yeah now starting so I put in a one-day yeah now I get the probability and a node this is right now standardized true I think I was a little bit slow but I was still thinking for what every big man and this is where maybe you had practice and I did practice it to be honest but you practice it enough then maybe you'll be able to type it faster but I was just I don't know mm-hmm don't know mm-hmm don't know mm-hmm I think I was pretty fast for these first three problems yeah and this is again still standard Dijkstra but instead of using you know adding as to wait I did the probability times to the weight after the success probability and I call it the weight but yeah that's pretty much it and then I just have to add one more if statement for you know for the end node and then that's pretty much it I have to unpack correctly for my four loops I think that's mostly it made them I don't remember let's see yeah it looks okay it looks to match the example so I submit it wasn't 100% sure example so I submit it wasn't 100% sure example so I submit it wasn't 100% sure on down
|
Path with Maximum Probability
|
minimum-value-to-get-positive-step-by-step-sum
|
You are given an undirected weighted graph of `n` nodes (0-indexed), represented by an edge list where `edges[i] = [a, b]` is an undirected edge connecting the nodes `a` and `b` with a probability of success of traversing that edge `succProb[i]`.
Given two nodes `start` and `end`, find the path with the maximum probability of success to go from `start` to `end` and return its success probability.
If there is no path from `start` to `end`, **return 0**. Your answer will be accepted if it differs from the correct answer by at most **1e-5**.
**Example 1:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.2\], start = 0, end = 2
**Output:** 0.25000
**Explanation:** There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 \* 0.5 = 0.25.
**Example 2:**
**Input:** n = 3, edges = \[\[0,1\],\[1,2\],\[0,2\]\], succProb = \[0.5,0.5,0.3\], start = 0, end = 2
**Output:** 0.30000
**Example 3:**
**Input:** n = 3, edges = \[\[0,1\]\], succProb = \[0.5\], start = 0, end = 2
**Output:** 0.00000
**Explanation:** There is no path between 0 and 2.
**Constraints:**
* `2 <= n <= 10^4`
* `0 <= start, end < n`
* `start != end`
* `0 <= a, b < n`
* `a != b`
* `0 <= succProb.length == edges.length <= 2*10^4`
* `0 <= succProb[i] <= 1`
* There is at most one edge between every two nodes.
|
Find the minimum prefix sum.
|
Array,Prefix Sum
|
Easy
| null |
1,700 |
okay hello so today we're looking at question 71700 number of students unable to eat lunch so at a school cafe we they offer circular and square sandwiches at lunch break referred to by numbers 0 and 1 respectively all students stand in a queue students will either prefer square so 0 or 1 sandwiches note that the number of sandwiches in the cafeteria is equal to the number of students sandwiches are placed in a stack at each step the student at the front of the queue will like prefer which sandwich is on top of the stack they will take it and leave the queue if they prefer it otherwise they will just leave it and go to the queue's end so this continues until none of the q students wants to take the top sandwich and are thus unable to eat okay so this tells us that the stop the sandwich line is basically the determining factor of our loop right because like no matter students can go from front to back but the savage's line doesn't move so let's now look at a an example so we have students q and then we have sandwiches okay so first student doesn't want this what happens is he'll go to the back of the queue wait am i doing this right yeah okay one zero one again he doesn't want it because it's a cereal sandwich and person one doesn't want the cereal sandwich this won't happen perfect so this matches up with the top sandwich and this person doesn't want so he'll move to the back of the queue we'll have one zero oh we met another match okay now again he wants to move to the back of the queue and we have our match so everything matches up so one way of solving this question is we can count the frequency or the number of students who wants a zero sandwich and the number of students who wants a one sandwich so we put them we can use the counter method and put them into a dictionary something like that and then we traverse through the sandwich array sandwiches array to determine and we keep on decrementing the basically keep giving out the top sandwich to students and when we meet the point where no students want the top sandwich anymore we break out of the loop because well no matter how many times they rotate through the students rotate through there's no point because no one wants the top sandwich so to kind of simulate through this let's do something like one okay so top sandwich zero right first time round this uh number of zero number of students who want zero were minus one because he took the top sandwich second time so let's draw it out oh okay because it minus this one strike this off next sandwich is a one so we strike the first sandwich off and we decrement the number of students who wants a sandwich one because we gave one out already and now let me put in the arrow and now because uh we decrement this because we give this out so we're left with a1 finally what we do is we um give this last sandwich out to the last student who once can see i'm blocked by the mic who wants this last one sandwich oh who wants this last sandwich oops who wants this last sandwich so we return the answer by summing the final answer number of people who are left in this dictionary like the values left zero and we return zero now we can look at another example with this one and let's see if it works let me try to move this away how do i shift move around the board with the right mouse button oh perfect okay very cool so let's paste it in input okay zoom in a bit let's try what we talked about so students uh we have here how many ones and how many zeros so we have two students who wants the zero sandwich and we have four students who wants the uh one steam one sandwich i'm sorry it's very late at night um okay so count we have this now we traverse through the sandwiches array okay now we first strike off one and we decrement one now it's this decrement zero and not the zero oh okay look so we are at a point where we have three more students who want sandwich one but even if they move to the back of the queue it doesn't matter because the sandwich that we're looking at the top of the sandwich stack now is zero but no one wants zero anymore so we break out of this loop and then we return the total of this two add up we get three so we three students are unable to eat now with that said let's begin implementation okay from collections import counter i think that's how it's imported right so my counter is counter students just to be sure let's print it out and see if it's correct okay yeah looks correct okay now we have this um so for sandwich in sandwiches if sandwich if we need to access the if my counter sand which is zero we immediately break out of this for loop else we take it we minus one to it in the end we return my counter let's see if it works i feel like there might be a syntax error somewhere oh okay all right so that's it for today's video thank you for watching
|
Number of Students Unable to Eat Lunch
|
minimum-time-to-make-rope-colorful
|
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step:
* If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue.
* Otherwise, they will **leave it** and go to the queue's end.
This continues until none of the queue students want to take the top sandwich and are thus unable to eat.
You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `ith` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `jth` student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._
**Example 1:**
**Input:** students = \[1,1,0,0\], sandwiches = \[0,1,0,1\]
**Output:** 0
**Explanation:**
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,0,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,0,1,1\].
- Front student takes the top sandwich and leaves the line making students = \[0,1,1\] and sandwiches = \[1,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,1,0\].
- Front student takes the top sandwich and leaves the line making students = \[1,0\] and sandwiches = \[0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,1\].
- Front student takes the top sandwich and leaves the line making students = \[1\] and sandwiches = \[1\].
- Front student takes the top sandwich and leaves the line making students = \[\] and sandwiches = \[\].
Hence all students are able to eat.
**Example 2:**
**Input:** students = \[1,1,1,0,0,1\], sandwiches = \[1,0,0,0,1,1\]
**Output:** 3
**Constraints:**
* `1 <= students.length, sandwiches.length <= 100`
* `students.length == sandwiches.length`
* `sandwiches[i]` is `0` or `1`.
* `students[i]` is `0` or `1`.
|
Maintain the running sum and max value for repeated letters.
|
Array,String,Dynamic Programming,Greedy
|
Medium
| null |
336 |
welcome to june's legal challenge today's problem is palindrome pairs given a list of unique words return all the pairs of the distinct indices in a given list so that the concatenation of the two words i plus words j is a palindrome straightforward problem i don't think i need to explain any further we just want to find every single pair in order that's going to form a palindrome now how do we know something's a pound realm basically the reversed word is the same as the word itself and we can do that by having a two pointer solution um so at first it looks like our constraints are fairly small maybe we can do this brute force just find every single pair concatenate the two in order and see if it's poundrum and if it is add the indexes into our output so let's begin by going with that approach how we do that well let's first write some sort of helper method called ispal which will tell us whether this word itself is a palindrome or not so we'll pass in a word as well as the start and end of what we're trying to check to see if it's a chondrome i'll mention i'll talk about why we're doing that in a bit but uh this would just be while start is less than n we'll check to see look is the beginning of our word not equal to the end that we're checking right now and if it isn't then we can immediately return false because this is not a palindrome otherwise we're going to increase our start and decrease our end and we'll continue on until we get the middle and if we can get to the middle we return it true so that'll be our little helper function to help us see whether the word is a palindrome or not so if we were to do this straightforwardly what would we do we just do a nested for loop right we'd say length of words get our output and we'll say 4i in range of n and then for j in range of n let's calculate our candidate here which should just be equal to words i plus words j now as long as these two indexes are not equal to one another and we'll say is pal this candidate passing the start and the length of the candidate minus one then we'll this means that these two aren't the same word and they form a they can candidate to form a palindrome so we'll add that to our output a list of i and j and that would be it we could go with this solution um it should be fine for most test cases but this reaches a timeline exception if i submitted it and the reason for that is it's not really optimal it's boot force we end up becoming n squared times k because of our palindrome function here so is there a way that we could make it better than that do we have to find every single pair is any other way we can do it well that makes it a little bit tricky because you need to figure out could we given a word could we find out all possible words that we could add here to make this a palindrome and that becomes pretty difficult i shouldn't say all possible but certain possible ones given our string here so let's just think if we had the words aaa what string could we add this to make it a palindrome well the first case here is we could add a blank string to the beginning or the end right if it's a blank string and the word itself is a palindrome that's a palindrome so if it's a blank string and the word is a palindrome then we should that's kind of like an edge case we should add the two indices and we should add it both ways right because whether we add it to the beginning here or the end it doesn't matter it's still a palindrome okay so if we see a blank string that's one thing we'll do we'll check all our words to see which ones are palindromes and add those to this index point both sides now second case let's just say we have like abcd what work we add here to make it a pound row well obviously we can just add the reverse right we can say dcba just reverse this word and add that will make a palindrome for sure so if we just reverse the word that also makes a pandome now this is the hard part say that we had a word like aaa bc or something like this what word can we add to the beginning to make this a palindrome after doing some research what i found is if we start at the beginning and check to see if this substring is a palindrome so say that we're checking the first part we see that this is a pendulum already right because it's just one word one letter now the rest here aabc if we found the reversed part of this in our word list we can put that like the word list in a hash and if we see this word reversed inside the word list so say that we see c b a that means we can add this part to the beginning and that will also make it a palindrome no that's not right this would be b yeah c b a this also makes a pound drum right so one function we can do is like first check at the beginning is this a palindrome if it is check to see if we find the reversed part of this next same here is the pound dome yes check to see if we can find the reverse part of this next and just make sure that if we do find it put that index point in front we also want to do the opposite way where say it was like c b a we'll start like right here and check hey is this a pound drum no okay this is a palindrome right so that means can we find the beginning part reversed in our word list we find a bc here that means yeah we could add this part and make this a palindrome so we're going to have to do this k times every single index point and just check to see can we find is this up to this substring a palindrome if it is find the rest of the string backwards whether it's in front or in the beginning and add that to our output so those are kind of our three cases so let's begin by first taking care of the first edge case here we'll go same thing for in range of n let's first check to see if it's a blank string and i'm going to make it a little easier say w equals words of i just make it easier to type first thing we'll check to see is this a blank string if it's a blank string then we're just going to look through all the words in our list and see if uh any of them are palindromes so for j in range of n it's kind of the same thing um we'll check to see look is if i does not equal j and is pal let's pass in words j pass in 0 and pass in the length of words j minus 1. then let's add that to our outfit i and j and we also want to do the opposite way j of j and i now once we're finished with this we can actually just continue because everything else we don't care about like we know this string is blank so the only possibilities is finding a word that's a palindrome so we just end that part here so that takes care of that first edge case now what about the second edge case well that's easy we just need to reverse our word so we can just do that by uh getting our word and saying negative one that'll make it reversed if we find bw in our lookup then we're going to add that and i just forgot we need to make our lookup first so lookup is just going to be a hash with four index value and word and enumerate words we're going to make the word the key and the index the value okay so we have our lookup right here so if bw in lookup um i should also mention and look up bw is not equal to you know the i that we're on well then we'll assign that to our output and that's just going to be i and lookup bw right so that one's easy so we take care of that one okay so now the hard part we want to take care of these weird cases uh where without having like a like bc like that i'm sorry cb plus and something like this so to do this what do we need to do okay well we'll have to have another for loop we'll say four i'll call it k in range of starting at one because we don't care about it's like nothing we want to at least check one substring so for i to uh it's the length of words see we're going to check two things one check starting with the beginning all the way to the end like this and we'll start from like partially substring all the way to the end like that okay so let's first take care of the first thing we'll say uh let's see if is pal we're going to pass in the word and we'll say starting from i guess it would be we're going like this starting from zero well all the way to k minus one i believe now if we find that this part right here is a palindrome we're going to check to see the rest of our word reverse it and see if that's in our lookup so this is a palindrome and we'll take our word up to the cave character up to the character right yeah because we're building up and we're going to reverse it so if this word is in our lookup that means we found a pair so then let's add that we'll say i'll put a pen but make sure to add this part in the beginning here so we'll get this word say look up this word and i finally want to also do the opposite way so this would be just pal w and this will begin with um think not zero but this will begin with k i believe and it will go to all the way to the end which would just be the length of our word minus one so if this is in our or if this is a pound realm then we want to get the word up to k here reverse it and if that's in our lookup then we'll add that as well but this time it's going to be i in front and this word or this index point for this word second okay finally that should have taken care of it so we just return our output after this let's get rid of this and let's see if that works so uh okay looks like i'm hmm yeah flip this where was that what was before uh all right so i think that's working so let's go and submit it ah there we go and accepted so time complexity wise it's going to be n times k squared because of this for loop with the k's i know we do a n squared technically here one time but because it's just once well depending on how many empty strings there are but i think we can ignore that one like make it a plus n squared so this does become more efficient and ends up becoming accepted so that would be it now the hardest part here is this like i was able to get all the way up to here but once we got to like this area i had to like look it up because it was really hard to come up with this but you know if you can get even close i think that's pretty good um yeah but otherwise don't feel bad because this is another very hard question all right thanks for watching my channel remember do not trust me i know nothing
|
Palindrome Pairs
|
palindrome-pairs
|
You are given a **0-indexed** array of **unique** strings `words`.
A **palindrome pair** is a pair of integers `(i, j)` such that:
* `0 <= i, j < words.length`,
* `i != j`, and
* `words[i] + words[j]` (the concatenation of the two strings) is a palindrome.
Return _an array of all the **palindrome pairs** of_ `words`.
**Example 1:**
**Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\]
**Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\]
**Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\]
**Example 2:**
**Input:** words = \[ "bat ", "tab ", "cat "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "battab ", "tabbat "\]
**Example 3:**
**Input:** words = \[ "a ", " "\]
**Output:** \[\[0,1\],\[1,0\]\]
**Explanation:** The palindromes are \[ "a ", "a "\]
**Constraints:**
* `1 <= words.length <= 5000`
* `0 <= words[i].length <= 300`
* `words[i]` consists of lowercase English letters.
| null |
Array,Hash Table,String,Trie
|
Hard
|
5,214,2237
|
331 |
hello everyone welcome to coding culture this channel will contain those programs whose explanation is either not present on youtube or the explanation is present but not up to the mark so without wasting time let's get started today's question is the verify pre-order question is the verify pre-order question is the verify pre-order serialization of a binary tree which is also the daily question of the 26th august 2021 okay so what we have to do in this question okay so first of all this question looks a bit tough and is but not that much but it seems like it's a bit more tough okay so first of all let's try to understand what the question is saying and okay so we will be given a string in which we in which the node's value will be given and null nodes will be denoted by hash symbol okay and we are given a pre-order like okay and we are given a pre-order like okay and we are given a pre-order like the pre-order of this is nine three four the pre-order of this is nine three four the pre-order of this is nine three four one two six okay and whenever there will be null nodes they will be represented by hash like four after four there will be two nodes then have two null nodes then it will be denoted by a two hash okay like here this four after four there are two hashes okay and after one also there are two hashes after six there are two hash symbols and after two there is only one hash okay so the null node will be denoted by hash and what we have to do is uh we have to check if the pre-order is uh we have to check if the pre-order is uh we have to check if the pre-order traversal is correct or not okay if the pre-order traversal is correct or if the pre-order traversal is correct or if the pre-order traversal is correct or not like yeah i think the questions explanation is a bit easy but uh okay so what we can do it how we can solve this question is the big task okay so yeah first of all let's uh try to understand that if okay i'm just trying to explain you that if a node is not null then it's in degree equal to 1 and out degree equal to 2 okay if a node is not null and if a node is null like if a node is null it's in degree it's 1 okay in degree of every node is one but its out degree is zero okay so let's take a tree in which there is a like nine here and okay and one here two notes and both are null both notes are null okay so if we are given this tree and how we will be given the pre-order what how we will be given the pre-order what how we will be given the pre-order what will be the pre-order it's beautiful will be the pre-order it's beautiful will be the pre-order it's beautiful will be nine as hash okay yeah it will be like this it's pre-order and how we be like this it's pre-order and how we be like this it's pre-order and how we will check if this is correct or not okay so it's in degree will be one and out degree is two it's in degree is one out degree is zero it's in degree is one and out degree is zero okay so if in degree minus out degree equal to 1 then we can say that it's a balanced tree okay and their difference any times difference would not be greater than 1 yeah okay so we can say that it is correct this binary tree is correct okay i hope that you are understanding like okay so let's try to analyze once again like now in degree is what will be the in degree of nine one everything's in degree is one and it's out degree is two okay if the node is not null then it's all degree is two and in degree will always be one if the it's this node is null if it's node is no it's in degrees one like suppose the one arrow is coming so it's in degrees one out degree is zero like after it no arrows are going okay so total number of in degrees in this tree is three and out degree is two difference is one okay so from here we got to a conclusion that the difference between the in degree and our degree should not be greater than one for a tree to be successful okay so i think the explanation is a bit enough and now we will try to code i want you to code by yourself first then come to the explanation okay so yeah okay so now let's try to code it okay so first of all what i will do i will divide this array this string into a string array by using the split function pre dot is split under by the comma if there is comma i will split it into two okay and now what i will do i will take my in degree equal to zero and out degree equal to what i'll do equal to one now why one big y one i will keep out degree as one because for a valid tree our total in degree is one greater than our out degree so if we take our degree as one already so the difference between them will be zero so we can simply check that okay you can't take it and check if the difference is one or you can take out degree as one and check if the difference is zero then the tree is valid okay both points are correct yeah what points are correct so now what i will do is i will take out a string node from the nodes array and what i will do i will first of all increase our in degree because either it's a null node or it's a normal node our in degree of every node is one whether it's the node is null or it's not enough so again now i will check if out degree minus in degree is greater than zero is less than zero sorry so written false why i have written it i will explain you don't worry okay and now what if not no dot equals what hash i will increase my out degree by two okay so yeah and now what i will at last check if my out degree minus in degree equal to zero okay if it is zero it means that our tree is valid okay so now let's uh yeah it's running okay now let's try to submit it yeah it's submitted and it's accepted so okay so why i have taken this is because of this test case okay yeah because of this test case only i have taken this because um there will be a hash for the left as the left is not and right is not null okay so for this i have taken this test keep this condition and okay now let's try to explain it in hindi for once okay so okay that's it that was the video hope you have liked it if you have liked please like the video okay and if this video has helped you in understanding this question so i think the channel deserve a follow and you should follow it as it will motivate me to make more and more videos okay and till then keep on quoting ask your doubts in the comment section and enjoy bye
|
Verify Preorder Serialization of a Binary Tree
|
verify-preorder-serialization-of-a-binary-tree
|
One way to serialize a binary tree is to use **preorder traversal**. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as `'#'`.
For example, the above binary tree can be serialized to the string `"9,3,4,#,#,1,#,#,2,#,6,#,# "`, where `'#'` represents a null node.
Given a string of comma-separated values `preorder`, return `true` if it is a correct preorder traversal serialization of a binary tree.
It is **guaranteed** that each comma-separated value in the string must be either an integer or a character `'#'` representing null pointer.
You may assume that the input format is always valid.
* For example, it could never contain two consecutive commas, such as `"1,,3 "`.
**Note:** You are not allowed to reconstruct the tree.
**Example 1:**
**Input:** preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
**Output:** true
**Example 2:**
**Input:** preorder = "1,#"
**Output:** false
**Example 3:**
**Input:** preorder = "9,#,#,1"
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `preorder` consist of integers in the range `[0, 100]` and `'#'` separated by commas `','`.
| null |
String,Stack,Tree,Binary Tree
|
Medium
| null |
688 |
hey what's up guys this is chung here so uh today uh let's take a look at this uh 688 night probability in chessboard um i think this is like it's a good question basically you know it's given like a 2d board uh an m by n chessboard and the knight starts at uh our earth row and six column okay and then the knight will attempt to make exactly k movements okay and the rows and columns are zero as zero indexed so the top left corner is zero okay basically this is the one right and this is zero okay and this is a n minus one and n minus one basically there are like uh un rows and the under n columns as you guys can see so a knight at any moment at any uh position it can make like eight possible movements okay so basically each time the knight can make like a one out of one divided by eight probabilities move and then it asks you to return like after case movement what's the total probabilities that the knight remains on the board okay i mean because if the board can jump in either directions i mean some of them are not valid basically it will be out of the board so the problem is just asking you to return the total probabilities after case movements where the uh the knight is still on the board okay so i think the first i mean this one it is like a dp problem right because you know actually the state what's going to be the state that state is this the state is like uh it's at the case like at case step and like at a row and column that's basically that's the state it's like a three-dimensional state right at like a three-dimensional state right at like a three-dimensional state right at k-step k-step k-step and the knight is at like uh at the uh this row and column if there if these three props are the same then we know okay we have seen this state before okay and the value for this dp basically it's a probability okay it's the probabilities uh after case moves and the ending at the position r and c and what's the probability of that okay so the first solutions like top down right basically we just followed what the uh the problem what the question is asking us to do okay i'm gonna do that the first top down first i mean so that i mean since it's like it's easier to understand so basically we're gonna have like a define like a dp right the dp like the current k current row and current column okay how about this and then you know okay since uh we need the knights can at any moment can make two sorry can make eight movements uh i'm gonna define those eight movements first basically i uh i start from i mean the direction doesn't really matter right so basically i start from the from this one i start from here and then i define this i basically just follow the counter clock clockwise i mean you guys can do it whichever what whatever the uh sequence you guys need it just i mean this we just need to define all uh eight directions here so basically the first one is this one it's like removing on rows level we are like minus two row and on column level we do a minus one column okay and then the next one is this one right this one is like still minus two row but plus one column okay and then the next one is the uh minus one two and then the next one is one two okay then keep going as two one and then 2 minus 1 and then 1 minus 2 the last one is minus 1 minus 2 okay sorry minus 1 minus two yeah so and then we simply return this we return the uh at zero uh row and the column okay and since we are like doing the dp here i know i'm gonna define like this dp memorizations myself just to make this solutions language uh agnostic so if in mem so we return this memorization okay this one right and then we have our answer here equal to zero and then we set these things in the end i mean this is just like template for the top down dp okay return now sir okay the uh okay so i mean at this moment right i mean basically we have four directions i'm sorry we have eight directions it moves okay and then the uh the new r will becomes to the current r plus d0 okay and the new c goes to the current column plus d one okay and then since all the uh we just need to check if the new location is in the board or not if not we simply can abort we can just ignore it right basically if the new are and n okay and zero same thing for the new column here okay i mean if that's the case right so the answer is what since you know since we have eight directions i mean so we have to accumulate all the answers from the eight directions basically you know what we have there we have like a dp like a new r like new c and the current sorry so k plot k plus one okay current k plus one okay that's basically the uh the dv right and uh okay so that's the uh the next step right but what so after this i mean from the current one to jump to the uh to this uh state here what's the probability right we have uh 1 divided by 8 which is a 0.125 1 divided by 8 which is a 0.125 1 divided by 8 which is a 0.125 okay right so we just need to multiply what whatever from the next step with the current probability to this state okay cool yeah so that's oh sorry so the most important thing so for any anytime for the top down you need to define a base case well so what's the basic case the base case is the current if the current k is equal to the k okay because you know we are making case jumps right so basically we're starting from zero okay and at the moment we're reaching k here we know okay we have made uh case move uh movements and at this moment we need to return one so why one because and at the last moment since we are doing like uh um and multiply here if we return zero everything will be zero but since we need a base case right the base case in the further multi for anything that's uh we do a product right we need a one here so that we can have like a zero uh we can have this like 0.125 uh we can have this like 0.125 uh we can have this like 0.125 as a base case for the last movement cool i think that should that i think that's it let's try to run it uh return double what 65 row column okay let me see here oh sorry here what a stupid mistake here cool so accept it let's try to run it yeah so it passed i mean it's pretty it's not that hard right it's pretty standard like dp problem you know you can call it like dfs you i think dfs is more appropriate dfs with memorizations right basically you know the uh so the time complexity of course the time complexity is the uh it's a combination of this right so basically it's gonna be the n square uh times k right and then times what time times eight right but since eight is like a constant so i think the total complexity is this n squared times k right and then the space complex there is also this it's also like n square times k okay time and space yeah cool so i mean it's pretty straightforward right basically we just uh do it with dfs right from the start to the end and then but remember so i think you just need to realize that so with these three properties you know you can uniquely identify state of this of these night movements here and after that it's just like for each of the moments you just check if the other move is valid if it's a valid and then we try to accumulate accumulates that moves uh by uh multiply the current probabilities and with the next step okay and then this is the base case right so we return one when we when it is still valid okay cool so that's that i mean how it's okay so next uh i'm gonna do the bottom up so for those who are uh interested in the bottom up solutions okay you know i think one of the advantage of the bottom up is that we can even like surprise i mean improve the space complexity from o n squared plus k to the o n square because you know we are only relying on the previous step okay so which means we can uh we can remove in reduce one of the space dimension okay so but let me try to implement the original versions okay so for that we need this and then in the dp right so the dp the first dimension is the i mean we're going to have a zero okay so start and end for this in range in and we need another like a layer of brackets okay so basically this is how the python like python defined like three-dimensional of python defined like three-dimensional of python defined like three-dimensional of the uh okay of the uh of the list here okay sorry uh okay so i mean this end is pretty straightforward but why do we do a k plus one here this is because you know um we need k movements right we need k movement but for the first but we still need like a base case for the k equals to zero okay that's why we need that because for the zero we need to set it to a base case which is one in this case and then after that we need to make like case movements that's that makes this dp a total dp uh size like k plus one size okay so same thing for this so the first loop is a k range a 1 plus 1 to k plus 1 and then j for i in range n for j in range and okay you know i think one of the difference between the top down and bottom up is you know for the top down you know it's easier you just follow the uh the step basically right you just follow the current step and you all you need to carry is that okay from the current step uh what's the next step right that's the uh that's the main thing you need to take care of for the top down but for the bottom up you know the bottom of the one of the essential uh the essential like the essential i mean the nature of the bottom up is that you know you have to be you have to i mean start thinking in a different way basically from that from this the k step i need to try all the possible possibilities of the i and j basically that's what this two for loop is for right i mean at the step k here i mean i need to try all the possible locations on this board so that i can populate everything but from this top down here i mean you don't need to think in think that way right because all you need to carry is that i mean for the current state right what's going to be the next state okay because you know this thing here this re this recursive car is taking care of this uh this nested for loop for you but from the part from the bottom up here you have to be basically you have to manually try all the possible scenarios okay from this 2d board here okay and then here same thing all right we're going to loop through them the moves here basically you know from the current uh i and j lo our ing location let's say we have a this is i and j here so we need to think in this in a reverse way basically how many ways we can get to the current low carbon iron j lo location same thing there are eight ways right i mean we can just reuse the same moves here you know e uh even though you know even though like we're defining like this moves by uh by going forward but you know this move is bi-direction okay you know this move is bi-direction okay you know this move is bi-direction okay so one moving forward you can think it in a different way basically you know if like if let's say for example if we are like it's minus two and minus one so the opposite of that is the two and one okay right so basically you know even though we're defining we're thinking this like in a re in the reverse way right how many how can we get the previously location from the current one we can still use the same moves uh this movement list here because those because everything every two moves there are pair right so it doesn't really matter the sequence doesn't really matter as long as we have the same moves here okay that's why we can just use the same moves here and instead here you know uh we have a new r here right but here actually what we are getting is the old i okay is that then is the i plus the d zero okay and the old j equals to the uh j plus the d one okay same thing we have to check the validity of this old i and j okay if the old i okay and same thing for the old j here okay so then the current k right the current k and i and j plus same thing 0.125 and j plus same thing 0.125 and j plus same thing 0.125 times dp k minus 1 and the old i and the new i sorry the old j okay so that's that and how about like the base case right like i said so the base case what the what is so what is the base case in our case the base case is dp0 and this rnc r and c equals to one basically at without any movements right our base case is only the r and c locations one because all the others they're all like invalid movements right that's why we just leave them at zero all we care about the starting point is one similar like this one right i mean so in the top down here we are we're like we're saying that okay so the end point is one but here like it's we're doing like in the in a reverse way right basically the starting point is one so okay so that's that and how about the final answer can we just return everything uh can we return the dp like k uh k and then n minus one no right because that stands for uh at the last step at this the last this position what's the prob the possibility ending at this position but since we have we need to consider all the possible locations that's why we need to accumulate everything together okay for i in range integer n and then for j in range n okay and we have dp like k okay because we are looking we're looking at the last step right basically for as for the last step we need to accumulate everything from the last step and that's going to be our total that's going to be our final answer here and again so we're doing like this k not k minus 1 because we need to make case movements since zero means we don't there's we don't make we didn't move anything yet right so that's why we need to start from one to k to make case movements and the last one is the dpk okay let's try to run this one here oh yeah all right so this will accept it let's try to submit it all right also successful i mean same thing same like same idea it's just like uh from a uh opposite way of thinking uh thinking of this of thinking this problem you know so same thing right the time and space complexity is all same thing as the uh the top down there they're both like n square times m that's our times k but like i said you know since all we need it since the case state case uh statement only relies on the k minus one we can like remove one of the dimension from our dp array here and we can simply we can just remove the this one here we just remove the case here okay the case dimension and here we simply remove doing this and same thing here but uh remember to do that right we need like a dp uh dp2 here right to uh to rotate the uh the current state and then the previous state i mean it's similar like the 1d uh to compress uh the 2d to 1d to compress the 3 to from 3d to 2d we just need to maintain like a 2d array okay so same thing here going to be a zero okay start n for range uh well we can do this i think we can do a dp dot copy okay right we just store the previously dp to this dp2 here okay so i mean so that here we can simply remove this one here i mean and then we remove this but here i mean so it's going to be a dp2 here okay because we are using like the dp2s are like the old dp right and this one here yeah so it means for that case in that way we don't have to reassign this one here yeah and here we can simply remove this one here yeah i think this should just work let's try to run this no maybe this copy is not right i mean let's see copy okay so we have dp2 here that's the old one okay let me try this i think there is a deep copy here i think this should work no deep copy okay you know fine i'll just use the uh brutal force way here so basically i'm gonna define like yeah i don't know why this thing doesn't work maybe i did something stupid i don't know tp here so okay dp2 here and then in the end i'll just assign dp to the dp2 okay so let's run it yeah cool submit all right works and i mean i don't know why i'm not i don't know why this deep copy thing the word copy doesn't work maybe it's still making a shallow copy anyway so they just make like a new variables and then let's assign it in the end i just assign this back to dp here so basically i'm rotating this like dp this one dp like by introducing a temporary like variable similar like the 1d compression here okay cool i think that's it for this problem i mean uh yeah let me know what you guys think and thank you so much for watching the videos guys stay tuned see you guys soon bye
|
Knight Probability in Chessboard
|
knight-probability-in-chessboard
|
On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction.
Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.
The knight continues moving until it has made exactly `k` moves or has moved off the chessboard.
Return _the probability that the knight remains on the board after it has stopped moving_.
**Example 1:**
**Input:** n = 3, k = 2, row = 0, column = 0
**Output:** 0.06250
**Explanation:** There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.
**Example 2:**
**Input:** n = 1, k = 0, row = 0, column = 0
**Output:** 1.00000
**Constraints:**
* `1 <= n <= 25`
* `0 <= k <= 100`
* `0 <= row, column <= n - 1`
| null |
Dynamic Programming
|
Medium
|
576
|
1,624 |
Hello and Good Morning So today's question is Largest sub string between two equal characters So let's move to the problem statement Given string A returns the length of the longest sub string between two equal characters excluding the two characters If there is no true sub string returns my So basically we have been given a string and what we have to do is to find the largest distance between two equal characters. So before moving ahead in the video, if you are new to this then Please keep subscribing and if you like the video then please give a like and Happy New Year to everyone in advance. So let's move towards the problem. So in the problem, the string given to us is ABC and A. It is ok and we What people have to do is that we have to return the maximum distance between two similar characters, so for that it is necessary to have two similar characters first, so what is there in this, which is the similar character, which is ours. It is a similar character and the distance between it is BC, that is, the answer we have for this will be two. Well, if the answer for this is two, then what will we do for this, so what do we do? The second attack that will be ours will come from the right side only, it will come from here and the first attack will come from the left side. Okay, so what do we do that the brute force will approach us, what do we do that we attack from the left. Let's start iterating from the left and choose the first character. To iterate, start from the left and the second character we choose will start from the right. That second foreloop is fine and after that we will see that as soon as our first character is Character I is equal to sorry Character to the left Character to the right Character to the left If equal is equal to right then what will we do If we calculate the answer there then what will be our answer Answer I will be equal to Two Max of Answer Comma Left Sorry Right Minus Left and -1 Okay because we have to Minus Left and -1 Okay because we have to exclude this one, whatever distance we have, for that we have to do -1 -1 -1 because if we do 0 1 2 3 then 3 - 0 then the length. If because if we do 0 1 2 3 then 3 - 0 then the length. If because if we do 0 1 2 3 then 3 - 0 then the length. If 3 comes, not this three, we will have to do -1 3 comes, not this three, we will have to do -1 3 comes, not this three, we will have to do -1 so that two comes, hence we did -1. so that two comes, hence we did -1. so that two comes, hence we did -1. Here, this is our approach, so what will we do, we will make a four loop, in which what we will do is go from row to n and second four loop. Which will be our second foreloop, which will be ours, what will they do, n will go from MIVE to lake zero and inside that we will calculate, this answer is correct and which is its time, we can do it in Big of N by taking some space, so yes. We can do it because what do we need to calculate the answer, so what do we do, we store it in the map as soon as we do it. If that character comes to us for the first time, then its meaning will be in the map, then if it is in the map, sorry, if it comes for the first time, then it will not be in the map, if not, then what will we do, we will put it in the map, right after that, we will trade and check. Every time, is it in the map? If it is already in the map, what will we do? We will calculate the answer and if it is not in the map, what will we do? We will put it in the map. Okay, so we have to do just that. 0 1 2 And this is our index, so suppose that in the map, we will create a map, what will we do with care and int and inside this what will we do, we will store our characters, so first of all, we will If people iterate then A will come, our A is already present in it, if it is not present then what will we do with A, we will put its index, what is its index, its zero, then when we move ahead, we come to BB, what is the index of B? One first. If this is not present then also put it, then we will trade, so what is the index of CC, if it is two, then we will put this too. Okay, then our A came, so A, we will find it first, so A, how much is our Aa? A, this time ours came on three and this is our already present. Okay, so we will calculate the answer in the same way as we calculated it in the yes people which was our approach. What will we do in this? Same work has to be done in this. Answer is equal to max of answer comma which is our index which has just come, so what is the present index assuming it will be I minus M P of S of I M P of which is our S of I i.e. which is our S of I i.e. which is our S of I i.e. which is already present which is our index. This is the index of P and we will subtract one from it and we will keep on maximizing it every time, then in the last our answer will be, Khud Bakhuda Asar, Khud Bakhuda Plus, what will we do inside it to check? First of all, we will check whether which Is the character that has just arrived for us already present in the map or not? If it is already present in the map, then the character that has come this time will be the second one, so if we have to find the distance between it, then we will find the distance. If we remove then we will first check if first we will check if m p dot find s of i not equal to add and if not go till the end of the map it means that is present then if present then calculate the answer is equal to what will be the max of answer comma Aa O's index minus which is the previous index, then how will we get the previs index A of Aa and from this we will do minus a, okay then our answer will be calculated here and if it is not present then we put the else condition if it is already present. If it is not there, then first put it in that map, then what will happen is MP of A of s of A is equal to two, sorry s of A, we will simply do i and what will we do in the last and then what will we do in the last, we will return the answer. Now let's do this. If we run then our code has been run and if we submit it our code has been successfully submitted. So this was today's code. So if you liked this video then please give it a like. Till then we will see you in the next video. Keep Learning Keep Exploring
|
Largest Substring Between Two Equal Characters
|
clone-binary-tree-with-random-pointer
|
Given a string `s`, return _the length of the longest substring between two equal characters, excluding the two characters._ If there is no such substring return `-1`.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** s = "aa "
**Output:** 0
**Explanation:** The optimal substring here is an empty substring between the two `'a's`.
**Example 2:**
**Input:** s = "abca "
**Output:** 2
**Explanation:** The optimal substring here is "bc ".
**Example 3:**
**Input:** s = "cbzxy "
**Output:** -1
**Explanation:** There are no characters that appear twice in s.
**Constraints:**
* `1 <= s.length <= 300`
* `s` contains only lowercase English letters.
|
Traverse the tree, keep a hashtable with you and create a nodecopy for each node in the tree. Start traversing the original tree again and connect the left, right and random pointers in the cloned tree the same way as the original tree with the help of the hashtable.
|
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
133,138,1634
|
476 |
hey everybody this is larry this is day 27 of the december lego day challenge hit the like button hit the subscriber and drop me a discord let me know what you think about this problem whatever you like and or the video before um i don't know i'm in panama still right now just to give y'all an update maybe obviously um so i'm gonna cut in some drone videos and if you like them i don't know hit the like button or subscribe button or just leave in the comment let me know what you think uh hopefully now that i'm back in panama city and not in a quiet place um i can bring the energy and hopefully that matches the music because the music was really off for the one earlier a couple of days ago but you know you're always trying anyway today's problem is 476 number compliment a yeezy prawn um okay so the return is complement okay what are we doing with leading zero i guess that's the only question this is a very weird question though because i guess not maybe i don't know i was going to say that you can just do a bit wise not but i guess that technically gets rid of the prefixes so i mean there's so many ways to do this you can definitely do it whatever you like right um yeah i don't know i mean the one way that you can think about uh yeah i mean you're gonna also obviously get it bit by bit i'm gonna play around with it the way that i'm gonna write it is uh i don't know let's say n is equal to length of the string of num and you can i'm just running it this way because i'm lazy um you can definitely you know use phase two log or something like that um and you know and just figure it out uh but i'm just doing it this way and then now what i want is let's say two power and minus one right maybe that's good enough uh yeah and then you from this you subtract num and i think that should be good enough um because by default or by definition okay maybe not or maybe i have a typo let's see num oh uh this is obviously wrong i meant the binary version of it um and also getting rid of the prefix so hopefully this is right uh that's what i kind of meant given that i did not implement it correctly uh yeah and how big does this go to do and then 2 to the 31st is probably a big one so let's try that what's 2 to the 31st uh i'm just finding my calculator to plug it in i don't know why my calculator doesn't show it okay two three one uh so you have this number don't know copy still don't have a copy this is so awkward okay there we go uh and then minus one right because it's less than strictly let's see how that goes so that should return one i believe uh yeah and it looks good so i am happy and confident uh if it goes back to one it works for all these numbers that is probably good so let's give it a submit um obviously today i'm doing a little bit funky so we'll see how that goes and it's good yay the sugar 636 which is of course an area coding somewhere anyway um i don't think there's that much to talk about this is a linear time algorithm linear space if you consider the input bits as the number of uh you know the input size i mean the number of the input size is of course number bits so this is going to be yeah um that's pretty much all i have for this one though uh what do you think let me know what you think uh hit the like button hit the subscribe button join me on discord um i hope i didn't waste a good drone video for this because this is such a silly problem anyway that's all i have i'll see you later stay good stay healthy too good mental health i'll see you tomorrow bye
|
Number Complement
|
number-complement
|
The **complement** of an integer is the integer you get when you flip all the `0`'s to `1`'s and all the `1`'s to `0`'s in its binary representation.
* For example, The integer `5` is `"101 "` in binary and its **complement** is `"010 "` which is the integer `2`.
Given an integer `num`, return _its complement_.
**Example 1:**
**Input:** num = 5
**Output:** 2
**Explanation:** The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
**Example 2:**
**Input:** num = 1
**Output:** 0
**Explanation:** The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
**Constraints:**
* `1 <= num < 231`
**Note:** This question is the same as 1009: [https://leetcode.com/problems/complement-of-base-10-integer/](https://leetcode.com/problems/complement-of-base-10-integer/)
| null |
Bit Manipulation
|
Easy
| null |
228 |
hello and welcome to another daily leap code challenge let's begin question 228 summary arranges you're given assorted unique integer array nums arrange a b is set of all integers from A to B inclusive okay one more time arrange a b is the set of all integers from A to B inclusive return the smallest sorted list of ranges that cover all the numbers in the array exactly that is each element of nums is covered by exactly one of the ranges and there is no integer X such as X is in one of the ranges but not in nums I think I understand we're given a uh sorted unique array assorted unique array of integers and we're supposed to essentially summarize that list into what it would be summarize that list as a set of ranges so for example um if it were to given an array 0 1 2 4 5 7 then the set of ranges that could be set are zero two because these zero one two are consecutive four five and finally seven two and four have one between them and five and seven have also one between them so a summary of this nums would be icy I see okay um any other examples um zero two three four so zero is supposed to be alone two three four is together two four six is a loan eight nine together and okay um so these sorts of questions um should probably be approached almost like a state machine uh there's seems like there's a lot of moving Parts but at the end of the day what you're really just doing is um keeping track of a couple of well first of all going through the array once but also as you're going through keeping track of the of some variables that you introduce and let's start by introducing something called a start and something called an end start at an end will as we're iterating through the array represent the first and the second number in the output obviously Also let's have an out be an empty list and now for n in or let's iterate over the indexes of these nums because we will actually have to be looking ahead at some point so for I in uh range Len nums we're going to have a current uh be equal to nums I and the next be equal to uh let's see negative one if so this is the next we're yeah next negative one if um if I is less no one more time nums I uh plus one if I is less than Len nums minus one else negative one so in the case that we're looking at the um in the case that we are looking at these second at the last index in the array give us negative one last index in the array so wouldn't this also be okay if I just do if I is equal to this might be more because um nums I plus one I think I like this more uh because this clearly indicates that we're looking at the last element in the array and if we're looking at the last element the next is going to be negative one else give us the next number um that's it at this point let's start updating uh things that we care about so um what do we care about which two values did we introduce to sort of emulate a state machine uh let's see um if start is none then let's just set start to current right um this would work in the instance where we first encounter an integer uh the first index in the array and potentially other times when we drop start and end to essentially emulate us writing to Output so if start is none then start is equal to current but now what now we need to check the time where we would write a and next uh oh sorry an end we would write if current plus one does not equal to next then and is going to be equal to current and that's it at this point we already found two conditions one uh at which point we will update start the other at which point we would update end finally the third condition is if we have both of these uh both start and end filled out then we would actually want to update our out so if uh start is not none and is not none as well then let's say out append and let's have a formatted string here that would look something like start and of course let's update both a start and end to equal none uh this should be it um let's go through this state machine one more time uh the two states that we care about are start and end um each indicating each being updated as we iterate through our input array nums we start at we start updating start if it's set To None which covers the cases where we first start iterating over the input array as well as times where we've already maybe somewhere down the line but we have actually just wrote a range to our out file uh out output and we have restarted start find and then the next state that we care about is when to write end and end can be written in two cases uh well actually end is always written in one case if the current element that you're looking at plus one does not equal next let's see if this runs um and it does not we right uh what about the case where um start and end are the same value well if start and end are the same value that directly shows us where we would be worrying about that so if start is equal to end uh let's have this out append uh f formatted string or just a string of the start and else of course let's have this and both tests are passing let's see if everything passes and no not everything passes and we have negatives let's see was that part of the constraints is that we do have negatives okay where did I mess where did I oh I said that nums would be equal to negative one so okay let's start treating negative numbers as potential values in the array uh instead of setting next to negative one in the case where we have reached the end let's call next none at that point and then let's see if NXT is none or and let's use this test case right here and run this once again all three tests pass we submit our solution once again and perfect Okay so we've uh We've not beating a lot of people let's see what are some better Solutions um sample of 15 millisecond submission start to end result same approach while start is smaller than length of nums and is less than length of nums interesting and plus one if n plus one okay so they have a while loop instead of the for Loop that we were doing and what are they doing inside of this while loop well first of all the while loop only goes as long as start and end have not exceeded the limits of the array so at some point they're going to be updating start and end if um and plus one is less than nums and okay so this condition is where is checking if current is exactly one greater than next so and what is this if n plus okay so this is checking if um if we're in this situation where um index which currently is just end is not the last element and are conditioned for a continuous sequence of integers checks out then we just append one two and else we write else we um oh so in which case would that not work though we start off with both with end equaling 0 and start equaling zero so in the case for this doesn't check out one of these two either we're looking at the as last element or the next sequence or the next integer is not greater than one then if start is equal to end means that we have one um then we would simply do this and end I think I understand it I don't understand where the increase in speed is coming from because it seems like they're still iterating over the array they're still they're just doing it in a more complex situation let's can I would this be allowed um I want to copy the submission and make sure that it's not significantly faster uh let's restart this okay and just as I thought this same solution that was beating a while uh everyone a while ago seems to lie in the same um sort of run time percentile is what we did and honestly this state machine approach which that one was as well is much more explicit with regards to what start is what end is what current is and what next are so I would probably just use this instead um unless let's see how are we doing on time um okay honestly this is a good enough solution I would stick to being more explicit with the naming variables and more explicit with what the conditions are rather than maybe saving a few seconds milliseconds on the runtime so with that let's end for today thank you for watching please like And subscribe see you soon bye
|
Summary Ranges
|
summary-ranges
|
You are given a **sorted unique** integer array `nums`.
A **range** `[a,b]` is the set of all integers from `a` to `b` (inclusive).
Return _the **smallest sorted** list of ranges that **cover all the numbers in the array exactly**_. That is, each element of `nums` is covered by exactly one of the ranges, and there is no integer `x` such that `x` is in one of the ranges but not in `nums`.
Each range `[a,b]` in the list should be output as:
* `"a->b "` if `a != b`
* `"a "` if `a == b`
**Example 1:**
**Input:** nums = \[0,1,2,4,5,7\]
**Output:** \[ "0->2 ", "4->5 ", "7 "\]
**Explanation:** The ranges are:
\[0,2\] --> "0->2 "
\[4,5\] --> "4->5 "
\[7,7\] --> "7 "
**Example 2:**
**Input:** nums = \[0,2,3,4,6,8,9\]
**Output:** \[ "0 ", "2->4 ", "6 ", "8->9 "\]
**Explanation:** The ranges are:
\[0,0\] --> "0 "
\[2,4\] --> "2->4 "
\[6,6\] --> "6 "
\[8,9\] --> "8->9 "
**Constraints:**
* `0 <= nums.length <= 20`
* `-231 <= nums[i] <= 231 - 1`
* All the values of `nums` are **unique**.
* `nums` is sorted in ascending order.
| null |
Array
|
Easy
|
163,352
|
746 |
If possible, hello everyone welcome to our channel and this onion in this video you will be getting water easy problem no nuker stuffing states and 1746 and the problem is only visit of a positive set saunf 125 request they request your files actually the cost of fire Stick Pan Staircase Detail Sapoch Web Semester's Slide Enemy Unheralded Counterpart David Tools and Channels We Question Inside We Question Restricting The First Day of the Year Second Step and Definition of Sop President 2012 subscribe and subscirbe Okay so and subscribe that by them Too Possible Per Student Ok Sorry Contest With 300 Bones But And You Can Start With His Position Or Can Start This Position And Moving Faster Than Ok That And Return The Minimum Cost To Reach The Top 10 Or Ok What Is The Mean What Is The Cost To Reach The Top Up Before Finally Chehra 10 Rich Will Discuss With The Stars Detox Water Questions Like This Point To Start Length 0.5 Inch 299 OK So He Can See Start Length 0.5 Inch 299 OK So He Can See Start Length 0.5 Inch 299 OK So He Can See The Financial Solution Is Going To Be Accepted Patel Not Considering The Hidden Open Time And Here Subscribe to Channel Related Topics in C Programming Open the YouTube Then How the Concept Dynamic Programming Addresses Required Eco System Develop Basic Problems of Doom You Must Have to Proceed with this problem in the space of Dynamic Programming Let's move on if but with a solution Of this problem and you can build a temple in the middle eastern states basically airtel co 610 what is the 10 and its leaders like subscribe and then enters the top o yo honey to come over the top they can start this position or a constructive and Support this later semester ok so it's NCI I will start my pimples on this day of dynamic programming ok inverter subs ok tawa par sunny standing on but this position and subscribe now to my step to third subscribe The Video is then and I can come From this only position it is possible 30-day test in position it is possible 30-day test in position it is possible 30-day test in reverse pendant that time thank you can we us Apollo tubes stretched and you want to move with this app you can jump to Table Tennis Championship and subscribe to the Page if you liked The Video then that if don't continue for now ok melta the meaning of history can come from dushman aur dushman in general can you write dp validation for the dynamic programming relation relation relation jhaal ayyapan here come from dushman aur dushman that is those problems tips backward of From One State Bank and Shlok Android Relation Like Minimum What is the Minimum Cost to be Spent to Less Time Step of the Video then subscribe to the Plus Jumping from his position will cost - 2 This is the worst thing that you need to Take Care Product And Worst When Invented Acid Violence And Second Oil More Similar To This You Can Learn From It - Similar To This You Can Learn From It - Similar To This You Can Learn From It - Sudarshan That And Stop Spending This Amount Cost Of Events 2382 This For Every I Belongs To How To N9 Tennis Basically The One That To Only from like pizza any one to three id have to free laptop to any one adhicen plus one ok to like basically deputy relation more particular state of the step by step maximum provident fund management and from the ministry very soon basically of person question related to the Telegraph so let's move to do the types of the cost size to handle tips is but ep are individual whiteness dp of ten plus 120 footy stop nh20 made sitting on the work and it's but ep 90 and defeat of one in 30 chakli equal to Zero Gravity Notes20 At This Time A Number Of Prayer For Equal To 2016 Defield Like This 1012 Start From Icon In This Tool Which To End Thunders The Top Most Inheritance Maintain Maximum Minimum Mode To Things Paper Pivot Channel Subscribe - To Plus Subscribe What Is The Name Of The Aa - To Plus Subscribe What Is The Name Of The Aa - To Plus Subscribe What Is The Name Of The Aa Raha Hai Tu Beach Top Load On Ki Cutting Pure Humor And That A Many Fancy Dress Power Terrific In Its Too Let Me Know Comment Section Or The Video And Vilas Ki Vastu Like This Video Share This Video And Subscribe My YouTube Channel For Latest Updates Thank you for watching this video
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
1,099 |
welcome back to tekken navi today i'll be going over to some less than k liquid question number 1099 so let's jump right into it given an array numbers of integers and integer k return the maximum sum such that exists i is less than k with nums plus i or nums plus j equals sum and sum is less than k if no and i j exists satisfying this equation return negative 1. so essentially um if known ij is a satisfying equation for number one so basically what's asking us to essentially it's a variation of two sum to say the least if you've done two sum i've made a video on it please go check it out the link in the description will be right here and what it essentially is that it's asking us given an array of nums it wants us to see what two numbers just like to sum add up to a target value in this case is k but the caveat is that it wants us to find what two numbers add up to the target value but less than the target value so what two values when added up in this nums array essentially gets us the closest that we can to the value k that's given to us but not essentially k so essentially we want to have our answer so we want our answer to be less than not equal to so essentially it wants us to be less than 60 but essentially the biggest value that we have in nums it doesn't want it not less than equal to it doesn't want us to get to k it just wants it to be less than 60 but the biggest possible value in nums so if we see the explanation for example number one we can use 34 and 24 to sum to 58 because 58 out of all the values in this nums array is the biggest value that you can get that's not 60 but it's the closest value you can get to 60. so to approach this problem i'm going to use something called cadence algorithm and a little bit of twosome thinking so essentially we want to do what we did in two sum and add up all the values to see if we can get the value k and that'll be our first approach so just like we did in the two sum we're going to make a size variable we're going to use the length of nums as our input for that size variable and it's going to hold all the elements for nums and how big that size is for nums next we're going to do the same two pointer method that we did in twosome remember in twosum we did two scanners that iterated through each element of the array and each scanner essentially took one element for i and i actually write it out first and then i'll explain it so for i and range of size and for j in range of i plus one starting index positions is two or index position one element position two that's what it's essentially saying size so yeah that's essentially our thinking that we did for twosum and we're gonna use it here again so we're making two scanners for i the i scanner is essentially starting off the first and next position so let's say 34. next is going to use the j scanner and it's going to see 34 plus 23 34 plus 1 30 plus 24 75 et cetera after it's done after j is done iterating through all the other possible variations of nums because we're going to start at i plus 1 it's not going to do 34 again so it's going to do all the possible variations it's going to go into the next element after j is done it's going to go into i and do all the possible variations so on and so on we're going to essentially check so for i and range of size and then for j in range of size we're going to do i plus 1 size so for this problem we're going to essentially use a we're going to make a variable called sum less than k and we're going to set this as zero this is essentially to keep track of our biggest value possible in this nums array as we're traversing through it and we'll update this when we found what we want and then basic logical thinking just like in twosome we made if condition that if we found what we were looking for just return the value we're gonna do the same thing here as we're iterating through the array we're gonna say if we find at num value i plus num value j is greater than sum less than k so this will update as we go through the array and known value i plus num value j is less than oh am i called k all we want to do then is return or no all we want to do now is update sum last k to equal num value i and num value j's value and then all we want to do here is return some less than k so i think we're getting into error right here um oops it's not in the air i'm looking for right now numbers are divine did you mean numbs oops yep i said numbs instead of noms let me just go ahead and clean that up so i'm excited to get into error here and i want to get into error to explain it yep so our input is wrong right here our outputs will be 57 not 58. so what is essentially happening here is that we have the return statement in the wrong position it's returning it immediately if it finds the first iteration that is bigger than some less than k so essentially just found 34 plus 23 and yeah that is bigger than zero and just return it so all we want to do right here is essentially put in the return statement towards the end of the for loop and once everything is done just iterate it up when everything is done it's going to return that and we're going to get another error here but i'm going to go ahead and submit it so we can see together what the error is so 10 20 30 our output is um 15 and we're not giving the correct output we're getting negative one or we want negative one and our output is zero so if we go back to the project description we can see that or the question description if it's saying if no i and j exists satisfying this equation return negative 1. we're not doing that here so we want to make an edge case essentially that says if some less than k equals zero all we want to do then is return negative one and that'll essentially take in the condition of i and j not satisfying the k value if we have a nums array that essentially doesn't get all the values or doesn't have a value that's essentially less than the value of k then num's array is just going to return negative 1 because it's not going to be changed at all we go ahead and submit that yep there we go and this is essentially a brute force approach we can clean up a little bit to make it a little bit faster and these questions are really nice because they show you how to think about the problem without optimizing worrying about time complexity and all that's so this would be oh squared time complexity but it's also not the most optimized solution so i wouldn't worry too much about that and lee code has a notorious for giving you the most random runtime solutions but anyways i hope this video was helpful that was essentially twosome less than k i plan to make more videos in the future please like subscribe it would really help my channel up and i hope to see you in the next video guys peace
|
Two Sum Less Than K
|
path-with-maximum-minimum-value
|
Given an array `nums` of integers and integer `k`, return the maximum `sum` such that there exists `i < j` with `nums[i] + nums[j] = sum` and `sum < k`. If no `i`, `j` exist satisfying this equation, return `-1`.
**Example 1:**
**Input:** nums = \[34,23,1,24,75,33,54,8\], k = 60
**Output:** 58
**Explanation:** We can use 34 and 24 to sum 58 which is less than 60.
**Example 2:**
**Input:** nums = \[10,20,30\], k = 15
**Output:** -1
**Explanation:** In this case it is not possible to get a pair sum less that 15.
**Constraints:**
* `1 <= nums.length <= 100`
* `1 <= nums[i] <= 1000`
* `1 <= k <= 2000`
|
What if we sort each cell of the matrix by the value? Don't include small values in your path if you can only include large values. Let's keep adding a possible cell to use in the path incrementally with decreasing values. If the start and end cells are connected then we don't need to add more cells. Use union-find data structure to check connectivity and return as answer the value of the given cell that makes start and end cells connected.
|
Array,Depth-First Search,Breadth-First Search,Union Find,Heap (Priority Queue),Matrix
|
Medium
|
1753
|
746 |
hey everybody this is lry this is uh day oh Friday to 133 wow hope everyone's having a good Friday to 13 H actually I like this uh wallpaper background it makes me looks like uh like I intentionally care for uh setting this up or something you know uh looks also like very instagrammable I don't know let me know if it matches my skin tone or whatever I don't know you even know what that means but it looks very like I don't know now I feel like I'm uh no I'm doing this professionally or something oh snap uh yeah Sor I just looking at my camera I didn't even look at the farm yet uh as I don't know if I mentioned it yesterday I think I did at the end but you might not have you know caught it just because I was just so out but I'm in taipe right now uh it is 8ish a.m. I need to do some uh errands uh but a.m. I need to do some uh errands uh but a.m. I need to do some uh errands uh but you know follow me on Instagram if you're kind of curious what I'm up to uh I promise I will post way too much and you know you almost feel like you're there with me huh if you want to be anyway I don't know I mean I do pretty boring things but I'm saying you can do boring things with me anyway um today's a Yeezy bom so hopefully uh you know you enjoy that or the amusement for now uh but today's problem is 7:46 Min now uh but today's problem is 7:46 Min now uh but today's problem is 7:46 Min cost climbing stairs okay so you're given an away cost and cost of I where the cost of I step on a staircase once you pay the cost you can climb one or two steps okay like Fibonacci a cost and minimize it I suppose right yeah minimize it so okay I mean there a couple ways you can do it really Bottoms Up tops down space optimization you know all the usual thing is this the start of uh dynamic programming week I guess we will find out but for now I mean I think um yeah I mean I think this is one of those things that you know hopefully you're not struggling with and if you're struggling with there's no shame because if you trugging it just means that you haven't learned this yet because this is B probably one of the most basic things uh defin we read about on fracci and all those things but yeah I otherwise uh you can do this a number of ways uh and yeah the idea and I'm going to see if I could do this off uh I probably already have like three or four videos on this already uh maybe uh at least two maybe so uh so I'm going to try to um not kind of do the same thing cuz I proba just did the top down with the memorization thing right uh no I did not so Okay I lied so okay so the last video I was just wred this way the last video uh so and then this is the way that I did it the first time uh I guess I did it both ways but uh but this is pretty basic so I don't know oh man I was going to do the space optimization this time and be like ah look uh but okay fine uh but yeah I mean to be frank there's really not much complicated about the idea is that like you have some f of X that's equal to some function of uh you know uh some function of F ofx - one uh f ofx - 2 right and of F ofx - one uh f ofx - 2 right and of F ofx - one uh f ofx - 2 right and that's really all that is right that's the recurrence and the g function is actually the Min function so uh yeah uh and technically this is uh you know plus some constant right but that's basically the idea that's kind of what the function is um so yeah and once you have a recurrence the way to I do it is just kind of um do recursively right by writing it out directly right so now we have some x uh and in this case I just say it's index just so it's slightly easier to read uh and we can go from uh this is also one of those problems that I actually mention a lot right uh or I try to I don't know if I do anymore but uh but definitely in the past where this is symmetric right meaning you can go from the beginning to the end or the end to the beginning and has the same thing because uh addition is um commutative right yeah so you know so what I want to emphasize that is that it's easy to get it right but uh or it's easy to get the right answer but you may not be consistent in the direction um which does not penalize in this one because it's symmetric but it may you know impede you on future problems definitely be aware of it uh and in this particular problem it doesn't matter so it's fine I'm going to just go left to right or from bottom to top so technically this form is wrong uh but you know right let's do it this way right if index is 0 um then we return cost of zero and that's it right and we have to go there anyway that's the base case otherwise we return Min of uh F of index minus one uh f of index minus 2 plus cost of Index right and that's really pretty much it we return F of n minus one where n is equal to length of cost that's pretty much it I know we have to do memorization but um oh yeah okay fine uh I guess I'm a little bit sloppy on this one I guess the Queener way to do it is that this is case we turn uh zero uh fine uh all right so apparently it's very easy to get well um oh because you cannot jump over okay fine uh all right definitely Rush this a little bit and a little bit sloppy uh but yeah 15 did I misunderstand this uh oh I actually I mean I didn't misunder understand I just literally missed uh this case h all right well uh so that means you know uh that's pretty much it but uh H but that also means that we don't have to H I think I messed this up so even despite me saying how easy it is I kind of misunderstood uh or misunderstand some base case so the base case is going to be you know um you can go uh afterwards so yeah okay fine uh they probably you can do something better about this but fine um yeah okay right uh yeah and of course next step is memorization uh this Branch us out has a branch factor of two which means that this is you know exponential and of course if you know your Fibonacci series this is actually x to the like 1.6 or this is actually x to the like 1.6 or this is actually x to the like 1.6 or whatever it is right 1.66 uh you know Fibonacci stuff I'm not 1.66 uh you know Fibonacci stuff I'm not 1.66 uh you know Fibonacci stuff I'm not going to get into it that quick uh that uh soon and also maybe I'm wrong it's been a while so and if I am wrong then but it's still it is exponential and that means that uh for n is well a thousand it is it doesn't really need the exponent to be big to make a huge impact so you want to memor memorize this and there a couple ways you can do it I know people always tell me to just use cache if you don't know what that means then don't worry about it but I like to write it out uh it's a little bit easier to understand maybe not I don't know but it is easier to analyze the space and time because now the index can only go from 0 to n and so and we do two operations per input not two operations per s obviously there's more but just like two uh lookup course lookup operations so yeah so this is going to be all of n once we cash it so let's do it but yeah kind of I would also point out that um the Symmetry stuff you know it probably is easier to write it the other way but you have to be really careful about how you do the dynamic program because you can see that the base case is that you know this is I have to change this and I have to add this to kind of accommodate for I mean the structure is still mostly the same but you just have to be careful it is very easy to get wrong right and that's pretty much the idea uh so yeah let's go some of it hopefully I didn't really mess up after saying how you talking about how easy it is I messed up a couple times and then it's going to be even more mess up that'll be a little bit silly um but yeah that's all I have for this one that's all I have for today let me know what you think stay good stay healthy to your mental health I'll see yall later and take care byebye
|
Min Cost Climbing Stairs
|
prefix-and-suffix-search
|
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps.
You can either start from the step with index `0`, or the step with index `1`.
Return _the minimum cost to reach the top of the floor_.
**Example 1:**
**Input:** cost = \[10,15,20\]
**Output:** 15
**Explanation:** You will start at index 1.
- Pay 15 and climb two steps to reach the top.
The total cost is 15.
**Example 2:**
**Input:** cost = \[1,100,1,1,1,100,1,1,100,1\]
**Output:** 6
**Explanation:** You will start at index 0.
- Pay 1 and climb two steps to reach index 2.
- Pay 1 and climb two steps to reach index 4.
- Pay 1 and climb two steps to reach index 6.
- Pay 1 and climb one step to reach index 7.
- Pay 1 and climb two steps to reach index 9.
- Pay 1 and climb one step to reach the top.
The total cost is 6.
**Constraints:**
* `2 <= cost.length <= 1000`
* `0 <= cost[i] <= 999`
|
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
|
String,Design,Trie
|
Hard
|
211
|
1,027 |
hello everyone welcome back here is van damson and today we are going to tackle a very interesting problem longest arithmetic subsequence uh this time in C sharp so it's medium difficulty problem so it might be tricky to understand it and so with efficiently but we will explain everything so we will try to use dynamic programming and also uh knowledge about the constraints that in this particular example are very important so first understand the problem we are given an array of integers and we need to find the length of the longest arithmetic subsequence in the array so remember sequence is in arithmetic is difference between every two executive number remains constant and subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order so we are given some test cases so for example if the array is 947210 the longest arithmetic subsequence is 4 7 10. so difference between every element for 7 10 is 3 and we need to Output the three so the length of this sequence so let's Implement and I will explain how we utilize it so n will be num of length and if n is less than 2 so return and so and longest will be initialized as two and int DP of new int n and for INT I less than n increment and DPI will be new int thousand two and RI fill DP I with one and for j 0 J less than I increment int difference will be num 1 minus num J and plus 512 not go out of bond exception so DPI difference DP J difference plus one and longest will be math Max of longest element and DP of I at difference so return longest uh with track so let's run our code and see if it's working so uh it's working hopefully yeah it's working so as you can see uh case we mentioned before uh is passed so we can run it for unseen test cases and see how efficient is our solution and I will explain right away what we did so we beat 100 of other uh Solutions and with respect to memory 83 so as you can see it's quite efficient one so we use two dynamic programming approach the idea here is to create an array uh where each diction array keep track of maximum length of arithmetic subsequence that ends with a particular difference and we start by iterating over the array from the beginning and for each pair of numbers we calculate their uh difference moving forward and then we update the maximum length of the arithmetic sequence that can end with this particular difference so we continue this process for all pairs of numbers always updating the max length in corresponding DP RI and in the end we return the max length found during this process and the beauty of this solution like in the concept of cleverly reusing previously uh found knowledge and storing and updating finding as we progress through the array rather than using some exhaustive search and yeah so remember the key of mastering this kind of problem is practice and the more problem you solve the better you become in recognizing a pattern in problem and reusing in new one previously unseen and yep if you like this video please like it and don't forget to hit uh the Subscribe button for more coding tutorial challenges and tips and as usual keep practicing stay motivated happy coding and see you next time
|
Longest Arithmetic Subsequence
|
sum-of-even-numbers-after-queries
|
Given an array `nums` of integers, return _the length of the longest arithmetic subsequence in_ `nums`.
**Note** that:
* A **subsequence** is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
* A sequence `seq` is arithmetic if `seq[i + 1] - seq[i]` are all the same value (for `0 <= i < seq.length - 1`).
**Example 1:**
**Input:** nums = \[3,6,9,12\]
**Output:** 4
**Explanation: ** The whole array is an arithmetic sequence with steps of length = 3.
**Example 2:**
**Input:** nums = \[9,4,7,2,10\]
**Output:** 3
**Explanation: ** The longest arithmetic subsequence is \[4,7,10\].
**Example 3:**
**Input:** nums = \[20,1,15,3,10,5,8\]
**Output:** 4
**Explanation: ** The longest arithmetic subsequence is \[20,15,10,5\].
**Constraints:**
* `2 <= nums.length <= 1000`
* `0 <= nums[i] <= 500`
| null |
Array,Simulation
|
Medium
| null |
1,191 |
Hi Everyone Welcome Back To Coding With Bharat Channel So We Are Back In To The Series On Kaden Algorithm And Will Be Dying Our Third Problem Today Why Is This One's Problem Maximum Some So Without Wasting Any Further Time Let's Get Into The Problem So It Says that we are given an array of some size n and we are also given an integer array k so two things and array and integer array k first thing it says what we are going to do we are going to repeat this value k times this array k times and continue them one after the other for example if the array is t and k is 3 the actual array will become 12 2 1 2 so three times appended now in this new modified array we need to find the maximum sum sub Are so or that is what the problem talks about so given n are repeated k times and then find maximum sum sub are so if you have been following our Kaden Algorithm series so far you would be knowing that the main purpose of this algorithm is to find maximum sums an array so without wasting and going into all the random brute forces the first and foremost brute force that can come to mind is let's just do what the question says we will make copies of this array k times so if our array let's say two I will go over it and append the same array k times so let's set OK we will again append and l again append and then let's do this in a given algorithm and find the maximum sum so simple repeated k times And find the maximum sum all but if you go over the question and go into the text it says that your K can go up to 10 to the power 5 so if the array it itself is 10 to the power 5 and K is also 10 to The power 5 then the combined array would actually become of the size 10 to the power 5 * 10 to the power 5 * 10 to the power 5 * 10 to the power 5 10 to the power 10 so we will not be able to get this much elements in memory first of all and then obviously we will also Fail So We Have To Do It Without Pending And Creating Are Modified Array Ok Let's Go Into How We Can Go About Doing It Right So Let's First Start With Base Cases So If I Say My k Is One If My k It Self Is One That Means the array is just repeated once and you can directly use cadence algorithm to make your thing work okay now let's think about one more case where my k is just two so let's take an example so let's take our array s to write it yourself and And let me take another one let's take two 5 to -5 2 and let me take another one let's take two 5 to -5 2 and let me take another one let's take two 5 to -5 2 and 3 okay so if I use a normal Kaden algorithm on it right what will I get the maximum sum only that I can get is this right if you look into it we Try to take the previous five it becomes zero and then if you try to take two or one then it will still remain less than five so simple one coded algorithm will simply give us five but if I make two copies of it you will see that I Will Be Getting All This Having Some Vt 5 P 2 7 Pv 8 Ch I Obviously A Better Some So Another Possibility S Soon S K Become More Than One Is To Take Some Prefix And Take Some Suffix Of The Are Because Suffix Of The Will Now Be Related to the prefix of the are and we can actually take that conjunction here so this is in fact our suffix and this is in fact your prefix OK let's think about one more thing if we go ahead and make this as 3 right then You see one more interesting thing arrived into the picture can in fact take the antays right so here we will have one more copy of the array and if you see the antays sums up to three so we can take that entire array combined with our prefix and Suffix And Then We Can Go About Doing It So Entays Is Also Three So We Can Take This Five Plus This Three Ps This Three Which Becomes 11 Right Similarly You Can Extend If k Becomes 4k Becomes F You Can Keep On Taking The Entays Then A suffix and a prefix right so that is how we can come up with the best way to go about finding the solution one corner case here if the sum of the array was negative in fact so let's take a let's say if these two are also negative and Let's Not Take One As Negative Probably Just Take A Might Right So Now If I Take The Sum Of The Antayas And So What Do You Think Is It A Good Idea To Take The Antayas Array Answer Is No It is not so in case that sum of the total array is negative so we would omit the exceptions we would just go for maximum of the two cases i.e. we run a gains algorithm on the two cases i.e. we run a gains algorithm on the two cases i.e. we run a gains algorithm on a single array and we can take sum suffix and sum prefix and Combine it right so or that is how we can proceed with our solution so just to surprise first we can probably calculate sum of the ant is negative and if it is positive if it is negative then even if k is more than two then that would not be a point of Taking the Enthusiasm Right Then What We Can Simply Do We Can Combine Two Arrays and Probably Run Cadence That Is One Option If We Actually Think About It We Can Run Cadence on a Single Part and Find and Prefix and Suffix Maximum Prefix and Maximum Suffix and Sum that up if k is if sum is positive that means taking all the arrays makes much more sense so we will take all the middle arrays and with that we will append sum suffix and sum prefix and use that ok that is the whole idea of this use that ok that is the whole idea of this use that ok that is the whole idea of this solution So or let's get into the coding part of It let's go to my submission and open this okay so first thing I've done I've taken some equal to 0 I'm going over my array calculating the sum and I've made two cases if some is Greater Than Equal To 0 Then I'm Passing It To A Function To Handle Positive Sum Case Other Wise I'm Passing It To A Function To Handle Negative Sum Case So I Made Two Functions One To Handle Positive Sum One To Handle Negative Sum So Let's First Get in to the negative one because it's much more easier OK handle negative sum so when it's negative sum What do we want to do We want to look at the maximum prefix and maximum suffix so I've called the function get maxus right so this actually gives Me the maximum sum we can get from a suffix and maximum sum we can get from a prefix so that I have stored here in this pair first one gives maximum prefix second one gives maximum suffix Now one option of the solution could be just the cadence running On one single are like if a if I'm not taking any other instance of it and just finding something in the middle that is one possible way so that I'm doing by this if k is one then this is the only way if there is A single array then this is the only way otherwise you can take the middle one and in the combination you can take a suffix from the first and the prefix from a second so that is what I have done maximum dot first will give You the maximum prefix for the second is maximum second will give you the suffix for the first ray and combining it gives you the best answer so respect you can take from middle and you can take from this sum so that is how we have gone ahead with Okay I'll talk about this get max and cadden also quickly what these functions are and then we will jump on to the positive case okay so get max the duty is find the best sum prefix and be best sum suffix so what I've done I have my sum so initially I'm starting at the initial position where suffix is the entire are initial position where suffix is the entire are initial position where suffix is the entire are prefix is zero so that's what I've done so right now the current prefix sum prefix is zero so that's what I've done so right now the current prefix sum prefix is zero so that's what I've done so right now the current prefix sum is zero current suffix sum is the entire so we're here every Time I go forward I will add this element to prefix and remove it from my suffix so that you can see here as well I am going over the elements adding my current element into current prefix sum and removing it from the current suffix sum this part then I'm calculating the maximum prefix sum and maximum suffix sum so that's also I've done maximum prefix sum as zero maximum suffix sum is the entire sum and I'm updating that with the current prefix sum so find the maximum prefix sum find the maximum suffix Sum and that I'm returning here okay so or take the entire thing and zero here then move on adding removing and find the maximum one okay so that's how I've got the suffix and prefix max let's also look at cat cadence so it Does nothing it does the same thing as always it initially is at zero if array zero is negative we replace it with zero we update our answer then go from one add the previous if it is negative again update and update your answer so or just keep on Taking prefix sum if something becomes negative replace it with zero and on taking the maximum so far OK so we have our cadence we have our get max done let's look at the positive sum case na OK positive sum so in case our array is giving a Positive sum that means what if we can make copies of it then it's a good idea to take all the copies and sum them up and then take as a prefix from here and a suffix from here so first thing that I've done again got the Prefix Suffix Sums Calling Our Maximum Prefix Suffix Sum Calling Our Get Maxus Function I Also Run Cadence And Got My Maximum Sum From The Middle First Case If K Is One If We Can Only Make One Copy Then We Have To Run Cadence And Get That Back So Return directly each other wise what you would do is k - 2 times why k - 2 is k - 2 times why k - 2 is k - 2 times why k - 2 because the first and the last you are taking prefix and suffix so rest of them in the middle you add that into some so k - 2 into some the middle you add that into some so k - 2 into some the middle you add that into some so k - 2 into some taking With Mode So Take Them Entire Because They Have Positive Sum Then In The Answer You Add Up The Prefix And The Suffix And You Get Your Answer And Return It So That's What Is Exactly Happening Here's Cool A Sum Of You Might Argue Why Are We Not Taking Cadence A Maximum Sum From The Middle Because Actually If You Think About It If You Take Something From The Middle You Can't Take The Other Copies Of It That Are Coming Right For Example If K Was Five When You're Taking When You're Removing The First and the last so you are still left with three copies so in these two three copies you are taking the answer so they would be including this sub array as well so definitely the answer would be much more than that okay or but if you want to be Safe You Can Take Maximum With Your Cadden Result As Well That Will Never Be Answer Great Than I Think That Finished Up The Problem Right So Or I Think Done With The Problem So Let's See You Go In The Next One We Will Take Up A New Algorithm If You Like This Video Make Share That You Hit The Like Button And Subscribe To The Channel If You Are New Here See You Guys In The Next Week We Will Take Up One More Algorithm To Do Our Problems On
|
K-Concatenation Maximum Sum
|
synonymous-sentences
|
Given an integer array `arr` and an integer `k`, modify the array by repeating it `k` times.
For example, if `arr = [1, 2]` and `k = 3` then the modified array will be `[1, 2, 1, 2, 1, 2]`.
Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0` and its sum in that case is `0`.
As the answer can be very large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[1,2\], k = 3
**Output:** 9
**Example 2:**
**Input:** arr = \[1,-2,1\], k = 5
**Output:** 2
**Example 3:**
**Input:** arr = \[-1,-2\], k = 7
**Output:** 0
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= k <= 105`
* `-104 <= arr[i] <= 104`
|
Find all synonymous groups of words. Use union-find data structure. By backtracking, generate all possible statements.
|
Array,Hash Table,String,Backtracking,Union Find
|
Medium
| null |
1,386 |
hello yours welcome back to my channel I hope you're enjoying all the videos that I am uploading I'm back with another problem from read code today cinema seat allocation a cinema has n rows of seats numbered from 1 to N and there are 10 seats in each row labeled from 1 to 10 as shown in the figure so there are n rows and in each row there are 10 seats given the array reserved seats containing the number of seats already reserved for example reserved of I is equal to 3 comma 8 means the seat located in the row 3 and labeled 8 is already reserved written the maximum number of 4% families you can allocate number of 4% families you can allocate number of 4% families you can allocate in cinemas it's a 4% family occupies 4 in cinemas it's a 4% family occupies 4 in cinemas it's a 4% family occupies 4 seats in one row that are next to each other seats across an aisle such as 3 4 that means we are referring to the third row and the seats numbers are 3 and 4 are not considered to be next to each other however it is permissible for 4% family to be separated by an aisle 4% family to be separated by an aisle 4% family to be separated by an aisle but in that case exactly two people have to sit on each side of the aisle so out of the four people two will be sitting in 2 3 that's 8 numbers 2 3 and the other two people are sitting in 4 & 5 other two people are sitting in 4 & 5 other two people are sitting in 4 & 5 that's one possible case the other possible cases two people could sit at 6 7 and 2 people could sit at 8 & 9 so 7 and 2 people could sit at 8 & 9 so 7 and 2 people could sit at 8 & 9 so that is a condition so it's not like a one people one person sitting on to the left side of the aisle three percent sitting on side it's a tie so that is not allowed so that's what it is so exactly two people on each side of the aisle so now we have to return how many number of 4% families can occupy the number of 4% families can occupy the number of 4% families can occupy the remaining seats we're in the reserved seats right so let's go look at the example right so if there are three rows that was shown the example one right and the rivers results it's our 1 2 1 3 1 8 2 6 3 1 & 3 10 so in the first row 2 1 8 2 6 3 1 & 3 10 so in the first row 2 1 8 2 6 3 1 & 3 10 so in the first row 2 3 8 the marked with X right blue x-axis 3 8 the marked with X right blue x-axis 3 8 the marked with X right blue x-axis so they are all reserved and in second row the seat number 6 is reserved in the third row one antenna reserved so from this configuration how many 4 people families can sit so in the first row the 4 5 6 7 we can make one family and in the second row 2 3 4 5 we can make it one family the 6 7 8 9 we cannot and 7 8 9 10 also we cannot even though there are 4 empty seats the condition is exactly two people have to sit on et cetera so we cannot make use of these 7 8 9 and 10 in the second row right so this is for one family can sit in the second row second family can sit and third row so two people here to Google here that is one thing and two people here to over here one more family so finally we will be able to read four families right that's the number of families that we are going to write on right so basically let's go look at little logic that we have to prepare right so as we are saying the answer is we need to get the number of 4 people family right we need to arrange for person family in the rows that's the requirement we are given with the already reserves it so we can split across that but exactly two people on each side so that is another condition so with that right we can say if there are n rows right the maximum that we can make is 2 people 2 into n times families can be arranged right so assuming there are no results see it's right so we can say there are 2 into n so if there are n rows the maximum you can allocate is - into n 4% family friends so that is - into n 4% family friends so that is - into n 4% family friends so that is what we are saying so if there are M rows there are 2 into n that is a total count that can be arranged but there are result seats so this is the total count so keep them keep that in mind so now we have to keep decrementing discount if we are not able to make one of the line one of the rows we cannot make 4 percent to 4 percent family to sit so we have to keep decreasing the count so depending on the constraints that are given right for example by looking at this for a given seat if Rho 2 3 or 4 or 5 reserved then we cannot allocate a family way spreading it right if any of the seats 2 3 4 5 then we cannot make one family to sleep it right so we go decrement the count and in the similarly if you have six or seven or eight or nine reserved then also we cannot allocate the family but the final case for example if Rho is 2 is reserved and 8 is reserved but still we can sit one family that is 4 5 6 7 right the final cases if 4 5 6 7 if any of them are reserved then also we cannot allocate family right so we need we have to be together we have to look at 3 different cases to come up with the final number so that is the final thing that we are going to written so for this right so what we are exactly going to do is we keep track of how many seats are reserved in each row right so because that is the input for us n is just the number right so for that so we are keeping track of the number of seats reserved in each row with the map this dictionary and we are initializing number of for families to n into 2 so because that is what the maximum right so now we have to workout and decrement the number of four families that we will be able to set right so go through the results eats right and fill out this map saying in each row how many seats are already reserved right so that is what is being done by this four so you go through the each results it right and then go through the map whatever we got the map right so this is the map so see how many we are decrementing right so for each row how many we are decrementing if the map for a given row right map has key values so it has a key and value key is a obviously a row number and value is how what are the seats that are each book or razor already right if the row has either to book or three book or four book or five book that means we won't be able to allocate onto the left side one two three when two three four five that row and in that place we cannot use for the one family so what we are going to do is decremented we are incrementing it and for families the final initial count that we initialized to double the number of rows we are decrementing so that's one case this is the first case and the second case is if six seven eight nine right even in that case they're in decrementing and if at all if the value doesn't contain 4 and it doesn't contain 5 and doesn't contain 6 and it doesn't contain 7 in that case and if decremented is also equal to 2 for a chance so that means for example 2 is booked and 8 is booked in that case we still be able to allocate one family right so we decremented 2 but in this case 4 is not for is a 0.5 is open 6 is open is not for is a 0.5 is open 6 is open is not for is a 0.5 is open 6 is open and 7 is open so that means either 2 3 or 6 7 sorry 2 3 or 8 9 are taken right so in that case what we are going to do is if decremented is 2 then we are saying increment the four family so this is what will be done only for the rows which are having results it so all other non result seats if a row has all non reserved seats right then we are saying okay we can allocate two people - saying okay we can allocate two people - saying okay we can allocate two people - purrs - families so that is what this purrs - families so that is what this purrs - families so that is what this initialization is so finally whatever we're finally after going through the map how many ever number of families are left we are going to return that okay so let's go look at the time complexity for this algorithm so this for loop is getting executed based on the number of results seeds right so number of result seats in each row so number of rows having results it's let's say there are M rows which are having a result seed wizard rows basically right so M rows so this goes through the this goes through M Resort seeds right and in here this for loop is going through M actually the rows here M actually the reserved seeds right so these are seeds result seeds and these are result rows so this obviously in a best case you could say all the result rows are results are in a single room right but in the worst case you could say okay you are reserving one seat per row that means this could be also worst cases order of M so this is the order of M and this is also order so finally what we can say is this algorithms complexity is order of M right so where m is the number of result seats in a given problem right so hope you understood the solution if you like the solution please subscribe to my channel and click on the bell icon so that you get all my future video updates if you are looking for more control or interview guidance please leave your e-mail in the comment please leave your e-mail in the comment please leave your e-mail in the comment section I will reach out to you thanks for watching I'll be back with another video very soon till then bye
|
Cinema Seat Allocation
|
shift-2d-grid
|
A cinema has `n` rows of seats, numbered from 1 to `n` and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
Given the array `reservedSeats` containing the numbers of seats already reserved, for example, `reservedSeats[i] = [3,8]` means the seat located in row **3** and labelled with **8** is already reserved.
_Return the maximum number of four-person groups you can assign on the cinema seats._ A four-person group occupies four adjacent seats **in one single row**. Seats across an aisle (such as \[3,3\] and \[3,4\]) are not considered to be adjacent, but there is an exceptional case on which an aisle split a four-person group, in that case, the aisle split a four-person group in the middle, which means to have two people on each side.
**Example 1:**
**Input:** n = 3, reservedSeats = \[\[1,2\],\[1,3\],\[1,8\],\[2,6\],\[3,1\],\[3,10\]\]
**Output:** 4
**Explanation:** The figure above shows the optimal allocation for four groups, where seats mark with blue are already reserved and contiguous seats mark with orange are for one group.
**Example 2:**
**Input:** n = 2, reservedSeats = \[\[2,1\],\[1,8\],\[2,6\]\]
**Output:** 2
**Example 3:**
**Input:** n = 4, reservedSeats = \[\[4,3\],\[1,4\],\[4,6\],\[1,7\]\]
**Output:** 4
**Constraints:**
* `1 <= n <= 10^9`
* `1 <= reservedSeats.length <= min(10*n, 10^4)`
* `reservedSeats[i].length == 2`
* `1 <= reservedSeats[i][0] <= n`
* `1 <= reservedSeats[i][1] <= 10`
* All `reservedSeats[i]` are distinct.
|
Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid. Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.
|
Array,Matrix,Simulation
|
Easy
| null |
109 |
all right let's talk about conversation binary search trees so you are given a single linked list and the elements are sorted for sure so you are going to convert this linked list to a tree so you are going to find where is the middle value which is your group right so your root has to be a middle value for the language so the standard way to traverse the linked list is using a fast and slow pointer and snow just has to uh jump uh one distance every single time but fast has to jump two uh two units for every single class so i have a previous is actually stored uh the left subtree which is okay i want to stop at one point which is for negative three right i want to stop at negative three so negative three dot max is actually equal to no on the left substrate so i'm not going to try versus 0 on the left subtree so that would be the idea and on the right i can just start from the middle plus one which is slow down next and that substrate is just half so i'm not going to change the pointer for the head and you just return the groups so the middle value is still the value and the root of left is actually the beginning i mean you recursive score in the beginning and root out right is actually recursive score on your metabolic plus one which is slow down next and the basis is when head able to know you just return no and then hit up next which is 9 hit that next is no you just return the value for itself and there will be a simple enough and let's run it okay it's fast so let's talk about uh the timing space capacity so polar space is definitely going to be all the fun right you are going to create unknowns for uh the center amount of linkers right so space is easy about the time so you jump every two times at for every uh single like this which is still all of n right because all of um divided by two is equal to all of that but when you request this code uh on the left and right this won't be 11 right because it's going to be the depth of the tree so it's log n times and so unlock and follow the time capacity and space capacity is all of n and this is standard and it somehow is hard for people to do it because they will actually convert to the list in i mean in the rate or something else and when they find the middle value they would just do the index stuff in the rating and that would be good but it turned out the bank the binary search tree you are not allowed to convert to in the array um obviously you are going to waste a lot of time or space to do it and that would be pretty straightforward and good
|
Convert Sorted List to Binary Search Tree
|
convert-sorted-list-to-binary-search-tree
|
Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** head = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST.
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in `head` is in the range `[0, 2 * 104]`.
* `-105 <= Node.val <= 105`
| null |
Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Medium
|
108,2306
|
1,584 |
hey what's up guys this is chung here so today uh before going to bed i would like to talk about uh this week's uh weekly contest 1584 minimum cost to connect all points it's a medium problem i think it's a good problem anyway so you're given like an array point representing integer coordinates of some points on the 2d plane so we have a basically an array a list of a list each element represents a point on this uh on this 2d plane and the cost of connecting two points these two points is the manhattan distance which is the absolute difference between the x and the y's okay and it asks you to re to return the minimum cost to make all points connected all points are connected if there is exactly one simple path between any two points okay and for example the first one the points so we have like five points and the minimum cost to connect all the points is this one it which is 20 okay so i mean the thinking i process for this problem you know the uh you know every time when you guys see like uh try to connect uh like connect the points right to uh this is a graph right basically you know this is like the uh well you can well this one is like minimum this spinning tree right basically uh each one uh between any two point there is only one edge to connect uh to connect them and there's also like an algorithm called cro cross cal if i'm not mistaken basically it's the same idea i actually as a union find basically you know as you guys can see basically we're trying to follow the follow what the problem is asking us to do right we're trying to connect several points together which is it's a perfect fit for the union find data structure okay basically we will have like we'll try to union find some address sorry some points in a certain order so that we can get like the uh the minimum cost but now the question comes down to how can we get the minimum cost okay so for that one basically what we need to do is we just need to uh pre-calculate we just need to uh pre-calculate we just need to uh pre-calculate all the distances between each of the notes and then we'll be basically it's kind of like a great uh greedy idea here we'll be sorting those like those edges right so the edges has like starting uh starting point an ending point right i have two points and then it also has a distance basically we're gonna we will be uh trying to union find those two points whose is the least so that we can it's guaranteed that we can get the minimum cost okay and so here is here's comes the beauty of the union find right basically you know as long as every time we try to union two points uh from an edge tuple here i mean we can simply use the union find to check if those two points have already been a union b or before or not it when we only add the cost when those two points have not been had not been union before okay that's the beauty of the union find like data structure okay cool i think that's pretty much the idea behind this problem and let me try to implement the solution real quick here so like i said uh to do the unifying right we need to do like i define the data structure here okay so and i'm going to just use the simply simplified version of the unified basically for union fines remember we always need to like have like the parents at the beginning right each of the elements pointing to it to itself okay because we have n points and basically we're using the index for each point to represent the index of the point to represent the node itself that's why we do a range n here and then we have a find right find and with the fine we basically use the uh that the past compression okay uh if the parent's x right that's not equal to the x then we do this equals defined parent x okay and then in the end we simply return the parents you know for those whose not who is not familiar still not familiar with the union find uh template i suggest you guys uh try to look for uh try to uh understand the basic unifying templates first from maybe from anywhere maybe for example the wikipedia i'm pretty sure you can find a lot of articles regarding how to implement the union find data structure so but that's basically the defined parts where basically as long as the parent is not the same as the x itself basically as long as x is not the root right because at the root we the root is always pointing to itself basically if the current one is not the root itself we keep looking for its parents okay while we keep looking for it we are we're trying to like uh doing the past compression by doing this until we reach the uh the root then we simply return the root itself okay and then for the union right for the union here uh we do a x and y okay so for the union here you know it's we're going to root 1 equals to the find x okay and root two equals to find y okay and we only do the union when whenever the if r one is not equal to r two and then we do the union okay i mean so for the complete union find uh i mean structure i mean ideally we should also have like uh like a ranks you know ranks equals to uh for each of the ranks maybe after zero okay you know something like this you know basically uh based on the current ranks we'll be uh assigning the routes from one to the others i mean just to make sure the uh so that we can basically balance the trees a little bit better which it can also improve the uh i mean the uh the time complexity but you know basically what we're doing here basically if the ranks uh r1 is greater or equal than ranks are r2 something like this right basically will assign the parents of r2 to r1 something like this the other or if otherwise we sign the other one assign the parents r r1 uh to r2 but for the simplicity case here i'm going to remove the ranks here which means uh i'm always assigning the r2 to r1 or we're always assigning uh r1 to r2 it doesn't really matter for now i'm just signing this one here okay that's why i'm what i'm saying that what i said i'm using a simplified version okay so basically that's the two basic uh operations for this for the unifying and now since we have a unifying structures and we can simply uh construct the i mean the address right basically we have a sim one path between the two points uh okay probably i'm going to use the path here okay and to construct the path right in range and basically we're going to calculate uh the adjacent for uh between each of the uh the each of the two nodes to do that i'm also going to pre uh define like hyper functions to help us define the uh calculate the uh the distance okay so this one is pretty simple right p1 0 minus p2 0 plus abs p1 1 minus p2 1 okay so i plus one dot n right that's how we uh select all the pairs right because the sequence of the pair doesn't really matter so that's why we can simply do of what the for loop here okay and the distance right the distance is what is this right so the uh gat distance points i and points j okay so with each of the edge of the pair the points edge points pair here i'm going to add that dot append okay append to what so the first one is distance the reason we put the distance at the first element is because we want to sort by a distance later on and second one is i and j basically we use the index right the index uh of the two points to represent the point itself so that's when we are going to use and we'll be using the index and to do the unit and find okay so that's that now we have all the paths here now i just need to do the sort okay so now the uh now we just start processing the path from the smallest to the biggest distance and p1 and p2 okay from pass sorry in impasse okay and like i said you know uh things okay sorry we also i'm also going to create uh define the answer here basically we only going to add at this distance the answer when they're when we actually do it during the union right if it if the root even if we don't need to do the unions we don't add a distance so the way we're checking here is that we have to utilize this one here basically if the r1 is not equal to r2 this is when we do the union uh one way of doing this is we can simply return a flag from the unit here basically if we do a reu the union we return true here otherwise we just return false okay so this way we can just simply uh use this union to check if we have ever if we really did a unit or not basically so uh union okay p1 p2 okay basically if the union p1 and p2 return a true value then we know okay we did a union so that we can just add this the distance okay otherwise we don't do it and then we simply return the answer here okay yeah i think that's pretty much it is i think let's try to run the code okay so the test case passed and submit cool so it's it accepted you know it's not the fastest one but it's i think it's mo it's the most easiest way the most easy i mean it's what it's the easiest way of solving this problem at least for me you know because and the unifying i mean this follows the intuition right of this problem basically we need to use the unit find to help us to determine uh when to union those two nodes because you know the way this problem is asking us to connect the those two other points it's is essentially the same thing that the unit find is doing here so it's just like i as if we were doing a union find but this is the uh a cost of each union basically that's the nature of this of the of this problem so next time when you guys see like a problem that asks you to connect different points or different set uh different parts or components try to use the unit try to use the union find okay and also and after the union find it also ask us to find the minimum cost okay so in order to find the minimum cost uh we need to uh pre-cut uh we need to uh pre-cut uh we need to uh pre-cut calculate all the possible paths first with the distance okay and then we just sort we sort the sort by the distance so that we will always pick the minimum distance and then to do the union find and when we do the unifying we do this right we uh we unit and then whenever there's a union really happened then we add the distance to the answer otherwise we know that okay those two nodes those two points had already been union before so there's no point of union uh connecting them again okay i think that's pretty much it is for this problem yeah and okay cool thank you so much for watching the videos guys and i hope you guys liked the video stay tuned see you guys soon bye
|
Min Cost to Connect All Points
|
average-salary-excluding-the-minimum-and-maximum-salary
|
You are given an array `points` representing integer coordinates of some points on a 2D-plane, where `points[i] = [xi, yi]`.
The cost of connecting two points `[xi, yi]` and `[xj, yj]` is the **manhattan distance** between them: `|xi - xj| + |yi - yj|`, where `|val|` denotes the absolute value of `val`.
Return _the minimum cost to make all points connected._ All points are connected if there is **exactly one** simple path between any two points.
**Example 1:**
**Input:** points = \[\[0,0\],\[2,2\],\[3,10\],\[5,2\],\[7,0\]\]
**Output:** 20
**Explanation:**
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
**Example 2:**
**Input:** points = \[\[3,12\],\[-2,5\],\[-4,1\]\]
**Output:** 18
**Constraints:**
* `1 <= points.length <= 1000`
* `-106 <= xi, yi <= 106`
* All pairs `(xi, yi)` are distinct.
|
Get the total sum and subtract the minimum and maximum value in the array. Finally divide the result by n - 2.
|
Array,Sorting
|
Easy
| null |
296 |
hey everybody this is Larry this is me doing week three of the Leo premium challenge uh I haven't done it before and it's a hard so let's see how long this goes uh hit the like button hit the Subscribe button join me on Discord let me know what you think about today's F uh here I am in taipe uh no intro today so yeah uh let's look at today's Farm shall we uh we have 296 best meeting point given an all by uh or M by and binary grid where one is the home of one friend return minimum each one is the home of one minimum total travel distance the some what does that mean how this in a meeting oh you have to find a meeting point they don't this is a very award we phrasing it but I get what they're trying to say uh okay there'll be at least two friends that makes sense I guess actually doesn't I mean it doesn't matter either way um all right let's think right so this is a med hand distance problem so um I want to say that you can treat the dimensions independently as a result uh what I mean by that is that um you know uh the optimal X and optimal y are kind of like can we treat independently of each other soor I keep dropping my laptop um the reason being that they you know uh it doesn't affect each other that at all right they're independent so that means that we look at all the x's and all the Y's of them and then now we're trying to find a minimum uh point for x and the minimum point for y and in that it is also a known thing where you just have to find the media right uh so yeah so I think that's the way to do it and the medium thing is kind of uh all right let's say we already reduced this to I usually draw this out but I don't maybe I could still do it look it let me try to draw it up all right let's say you believe me that uh they're independent right uh then now the median is the ideal thing because let's say you have a number line right uh you have all these numbers that are you know that you're trying to figure out the best meaning point for um and let's say yeah okay let just add numbers good uh because and you want the medium because if you go a little bit to the left that means uh you go closer to two of them and you go farther for to three of them right which means that you're farther from the optimal if you go to the right same thing uh you move three uh three of them are moving farther and two of them are moving closer which means that you're adding uh distance Which is less optimal so and you can do this with even numbers too or even number of uh and two uh then it's just any number in this middle for the same idea right okay so then now you just have to figure out the median for x's and the Y so X's uh isal to YX Y is are equal to this and then just do a loop to kind of see the ones if grid of i j is equal to one then XX of I or append I append J right and I know just linear median finding if you want to do that's fine I'm lazy I'm not going to do median finding at least not today so uh you can you know I'll just add a note you can input this to actually I guess it's not really lit um improve this using linear medium finding that's what I mean to say it doesn't actually improve uh the complexity but it is faster to run in practice I guess uh it doesn't because you get dominated by All Time C here right so you still so yeah all time C is bigger than all or anyway well that probably may not be true but yeah you can improve it but complexity it doesn't uh all time see yeah I mean yeah I guess it does improve it a little bit I miss spoke uh I'm well I just woke up that's my excuse I'm sticking to it uh but yeah and then now you can take uh or maybe I'll just right and this is just the medium uh the median element of course uh oh maybe X Y is and it's okay to kind of um whatam I call it uh take the four of this because um anything if it's even number of element that doesn't matter which one you take so or anything any number in between really so yeah and then now go back Actually I don't even need I could do it this way but I think you just do it independently on x's and y's anyway right so yeah so then now for X in mid X oh no in YX oops what am I say XS uh total x I guess it's technically more correct and that's it hopefully there we go 1354 day streak uh pretty good time and yeah that's all I have for this one um I think the key thing is to recognize that well one it's man hand distance so you could make it independent uh and once you make it independent the other thing uh is about the median finding part uh which I know that I kind of went through the proof really quickly but it is something that shows up a few times on lead code and competitive in general um but the proof is pretty I mean the proof is pretty good I think it's just that uh it may take a little bit of time to understand because it is a little bit quick uh that's all I have for this one let me know what you think and yeah stay good stay healthy to go mental health I'll see youall later and take care bye-bye
|
Best Meeting Point
|
best-meeting-point
|
Given an `m x n` binary grid `grid` where each `1` marks the home of one friend, return _the minimal **total travel distance**_.
The **total travel distance** is the sum of the distances between the houses of the friends and the meeting point.
The distance is calculated using [Manhattan Distance](http://en.wikipedia.org/wiki/Taxicab_geometry), where `distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|`.
**Example 1:**
**Input:** grid = \[\[1,0,0,0,1\],\[0,0,0,0,0\],\[0,0,1,0,0\]\]
**Output:** 6
**Explanation:** Given three friends living at (0,0), (0,4), and (2,2).
The point (0,2) is an ideal meeting point, as the total travel distance of 2 + 2 + 2 = 6 is minimal.
So return 6.
**Example 2:**
**Input:** grid = \[\[1,1\]\]
**Output:** 1
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 200`
* `grid[i][j]` is either `0` or `1`.
* There will be **at least two** friends in the `grid`.
|
Try to solve it in one dimension first. How can this solution apply to the two dimension case?
|
Array,Math,Sorting,Matrix
|
Hard
|
317,462
|
147 |
what's up i'm going to solve insertion list on leak code sort a linked list using insertion sort a graphical example of insertion sort the partial sorted list which is the black initially contains only the first element in the list with each iteration one element which is read is removed from the input data and inserted in place into the sorted list so basically we just have an array of numbers here and they're not sorted initially and then we use insertion sort to sort the array of numbers so insertion sort iterates consuming one input element each repetition and growing a sorted output list at each iteration insertion sort removes one element from the input data finds a location that belongs within the sorted list and inserts it there it repeats until no input elements remain left unsorted so if you just watch the graphic here see it starts unsorted it compares it to the next number and then those get sorted if the second number is less than the first number and now six is going to be compared to three those are going to get swapped and three is less than five also so three is going to go to the front of the list that's all we're doing now six compares to eight that stays because eight is larger than six seven moves but it's larger than six right here but it's larger than 6 so it stays and we have some data sample outputs right here pretty straightforward we have a negative number here we just put the negatives at the front because those are the lesser of the numbers today i'm going to do is initiate a variable called node and set that to a new list node built in javascript object i'm going to take this head parameter and create a while loop and say wow that head parameter exists the head parameter represents the first number in the array of numbers so four for this one negative one for this one and one for the graphic example create two variables here the first one is called temp and that's going to equal to head dot next so the next number after the head which is the first number in the array and then the next variable will be called current which is equal to the node variable we declared above the while loop so i'm going to create another while loop inside the while loop here the condition is going to be if the current variable dot next and the current dot next value are both less than or equal to the heads value so head dot val and if that's true current will equal current.next current will equal current.next current will equal current.next so it'll so current will be updated as a variable to current.next so now we're going to make three updates here the first is head dot next is going to equal to current.next print.next is going to then current.next print.next is going to then current.next print.next is going to then equal to head and then head will equal to temp so we're switching the variables around and then last but not least outside of the while loop will return node.next let's run that pass and that passes as well so i believe this is a quadratic or an exponential runtime complexity which isn't very good because we have a while loop nested inside of another while loop so that runtime mathematically is o um of n squared basically because we have a nested for loop here so while the head exists we also have to check if the current and the current dot next value is greater than or less two so we're checking two things that our space-time two things that our space-time two things that our space-time complexity is um o one constant because we aren't adding any more data to the function
|
Insertion Sort List
|
insertion-sort-list
|
Given the `head` of a singly linked list, sort the list using **insertion sort**, and return _the sorted list's head_.
The steps of the **insertion sort** algorithm:
1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
3. It repeats until no input elements remain.
The following is a graphical example of the insertion sort algorithm. The partially sorted list (black) initially contains only the first element in the list. One element (red) is removed from the input data and inserted in-place into the sorted list with each iteration.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Constraints:**
* The number of nodes in the list is in the range `[1, 5000]`.
* `-5000 <= Node.val <= 5000`
| null |
Linked List,Sorting
|
Medium
|
148,850
|
229 |
hey everybody this is Larry this is Day fth of the Leo daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about this problem if it ever loads why is my computer so slow I don't know uh so slow for lead code what is going on uh all right today's problem is H am I lagging no seems okay today's f is 229 majority element 2 given an integer we size and we find all elements that return more than n over three times huh okay I mean obviously you know linear time linear space is Trivial right um we just put everything in a dictionary and that should be fine um and then the other one is uh is it flud is someone's uh majority algorithm I forget the name huh but uh but that's also you know uh that's n/ two times so you can uh that's n/ two times so you can uh that's n/ two times so you can kind of do the Delta things and you could do that in also or one but that only do n/ two in also or one but that only do n/ two in also or one but that only do n/ two and not n/ three and in this particular and not n/ three and in this particular and not n/ three and in this particular case um I guess the four of n over three or more than four of n over three that could only be there could only be at most two elements right so yeah so maybe we just have to do some maths there um oh and just to kind of Jump Ahead a little bit is that I am follow I'm trying to attempt to solve the follow up the linear time constant space um because like I said otherwise you're just pring in a hash table or lookup table or Whatever frequency table and you know it's fine right um H let me think cuz I think you know I'm trying to see if I can generalize um is it Flo's majority Alor I forget the uh majority that's a thing right or uh or someone else who did it oh boiler more H okay so another famous computer scientist but I've been mixing it up today uh I think actually to be honest the majority one I always mix it up maybe I always say Freud I give Freud so much credit but in any case yes I'm trying to generalize try to see if I can generalize that to n over from n over two to n over three um I don't know if I can per se I do have some IDE I mean or I think I have some ideas around it but I have to kind of really work it out to be honest um because I think you know the over one space could be a number of things but really like I said you only have two possible answers right you have the number one answer or like the most common uh element and then the second most common element and then maybe the third if I'm wrong by a little bit off by WR by and off by one then you have three um majority elements right uh yeah I mean I think it still should be only two so maybe we can definitely uh consider doing that and then maybe keeping track of it right so and I'm just trying to generalize border more in my head anyway the uh the majority algorithm is just this idea of this Delta right um because basic the idea of I'm and you know I might be wrong here because I'm trying to do it from memory is that the majority algorithm is that any number that appears that is not the majority will be1 um that and it's very I mean I get the idea but it is still a little bit weird the way that it does like if uh yeah if a number is you know I mean of course I guess you're supposed to do one more pass at the end to kind of confirm it so I guess that's fine but the question now is then is there an idea that does that here right so what how do I check whether one number is uh appears one3 of the time or more and we can probably do it in a number of passes you know or like as long as a constant number passes but let's say and this is me fing off my head so definitely you're seeing the live uh thing now uh I have solved this before though I don't know if I was just lazy cuz I don't think I ever feeling about it but I sometimes I say that so and then I'm just wrong so uh but okay so how do you get one dir right that means that okay so I think my idea here now is that so to get one half uh you know the border of Mor's algorthm is that for every one there's a matching one um on the for every majority there's a matching minority uh and if you go over it that's fine so for one3 for every one you have two uh elements on the minority I wonder if that works right so basically one has to cancel out two things so you have you know I do wonder if that works I mean that's kind of my idea at the moment I think that works cuz I think the worst case would be something like um and I'm just going to use letters for laziness so a b right so then my algorithm would be like plus two and then now uh the four of these would cancel out the A's and then now we B's going forward yeah maybe that's fine I'm gonna try it YOLO right uh it sounds reasonable in the same IDE in the same way but I don't know is that true what if we have half no I guess half is fine and then we could do the second pass much easier right um okay let me try this I to be honest I the proof is tricky so I don't know but um I don't know if it quite works but we'll see so yeah so current is z just say and it could be negative number so that just say some numbers that still out range so Infinity right uh and then maybe the Delta is equal to zero I forget what they call it in the algorithm it's been a while and then now for each number if x is equal to current um Delta increment by let's say plus 2 so then we get Delta minus one uh else Delta minus one um right but if Delta is exactly zero then current is equal to X so then we can kind of just abuse it that way okay so then now if I guess okay so if Delta is greater than zero for sure we have a number that's that is uh more often than 1/3 that's that is uh more often than 1/3 that's that is uh more often than 1/3 but if it doesn't does that mean it is not hm that I'm unsure about uh like if it's if Delta is negative does that mean there's no elements that appears more than N /3 I think that's the thing that than N /3 I think that's the thing that than N /3 I think that's the thing that I'm not quite sure but I guess it cannot be negative actually so um and I guess it can always be Delta over one at the end but that's why you do a check right okay so then um if Delta is greater than zero because I guess if Delta is equal to zero then actually by definition it cannot exist maybe but maybe I'm wrong on this I may be wrong on a lot of things this is a really weird specific problem right that doesn't I don't know that generalized into anything so I don't know uh but yeah um yeah so okay so if it's greater than zero then we have to run through you know just num start count of current right so I don't know C is if C is uh let's just say an answer away uh if C is greater than n /3 multiply 3 uh if C is greater than n /3 multiply 3 uh if C is greater than n /3 multiply 3 by on both sides uh and then n. a pen code right and then now we um now we have to see if we can figure out the other one right I was initially going to think like oh you just do the n/2 algorithm for the rest just do the n/2 algorithm for the rest just do the n/2 algorithm for the rest which is not quite precisely true right but we can definitely like REM like what happens when we remove these elements well when we remove these elements if we remove these elements like the most popular element we still need n over three which is a little bit tricky I think we could do the Delta thing again and then do the math that way but that seems a little bit I don't know it's just too hand wavy for me to be honest um okay let's actually what I want to do now is just uh actually run it for some assemos first I know that is just going to be wrong cuz only I'll put one answer but I also want to put in like a few more other things um that should I actually return something even though this is zero something I don't know yeah H so maybe this is wrong because this should definitely like even if I had uh I think my logic is a little bit wrong here or there a lot of things that very wrong here but like even I have something like this two should be there so now the order is not quite right is it or like it's order sensitive oh well I guess the one works but that's like a really weird way to do it um cuz I think there is another invariant that I'm not considering because basically if let's just say ref yeah I mean I think this should enough still should have returned two we wanted to right as the most popular item and this definitely is not the case so maybe we have to do something else um H I don't know not that I think about it to be honest h is still a funky way to think about this problem uh I was just thinking about generalizing um B Mo's uh majority algorithm but maybe this isn't it maybe that was a red aing uh and I apologize for wasting 12 minutes but you know we trying to learn here I'm trying to think where I can binary search is what I'm think right now what does the binary search look like you do binary search or at least like for one of the answers not necessarily all of them have one two no you can binary search because let's say you have uh1 1 uh you have three I don't know some whatever right uh then in theory you would try to do a search on this side but that's just not how that works out right so I don't think that you could what the let going on uh I don't know that it's as easy as a binary search h Huh maybe I just don't know this one I mean this is a very weird thing yeah maybe the Delta F this doesn't work quite like that or maybe I just don't understand the uh the majority algorithm enough it's cuz I'm trying to think everything off my head I'm not you know Googling it over whatever oing it um or it's not yet huh I don't know how doing constant space just do um I'm just thinking about like if there's a peration thing but I don't think so there's no counting sword or anything like this that's still all in your space know that would be funny if that was just a thing like as a counting sword like okay that's not useful but oh man I'm tired how do I do this one I thought that this would give me the most popular element well I guess that's not true it's just at least one element um I actually did not anticipate it giving me nothing for this one I mean it makes sense it's just that I don't know I just didn't think of it all the way through um so now I mean I guess you can remove ones and then you need four how do you even calculate that you use the Delta trick again yeah I don't know is there anything like the pigeon ho that I can kind of use um or even publicistic okay let's try to solve the N over two case right if it exists can we binary or break like a divide and conquer with n over 2 Cas you could Divine conquer because the most common element oh I guess that's not true I was going to say that the most common element is probably the most common element on the left and on the right but I guess that's not technically true um cuz it could be like the second element on the left and second element on the right and then combines it is the number one element but you only need to go two deep how do we get the two most common elements without storing a frequency table I guess that's the question can I just do this with three elements okay do I subtract one on each one then if it's not I don't know I guess technically this as well because this is four of n over three which is what they want uh so this is too precise actually I don't know that I can times three h maybe it should still be fine I think but I'm trying to think whether um how to kind of quite translate this um I'm thinking maybe something like I don't know if this generalized I think that's the thing right so okay so you have like current um curent one Delta one right and then maybe like you know if current one is to go to in uh or if Delta 1 is equal to zero current 1 is equal to X else if Delta 2 is equal to Z then current 2 is equal to X oh well actually the order has to be precise I suppose if current 1 is equal to X then Delta one increment by one else if so then now it is not nothing to do then now two set it else if current 2 is equal to X then 2 increment by one else I don't know something like this maybe I don't even know if this is quite right um but I guess I mean I'm trying to make sense of it I think it makes sense in a way that like it matches the other thing CU if you think about it the same way then now but I don't know I think that's just really tricky to say and do right um right if Delta 1 is I me I think we just do like C1 or count one is equal to num sub count whatever I'm a little bit lazy on this one of course right all right and then now if and we could actually why there no Loop what is it I someone like that what uh this is a little bit awkward no but this should only happen if it is not this or this and they're both not zeros so I this means that this implies everything will be positive um I think this has to be okay I think I missed mix missed something here because you just start off at one uh okay give us a m bit yeah I wasn't confident about this so let's uh okay see why this is wrong so it goes two uh and then one three so the three deletes the two uh okay and then when it gets four it should go back to one uh and what is the answer one am I just off by one maybe I am a little bit the rounding is a little bit weird does that fix it nope okay uh let's see five and six uh okay so the four should not delete the one with the three would so okay the two one and then the three delete one of them four doesn't but then the five and the six so now is Delta Two is equal to zero oh when the six what maybe I'm do I have a typle or something let's uh let's put everything I think uh why is there so many things okay so 2 one okay that's good another two zero set oh I see so one of the ones uh got put it the other one okay so I guess we have to move these things up a little bit just in case I think I just headed with the other way in the other one and it kind of uh influenced my mind this is kind of a hard problem if we haven't done it before or you don't really understand the B Mo election algorithm or majority Al did it before what did I do I guess I did do it that way eventually huh that was yeah 3 years ago so maybe it was just a long time uh this is kind of hard to explain I mean this is linear time constant space uh it's a little bit hard to explain but it really is just the same idea as the bord more majority algorithm which is that you know the idea is kind of like pitchon hole in that um the majority algorithm or the majority element will cancel one non-majority element and then that means non-majority element and then that means non-majority element and then that means that if you kind of do a counting one by one there would be if there exist in majority algorithm um it will have more elements than uh it would have leftover because it's just a number of elements that are left and here but doing X over3 I guess you generalize it in a really awkward way for me it feels awkward which is that if you have two uh major Alor uh major elements then each of them not considering the other will cancel out one of uh the Third the all the non- one of uh the Third the all the non- one of uh the Third the all the non- majority algorithms or the minority uh elements I guess that's kind of the idea but it's still um kind of tricky to come with to be honest and it really doesn't come up that much but it is a classic problem I suppose in that uh CU I think the way that I read this is that you know back in the day like I don't know like caveman days or something right uh you don't even need a concept of numbers to know what is bigger because the way you would do it is just you would count them off one by one to kind of get the to see who has more right so that's kind of the basis for this one as well a little bit um but and but of course um uh it does not it's not sufficient so that's why I would do the account at the end because you can imagine you know you just have something like I don't know like one one11 one uh and then two so they can then do three and then now or oh even just like 3 4 5 6 7even eight or whatever it is right um then now uh you would have the last element have one extra element but that obviously is not a majority that's why you have to do a c but yeah uh linear time constant space that's all I have for this one I'm really exhausted on this one let me know what you think I don't know I don't how I feel about this one so yeah stay good stay healthy to good mental health I'll see yall later and take care bye-bye okay
|
Majority Element II
|
majority-element-ii
|
Given an integer array of size `n`, find all elements that appear more than `⌊ n/3 ⌋` times.
**Example 1:**
**Input:** nums = \[3,2,3\]
**Output:** \[3\]
**Example 2:**
**Input:** nums = \[1\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1,2\]
**Output:** \[1,2\]
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-109 <= nums[i] <= 109`
**Follow up:** Could you solve the problem in linear time and in `O(1)` space?
|
How many majority elements could it possibly have?
Do you have a better hint? Suggest it!
|
Array,Hash Table,Sorting,Counting
|
Medium
|
169,1102
|
375 |
so today we will be doing a lead code question number 375 that is guess number higher or lower so what is the Crux of the question is that we will be given a range from 1 up till 7 and we will be guessing some number let's say that we guessed 2 so now the now I will be said that the number which is chosen already as my answer the number which I have guessed is lower or higher than that volume than that number supposingly I supposingly the answer was seven and the range supposing the answer was five in the number I guess was two and the range given to me was one till seven until seven so if I guess the number five then the program initially tells me that the number that I have been looking is greater than the number I guessed and supposingly I guessed six then in that case the program tells me that the number which I have guessed or which is the answer is lesser than the number I guessed okay so I think this part is clear now for every wrong guess I would have to pay ayed dollar amount like here in this example my number that why I was Finding was supposingly I was supposedly I was Finding uh I am given with the range one up till 7. and I was to find five but the number I guessed was four so in now in the case of four I would be said that the answer is greater than my eye and I know that it is that this is not my correct answer so I would be charged I dollars that is four dollars as a penalty so I need to answer what is that a minimum amount what is that minimum amount of money that I will be keeping with myself such that I would never lose the game as the another rule says that if I am exhausted with the amount of money then I lose the game so what is that minimum amount of money that I need to keep in my pocket such that even if I do the wrong guesses and I am charged with penalty I do not lose the game I still have that much money so that I can make wrong guesses but still I can win the game because I am having that minimum amount of that certain amount of money with me so how are we going to initiate this one let me just create first and function that would be returning me the answer okay so I am pretty much very sure that I would be returning my answer function and initially what the question says is that I would be given a range n is my range up till and 1 up till n so I initially know that I would be passing one up till n in my answer function and my answer function would also be taking Intel and end are that is the leftmost left most range and the rightmost range hmm we will talk about previous condition at the end but for now what are we mean concerned is what is my main concern is that how will I go about finding that minimum amount of money okay I know that I want a certain amount of minimum money so whatever my answer variable whatever my resultant would be that would contain some max value that would be compared to something which would lead into leaders to that minimum amount which we will be comparing with our rest variable so initially what I am thinking is let me go about all of the range current I is equals to l up till I is less than equals to R and I plus what can I basically do press I am pretty much very sure that I would be requiring certain amount of minimum money as and when I will be comparing my rest and supposingly let's take an example that I am given with the range one up till three okay so if I and the number I want let us leave the number that I want so supposingly I guess one I guess for one my function says go a bit higher so now my range becomes 2 up till 3 supposedly I guess 2. any range lower than for the case of one any range lower than this would not exist I suppose 4 2 I get two cases one is I can go from one till one and the second is I can go from 3 up till 3. these are the two ranges that I would be getting and I would be taking the r max value hands and for three four three if I guess three then I would only be getting a single range that would be 1 up till 2. so choosing a number is in my hands and what is in my hands I would say that would be minimum what is in my hands that would always be chosen the minimum value and what is not in my hand that is the worst case that would lead to maximum of I Plus answer of 1 up till I minus 1 comma I Plus I plus 1 up till r so what we really did is that supposingly I make a wrong guess supposingly I made a wrong guess in that case I need to be charged with the penalty amount and that penalty amount was that I ith value I am charged with that penalty amount now my range becomes 1 up till I minus 1 if I have chosen that ith penalty amount then my range is divided into two parts one after I minus 1 and I plus 1 up to R I would be taking maximum value amongst the both ranges so that whatsoever range I choose the left or the right I would always be having the maximum amount of money and what a minimum signifies choosing any random number is in my hands so I would be choosing the minimum number the minimum amount of penalty that can be made from choosing a number that is the importance of choosing minimum so what is in my hands that would be minimum and what the function leads me to that would be a maximum value so that I am never exhausted with the amount of money so now our base condition becomes something like if L goes greater than equal to R then I would just return a zero value that is pretty much very sure so I think we are done with the basics I would be returning the rest value at the end of my function and let us hope that this runs let's try reloading the page okay so we have got 11 as our answer and the expected was a 16th and uh mistake we have done a mistake if L is greater than equal to r that is pretty much very sure and rest is equals to end Max that is also very much sure L is equals to I is equals to l um that is also nice rest is equals to minimum of rest comma maximum of I plus 1 and then okay so we did this one that it should not be always L it should be it should not be always wanted that should be L okay that is pretty much very short okay now also that becomes l oh okay I have not called the function okay sorry my bad okay so these test cases are accepted we go on now for submitting and I hope that this would lead us to a time limit exceeded error yeah that is it so now resolving that one would be going out for memoization so we would be declaring a vector of vector Vector of vector and DB Vector int uh wait a minute size would be n plus 1 and vector and size would be n plus 1 and a minus 1. y n plus 1 because we are having our ranges from one up till n so we want n included so that is why we are taking one up till n plus 0 up till n plus 1 so that we would be getting n and n in our Matrix in our DB Matrix I would be asking that if DP at l at R is not equal to minus 1 then in that case return d p of L at r and just call for the vector and Ampersand DP and then go on calling DP inside our function calls just return DP at l at r and return rest value inside it and I think we are pretty much very much clear and last but not the least I need to add DP here also and I think that this is good to go this would be submit DP at LED r uh okay sorry this is not a single array it is a term of vector and the DB okay Ampersand DP now that is very much it I suppose no error okay we are good to go and that is it guys that is it we have solved this question guess the number higher or lower if you like this video to hit the Subscribe button and we will meet on the next video thank you
|
Guess Number Higher or Lower II
|
guess-number-higher-or-lower-ii
|
We are playing the Guessing Game. The game will work as follows:
1. I pick a number between `1` and `n`.
2. You guess a number.
3. If you guess the right number, **you win the game**.
4. If you guess the wrong number, then I will tell you whether the number I picked is **higher or lower**, and you will continue guessing.
5. Every time you guess a wrong number `x`, you will pay `x` dollars. If you run out of money, **you lose the game**.
Given a particular `n`, return _the minimum amount of money you need to **guarantee a win regardless of what number I pick**_.
**Example 1:**
**Input:** n = 10
**Output:** 16
**Explanation:** The winning strategy is as follows:
- The range is \[1,10\]. Guess 7.
- If this is my number, your total is $0. Otherwise, you pay $7.
- If my number is higher, the range is \[8,10\]. Guess 9.
- If this is my number, your total is $7. Otherwise, you pay $9.
- If my number is higher, it must be 10. Guess 10. Your total is $7 + $9 = $16.
- If my number is lower, it must be 8. Guess 8. Your total is $7 + $9 = $16.
- If my number is lower, the range is \[1,6\]. Guess 3.
- If this is my number, your total is $7. Otherwise, you pay $3.
- If my number is higher, the range is \[4,6\]. Guess 5.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $5.
- If my number is higher, it must be 6. Guess 6. Your total is $7 + $3 + $5 = $15.
- If my number is lower, it must be 4. Guess 4. Your total is $7 + $3 + $5 = $15.
- If my number is lower, the range is \[1,2\]. Guess 1.
- If this is my number, your total is $7 + $3 = $10. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $7 + $3 + $1 = $11.
The worst case in all these scenarios is that you pay $16. Hence, you only need $16 to guarantee a win.
**Example 2:**
**Input:** n = 1
**Output:** 0
**Explanation:** There is only one possible number, so you can guess 1 and not have to pay anything.
**Example 3:**
**Input:** n = 2
**Output:** 1
**Explanation:** There are two possible numbers, 1 and 2.
- Guess 1.
- If this is my number, your total is $0. Otherwise, you pay $1.
- If my number is higher, it must be 2. Guess 2. Your total is $1.
The worst case is that you pay $1.
**Constraints:**
* `1 <= n <= 200`
|
The best strategy to play the game is to minimize the maximum loss you could possibly face. Another strategy is to minimize the expected loss. Here, we are interested in the first scenario. Take a small example (n = 3). What do you end up paying in the worst case? Check out this article if you're still stuck. The purely recursive implementation of minimax would be worthless for even a small n. You MUST use dynamic programming. As a follow-up, how would you modify your code to solve the problem of minimizing the expected loss, instead of the worst-case loss?
|
Math,Dynamic Programming,Game Theory
|
Medium
|
294,374,464,658
|
198 |
hey guys it's offi1 here and today we're going to be solving House robber in this problem we're told that we're a professional robber and we're planning to rob houses along the street each house has a certain amount of money stashed and the only constraint stopping us from robbing each of them is that the adjacent houses have security systems and it will automatically contact police if two adjacent houses were broken into in the same night so what that means is let's say we have a house like here and a house right here we can rob House 1 and House 3 but we can't Rob House 2 after robbing house one or house three because that would be an adjacent house so we're given an integer array nums that represent the amount of money in each house and they want us to return the maximum amount of money we can rob without alerting the police so in other words let's say this is house one two three and four we can rob here and here or we could Rob here and here without learning the police we could also Rob just house one and house four so we have to consider that in our edge cases later on so if you've ever wanted to rob houses this is the perfect problem for you and I'm going to show you how to do that so here I've modified the example from the original problem and I added house 5 and house 6 with a value of one and five and I think a good way to approach this problem is by thinking about it backwards so let's say we want to wrap house 6 for example because we know they have super valuable stuff well from how six we need to know what the max is before that because there's a lot of options to get to how six so for example we could start a house one then go to house three and then go to house six we can go to house one and then go to house four and then house six or we can go to house two first and then house four and then house six or we can just go to house two and then house six and I'm sure I might be missing one or two here but you get the point there's a lot of different combinations we can use and calculating them for each and every house would lose up a lot of time so what we can do is use dynamic programming to keep track of the max up to that house so what do I mean by that well by the time I get to house six I want to have the most optimal route to get the most money from all the houses and doing this every single time for every single one of these houses would take up a lot of time so maybe we can just save the Max and use it later on so we know that robbing has one and House 3 would give us a result of four so if you go to house three we can just say the max amount of money we can Rob is four dollars and then now if you were to skip to house six we can see that we would have four dollars already so we don't even have to recalculate all of this stuff and we can just add the value of Hell six at the end so we would have four dollars plus five and that would give us nine which is the max for this nums array so here I've drawn an array in this array we're going to keep track of the max we can rob up to that current house so for example House 1 will correspond to index one here and the max we can rob up to house one is only one since there are no houses before that then we can Rob and thinking for house two the Mac 2 can rob up to house two is only two since there are no houses before that and now we go to three what's the max we can rob here well as you can see we could wrap house one and then we go we can go to house three so that will give us a Max of four okay well what about house four well the max we can rob here would be either one and one which is two or two and one which is three but the problem with that is when we get to house six we want to already know what the max is at this point without having to recalculate it so we can just say that house 4 could be four as well since we're not actually ever going to use the three here because that would not be the most optimal route and at five we can go from one three and one which would give us a result of five and that would be the max because starting at 2 and going to 5 put only give us three so the max is five and now for six we can't Rob house five and then house six because that would alert the Police so we have to Rob either House 3 or house four and like we said earlier the max here would be three and the max here would be four so we would want to Rob house three and then we can go to house six because that would be the most optimal route so the max here would be one plus three plus five and that would give us 9. so I just want to go back real quick to this four and explain why we stored 4 here so the reason we didn't store a three is because it would be useless for us we could do it but the code would be a little more complicated because then we would have to go all the way back here and then all the way back here which means that when we iterate through this array we would have to have a lot of Base cases I think up to here for it to work and what I'm trying to do is only use these previous two and that's why I want to keep this as a 4. so the actual algorithm let's say we're doing it for this point so it makes a little more sense we would want to do result of four is equal to the max between results at 3 or results at 2 plus the house value and as you can see result at 3 would be 4 and result at 2 would be 2 plus the house value of 4 which is one so two plus one that would equal three and the max between these two would be a four and that's the reason to be stored a four here so now that we know how the algorithm works for four let's try and generalize it for every index so let's say we're trying to calculate the result at a random index how would we do that well we can just take the max of results at I minus 1 because as we can see here we're at 4 and then here we do three and the way to do that would be four minus one and that would give us a three or we could take the results at I minus 2 Plus the current value of the house so now that we generalize the algorithm what is I exactly well I is just every iteration that is in this result array so we want to iterate through the whole result array and the size of our result array would be the size of nums plus one because we want to include space for our base case so our full algorithm is going to be a for Loop from 0 to the size of nums plus one so now let me clean this part up so our time and space complexity for this algorithm is going to be o of n for time because we're iterating through every num and for the space it's going to be all of n as well because we're using our result array here but actually this problem can be solved in constant space the way we do that is by noticing that we're only ever accessing I minus 1 and I minus 2. so maybe we can just keep track of these in variables and then access them in our code that way and then update our current value to that and I'll show you how to do that in the code so let's get into it so to start we're going to initialize three variables the first we're going to do is current Max and we're going to set that equal to zero and then we're going to have previous one and set that equal to zero and then we're going to have previous two and set that equal to zero and what these mean is current Max is going to be our current resulted I previous one is going to be resulted I minus 1 and previous two is going to be resulted I minus 2. so hopefully that makes sense and now we want to iterate through every num in our nums array and from here we want to update our current Max to be equal to the max between our resultant I minus 1 so we can just do previous one or result at I minus 2 plus our current number so previous two plus nub and then now we want to update our previous one in previous two so they're actually pointing to the correct result so previous two is going to be pointing to previous one now because if you imagine the array we're iterating one forward now and now we want to set our previous one to be equal to our current Max so if you think about this previous one would eventually be resulted I and that's the reason we're doing this and then at the end all you have to do is return the current Max and that should work so as you can see this code is pretty efficient and now I'll go through the code manually so to start we have to initialize all of our variables to zero which I've already done here so we can check that off and now we want to iterate through every num in nums so our first num is going to be one so our current Max is going to be the max between previous one which is zero or previous two plus num which would be 1 because 0 plus 1 would be one so now our current Max is going to be updated to one and previous two is going to be updated the previous one which is zero and previous one is going to be updated to our current Max so we can do that set that equal to one and now we go to the next iteration so our current number now is 2. so now we do current Max is equal to the max between previous one or previous two plus num and previous two would be zero but our num is two so that means that our current Max is going to be updated to 2. and now we update our other pointers so previous two is going to be equal to previous one which would be one and previous one is going to be updated to our current Max which is two and now we go to the next iteration so we're at num equals three so our current Max is the max between previous one or previous two plus num so what is bigger two or one plus three well obviously that's going to be bigger because that gives us four so we're going to update our current Max to four and now we want to update previous two to be equal to previous one and previous one is going to be updated to our current Max and now we go to the last iteration so our Norm is one again so the max between previous one and previous two plus num would be four because previous two is two and our num is one and that only gives us three so we don't want to update that so our current Max is still going to be four and now we want to update previous two to be equal to previous one which is 4 and previous one is going to be updated to our current Max which is still four and now we can just return our current Max and as you can see our current Max is 4 and that is correct if this video helped me anyway please leave a like And subscribe thanks for watching and I'll see you in the next video
|
House Robber
|
house-robber
|
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**.
Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_.
**Example 1:**
**Input:** nums = \[1,2,3,1\]
**Output:** 4
**Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
**Example 2:**
**Input:** nums = \[2,7,9,3,1\]
**Output:** 12
**Explanation:** Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
**Constraints:**
* `1 <= nums.length <= 100`
* `0 <= nums[i] <= 400`
| null |
Array,Dynamic Programming
|
Medium
|
152,213,256,276,337,600,656,740,2262
|
1,910 |
So Hi Everyone this is Abhay Mittal and today we will be doing a question in this video which is which question of lead code 1910 11 19 and 10 so this is the question and what you have to do in this question is remove all traces of a If the sub string is fine, then what you have to do in this is that whatever sub string has meaning, you have to remove it, which is the main string, it is given that S is that and whatever is your sub string, name it. The part is ok. If you have to remove 'S' from the part is ok. If you have to remove 'S' from the part is ok. If you have to remove 'S' from the part, then what will you do to remove 'A'. then what will you do to remove 'A'. then what will you do to remove 'A'. Look, that is, what has to be done to remove the part. Like, he has taken the example. We learn from the example that 'A, he has taken the 'S' string, ' learn from the example that 'A, he has taken the 'S' string, ' learn from the example that 'A, he has taken the 'S' string, ' Ded, A, B, C, Bead'. A B S Okay, so the Ded, A, B, C, Bead'. A B S Okay, so the Ded, A, B, C, Bead'. A B S Okay, so the part you have to remove is A B C and A B C part, like this one you removed, this one has become a part A B C and what other part is there in it, this one has become a part. ABC, if you remove it, another ABC can be generated, but if you have to remove that too, then you have to remove it till the entire string is equal to A pose. It means whatever you are finding, what are you doing, if you are doing ABC then till it becomes equal to you, as long as you keep removing the A's, then how can you do this question, you can do it by two methods. There is a method that you can do it with Action and there is also one method where you can do it with Rig. Okay, so now we will do it with Rick. It is the same sequence as with A and you will still get a good beat, it should be a little cross 50. goes but can beat much less than the rick but still we will learn the rick first and then let's see whether we will do it or not and one more example he has already given example 2 so we have to find out the xwa extracted from here Extracted from and what is left in the ending, so no currency of So, if you have level memory, then let's start, okay, first do the video, first you have to give the function, right rim and string, okay, you have to give the function, so we will take this function and create another function. Yes, we will call the reference which are the questions, you try to do it by call by reference only, okay then we will make a copy of it every time, otherwise you will not have to make a copy every time, you will do call by reference. What can you do for call by reference? Yes, you create another function, we will not create one with the name of Remove Arrays. To create one with the name of Remove, you can create anything, Chapa, create anything, but we will create one so that we can get a clear idea of what we are doing, okay. You can create many names to create 'Ha', okay so can create many names to create 'Ha', okay so can create many names to create 'Ha', okay so we took remove one function, remove function is done and in it we passed what ' and in it we passed what ' and in it we passed what ' S' and what will we make 'Part' pass, 'What is part', 'What is part', 'What is part', S' and what will we make 'Part' pass, 'What is part', 'What is part', 'What is part', S' and what will we make 'Part' pass, 'What is part', 'What is part', 'What is part', tell me, what is part subbing and 'S'? Whatever part subbing and 'S'? Whatever part subbing and 'S'? Whatever string is given to us is the full string which is A and the part which is sub string which we have to find and which we have to remove is the part, okay, will we pass it and return it, I will tell you later. I will tell you why I have written, so first we create a function here. How to create a function. We will create a string. You will have to give the return type in the string. It is like 'e', 'b' is like give the return type in the string. It is like 'e', 'b' is like give the return type in the string. It is like 'e', 'b' is like this string, 'character' is this string, 'character' is this string, 'character' is that of the character, ' that of the character, ' that of the character, ' more' comes in the 'character'. So there is a string more' comes in the 'character'. So there is a string more' comes in the 'character'. So there is a string and in this you have to give the return type only, it is similar to int, in a way int comes with numbers and comes with vectors, the difference is this, okay, so you have given the string and you have removed the string, its name is remove. You have passed two strings in it, which one is the string which is complete which will be given to us and one string which is the other string of yours which we have to remove. Okay, so we came and now see what we do. Now what do we do? Let's create an int fund. What will be the int fund? The int fund will be the part from where your indexing of ABC starts, that is, the ABC is A, right from where your indexing starts, all that part of that part. Finding the index of what is going on. How to find the index? Find is an inbuilt function. From there we will use find to find the value of the fund. I will tell you its use further. Finding the index is done. We have made the fund. And from this we find out how to find and whatever you have to find in it, what to do, to divide, now see how much will be its value, now how much will be the value of the fund, tell me quickly, then the value of find will be this. We have to see the part in this, A is okay, so in s, if you look at the part is first, what actually is the part, in example one, it is ABC, OK, ABC's, you see where ABC is coming. D A B S is coming, so see from where the indexing of A B S has started. 0 1 2 So the value of found will be equal to 2. Okay, so the value of found will be equal to 2. It's ok, it's here brother, now we will run the loop, don't know for how long we will run it until we get A B C in that st, meaning whatever we have found should not be equal to N Po, when we keep running the loop. Ok so this is found which is fun my friend one minute which is found is ok and this which is not equal to zero hold for a minute ok sir let me tell you the location ok a little busy right now oh ok sir Coming back to our topic, what is F? Yours is found, which is not equal to zero, until it is found, which means, as I tell you, it is now stinging, it is okay, what to do now, until it is found, not equal to zero. Our F should be equal to F. What does it mean as long as we get How can you remove it? Look, the approach is that look at ABC, how I keep it, okay, I see, it is not in it, okay, let's see how long this will last, whatever ABC is, it is your part, okay. A BC is your part, you can extract it on the left side of A BC. How to extract it all, by applying AT function, it is ok, there is this function, now extract it by using it, extract the left part and extract the right part of AC, that is complete. Will go bead A B C B S Okay, this is done, take out its right part, left part and right part, merge it and call recursion again. Have you understood the theme? What are you doing? Have you understood the theme or not? This is, we will take out the left part of A and B and we will take out the right part of A and we will merge the right, left and right plus and after merging, we will apply recursion call till it becomes equal to A force, what does this mean? What will happen is that all the energy of yours will disappear, then it will be nothing. Now we will put left p aya and left put and this will become equal to your kiss. We give you a thing and I tell you that it has become zero. We have given one. Okay, it is done. Now let me tell you the meaning of this. What is the meaning of this? Wait for a minute, I will also write the string one. Whatever string it is, the Rat person would also have written it. I am right, what will be the right part, we will do it like this R and this will be Panda Ps and what will be its size will be the size of Pat and this we have made it run, when tad size, now what is the meaning? Meaning Necessary Samna Okay, everything is okay, what do we need? This is the left part from where you are starting, meaning starting from zero is the index and found is what is the value of found, right, so 0 is to zero, this means that That is because of that indexing, it is being started, Pat means whatever A they are making and Fund means if there are two then two characters then all the sting which is there will last till two characters, if one character becomes this and if two characters become this then D If it comes here, then one meaning is this is what your P is here, the battery is low, no, I will put the battery, this is okay, so here we go ahead, here P, we will put the semen, okay now. If you understand all the meaning in it, the first 0 to means that you are starting from here and how many indus means how many characters will be passed in it. If two characters are passed then two will be passed. Okay, what did we do for Raat right, see what? If there is ABC in it, is it B, then see what is the value of found Ps found, how much will be the size of two parts, how many characters are there in th part, if ABC becomes three, then 2 x 3, how much will it become, if it becomes five? Look at the value of five, which is five, it will start from 0 2 give 0 first ho ya and where it is going we will do ya aaya dobara na kya banayegi left put and plus take plus right put right left It was right and Dra said that we will put it in. Sorry, we have made a mistake. Can you tell us the mistake? What did we say? So, we had to make it for reference and if we had to pass the value through call, then we could have done it from here only. This is where you can call by value, so you can pass it from here, we did not do this, we need call by reference, now we had created a new function, why do we create a new function, okay, remove has come, remove the return. Earlier I had said that it works like this top, it is okay to return it and it will go and you can give a condition in else till this mean becomes equal to N. What will come after that, it will come that you have to return whatever you want. Will you do it? This is your code. Look, you must have understood. Look, we have not done anything in the question. In this, first remove was given in the function line. What did we do for call by reference? For call by reference, what we did was remove. By doing S spot in the call ba reference, we made it Y A B S, so the call ba reference started and then we took out the fund, what part, whichever part is being triggered by the index, then we took out the fund and till I am the fund, which is not F, when nut becomes equal to A, it is met, not Pat is met, it will keep going on, then what will happen to the lift, add sub is to be taken out, when used, it is zero and what will happen to the right, it will become PS PSY. And it will be done and let's run and see Do n't know what the problem is, do n't give the problem Arhi This is what it is, This is what it is, this is what it is in today's video, itna yaar and in the next video we will do more questions, okay and meet ne take care 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
|
702 |
That high court se divide yes powder number 02 113 according to pinpoint not only multiple times but Google pass smart subscribe problem that get function qualities in eyes to tears lifted highlighted problem limit for be id - subscribe to the first come for time complexity of authors english chemist Option substance cost to your 2002 security duplicate element time limit for be id am id wood problem share and subscribe vid oo jhal hindu dharam ko ki related interview want acid smart approved that is less how first one and rock placid in the mid Term and condition of pimples and time complexity of popular see that a pregnancy to me to continue certificate where the volume from this want to replace multiplication operation under subscribe to that Africa don't want tell multiplication is more return ki tejaswita to enter Chittor Do n't forget to subscribe the channel Subscribe to that police party fold and shelter to submit A tomorrow morning sarpanch and clutch 60 seconds open the app loot time hai told the police in writing this question play list play account here education tax the institutions
|
Search in a Sorted Array of Unknown Size
|
search-in-a-sorted-array-of-unknown-size
|
This is an **_interactive problem_**.
You have a sorted array of **unique** elements and an **unknown size**. You do not have an access to the array but you can use the `ArrayReader` interface to access it. You can call `ArrayReader.get(i)` that:
* returns the value at the `ith` index (**0-indexed**) of the secret array (i.e., `secret[i]`), or
* returns `231 - 1` if the `i` is out of the boundary of the array.
You are also given an integer `target`.
Return the index `k` of the hidden array where `secret[k] == target` or return `-1` otherwise.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** secret = \[-1,0,3,5,9,12\], target = 9
**Output:** 4
**Explanation:** 9 exists in secret and its index is 4.
**Example 2:**
**Input:** secret = \[-1,0,3,5,9,12\], target = 2
**Output:** -1
**Explanation:** 2 does not exist in secret so return -1.
**Constraints:**
* `1 <= secret.length <= 104`
* `-104 <= secret[i], target <= 104`
* `secret` is sorted in a strictly increasing order.
| null | null |
Medium
| null |
893 |
yeahyeah Hi Hi Hi everyone, I'm a programmer. Today I'm going to introduce to you a math problem that involves multiplication after groups of equivalent strings, especially detailed topics like Then you will be given a copy A consisting of strings, then it is defined that an internal move consists of swapping any two characters at the position at the indexes which are any even numbers. period of strings s or two positions of characters at any odd index tree of the second definition is that two strings s and T are called special equivalence If the following After each number of moves, you will become T. I see people have an example for the above two definitions. They have the letter S as a string consisting of z knowing x y and T are one For the string xy&z, knowing x y and T are one For the string xy&z, knowing x y and T are one For the string xy&z, these two places are equivalent, especially because we can make moves zz xy then it will become xy&z by it will become xy&z by it will become xy&z by swapping the characters at the position. The thing without subject is pressed with the character at the second position of the letter s, we see that the character is at the position, not the slipper, the character at the position, not at the second position is the idea, we change the place A and Together with That's exchanging the character in your 1st position and the character in your 3rd position, which means nothing and exchanging places with y. In the end, we will benefit xy&z and In the end, we will benefit xy&z and In the end, we will benefit xy&z and die, why do we exchange places? these two positions because these two positions are two positions with even indices as defined above, we only swap any 2 characters at the position with even indices or two irregular characters. If there is an odd index, this is the odd index S11 and three is an odd number, or if it is an even number, then after we swap places, we declare and change this place, then Tuyet becomes the subject. Just like the second definition is that the frog becomes a coin after any number of moves, then we call s&t two special equivalence strings. call s&t two special equivalence strings. call s&t two special equivalence strings. Okay, now we will move on to the problem requirements now. a group of special equivalence strings from A is a thing a face plus a negative a subset of a that is not so large that each pair curses you just met Strings in this group are specifically equivalent to each other and this place and the group are of the largest possible size without any constraints that are not in the group so that there are no constraints. Any right us that is not in any group so that for each I give special each string that group only Well then we will task we have to return the number of groups that have special equivalent strings together are built from a we just return to the number of groups of 2 hectares then now we will go into example one to better understand the requirements of the problem then give example one We have the main thing The first is a b c d the second is CD AB the third is cbd the fourth is xy&z the fifth is xzzx y fourth is xy&z the fifth is xzzx y fourth is xy&z the fifth is xzzx y and the sixth cylinder is zz IX then we see that we will have the first group of characters Following Then the following strings or the string ABCD, CD owner, AB and C owner, with ad, then these three groups of 3 owners will form a group where the strange characters go pair by pair, they will be strangely equivalent, special to each other then there is How can we check? We just need to check that the even numbers, the characters at the even numbers of these three places are the same and the characters at the odd digits of these three numbers are the same. like opposing each other with both even and odd numbers, then these indices are definitely equivalent, especially because when the letters are in zero positions and are the same, we just need to swap them in many ways to After creating many different permutations, we see, for example, if we look at the first one, the fish with even index is AC, then the second owner with even index is c a c AC, but it doesn't matter what the sign is. The important thing is that it's the same as all the characters, it's the same, AC and C are accepted. The third is just null, that's ck, then the odd number to measure the odd number is B, the first is PD, The second is DB and the third owner is also BD. I understand you find it strange that the characters at the even and odd numbers of these three places are the same, the only difference is before the word. Well, the order is different. We can use the number of times so we can change its position so that a little string becomes a force to become a subject, so these three places are three special equivalent Troi to each other pair by pair and then we have the second owner Who has the second group which is this group which is x y z and z x y then we see that this group produces a string of characters at the first non-miss position which is at least Z xz and the For the first non-miss position which is at least Z xz and the For the first non-miss position which is at least Z xz and the For the second subject, there are letters between even numbers which is cold then carefully the letters at odd numbers of the first subject are y z and the second subject is cold when yzy is also possible so we can infer that Yes these two bananas form a special equivalence group with each other and finally we have the last group which is the Z is group, this group only has one series because it will be specially equivalent to itself ha Okay So then we how many groups will we have in total a group 2 groups and 3 groups of many types we will return for example one is three then equivalently like that we will go into example 2 in video two we have If a piece has 6 ages, then the box corresponding to these 6 pieces can also be divided into 3 groups, each group has two strings and those two are specially equivalent to each other, we can easily notice that the first host a b c hey ABC this will be especially equivalent to C AB right c&b Hey a&c hey at equivalent to C AB right c&b Hey a&c hey at equivalent to C AB right c&b Hey a&c hey at Sorry guys it's ABC then it will be specially equivalent to CPA then there is ah the second host is a c b then it will be specially equivalent to BC CA and Bac can be specially equivalent to c a b Bac will be specially equivalent to that AB. That means it will form 3 groups, each group has two special equivalence chains with each other. so the return result of the program is three Okay, now we them now we will step into web scraping and proceed with algorithmic thinking to solve the problem for In these problems, we see that with characters and strings in common, they are also in the same group, so if we take Ha characters at even numbers, we take characters at even numbers and the characters at the odd index of a string then we put them together and we arrange A and we arrange in ascending order then 33 characters and ages are in the same group it will have the same string after we do it first and we take the order of the characters at even numbers. We sort then we take the characters at the index odd We arrange then we combine two banana trees after we arrange them together to form a chain then that place will be the same with all two places that place will be the same with all the characters in In group A, for this group, the string I we it will be. You see, for example, our sign is like that, right ? Well, you see, if we do ? Well, you see, if we do ? Well, you see, if we do it like before, it's The place we should put is a c then BD and AC are the characters at even numbers, we take them out and arrange them in ascending alphabetical order, then BD are the characters at odd numbers. We take it out and we also arrange it in ascending order for alt. Then we say the two topics together to form a complete place, AC BD, then this chain AC BD will be the same for all 3 things. this place, these three places, if the second cabinet we make is similar to the way we mastered this latest one, we will gun the AC cabinet bd this switchboard station AC BD chain similar then for For the second group, we have this. For the second group, we will have a string that we combine into something, then we call it by name, we take the characters at even numbers, which is less cold. Then the characters at the odd index are y z then you can see that there are few tickets after we sort them, they are also xsz after we sort them, they are also cold again. Then we say or curse back at you again, zyz and so on. here the host tree. Second, we also say again because of this word, we call these two places a chain that is created from all the chains in the group that are specifically related to each other, it will It's called a string, a standard string. Ha each word has a standard format, then in each group it will have an old one representing it. I understand the songs that have the last group included in this song. is what we will have is the place who are we Z In the group, we will put this place in to make that one map and we will mark this key as Chu bibury which means we already have a group where all the parts The goal is to create this place, then after we have a set, we go through all the chains and have to plant this piece, then we will create a map with a cutting list. The list of branches is this common server and the suitcase will be Chu, we just need to return the length of the key of the cooler and we will solve the requirements of this problem with Yes, I see I hope you have grasped the idea of our problems. grasped the idea of our problems. grasped the idea of our problems. Now we will proceed to install this problem in the Vu Lan programming language. First, I will declare a map, this map. I'm still a man's eye. Yes, my eye is cooled because after that. Then I declare with the map key. Yes. Then the other room and the curtain will make a word Trinh and my beloved bars are the owners. times is a variable once and then I will go through all the elements in the original fragment over all the strings in the original pieces that way I have a loop to create a list The index is taken and gets the string. Well, the place is called Ashley, let's go to this one to master the lace keyword, let's go to you guys a. Then we will declare 2 empty pieces, one of which is an odd number. Then I call it without the even-numbered male image, I call it y yellow. without the even-numbered male image, I call it y yellow. without the even-numbered male image, I call it y yellow. Then I will declare it as run MP which always means bye. When I browse through the strong Vietnamese including The Fast lane, it will become and then run MV Yes And then we will start reviewing the when we will start reviewing the sounds of each character in this pressed string , I will call the characters in , I will call the characters in , I will call the characters in this US I call it Intex and then the character I call father then I will browse through this place where Zen shouts and then I will check If my Indexes are strange then they are not Intex But if they are not then I will meet me an element in the fragment Isn't that right, it doesn't match me an element in you guys are definitely Ivan even father but in the opposite case it's an Intex again ah then I'll be flower D myself affair into the obod piece is the last piece and after we finish this filter, we have divided this string s into 2 groups: a group of this string s into 2 groups: a group of this string s into 2 groups: a group of even characters, zero and zero address characters. If a group is a group of characters in odd numbers, now we have to sort the letters in these two pieces in ascending order, and if we arrange the alphabet in ascending order, we call it a dotted basket. slide is a method in Cola that supports sorting, then we pass the piece we want to sort and must be even, then there is a division, let's sort it as yj type in. That means the Index is in front and I hate the back. and return one of the variables Buon Lang and then we will do the sorting by returning the y yellow in the y position but the small one is a little bit yellow in the expert position then I return the longer one. On the contrary, I return to Phone because now I want to sort in ascending order, and then we put the slide I a bede fashion similarly in fun and then I return to the brain to go smaller y go. After we have arranged these two things together, we will combine the two topics together. When we call a variable, then we declare a new variable. So I will append the Ivan first and then all the stars. Remember, add these three dots to get all the elements of its brain, add it to something and then return the results to it. Try to call that one, then we will get JJ. In the position assigned to that one. That means take this map, consider this tree and sell it. Then you mouse, then after we finish this loop, that is that we have gone through all the strings in you a we have built the cooler then here we are the length of a cooler this is the number of groups that we divided Okay, let's put the server parts in that group, isn't it strange? Yes, there is a special relationship with each other, so let's try running this procedure with example 1, I have one. Ah, this one. I'm sorry. Yes, I'll return it. I can't use these two. This one is Yin. It's not the main tree right now. We have to change it. I'm cursing. It's currently the word "bye." cursing. It's currently the word "bye." cursing. It's currently the word "bye." rust ah Yes. So we have returned the result of three which is correct with the result of the question. That means we only get this one. We divide it into 3 groups and then we will mic Yes to solve the problems. There are remaining examples. So I have successfully submitted the remaining cases of the problem. Now I will analyze a bit about the complexity of this algorithm. For these problems, we call N the number. Your broom a m is the length of the strings in the array ha then we have this is a drop multiplied N times by a filter ring each inside is M times then is n multiplied by me but We also have to add the sorting function, then this EVN hook has the worst length. It's also the same length as you, but its length is the same. So it turns out it's you, lol. Well the world is n but for m + m fashion m lol. Well the world is n but for m + m fashion m lol. Well the world is n but for m + m fashion m stay the complexity of our algorithm requires the complexity of the storage space we will alo n Because we use a map and the map This has the number of keys in the worst case, it will be equal to the number of curses in the number of strings in the network, then n then I will end the video here. Thank you all for watching if you find it interesting. Please give me a like, sub, like and share the experience. If you have any questions, comments or better solutions , you can write them down in the comments section , you can write them down in the comments section , you can write them down in the comments section below the video. Thank you for watching temporarily. Goodbye and see you, yeah
|
Groups of Special-Equivalent Strings
|
all-nodes-distance-k-in-binary-tree
|
You are given an array of strings of the same length `words`.
In one **move**, you can swap any two even indexed characters or any two odd indexed characters of a string `words[i]`.
Two strings `words[i]` and `words[j]` are **special-equivalent** if after any number of moves, `words[i] == words[j]`.
* For example, `words[i] = "zzxy "` and `words[j] = "xyzz "` are **special-equivalent** because we may make the moves `"zzxy " -> "xzzy " -> "xyzz "`.
A **group of special-equivalent strings** from `words` is a non-empty subset of words such that:
* Every pair of strings in the group are special equivalent, and
* The group is the largest size possible (i.e., there is not a string `words[i]` not in the group such that `words[i]` is special-equivalent to every string in the group).
Return _the number of **groups of special-equivalent strings** from_ `words`.
**Example 1:**
**Input:** words = \[ "abcd ", "cdab ", "cbad ", "xyzz ", "zzxy ", "zzyx "\]
**Output:** 3
**Explanation:**
One group is \[ "abcd ", "cdab ", "cbad "\], since they are all pairwise special equivalent, and none of the other strings is all pairwise special equivalent to these.
The other two groups are \[ "xyzz ", "zzxy "\] and \[ "zzyx "\].
Note that in particular, "zzxy " is not special equivalent to "zzyx ".
**Example 2:**
**Input:** words = \[ "abc ", "acb ", "bac ", "bca ", "cab ", "cba "\]
**Output:** 3
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 20`
* `words[i]` consist of lowercase English letters.
* All the strings are of the same length.
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
20 |
Hello everyone, Evgeniy Sulima, today we will look at solving the problem easily from number twenty, valid brackets according to the conditions of this problem are given to me from lines that contain only the following set of characters, that is, open and close rounded curly and square brackets and I also eat that given The line is felted to lead us is defined by the following that open brackets must be closed close a bracket of the same type that is large round curly square and all open brackets must be closed will be in the correct order with the empty string being the currency then there are 5 examples that is the first example hospitals without any questions the second example in a row three are open and closed all blame on Denmark the third example is not valid because we are trying to open close open round close square here everything seems to be correct but the order is wrong therefore the sauce and 5th example are correct because the nested ones here are correct pairs of brackets how can I solve this problem, that is, first of all, I understand that I have a fixed set of brackets that has a correspondence, that is, some kind of key-value, key-value, key-value, respectively, I understand that here it’s respectively, I understand that here it’s respectively, I understand that here it’s very, that is, I’m writing that I have cattle very, that is, I’m writing that I have cattle very, that is, I’m writing that I have cattle mcpatcher acts of the devil, let’s call it all mcpatcher acts of the devil, let’s call it all mcpatcher acts of the devil, let’s call it all breakers which is equal to new fashion man further into these brackets and I begin to put the elements that I need, that is, these are three pairs, that is, here now for a second we will align beautifully for some reason it didn’t turn out very beautifully for some reason it didn’t turn out very beautifully for some reason it didn’t turn out very beautifully I copy this line one more time here for me the key will be the closing brackets and the value will be the corresponding day of the opening bracket and here it goes like this further that where, for example, I received this line as input, now I have a melon stack in which I alternately know the plastic is not needed for the element, that is, let’s say I pushed it into the element, that is, let’s say I pushed it into the element, that is, let’s say I pushed it into the open bracket further I got a closing element, that is, I now analyze that if I have the data for this symbol in my keys about and then I understand that the element that is at the top of the stack, that is, the top element, it is equal to the value that is stored according to the code for this symbol if this is an equality the lines didn’t match, if this is an equality the lines didn’t match, if this is an equality the lines didn’t match, so it’s not valid and in so it’s not valid and in so it’s not valid and in the end I have to understand that it’s empty, the end I have to understand that it’s empty, the end I have to understand that it’s empty, I never received a message that I have a nice line, that is, some expressing in code, that is, a clear certain stack that stores characters and let’s just call it junction here I write new and let’s just call it junction here I write new and let’s just call it junction here I write new style and Williams further after that I loop through my line and is equal to zero and less than s . lynx ii i + + less than s . lynx ii i + + less than s . lynx ii i + + further games that each current element is named Richard Mullein with a charm and is after that I say that if the current symbol is not in the set of keys of my mother, yes I’m just a symbol, mine is yes I’m just a symbol, mine is yes I’m just a symbol, mine is so that is, if brackets edge else ki given 7 is a lie, then I say that the stack get and sign the entire given element, if I have it in a set of keys, then I have to check if it matches, that is, I say that I have some element of enchantment crowds, that is, if it becomes empty then I can , any character is acceptable? , any character is acceptable? , any character is acceptable? that is, their effectiveness is empty, then I’m returning it here simply for the reason? then I’m returning it here simply for the reason? then I’m returning it here simply for the reason? if you are not empty and I will stack and yes and please your top element and then the Negro what if my top is not robin breakers that is, there are elements that analyze then I return the falls there are short-range ones when then I return the falls there are short-range ones when then I return the falls there are short-range ones when I completely passed slept my lines and paste on all with my symbol in my line, I must understand that my stack remains empty, that is, I generally need to go out to these views from someone, that is, mopar everything is correct, the stack is declared in a loop, the links are written incorrectly, here everything is fine, then Char and Kandinsky and everything seems to be fine here, too, it seems that without errors, let the industry run this example, for example, the presence of compilation errors, that the first test, for example, it will work correctly trump rubrum, we are waiting to see that we need to try everything correctly using the example, and now it’s time to send the question to a solution for now it’s time to send the question to a solution for now it’s time to send the question to a solution for all the test cases that I had which if Gullit of the year we see that the correction solution is quite fast and the complexity of this solution in terms of time is aten because I need to go through all the elements and from memory also the hotel because I select a separate data structure that will store all the elements of the line ok, here we are We finish the video, in case of a survey, write in the comments under the video of houses, you’re all right
|
Valid Parentheses
|
valid-parentheses
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`.
|
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
|
String,Stack
|
Easy
|
22,32,301,1045,2221
|
1,254 |
hello so continuing on this lead code contest 162 the third problem was a 1 to 5 for number of closed islands and the problem says we get a grid that has zeros and ones zero represents land and one represents water and consider an island to be a maximal four directionally connected group of zeros that's basically what on a definition of help of an island here it's when you have connected group of zeros that in all five four directions it has ones as borders basically and we want to return the number of closed islands so you can see in this example here we have this number of zeros here that have the blue ones as border on all four directions and the same thing for this single to 0 over here and so as a result we return to all right if we look at the second example we have only one zero here that has border of one the rest don't have a border fun and so we written just one and if you draw this one you realize it has to these are the constraint and the grid has almost zero into one value so we don't need to worry about anything else and yeah so let's see how we can solve this problem so this is very similar to like counting the number of connected components when there are zeros but here it's a little bit different where we are using there is the one thing that is different here where usually in these kind of problems land is represented by one and water by zero here is the reverse that's fine we could just change the checks that we will do but with the connected components with the zeros we could solve it with DFS and so the first thing to come to mind here is let's just adapt the FS to work with this case and that's what I will where I will do in there in the overview here for solution okay so let's see how we can solve this problem so I just draw here an example so that you could see how to saw how we can solve something like this so the idea here is of this solution is to do two passes basically but still with the original idea of using DFS so two passes of DFS so what we were doing the first pass is our problem mainly is these here these this case here where we have the border here is not one so our the problem comes when border of a set of zeros of zero it's not one like any border right so that's our main problem so what we can do is just focus on this and those cases where the border is not one which are this one and then this one so in the first pass what we'll do is basically or place these with ones because these don't count we shouldn't count these as closer to ions right so just replace them with one's using DFS so basically what will happen here is that first pass of DFS fluid-filled we just fluid-filled this fluid-filled we just fluid-filled this fluid-filled we just fluid-filled this basically replacing with once all the connected 0s that have an edge that there is a border and it is zero right so flood-fill so flood-fill so flood-fill all connected component of zeros that have a zero as Porter as a border right and once we do that basically what I'll done after that and then in the second step just count the number of connected components of zeros right and using DFS also we can do this is the second step is the usual problem that we have we get something like this we have zeros as that are like have ones next to them and we wanna count the number of connected zeros or the number of components that are constituted of zeros so this is the original so this is the idea of what we all try to do so basically once it becomes like this and these values became one then after that is pretty straightforward to detect the components so with this one and like this and you could see it has all ones next to it and then the other one is this one and so right away we'll returns to as the result right so that's pretty much all there is to it now coding it maybe would be actually pretty straightforward I think just using the usual DFS so let's go this idea up and see if it passes the test cases okay so I'll start coding the solution so we said that there are two steps the first step is remove all zeros connected zeros that have zero as a border right and then after that just count the number of connected zeros or connected components of zeros so that's pretty much it and we are won't be relying on doing our DFS right and DFS will usually start from some at some point and then we will need to go through the first pass which is here we need to go through all fine basically these zero these places that have zeros as borders and so that would mean going through loss initialize I usually like this to be named em solos mmm and then we'd have N and M as the length of the grid and the length of the grid zero or actually now that I named it M should just do this and this is M and this is in range of M and now we need to look for peace in this case here and that case is first it had the volume has to be 0 right and after that we check if it's a border so and is in border I so what's past that time Jerry I must find that function or actually on Porter we sell let's do that so it doesn't mean for it to be you know on a border it's basically if the eye is either equal to 0 or I is equal it in the left border like the top border so is also a the top border or the bottom border right so that's n minus 1 or J is the left border or J is the right border right and only we need only one of them to be true so that it's either the top one the bottom one regardless of J or the left one or the right one regardless of I right so that's the first step so what we do if it is a bordo we know one of we want a fruitful and replace its value and all the values connected to that are zeros we want to make these to be once so I told to here is real DFS on that value and here DFS just flowed for the first and the places all connected zeros to IJ with one essentially right so we will have excellent way I'll just define a function that returns the neighbors of inj and we will just reply just DFS on the neighbor right that's what fluid-filled does and what we want what fluid-filled does and what we want what fluid-filled does and what we want what this function does is replace it with one so what we that's what we want to do so J equal to 1 and here we want to just make sure that we are not calling it in something that is out of bounds right and so for that to be out of bound it just needs to be like so basically let's just is out of bounds it's also to find something a function for that make this more readable or if it's already visited right and already visited we already mark that here with one so no need to add something else that like a visited set to keep track of that we are already changing the values if it's zero well or just changing it so different than zero then we want to stop right and also if the value is one which means we no longer have connected zero in this direction so we should stop also right and let's just write this one so for I and J and this happens basically when it's not in bounds right which means it's basically not between in the bounds I and or if J is not in the bounds right maybe out of bounds and then after that we will need to so now we did our DFS we need so we called it here so now we did the first step now the second step is just to count them right so we count the closed islands right so closed islands that's what we call the problem coordinates okay so let's just do the same traversing here so that we can count all the connected zeros right and so same thing here we check if the value is zero because it's not zero it's definitely not a start of a components that constitute a closed Island right and if it's equal to zero we do the DFS and since we remove the connected components that are zeros that are not closed Island because we replaced them with ones in this step that means we can just count any connected components now because we are sure now that it has borders one because others that didn't have borders one we replace them with ones right and so here we could just write away just count immediately like you are doing normal DFS counting the number of connected components and after that we can just return that and here I need to there is one thing that I didn't define which is calculating the neighbors of opposition and so the neighbors are just four so it's just pretty much for an I and J in so it's basically going left right top and bottom right so it's I plus 1 J I minus 1 J IJ plus 1 and I J minus 1 PI and 1 re Python has this handy thing called yield which will just basically return to a for loop every time and you value is returned by this so we could just do that like this we could also just copy this here and put it here it's just more readable to have neighbors here and that's pretty much it solace run this and index out of range so usually if it's so this is in range right and we are saying that and if it's not we want to actually its end so it's in range if these two are true and it's our range if the reverse so not of that right okay submit okay so that solution passes so one thing you can you could think of is okay so it's cool to you this is a cross solution but it chooses to DFS pass can we get this down to one pass right and that's certainly possible so let's see how we can change this solution here to do that and so we will keep we'll just remove this pass right we'll keep the rest because that's useful utilities here and now what we will be doing so how can we solve the solution differently so let me just get rid of these changes that I made here that okay so must leave this as zeros as it was before right so now the difference this solution since I want to do one pass so instead of doing this so this one here was solution one so instead of doing that solution to here so what would happen is that I would just do the second step except with one difference if I find any case where the if I find any case where essentially where the border here is zero I would not I would in my DFS our return false so if basically what would happen is that if in Dhahran DFS a connected component of zeros is found but with border as zero any border or any side return false right otherwise I return true otherwise return true right and that way what I can do is just count the number of true values so I would count and so basically what this means is my DFS now instead of finding the connected components of zeros it will find the closet islands of zeros right and so basically using just a boolean value valueless a called res that I will initialize to true so I would suppose that in my DFS that my Island is closed and then when I find 0 at the border I would say okay Mira's add to it that I found false right so that basically anything else any other neighbor that says okay true I'm still closed interval maybe because for example because of this zero where it has one and so it reports that it has ones as neighbors and this zero opposite has once as neighbor but this one would say I'm a boarder and so false and so ending it would force would mark the entire DFS of the component as to return false and since the entire check for that connected component is false I won't count it and that way I will be excluding all these connected components that have zero as a border just because I'm doing an end where anytime a border any points that is connected only to zeros and then their border is one returns true but if any one of them finds one next to it that has a border it will propagate false and that will end up returning false and I will end up not counting that element the other change is that to mark the visited set I will be using value two since value two is not in the array right because I won't be marking this as once so I would need to be careful there and just put the value two to mark visited and that's pretty much it I think for this solution the rest is just normal DFS that we all that we did in the previous solution okay so let us cut this up and see how it works and see if it passes the test cases okay so now let's cut that solution the second source and that we just saw and see it passes the test cases so I left these method that we'll be using for this second solution that won't change learning so what we said is that we will just check if any time we find the zero I'll start checking if that component of zeros is a closed island and so to do that I won't just call DFS on inj but first I will mark that position as visited and as I said mark I'm going to use the value two to mark a position as cell as visited so I would just say that IJ is equal to two and if so if this returns are true so basically my DFS will return true if the connected component of zeros is a closed Island right otherwise it will return false and so basically now I know that it's a closed island I could just say okay let's take my clothes island here and add one to them and I understand that at the end so now let's make my DFS return force so as I said I'll use a boolean that initializes to true so I suppose it's a closed Island first and then I check the neighbors and see if any of them finds a zero at the border because any zero at the border means I have I don't have a closed Island right and so if what does it mean to find a zero at the border if I reach a position that is out of bounds and I haven't reached a one position yet that means that I had a position at zero because one will block me from going to a neighbor right and so if so first let me just first do an inj in neighbors so I'll just use the neighbors that I had earlier now if is out of bounds so if this neighbor is out of bounds what does that mean let's hold on that for a moment and then now if the value is in bounds because we had we went to the else and the value is equal to zero that means that I'm still in a connected component of zero so I need to continue so I need to do DFS on that next position right but and we need to mark it as visited and marking as visited is just doing an i and j equal to two right now I said that I need to end the result with for each neighbor because if this one returned me for false saying that I found the zero at the border I should end it with this so that this overall can be false and so that I don't count it right so at the end my DFS will return the result right and this basically means is closed now if it's out of bounds if we reach it out of bounds right what does that mean that means we went here and we found that it's equal to zero at the borders right but we can but we called the neighbor so the value was 0 and then we went to the DFS and called the neighbor until we got out of bounds that means that we didn't find the zero that stopped us right so that means that we found a zero at the border and so that's the case where our is closed should be set to false right and that's pretty much all there is to it so this case here means that we found a zero at a position border and then we continued it to its neighbor and then we found a lot of bounds and at that point it's not crossed I hope this explanation makes it a little bit clearer um and so that's pretty much it now I we can just run this it's pretty much done right we have the other methods already and that's pretty much it self I didn't use it this is important in this case I could have just check it is in bolt or also in this instead of checking out of bounds on the next iteration yeah you could try that if you want let's just run this and then submit so this solution also passes in terms of time complexity you can see here while doing open by M right and then in the DFS we go through at most the entire grid because maybe it's entirely kind of consistent it's like all the grid has zeros and just the border is once and so at most it would be this basically squared because we are doing a DFS here in V internally so that's the overall time complexity here yeah I think yeah okay so thanks for watching and see you next time
|
Number of Closed Islands
|
deepest-leaves-sum
|
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1`
|
Traverse the tree to find the max depth. Traverse the tree again to compute the sum required.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
| null |
314 |
to solve legal question 314 binary tree vertical order traversal it's a median legal question so given the root of any binary tree return the vertical order traversal of its node's value from top to bottom column by column so there's an example here if two nodes are the same row and column the order should be from left to right so if there are in the same row another column it should be left to right so basically if you look at the example that they give here the tree the end result what it wants you to print is basically this 9 first if you look at the result and then 3 15 and then 20 and 7. so by looking at the answer you kind of get the idea is that the function you write is what you wanted to do is print the first align here basically the column everything on the first column here and then from top to bottom then this second column including three and five and the third column is 20 the fourth column is seven right if you take a look at the second example so in this case it should be four nine and then three zero one and then this is eight and this is seven and then what the requirement was saying is that there if there are two number there you wanna bring from left to right so then the third example that i give to you should be 4 9 5 and then the third column is 3 0 1 and then a 2 and then 7. so it's uh the tree notes is in range zero to a hundred and uh the company asked this question facebook bloomberg amazon microsoft facebook asked 1790 times in the past six months so if you're going for facebook you should definitely look at this question um so think about this problem we can look at the most easy example here basically it want you to print not like a lot only left to right but also like the by the column so one column this column the next one right so if we are using buffer search the layering order is definitely there because breakfast search is the printed by layer right if we use breakfast search then we also use our cue structure so what we need to do is um i'm i drewed our photo to make sure it's easier for you to understand here and this is how it looks so basically this is something look like this um the top row that i wrote here is basically the column number and then the live side the left side is the roll number here so the root node which is 3 and the column number is 0 and then the 15 is right here and then on the left side and then the 9 the column number is minus 1 because it's on the left side and the 20th column number is 1 and 7 is 2 right and then each row we just go down and the number goes bigger so let's say the root number is 0 and then the 9 and 15 is at the row 1 and then the uh row 2 and then row 3 right something like this um so basically what we wanted to do is that we want to use a like a hash table or hash map to store the column number and uh basically the key should be let me write it here so the key should be the column number and then the uh value should be a list of everything that is in the same column for example 3 and 15 are in the same colon something like this so this should be the value should be a list whatever it is on the same column should be put in the same value because their column key is the same so you get an idea how the hashmap should be looking at looking like and then we want to use the queue data structure and when we what we wanted to do is basically append the rule value and its call column index which is zero to the q first and then when we're popping from the queue we want to pop the node and also we want to pop the column index as well so there are two values in the queue so when we popping each time we pop we want to add its child so we will add the left node we will also add the right node when we add the node then we know that the uh each the column number for the left node it will be one column minus one and the right side will be column plus one if that makes sense and then um and then all the value will also be added to the hashmap while we are popping each layer by layer and then in the end when the hashmap has everything we want to store the hashmap by the colon so when we saw the hash map by the column we will get 9 13 15 20 and seven so let me show you how to do this in code here so what we wanted to do is or do a hashmap here default direct list right and then we want to use uh q um q equals dq and then we want to append the rule value uh and also the column index which is the 0 to the q first so that we can pop from the queue so while q what we're going to do is we want to pop the node which is the root node in this case and then the column number first right and then we want to equal q dot pop left and then we pop from the queue and we get this value and if um if the node exists right what we wanted to do is we wanted uh the column number in the uh hashmap what we wanted to do is continue to append the node value no double ball and when we append the node value we want to q also append the value to the queue so no dot left and um the column number will be column minus one because the left node is has smaller column number and then we also wanted to append the right side of the column so we wanted to say no dot right here and then the column number will be plus one in this case so after that we actually already have everything in the uh hashmap already um so in that case what we wanted to do is actually saw the result and how do you saw the result is that map colon for c in sorted and what we want to sort is sorted by map dot keys so in this case it will have the results sorted by the column number so the minus 1 column the 9 should appear first let's see yep let's submit yep so let me know if this is helpful or if you have any questions please like my video and subscribe to my channel and i'll see you soon bye
|
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,968 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem array with elements not equal to the average of its neighbors we're given an array of distinct integers and we just want to rearrange the values in that array such that any particular value in the array such as 3 is not equal to the average of its neighbors in this case given this input array if you look at 3 and you take a look at its neighbors 2 and 4 when you add those neighbors together take the average 2 plus 4 divided by 2 gives us 3 which is not what we want we don't want the neighbors of 3 to be equal to 3. so how can we rearrange this so that's never going to be the case well a brute force approach would be to take every single permutation of the input array numbers and then find one that works well that's going to be n a factorial roughly that's going to be the time complexity question is can we do better and the answer is yes there is a greedy algorithm which is going to be roughly uh n login because we're going to need sorting and then once we sort the input array we can actually build the array in linear time let me show you how so take a look at this example first of all we have five values right so five different spots where we need to put a value in and we don't want the averages of any of the values you know if we put a value here we don't want the average of the neighbors to be equal to this value now we're given the fact that every value in the input array is distinct so if we sort this input array it's going to be basically how it is right now right one two three four five it's already sorted so what my question to you is what is a way that we can place these numbers such that there's never gonna be a case where a value is equal to the average of its neighbors well basically right now we have one two three right two is equal to the average of its neighbors if you take one plus three add them together it's equal to the average of its neighbors you wanna know a way that we could guarantee that this would never occur if maybe just maybe we could guarantee that two like for example wherever two happens to be in the input array if we could somehow guarantee that for two its neighbors both of the neighbors left and right are gonna be larger than two how could it be that we could guarantee that we could put four and five on the sides of 2 right because if both of the numbers are larger than 2 of course the average of these two numbers is never going to equal 2 right is there a way we can guarantee that right what are we trying to guarantee for every single number we're going to guarantee that its neighbors are going to be larger well what about a number like 5 right 5 is the largest number in the array so of course we can't guarantee that both of its neighbors left and right are going to be larger than 5 how about we try to do the opposite how about for 5 we guarantee that both of its neighbors are going to be less than 5 for example we have neighbors 2 and 3 right these are available values in the input array let's say the neighbors are two and three if you add these two together and take the average it's not equal to five so then we're also good is there a way we can guarantee this that for every single value both of its neighbors are either going to be less than it or are going to be greater than it and yes we can guarantee this let me show you how it's really simple we just take roughly the first half of the values in the input array which in this case is one two three we place them we basically insert them into the array but we're skipping an index each time so we put a one here and instead of putting two in the next spot we skip a spot and then put the two here and then instead of putting three here we skip a spot and then put three here right we put some spacing in between these values next we only have four and five left we're to put 4 and 5 in the remaining spot so we're going to put a 4 here because take a look now its neighbors are less than it and we're going to put a 5 here so take a look at 5 both of its neighbors are less than it take a look at 2 and both of its neighbors are greater than it 3 and 1 are both edge values so this is a valid ordering and we both we all know that this would be pretty straightforward to actually code up this is a linear time algorithm other than the sorting portion that i mentioned so it's definitely tricky to come up with this i hope that i explained the logic pretty well and that you can kind of understand why this works so now let's go ahead and jump into the code okay so now let's code this up and remember the first thing we want to do is sort the input array so let's do that and we want to build the output array we'll call it result and we want to build this with a loop and the way i'm going to code this up you can do it many different ways is basically while basically until the length of result is equal to the length of nums we know we still have to add some elements so basically while this is not true we are going to continue to add elements now how are we going to add elements well we're going to start with we're going to add we're basically going to have two pointers right so left and right pointers because we're going to alternate or when we're adding values we're going to first add a small value then we're going to add a large value right we're going to alternate and how we do that we have sorted the input array we're going to have our left pointer be at the beginning and our right partner be at the end and we're going to alternate uh where we take values from so first we'll take a value from the left side so we'll say result dot append nums of left and then we'll increment that left pointer and then we'll do the exact same thing with the right side so result dot append nums of right and right plus one but actually it could be possible that we have an odd number of total elements so we don't want to end up adding a duplicate right so basically if our after we increment the left pointer if it ends up being greater than this right pointer then we don't want to end up adding an element multiple times so let's just make that check so if left is greater than right then don't do this uh portion so let's actually change this to if only left is less than or equal to right then we're done and we can go ahead and return the result and actually since this is our right pointer we don't want to increment it we want to decrement it so that we can shift it to the other side so sorry about that bug but as you can see this is the entire code and yes the solution does work so i hope that this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching
|
Array With Elements Not Equal to Average of Neighbors
|
maximum-building-height
|
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors.
More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`.
Return _**any** rearrangement of_ `nums` _that meets the requirements_.
**Example 1:**
**Input:** nums = \[1,2,3,4,5\]
**Output:** \[1,2,4,5,3\]
**Explanation:**
When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5.
When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5.
When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5.
**Example 2:**
**Input:** nums = \[6,2,0,9,7\]
**Output:** \[9,7,6,2,0\]
**Explanation:**
When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5.
When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5.
When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3.
**Constraints:**
* `3 <= nums.length <= 105`
* `0 <= nums[i] <= 105`
|
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
|
Array,Math
|
Hard
| null |
718 |
hey everybody this is larry this is day eight of the july leco daily challenge hit the like button hit the subscribe button join me in discord let me know what you think um it's already a week into july i hope everyone's doing all right keep that streak going and let's go over today's problem maximum length of repeated sub array so i usually solve this live so if it's a little bit slow um you know fast forward or uh watch it on 2x whatever you need to do okay so given two integer arrays numbers one of them to turn the maximum length of sub array that appears in both arrays okay so this is essentially um a sub array right huh one make sure so i think one thing that you um you get used to is kind of re making sure you're getting the definition right on sub and sub sequences and all that stuff you know usually um and i know that especially on code force or other things um they're very well defined and they kind of give you and then they even give you the refresher of the very precise definition but definitely some of the older problems and older judges they are a little bit reagan ambiguous about it um in this case it seems like sub array um yeah i mean i actually to be honest when i first read this i was thinking longest common subsequence which is a very straightforward um dynamic programming problem i mean it's not that straightforward but it is if you're starting out with dynamic programming that's going to be one of the one of those example topics that you learn right um like very uh yeah it's just one of those topics that you learn very quickly um but here i'm going to read sub array as contiguous right and what i mean by contiguous is just you know they're all next to each other the other thing to kind of think about is that n is only a thousand so given that you can actually do this in n square time pretty trivially um i'm trying to think whether that is the right move to do um and i think that is maybe well i mean with dynamic programming it would have been n square anyway but it with respect to the longest common subsequence instead of sub array but try to think whether it could so my hesitancy about doing it the end square way is that it is a very trivial solution um and it's already not interesting solution which is why i'm like is there something that's less uh less obvious and maybe more interesting maybe i'll take a hint on that okay but that is a real really weird hint i mean it is something that we talked about for longest common subsequence um and i wish that they had a better example that showcases this because for both of these examples it can still be either answer and i don't know why you would do dynamic programming for straight and square loop which is why i'm also even getting a little bit phone off by the hint unless i'm really miss oh wait is so the idea behind the n square algorithm maybe we'll just do the n square uh algorithm way and then we'll see whether my interpretation is correct um if i was obviously in an interview i would just ask the interviewer but uh i don't you know that's not an option right now so yeah so the n square solution is just basically okay so you have given these two arrays you have some offset to kind of adjust and then after that you can just go one by one to um to get the maximum length of the repeated sub array right so okay so let's do it that way and if it happens that this is going to be subsequent we could go with that solution too um if not then well then we just get the answer right so now we can yeah so now we can weight of now what i'm thinking about is okay what's the easiest way to write it without or with as few special cases as possible so let's um that's why the helper function that goes get longest yeah let's just say you get longest and this will get us get the longest common sub uh sub array where we shift num we shift nums too right um and what i want to do here is just that roni shift num so when we're talking about just adjacent you can actually shift them like in both directions right because you can think about it as let's say you have one two three whatever i don't know four five six um and then actually n times two type ish shifting because you can shift this all the way here um so that there's overlaps and oops and you can also shift the one on the bottom and if we have one but they um they have a similar solution right so you can actually just write it once and then um change the order or something like that uh well and if that doesn't make sense yet uh we'll go over it yeah so now so the number of offset is the uh n is equal to length of numbers one m is equal to length of nums two say and then we have four offset is in range of n because we want to shift only nums too yeah then it so if num maybe we could write a helper function here as well so yeah let's do that so best is equal to zero best is equal to max of best get overlap maybe uh numbers one nums2 offset and then we just return best and then here we can just get the overlap numbs one nums2 and then offset and here we just move we just start num still with that offset so yeah so best is equal to zero count is equal to zero current count so we have four index is in range of um let's see where so basically is it n or m i think so basically the statement is if nums1 of index plus offset is equal to nums to the index then we do count increment by one else count is equal to zero um because if they're not the same then you know it's not going to take us anymore okay so then now this just basically goes until um i guess technically m but we also need to um yeah make sure that is within n and you can actually early terminate by breaking i know but i'm just trying to make sure that this is right so far and then we can in theory optimize later so then now we just return get longest of numbers one number two and then get longest of the other way numbers two numbers one due to symmetry and that's kind of the things that i would look for right it's symmetry so that you can um code things in a easier way i think that's the other example and then now here we can actually test if they mean longest repeated or longest common subsequence like array or a sub array i suppose um yeah and we can test that by having just i guess even here should be okay are they the same length nope okay basically yeah okay so that's good and then our assumption is correct because here we can see that we haven't for if there's a subsequence then this is you know four instead of three so okay so let's give it a submit oh okay um yeah i mean this is before we go over it i'm still curious about the dynamic programming solution in the sense that it doesn't i mean you can't do it that way obviously it's the same as uh the longest common subsequence except for in a very spec in a more specific way but i'm curious whether there's a solution that we missed but let's go over this one real quick um so this one um here we do it twice where we just you know like i said we shifted to the left shifted to the right um and shifting it to the left is equal to um swapping the arrays and then shipping it to the right so that's why we have we do this thing here um and then here this is going to be an obvious o of n time because uh this is all the iterate the loop iterates over n times um because well you only have you have a for loop and here it also um you iterate it over m times say uh n plus m because with whatever is shorter i suppose um so this is going to be n squared and we only do it twice so yeah at the end this is going to be n plus m squared roughly because that's the notation of uh so yeah so overall time m square and space is going to be o of one right because we don't we just keep pointers and i have a couple of variables yeah so that's all i have for my um code hope this is good i'm going to click on this to see what the intended solution is because i think that i know that there's a dynamic programming one but it seems unnecessary which is why it was a little bit of a confusion slash um yeah i think this is the more naive one um but yeah you should not do it that way because it's n cube say binary search with naive check why do they write all these weird algorithms dynamic programming i guess so i mean binary search with rolling hash wow why would they write such weird ones oh i didn't realize actually let me think about this um that is maybe interesting one but it requires a lot more math obviously with you know inverse modular inverse and stuff like that but we can binary search for the answer i guess so i mean yeah i mean this answers are uh actually it's kind of amusing because this is literally um the problem that we had for the last q4 except for we only have two numbers instead of or two arrays instead of k arrays so um so maybe if i if we had done this uh problem last week or something then we would have done it really well in the contest if we looked up the solution um but yeah um but for that video definitely well just check out my video from for the q4 on the contest that's all i'm going to have for this one for today stay good stay cool have a good rest of the week i will see you later and to good mental health bye
|
Maximum Length of Repeated Subarray
|
maximum-length-of-repeated-subarray
|
Given two integer arrays `nums1` and `nums2`, return _the maximum length of a subarray that appears in **both** arrays_.
**Example 1:**
**Input:** nums1 = \[1,2,3,2,1\], nums2 = \[3,2,1,4,7\]
**Output:** 3
**Explanation:** The repeated subarray with maximum length is \[3,2,1\].
**Example 2:**
**Input:** nums1 = \[0,0,0,0,0\], nums2 = \[0,0,0,0,0\]
**Output:** 5
**Explanation:** The repeated subarray with maximum length is \[0,0,0,0,0\].
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 100`
|
Use dynamic programming. dp[i][j] will be the answer for inputs A[i:], B[j:].
|
Array,Binary Search,Dynamic Programming,Sliding Window,Rolling Hash,Hash Function
|
Medium
|
209,2051
|
1,286 |
in this problem we have to design an iterator class and that iterator would support two methods or one will be to check whether next exists or not as next and the other one will be to get the next so what we will try to get here so you must have studied about actuators in different containers in languages like so for example we have iterator for vector list and so on and these iterate through the elements of the vector so there the value returned are the actual values stored here so here the iterator has to return one combination from a given input so first there will be one input string it will have some characters all in lowercase english letters in sorted order so this may not be abcde this can be like a k l m r so these are sorted orders this is input string and you will be given one length let's say three so what we have to do there are different ways of choosing three characters out of this larger string so that's how this combination term is coming so choose three characters from this and then these should be sorted and first time we will return the smallest possible string so for example let's take a look at an example so here we will define one constructor there we will pass an input string s and let's call it k so first time we call next it should always return this next should always return a substring out of this not substring but uh it should pick two characters from this not necessarily contiguous and first time it should be the smallest sub smallest string out of this so smallest 2 character longest string can be a b next smallest would be ac next it would be bc so first time we call next it should return a b the smallest one and has next should return true since there are more possibilities next time we call next it returns the next largest that is ac and again has next is true since there are more combinations possible and next time we call next it should return bc and in this case only three combinations are possible due to this simple formula and choose k so here n is 3 the length of string and k is 2 so 3 c 2 is same as 3 c 1 which is same as 3 so it's 3 factorial divided by 2 factorial divided by 1 factorial so it's 3 times 2 factorial divided by 2 factorial so this 3 is coming from that and now we have called next three times so if we call iterator dot has next it will return false since we have returned all the possible combinations of length two in alphabetical lexico lexicographically sorted order now let's look at one more example then we will see how to solve it so let's say we have a b c d e so this is the input string and k is 3 so we will start from a b c this is the smallest then a b we keep constant we will change the last one since we are looking in the sorted order so these are already sorted abc so we keep a b constant the next value is d then a b e then what can be the other possibility uh a c d a c e so now we have changed the second character so first we were trying to change the right most character we have exhausted all the options here then we come one step back and try to change the second character so that we have written all the possibilities with the smallest character as the first one and this will be lexicographically smaller a c d a c e and then a b e another possibility with starting with a so let's write b c d b c e and b d e and finally c d e so how many of these are there 1 2 3 4 5 6 7 8 9 10 and this comes from here its length is 5 so 5 choose 3 which is 5 factorial divided by 3 factorial divided by 2 factorial so it's 5 times 4 times 3 to 1 that is 3 factorial 2 factorial is 2 into 1 so this cancels 2 and it's 10. so how we should solve it so in this problem either you keep track of what was the last combination that we returned so we keep track of that in our class so we have to define a iterator class so previous value returned and next when next call to next comes then we will check what is the immediate larger value possible using these characters or the second approach would be that we pre-compute all of these and we pre-compute all of these and we pre-compute all of these and store them in a vector or a list and whenever next call comes we return the first one from the queue and then pop it so once next call comes we return abc then we return abd and we keep popping it and when the queue becomes empty uh has next if has next call comes we will return false otherwise we will return true and it has been given that you have to instantiate this class once but these calls will be made many times so it makes sense to store them process them once so that all the further calls of next and has next will be of one so let's see the approach so the main challenge here lies in generating and storing all these combinations other than that this next will simply return the first element and pop it and has next we'll check whether this is empty or not so the main job lies in the constructor itself so let's say we are given a string a b c d and we want abcde and k is three so how we generated it so we wrote here we started with abc in the first three characters so we can have one function let's say this is a recursive function where we pass the starting character and let's keep a q which will be empty so this is the starting position 0 and length is 3 so 0 3 and currently the text that we have formed is empty and what this will do it knows that we have to start from zero so it will immediately append the character at zeroth position that is a and then so we can call it text so text becomes a that is character at zero then we can call so we have included one character so the remaining length is one less and we have included the first one so the next starting position so we have included a and now we are looking for all the uh combinations from b to e and its length should be 2 so we pass 1 as the starting position length becomes 2 and the character becomes text becomes a so we will keep appending to it so again at position 1 it's b so append b to the existing text so it becomes a b so we call f starting at two the remaining length is one we already have two length and we pass the string a b then it will again append this character at position 2 which is c so it becomes abc and then call f start at 3 length is 0 and abc so in this we can add a condition that when length is 0 that is no more character needs to be added to this we will append it to q so now this abc comes here abc then this call will terminate so we add it to the queue and return so this will return and then delete it so we could have written here a b plus c so this now becomes a b and it will again call f 3 so make this text abd now so we had taken this c so take the next value of next character d and again call this finally all of this will return a b starting with a b d a b e then this call will return and now we will remove this b also so we will append the next character of b that is ac and repeat the same thing with ac as the first two characters so ac it will append d first time acd then remove the last one and the next character g so ace and remove the last one now there is no more character so we stop so this call will also return with ac so it will now become a d so in place of c we will add b and the same thing will repeat so a d is there next character is e a d e and now there is no more character here so this a d thing returns and next time here we delete d also so we have written everything with a so this a is again returned from here and we add next character that is b and again the same thing recursively repeated so b is the first character then starting position we will call for from 2 to length 2 so it will first append here b c then call with a length of 1 it will append d and next call with a length of 0 so length 0 means we have to enter it here delete d add next character delete e no more characters so return back and here it will delete c and add d and the same thing with bd so bde and nothing to add so it returns here so now it cannot add e here since there will be no more character so again it returns and now the next character will be c so repeat the logic with c so it will call c d and it will call c d e cde will be added here it will return here it will try it cannot add ce since there is no more character here so it will return with this so how should we implement it so here is a pseudo code of this let's say this is the queue which is empty initially this is the input string this is the length of this string and k is the length of combination so this is the case where we are inserting so the required length is zero so this text already holds a string of length k that's why this length is 0 so we insert it into the queue so this is very trivial and the main body of this function is i equal to start to l minus length so length is the required length of string so if this is the input string and its length is l so if starting position is here start then what is the smallest value that can be possible this should be at least length we can start anywhere from beginning till here or our start should be such that we should have a length so from start till some point where the length is length this required length because if we go beyond this if we start beyond this then the number of characters is less than length so we will never be able to form a such string that's why here i is from start to l which is the length of original string minus length so if we start from l minus length then if we take all the characters it will be of length l so that's why we will stop i when we reach l minus length there is no point in looking forward so what we did here in this case so we took uh c and then we did not try with d as the first character since we know that we cannot form d e and something else three character long so we stop at c so let's write the code for this so the hint that is there is that generate all combinations as a pre-processing since there will be as a pre-processing since there will be as a pre-processing since there will be multiple calls to the next and has next so let's save this string in the class so here we will save it so s equal to this characters and we should create a text empty text and then we will define a function so we start from next one i plus 1 and length becomes length minus 1 and d x t plus starting position is zero length is this text is empty so this we call from constructor itself so this will uh create all the combinations and insert it into the queue so our job is very simple now and we why we are not adding here check that if it's not empty then only push then only pop because it's guaranteed that all calls of the next are valid so we don't need that check here so there is a mistake here and the solution is accepted and we are right here at point two seven percent now let's write this in java and python so here uh since we need to add to this text we need to use a string builder and this would be q dot add q is of type int a string so we need to convert this string builder to string and the java solution is also accepted and again we are in the top zone finally let's do it in python 3. so and here we did not set s since it's already accessible and the python solution is also accepted
|
Iterator for Combination
|
constrained-subsequence-sum
|
Design the `CombinationIterator` class:
* `CombinationIterator(string characters, int combinationLength)` Initializes the object with a string `characters` of **sorted distinct** lowercase English letters and a number `combinationLength` as arguments.
* `next()` Returns the next combination of length `combinationLength` in **lexicographical order**.
* `hasNext()` Returns `true` if and only if there exists a next combination.
**Example 1:**
**Input**
\[ "CombinationIterator ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\]
\[\[ "abc ", 2\], \[\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, "ab ", true, "ac ", true, "bc ", false\]
**Explanation**
CombinationIterator itr = new CombinationIterator( "abc ", 2);
itr.next(); // return "ab "
itr.hasNext(); // return True
itr.next(); // return "ac "
itr.hasNext(); // return True
itr.next(); // return "bc "
itr.hasNext(); // return False
**Constraints:**
* `1 <= combinationLength <= characters.length <= 15`
* All the characters of `characters` are **unique**.
* At most `104` calls will be made to `next` and `hasNext`.
* It is guaranteed that all calls of the function `next` are valid.
|
Use dynamic programming. Let dp[i] be the solution for the prefix of the array that ends at index i, if the element at index i is in the subsequence. dp[i] = nums[i] + max(0, dp[i-k], dp[i-k+1], ..., dp[i-1]) Use a heap with the sliding window technique to optimize the dp.
|
Array,Dynamic Programming,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
|
Hard
| null |
79 |
Hello Hi Guys Welcome To Our Dhundhi Si Today We Will Go Through 321 Problem Light Ko Challenge Word Search Please Like Video And Don't Forget To Subscribe To Our Channel Never Miss Any Update On Ho Gayi 120 Board And Word Find The Word You Can Be Constructed From Letters of Sequential Different Cells to Juice and Cells and 200 Gently and Vertically Neighboring Nasim Latest Cell May Not Be Used in This for Example Aged First Second Third President The Great Kind Legitimate Agent Beautiful Program Returns Through for Boys 2 and Falls Over the World With This app you can strings attached question on is actually good example to learn about writing which will be learning in next few minutes in lips then give an example to the world will be left to right and continue to research in all directions for this most important question The Program's Exit With Here Of One State The Gold Was Found All The God Weight Front Documentary Condition Arises Only Dire Board And History Positive Width Sell Point Is The Character Did Not Match All His Condition Which Will Lead The Program Returning Officer Meaning Of The Word Weight From The Last Condition Is Well In Bihar After Match For The Whole Board In This Case Also Return To The Second Condition Tax Return Forms In The Sale Is Visit And Know How To Know The Celebrity Nude Need To Market Presented By Assigning Sub Differentiating Value are the great only content letters wikinews special characters and numbers for making profits in this example straight between all the directions cat to forms a ki sui back to the starting letter unreported value back to s love will again started searching for status in full screen status Will visit and research in law for interactions has apk file to matches brain visit and such rate members receiver match at the bottom the top vivek tarf developed a citizen end of the world will return through this was the complete backtracking process is laxative in the Form Panel Gautam Degree To Mother Board And All The Records I Third To Source Current Platform 5 Episode Method Returns Through It Means Award-2012 Method Returns Through It Means Award-2012 Method Returns Through It Means Award-2012 Return To Others Spirit And Falls On That In Soch Mein Thoda B.Tech Board Word Soch Mein Thoda B.Tech Board Word Soch Mein Thoda B.Tech Board Word Problem In Index Of Water Resources Parameters Posts Tagged Condition Apply Condition Total Subscribe Now To The Current Character Search Index Is Equal To The Last Visit Us On Twitter Visit Us On A Dozen Next Power To The Question Ladies More Advanced Cold Not Be Sworn-in Ladies More Advanced Cold Not Be Sworn-in Ladies More Advanced Cold Not Be Sworn-in But Instead Of Finding One Word For Any Two Find the list of present in the food at some places of interest in construction linked together to strange time constraints on another account video her shoulders top and also in description the time complexity years in the forest wealth of sales in is the length of the city of Make the question maximum to the length of Who is the capital goods Update from the method Ignore to final * 10th dinner Ignore to final * 10th dinner Ignore to final * 10th dinner Description Bills Thanks for watching the video This line The video Please like share and subscribe our channel Pad Media Comment Protein Kabaddi Video
|
Word Search
|
word-search
|
Given an `m x n` grid of characters `board` and a string `word`, return `true` _if_ `word` _exists in the grid_.
The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.
**Example 1:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCCED "
**Output:** true
**Example 2:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "SEE "
**Output:** true
**Example 3:**
**Input:** board = \[\[ "A ", "B ", "C ", "E "\],\[ "S ", "F ", "C ", "S "\],\[ "A ", "D ", "E ", "E "\]\], word = "ABCB "
**Output:** false
**Constraints:**
* `m == board.length`
* `n = board[i].length`
* `1 <= m, n <= 6`
* `1 <= word.length <= 15`
* `board` and `word` consists of only lowercase and uppercase English letters.
**Follow up:** Could you use search pruning to make your solution faster with a larger `board`?
| null |
Array,Backtracking,Matrix
|
Medium
|
212
|
34 |
Hello everyone Udayveer what position of elements for kids wear hai to janma chayan hai designer targeted to find lots of number three to the number 108 name - The Video then subscribe to the name - The Video then subscribe to the name - The Video then subscribe to the Page 10 class 5 by two Ajay ko ki hero plus five by Doing so or the answer is two to medium size 2012 this is the phone that no what will oo will apply to stay away from the brain research in the mid-day that they drivers in this cream and targeted violence bill to me - withdraw targeted violence bill to me - withdraw targeted violence bill to me - withdraw from - 2 from - 2 from - 2 To Phir Tu Aise Moderation Ab Line - 1090 Do To Phir Tu Aise Moderation Ab Line - 1090 Do To Phir Tu Aise Moderation Ab Line - 1090 Do Not Function On Tomorrow Morning Harpal Singh And Nurses Parameters In Neither Interactive White Board The Number 56 Minutes Ago Channel Ashram Trust Plus One Day Target Plus One To The Place Where The Voice Messages Also Calendar Forex Advisors Wearable Last Updated On That Sahiya Settings Condition Hello Friends 111th Size And Number Of Indian Republic Day To All Is Normal Chinh Ko DCM Ko Deals For The Brain Research Child First Time E Hey Brother Calling Apps Function in this game is the last updated one - Close Is Medium To Calculator Loot - Close Is Medium To Calculator Loot - Close Is Medium To Calculator Loot Minus Point Play To Log In Yo Honey Battery Force Tours Space Odysse Awal Ki Sudesh Dhawan Can Watch This Video More Elements
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
458 |
hello everyone welcome back here is vamson with another life coding uh challenge so today we got a fun coding challenge line up uh if you ever wonder how many pigs you would need to find out which bucket of water is poisonous well you are in right uh to find out uh all right so here's the problem statement we have a certain number of buckets and uh only one of them contains a poisonous substance and we'll also have some PS and a fixed amount of time to determine which bucket is the poisonous one and the challenge is to determine the minimum number of PS we need to figure out uh this so here is the quick uh example let's say h you have four buets and two picks so you could potentially fed pick one from buckets one and two uh and pick two from bucket uh three and four and if pick one dice you know Theos in the bucket is either one or two and if PS two dice it's either three or four and so on so all right let's uh really break down the logic behind this problem so the idea here is more mathematical than uh it initially appears and resolve around uh encoding States so imagine you had an uh yeah uh hugas that runs for a certain duration let's say the time uh it takes for a pig to show sign after drinking from a poisonous bucket so now given a total time frame you can flip uh this uh hourglass multiple times and in our problem this uh flipping of The Hourglass is equivalent to the time a pick drink from different buckets within the total test time so if our total test time is 60 minutes and it takes 50 minutes for a p to show science uh we can uh test the peak four times and this uh give us an encoding system so each time a pig drinks uh it adds another state another possibility so in the 60 Minute example a pig can drink at the start then at 50 minutes Mark then at 30 and finally at 45 and this single Peck can uh now uh help us differentiate between five buckets so it could show signs after the first second third or uh fourth uh drink or not at all so now here is where it gets even more interesting if we introduce a second Peak we exponentially increase our testing capabilities so the two PS together can help us differentiate between five time five that's 25 buckets so this is because they can drink from different combination of buckets at a different time creating a matrix of possibilities so in essence each PE we uh introduce increase our testing capabilities exponentially uh based on the number of times we can test within the given time frame and our task then becomes uh determining the minimum number of PS requires to cover all the buckets using this exponential encoding system and it's a bit like a base conversion problem in mathematic where uh we are trying to find a number in base X which can represent another number in base 10 only here our base is determined by the number of times we can test epic so all right let's start cutting this out so first we will handle an edge case uh if there is only one bucket we don't uh need any PS so we will return zero so if uh bucket equal one we return zero and now uh let's determine how many uh times we can test a single p uh within the given time frame so he will be minutes to test mod uh without remainder minut to die plus one and PS will be one so while key uh to the power of PS less than buckets uh P will be plus one and return number of PS so uh we initialize our pick count to one and then look to see how many buckets a given number of pcks can test so now uh for the fun part uh yeah and then we are counting to the uh Power of uh PS uh yeah uh so basically uh we are increasing number of pics every time by one and uh testing uh the loop to see how many buckets given number of pick I can test and if it's uh valid or not and if we reach a valid number of picks uh that can test all our buckets in given uh time we return number of P so let's run it to verify if it's working so yeah all good uh so buckets minutes today minutes to test and output two so now let's submit it for unnest cases to double check uh it's working as well so yeah all working perfectly and our implementation bit Yeah 68% with respect implementation bit Yeah 68% with respect implementation bit Yeah 68% with respect to uh runtime really interesting so previously I coded exactly uh same logic and yeah so really interesting I get even 99. uh2 uh milliseconds uh 99.2 bitting and uh2 uh milliseconds uh 99.2 bitting and uh2 uh milliseconds uh 99.2 bitting and 24 millisecond so now uh 39 so as you can see this person uh on runtime test is quite uh high but basically this uh solution is uh quite optimal so let wrap up uh our coding challenge for today uh I hope uh you enjoy it and uh yeah it's always fun to see how mathematical Insight can uh help solve a seemingly complex problems so if you enjoyed this video don't forget to uh hit the like button and uh for more fun coding challenges uh tutorial machine learning and much more uh yeah make sure to subscribe and also I will provide implementation in other programming languages like R go uh C++ and much more languages like R go uh C++ and much more languages like R go uh C++ and much more uh in the description below so keep practicing stay motivated and happy coding
|
Poor Pigs
|
poor-pigs
|
There are `buckets` buckets of liquid, where **exactly one** of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have `minutesToTest` minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
1. Choose some live pigs to feed.
2. For each pig, choose which buckets to feed it. The pig will consume all the chosen buckets simultaneously and will take no time. Each pig can feed from any number of buckets, and each bucket can be fed from by any number of pigs.
3. Wait for `minutesToDie` minutes. You may **not** feed any other pigs during this time.
4. After `minutesToDie` minutes have passed, any pigs that have been fed the poisonous bucket will die, and all others will survive.
5. Repeat this process until you run out of time.
Given `buckets`, `minutesToDie`, and `minutesToTest`, return _the **minimum** number of pigs needed to figure out which bucket is poisonous within the allotted time_.
**Example 1:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 15
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig buckets 1 and 2, and feed the second pig buckets 2 and 3.
At time 15, there are 4 possible outcomes:
- If only the first pig dies, then bucket 1 must be poisonous.
- If only the second pig dies, then bucket 3 must be poisonous.
- If both pigs die, then bucket 2 must be poisonous.
- If neither pig dies, then bucket 4 must be poisonous.
**Example 2:**
**Input:** buckets = 4, minutesToDie = 15, minutesToTest = 30
**Output:** 2
**Explanation:** We can determine the poisonous bucket as follows:
At time 0, feed the first pig bucket 1, and feed the second pig bucket 2.
At time 15, there are 2 possible outcomes:
- If either pig dies, then the poisonous bucket is the one it was fed.
- If neither pig dies, then feed the first pig bucket 3, and feed the second pig bucket 4.
At time 30, one of the two pigs must die, and the poisonous bucket is the one it was fed.
**Constraints:**
* `1 <= buckets <= 1000`
* `1 <= minutesToDie <= minutesToTest <= 100`
|
What if you only have one shot? Eg. 4 buckets, 15 mins to die, and 15 mins to test. How many states can we generate with x pigs and T tests? Find minimum x such that (T+1)^x >= N
|
Math,Dynamic Programming,Combinatorics
|
Hard
| null |
71 |
Hi everyone, I am Nishant and you have joined with the entry. In this video series, we will prepare for the interview by doing a lot of questions of lead code, so which question are we going to do today, let's see let's dive in. Hi everyone, I am Nishant. Entry from Elevate Hindi and today we are going to solve problem number 71 on Lead Code, Simplify Path, so this is a medium level problem marked, it can be solved very easily by using Butt Stacks on Lead Code. Let's see how. First let me read the problem, after that we will see how to solve this problem. Here the problem tells us to give a string path which is an absolute path starting with a slash to a file and directory in yx file system convert it. To the simplified canonical path, in Yx base systems using slashes, dots, and names, any file or directory entry is denoted by a dot that refers to the current directory entry. Meaning, if there is more than one slash, they are treated like a single slash. Any other format for this problem, i.e. like a single slash. Any other format for this problem, i.e. like a single slash. Any other format for this problem, i.e. three periods, will be treated as a directory entry. Okay, it is written in the question. Let's see further. Canonical path should have the following format, so what should be the format of canonical path and it is written here that path starts with single slash should start with single slash. Any two directories are separated by single slash. Any two directories should have a single slash. What you want to separate is Path does not end with a trailing slash. What you end up with is Path does not end with a trailing slash. Path only contains the directory entry. So this slash should be removed from here. Okay, so here's the slash twice. Period and then slash, so what does the slash mean? Here, first slash is the root directory, then two slashes here means go up once and then slash means come back to the root, so here only this is okay, so this is one level up. There is no work done there, above the root level, then this is the highest level you can go to the root, you cannot go above that, so it stayed here. Okay, further it is written slash home, double slash fu and slash, so this is the double slash. This will be converted into a single slash. Okay, so it will become a path in this way and the last slash will also be removed and then bin and then slash and then lib. The path is written something like this here then two slashes and then here. On the project, suppose any path is written, then we can solve it by using stacks. How to do it? First of all, what we will do is that we will get the string in the beginning and we will write this slash here. If we split on this basis, then if we split on this basis, then what will we get here? What will we get here? First of all, this is home, then this user, then these two dots, then this bin, then this lib, then this here. The MT character will remain MT and then this project is fine in this way, so if I do this, here I take a stack, okay, if I take the stack, then inside the stack here three types of things can come, what can come? If I separate everything here with a slash and then I am looking at these tokens which are marked in red, these red tokens can be of three types, one can be double dots. Okay, these double periods which are going to go up one directory can be one, this single period which is going to go up the current directory entry will be a single dot i.e. the current directory entry so see here what will I do if I am encountering a double dot then its Meaning, I have to go up one directory, okay like here there is home, then user, then there is a double dot, so double dot means I have to go up one directory, so I went from home to user and then after user I added this double dot. If I encounter, I will have to come back to home, then what will I do? If I get any particular name, then I will push it in the stack, like here I am looking at home, so I pushed home here, okay. Home Okay, I pushed it this way, then I saw the user. I pushed the user this way. Okay, I pushed the user this way, then I saw the double dot. Double dot. If I see it, I am this one who is the user. Right, I will pop it from here. Okay, I will pop it from here, so it will go here like this. Then I saw the bin, so I put the bin here. Okay, then I saw the lip, so I put the lip, then this MT here. If there is a thing, then I left it as MT, did not put it, then later I saw the project here, I put the project, okay, in this way I put all these things inside it, okay, so this is all the work I have done here, see first. I have split it with that slash, after that I have created a stack, then in the stack, I have done the same thing that after splitting the array that will be formed inside the array, pick each string of it and if the size of the string is not zero i.e. This thing is not zero i.e. This thing is not zero i.e. This thing is not being encountered here, if this string is not MT and if you see this double dot in the string, if you see double period, then if the stack is not MT, not the stack is MT, in that case pop it from the stack. The last value that was given is fine, if it is a single dot then don't do anything, look here I have written the pass, it is fine and if there is anything other than these two then push it inside the stack like any name is fine, for now this much The work is done, okay, this one which was to be my stack, it has been made, now look at the canonical simplified canonical path from this and how I will create it, from here I will go through this stack one by one, then here I have bin, so here But the bin has come, okay, in this way, the bin and then at the top, home, okay, so in this way, the home has come, okay, now if you guys look carefully, this home sl become slip sl project, this will be my simplified canonical path, so look again. Here I have done the same thing, this is a stack named temp, in this I have pushed the old stack from it till the MT is not done, I have pushed it into the new stack named temp and then I have pushed it. I have taken a string builder and then I am appending one by one its elements inside it by slashing until it is a tam stack MT, by popping it, okay, at last I have added that string builder to the string. One more thing to keep in mind is that if the length of your string at the end is zero, that means there is nothing in it then atleast you will have to put a slash in it, so I have put a slash here in this way, okay once. Try submitting it and see that it is being submitted comfortably. If it is ok, then this problem can be solved very easily by using stacks. I hope you have understood. I will meet you in the next video [ you in the next video [ you in the next video And
|
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 |
901 |
hi everyone so let's talk about the online stock span so basically the span of the stock price today is defined as the maximum number of consecutive states so this is an important keyword for which the stock price was less than or equal to today price so i'm going to just uh quickly go over it so um at first i wasn't sure what was happening but i'm going to tell you what's happening so if i'm the day one right there's only one price right so this is only one price is actually less than or equal to today price so you will say return one right and then move on to the next day so the next day is going it's going to be 80. so 80 is what it's curve it's going to be one day for sure right but the problem is the previous one is what the previous one is greater than 80. so you don't uh you cannot count this two so this is still only one and you are going to do the same thing for the 60 right 60 you i mean the previous price is what it's actually greater than your current price right so uh so you say goodbye to this one so it's still going to be one and go on the 70 so 70 y so the previous price is 60 and your current price is 70 right so which is what let's say equal to the current price so you have two right now uh move on to the 60 so 60 is going to be the same because the previous price is 70 so it's still going to be say one and then 75 so 75 you have well you have two days for the price uh lower than 75 but you also have to come as your current one so which is going to be what three but there's another one so it's going to be four sorry so this is like consecutive days sorry i miss uh seeing this number but you get the idea right and then for 85 right and you have one day two days three days four days and five days right and also plus yourself six days so you will return six so uh this is going to be pretty much the idea so how do you actually do this i'm going to just quickly tell you what happened so uh you definitely need two stack why one is stored in the stock price right the other one is going to store the frequency right well when i say the frequency it's going to say how many consecutive days and then uh i mean pretty much it right so let me just quickly go over so if i have the first index uh zero so i'm going to push my price into this uh stack price right and then the frequency for the first stage will be one and the 80 since the peak of the price stack is 100 it's lower than uh it's greater than 80 so you don't want to increment your frequency so it's going to be one and so on the 60 it's gonna be one right all right let's uh change another caller so another one the next one is probably 70 right so i would just compare the price stop the price right so i'm going to price the peak right so i'm gonna say okay if this number is what is less than equal to my current price for my current price 70 right so if this is happening i'm going to pull the number out of the price stack and also keep adding my counts for this current uh current frequency so i do have a current frequency count right so i'm going to plus equal the same number i mean the same rule the same data for the 60 and one right so it's going to be plus one right but uh just based on the frequency peak right so this is going to be pretty much it right so i'm going to delete it all right now uh since you are traversing the entire stack right until there's a price which is greater and then you will start then you will stop so again you will go on the 80 so 80 well uh well you cannot um while this doesn't work so you should push your uh push the value the price value into the price stack and then the frequency is going to be two right so let's move on the next one 60 simply the price for i mean the peak of the price is 70 so you push 60 into here right all right so let's move on to the next one i'm going to erase this just in case i don't have enough space right all right let's move on the next one 75 right so 75 is what uh definitely greater right greater uh so you are tall pull this all right so your pole so i have a curve frequency with current frequency so you'll initiate that one first right so one plus one right and then your computer 70 so 70 all right it's still less than that's like one plus two and then you'll traverse another one 80 all right 80 this is not allowed so basically you pull these two out right and adding the 75 into the price uh stack price and the frequency is gonna be what four right so again if you look at a number this is four right and then uh this is going to be pretty much the same idea for the 85 so 85 i'm going to check okay 85 75 okay wait hold on this is 85 right here and then my current stack uh peak is what 75 right so the fruit is definitely less than and i need to just pull the frequency count so it's going to be say one plus so i always have one this is going to be my default value 85 this is one right and plus four right because i pull out this one right so i say goodbye to this one i'm going to check the next one 80 so it's still going to be less than right 80 right so this is 85 right and then i will just pull again and i need to plus one right and then basically hundred years you'll stop right and then move on i would just say a5 equal to one plus four plus one and six all right that is six and then uh you just return so uh this is how you know it's consecutive days so if you have another 60 right and then use one all right so move on all right let's stop holding i'm going to exact integer right price right comma i need a frequency i'm going to initialize this into my constructor right you can see all right so i'm going to initial my current frequency equal to one and then we'll start for price uh it's not empty and also i stack up key but which is also buy stock pick so price copy is less than equal to r that's equal to price right then i would just say current frequency plus equal to what the frequency i key right and if i get a number i'm going to say pop so by stop top and then frequency dot top right so using a value to keep traversing the current peak uh intersects right and then they don't just push my what puts my value into percentage of stacker at price stop uh sorry this is nice i keep making mistakes sorry about this so frequency the ad i'm going to add a current frequency right and then return the current frequency but this is going to be pretty much it right so i'm going to run it and see if i have any error or not okay i don't have it then submit it all right so let's talk about time and space this is going to be a space all the time right the number of the uh number of the frequency and the price you have to add into the stack is all of them so for the while loop if this won't be a time right so every single time you need to traverse until it is soft right so the worst case won't be one all the time right so the timing space are all of them represent what but then of the length of the price you're giving and this is a solution and i will see you next time bye
|
Online Stock Span
|
advantage-shuffle
|
Design an algorithm that collects daily price quotes for some stock and returns **the span** of that stock's price for the current day.
The **span** of the stock's price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
* For example, if the prices of the stock in the last four days is `[7,2,1,2]` and the price of the stock today is `2`, then the span of today is `4` because starting from today, the price of the stock was less than or equal `2` for `4` consecutive days.
* Also, if the prices of the stock in the last four days is `[7,34,1,2]` and the price of the stock today is `8`, then the span of today is `3` because starting from today, the price of the stock was less than or equal `8` for `3` consecutive days.
Implement the `StockSpanner` class:
* `StockSpanner()` Initializes the object of the class.
* `int next(int price)` Returns the **span** of the stock's price given that today's price is `price`.
**Example 1:**
**Input**
\[ "StockSpanner ", "next ", "next ", "next ", "next ", "next ", "next ", "next "\]
\[\[\], \[100\], \[80\], \[60\], \[70\], \[60\], \[75\], \[85\]\]
**Output**
\[null, 1, 1, 1, 2, 1, 4, 6\]
**Explanation**
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today's price of 75) were less than or equal to today's price.
stockSpanner.next(85); // return 6
**Constraints:**
* `1 <= price <= 105`
* At most `104` calls will be made to `next`.
| null |
Array,Greedy,Sorting
|
Medium
| null |
47 |
foreign number 47 permutations 2. so the only difference is we have duplicate numbers inside the nums for example this is one two and we're gonna return one two one and two one let me first explain it in whiteboard and then go back to the code editor yeah to code it up for example we have one to two as our permutations so this is a MTR ring this is a my answer I will put something into the answer and then puts answer into the result so I have an empty without so I will permutate one by one so here is one inside and two so if I tickle one put one into the answer the result the Left Behind is what Left Behind is 22 so with the Left Behind one two and one two here if I take two out so what's left behind so here for the next permutation if I first I take two at the next I take one and I take two so if I take two and what's left behind that is one and two so I put one to two here yeah and then I go one by one for all the permutations so here we select the height and A2 and the left here is two and with the left here is two here is one two and one yeah as we already know there are a lot of uh duplicates so for example here one two from this two there are duplicated for this two one two here is a two one two yeah so for example here one two and one two they are also duplicated so we need to block these areas so the trick is bronze these areas we can also use a set for the answers if it's one of the answers we use a tuple answers and then if we use a result as our reset if the set is result is set we put everything inside the set we can also avoid but that is too slow we have to check one by one yeah but if we use Bronson we can stop earlier from here or from here how should we use bronzer so for each of the numbers for example we have a one to two so for the first permutation we take out one number this can be one and next we pick two out and another one should be two so can we use another two no we cannot because that will produce duplicate if we put another two here to 2 is duplicate how should we avoid that we should Define a set before this backtracking so for the first one we have a backtracking function so inside the backtracking before the for Loop before these areas we will on a set if we have a duplicate number we will just bronze it so here we just launch it yeah we let the for Loop continue so here is a bronze so here for example this one we have taker we've already taken one inside the answer sorry and What's Left Behind is 2 and 2. if we go through two these two we put the two inside our set so inside of the set we have a two what about another two if we go to another two with hack if it is inside the set we will not check these areas so this is another blunt yeah as you can see if we use like this way it can speed up yes speed up for the algorithm now let me go to the code Editor to finish the coding of the backtracking with the streaming method so I will Define a result and then I will Define the backtracking function so it is similarly like back permutation one so I will use nouns and answers so the conditions if so this is totally the same as permutations one yeah if you didn't know why I write this you can Circle my permutations one videos yeah and here if not announced I will put the answers inside the result here I will use a return to let it yeah led to the backtracking and finished quickly so before I use a for loop I will Define a set as I said this will be a bronze this will use like a training for the bronzes yeah so for I in race land nouns I will first attack this number if nums I inside the set will continue to avoid the back to just to return to go to the next iterator to avoid the backtracking yeah if numps is if it is not inside so the set will be add this nums I number yeah and then we can safely use a backtrack for the next yeah for the backtrack so if we take the numbers I out so here will be from I yeah here will be from I Plus nums I plus one because we takes the eyes out and what's inside the answer to the plus the nouns I yeah and then we finished our backtracking function what we should do is we just needed to call the backtrack and the numps and empty array after coding the backtrack we need to return the result now let me run it to attack if it works yeah yes you can see it works now let me submit it to tag if it can pass all the testing cases yeah as you can see it passed all the testing phases and it is around 70 percent of all prices submissions yeah if you think this is helpful please like And subscribe I will upload a module called permanent Black Faces thank you bye
|
Permutations II
|
permutations-ii
|
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._
**Example 1:**
**Input:** nums = \[1,1,2\]
**Output:**
\[\[1,1,2\],
\[1,2,1\],
\[2,1,1\]\]
**Example 2:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\]
**Constraints:**
* `1 <= nums.length <= 8`
* `-10 <= nums[i] <= 10`
| null |
Array,Backtracking
|
Medium
|
31,46,267,1038
|
399 |
hey what's up guys this is chung here so today uh let's revisit this problem 399 evaluate division you know so yesterday i we talked about this problem by utilizing uh like a graph and a dfs search solutions approach where you can call it basically we uh we just built like a graph with the edge from this a to b and with the weight of this and then later on we just uh for each of the queries here we just do a search uh with this the first element item is the start and the last one is the it's the end and we just do a search and while we're doing the search we also uh basically update our current values so that's the first approach so now for those for someone who is interested in like another solutions which is called floyd uh warshall algorithm you know i'm gonna so this time we're gonna use this floyd warshall algorithm to solve this problem you know so for those who don't know what or what is the floyd workshop algorithm it's an algorithm to calculate the shortest path between all the in nodes in a graph so basically if we have a note here we have a few notes here it doesn't really matter okay different notes and each note has like a different path right i mean something like this and each edge has like a value here 1 2 3 6 9 7 9 so here it's going to be the it's a weight on the edge here okay so i mean i think most of you have already must be familiar with that the diecast algorithm right so basically the dikes algorithm or the what is that like bellman fordman so those two algorithms is only designed to calculate the shortest distance or the shortest path between one set between one like between the starting point and the specific uh ending point okay and an ending point that's basically you have a fix you have a fake starting point and a fixed ending point and then you use the dextro to calculate that but you know the floyd workshop algorithm is designed to calculate the shortest distance among basically among other all the other pairs and this one this algorithm is especially used very useful to uh in the social network you know to calculate the uh basically for each of the persons what are the shortest distance between each of the person and this and the way this algorithm works is that because it's uh let's say from the i to j if there's a i to j okay and if there's i to j here so the way this one is i think it's utilizing the dynamic programming concept here so basically for each i and j let's say there's a star and an end point basically we're going we're trying to find all the possible uh in intermediate path which is the i to k and the k2 to j okay if we have if we find the intermedium here basically we try all the inter intermediate path from i to j and we're trying to see if this one plus this one is smaller than the current i to j and then we know okay we find a shorter path basically we're doing this by uh by looping through all the possible combinations of i to j and also for each of the combinations i to j we try out of out the possible uh k case node okay basically if the uh let's say if the v is the uh the v is the number of the vert of the node the number of nodes so we're basically we're going to have like a 4 1 2 v okay so basically this is for k one two one to v and then for i one two v and then here we have a four j for j one two v okay if there's a matrix right if the matrix what is that uh i k plus matrix of the k to j is smaller than the m of the i to j okay then we just assign this m to j we just update this i'm j with this one here okay right and as you guys can see so basically that's the basic uh solutions basically is for the for this floyd warshall algorithm the core piece is just uh like three nicett for loops basically you know for the uh for each of the i combinations so we are also including the i to i but it doesn't really matter so basically for each of the i and j pair combinations we try all the possible intermediate inter medium paths okay if this intermediate path of that can give us a smaller numbers right and then we just we will just update that one to uh basically after this for loop we have the smallest length from i to j so the basically this thing works because if we have a shortest path from for i to k and we have a shortest path from k to j and then the sum the total of those two will basically will give us the shortest path for i to j and we're doing this for all the other combinations of i to j cool yeah so that's basically how this floyd like workshop algorithm works and in terms when it comes down to our problem you know basically you know the v is what the v is the number of the uh of these letters here okay and the values right the values for like for i for eight a to b is k okay and of course the values for b to a is the one divided by k okay and but for our problem you know since it says there's no contradiction here and we don't have to worry we don't have to compare this value here so the contradiction means what the contradiction means from i to j there are like more than one ways to get here that's why we need to uh in the original uh floyd workshop algorithm we have to compare we have to find basically find the shortest path among all the passes from i to j okay that's why we need to do a if here and we update but in our case since there is no contradiction it means that from this i to j there's only one path to get to the i to j so all we need to do is that we just we're just uh utilizing we will just utilize this like uh the structure here but instead of doing this one we just multiply everything we multiply all these things we multiply all the other b all the inter medium uh path together to get our final one because that's how we calculate this uh our queries here because for a and c so for a and c what does this one do this one means that for m a to b times m b to c right that's how we get the a and c and the thing we just pre-calculated all everything we just pre-calculated all everything we just pre-calculated all everything all the possible things here and we'll just in the end we'll have like a matrix that can give us all the other results from any of the combinations here okay cool so enough talk let's code these things up here all right so um you know for the uh to be able to do this since we are going to loop through the all out of nodes here right so the nodes is we're using like the index here okay but we are having like uh a string here so for in my case i prefer to convert each of the numbers each of the strings here into it into its index so that later on we can just simply use the integer to loop through each of the notes here i mean of course you can still use the dictionary and later on you just look through the keys of the dictionaries but either way is fine right so in that case you don't have to convert into index but in my case i still prefer like index so uh let's see i'm going to first create the indexes uh dictionary and then i'm going to convert those things into it into the index here so the way i'm converting it i'm just do a four a and b in equation equations okay here basically if a is not in the indexes and i just indexes dot a equals to index and after that we just increase it by one same thing for b right if b not in indexes it will index is b goes to index and then we do also do a index plus one so now we have a we have indexes for each of the letters here and then so now the total number is n here right so the number is the length of indexes here that's basically this is the vertices of the entire graph so now we just need to have we just need a matrix here so the matrix and let me see at the beginning right so i mean not all the other nodes on the matrix is it's valid right i mean uh we can set that value to uh to system max or we can simply just set everything to none at the beginning okay n for any range n okay so now let's populate let's we need to pre-populate this graph first pre-populate this graph first pre-populate this graph first okay so that we can loop through that because we need to initialize th this uh this 2d matrix with this equation here so basically for i in the a and b okay in enumerate this uh equations here and cool so what do we have uh i'm gonna have index one equals index is a here okay and index 2 equals to index is b and i'm going to have a value here so the value is the values of i so basically the m of i1 to i2 will be equal to v and same thing for the reverse direction okay and we can also set these things here so basically i1 and i1 equal to 1 and m i2 is equal to one right so this is also obvious right because for this divider itself i mean right for the letters divided by itself but that's basically the aa case here we set these things to uh to one okay now uh we have an answer here right so we have an answer here and uh now the uh it's the uh sorry not the answer so now we have to uh basically to update to calculate the shortest path among each of these combinations of our index of our the each of the nodes here basically for k in range n right and then for i in range n and then for j in range n okay so like i said since we since there's where there's no contradiction path from i to j we can simply do this i j uh equals to m i to k times m k 2j okay yeah but i think we have to check if m i k it is a valid is valid right basically if and m k j yeah because not everything right since we're like checking all the possibilities and not and we initialize this matrix 2d matrix with like this and none here right i mean not the uh not all other combinations it's provided here basically our equations doesn't include all the combinations right from each of the node here that's why uh i'm going to check basically if both of these like that the two parts are a valid one then i update this okay so now we have everything in here okay which uh we everything we know for this query here so now we just need to uh populate this answer here right so basically that for a and be in the queries and of uh so the first thing is if a not in the not in indexes or b not in indexes okay we simply do a append minus one okay that's the first case then second one is elsewhat else which do i 1 equals to the indexes a and i 2 equals to the indexes of b here now we have those two index indices we simply uh we simply check okay simply check if this m i1 and i2 has a value right if it has a value and then that's our answer okay i1 and i2 else same thing also it's just another minus one here okay and here in the end we simply return the answer okay cool try to run this line three what oh come on yeah all right so this one let's try to run the code yeah of course as you guys can see this one's pretty fast you know so why is that because okay so the time complexity for this problem you know i think it's pretty straightforward right basically it's the uh o of the uh n cube so why is that because it's the uh is this one it's the uh we have uh here so we have n here right so that's the main part of the time compliance complexity which is the end of the o of the n cube here and the space uh space time uh space complexity is gonna be the o of an n square right and oh the uh so what is this n here so the n is the number of the uh of this the number of our on our nodes here and the notes is since our equation is within the length of 20 and each of the equation can have up to two notes here so in total the notes will be like 40 okay total in 40 and uh so basically the time complexity is the cube of 40. so which is pretty fast yeah i mean yeah basically that's the uh the floyd warshall algorithm you know i actually i haven't seen this algorithm a lot during like the interview problem but i think it's a good technique to know right especially for this like uh especially with the templates template is not that hard basically it's just trying to split uh split the uh the path from i to j into two parts and then we're trying to find out the smallest one from those two parts but since in our case you know since there's no contradictions here and we can simply uh assuming right we can simply assuming the uh the i the mik and mjk is one of our valid path because for those paths that are not valid they have already been filtered out by using this if statement here okay yeah i think that's it for this problem thank you so much uh for watching the videos guys stay tuned see you guys soon bye
|
Evaluate Division
|
evaluate-division
|
You are given an array of variable pairs `equations` and an array of real numbers `values`, where `equations[i] = [Ai, Bi]` and `values[i]` represent the equation `Ai / Bi = values[i]`. Each `Ai` or `Bi` is a string that represents a single variable.
You are also given some `queries`, where `queries[j] = [Cj, Dj]` represents the `jth` query where you must find the answer for `Cj / Dj = ?`.
Return _the answers to all queries_. If a single answer cannot be determined, return `-1.0`.
**Note:** The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.
**Example 1:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\]\], values = \[2.0,3.0\], queries = \[\[ "a ", "c "\],\[ "b ", "a "\],\[ "a ", "e "\],\[ "a ", "a "\],\[ "x ", "x "\]\]
**Output:** \[6.00000,0.50000,-1.00000,1.00000,-1.00000\]
**Explanation:**
Given: _a / b = 2.0_, _b / c = 3.0_
queries are: _a / c = ?_, _b / a = ?_, _a / e = ?_, _a / a = ?_, _x / x = ?_
return: \[6.0, 0.5, -1.0, 1.0, -1.0 \]
**Example 2:**
**Input:** equations = \[\[ "a ", "b "\],\[ "b ", "c "\],\[ "bc ", "cd "\]\], values = \[1.5,2.5,5.0\], queries = \[\[ "a ", "c "\],\[ "c ", "b "\],\[ "bc ", "cd "\],\[ "cd ", "bc "\]\]
**Output:** \[3.75000,0.40000,5.00000,0.20000\]
**Example 3:**
**Input:** equations = \[\[ "a ", "b "\]\], values = \[0.5\], queries = \[\[ "a ", "b "\],\[ "b ", "a "\],\[ "a ", "c "\],\[ "x ", "y "\]\]
**Output:** \[0.50000,2.00000,-1.00000,-1.00000\]
**Constraints:**
* `1 <= equations.length <= 20`
* `equations[i].length == 2`
* `1 <= Ai.length, Bi.length <= 5`
* `values.length == equations.length`
* `0.0 < values[i] <= 20.0`
* `1 <= queries.length <= 20`
* `queries[i].length == 2`
* `1 <= Cj.length, Dj.length <= 5`
* `Ai, Bi, Cj, Dj` consist of lower case English letters and digits.
|
Do you recognize this as a graph problem?
|
Array,Depth-First Search,Breadth-First Search,Union Find,Graph,Shortest Path
|
Medium
| null |
617 |
hi guys welcome to algorithms made easy my name is khushbu and in this video we are going to see the question merge two binary trees you are given two binary tree root one and root two imagine that when you put one of them to cover the other some nodes of the two trees are overlapped while the others are not you need to merge the two trees in a new binary tree the merge rule is that if two nodes overlap then sum the node values up as the new value of the merged node otherwise the non-null node will be node otherwise the non-null node will be node otherwise the non-null node will be used as the node of the new tree after we are doing this we need to return the merged tree the merging process must start from the root of both the trees this is the node that is given to us and now let's go to example number one so these are the two trees that are given to us in the example number one and over here we see that the structure of both the trees is different so what will happen when we merge these two trees if we try to perform an overlap of these we see that the three nodes are overlapping while these three are not overlapping so according to the rule we need to add the values for the overlapping nodes and otherwise we need to add the nodes that are there in the tree to form a resultant merged tree so this becomes our resultant merge tree wherein we have the three overlapped nodes one node from the first tree and these two nodes are from the second tree i hope the example is clear to you now let's go and understand the different approaches that we could apply in order to solve this question the first one is a recursion method wherein we are going to use basic recursive tree traversal in order to traverse over the tree and find the merged tree the another way would be an iterative way to do so by using either a pre-order way to do so by using either a pre-order way to do so by using either a pre-order in order or post order the third one is bfs which is iterative which means the level order traversal of the tree we'll see each one of these and we'll also see the questions that can come up in an interview while you implement one of these approaches so let's start with the first one now before starting with that we need to first jot down all the conditions that can occur while merging the tree so these are the four conditions that we can have the first one is that the node in both the trees is null in that case we do not need to do anything because the resultant tree node will also be null the second case is that the node in the first tree is null wherein we have the node in the secondary so in that case we will be considering the node from tree two similar case can appear with tree one also that is we have a node in tree one but the same node in tree two is null so in that case we'll just consider the node that is present in the first tree and the last condition is the overlap condition wherein we have the nodes in both the trees and so we need to do the sum of both the nodes so these are the basic four conditions that we are going to use in all the three approaches but only the traversal is going to change so let's go through the first one which is recursive dfs in this we are going to use pre-order in this we are going to use pre-order in this we are going to use pre-order traversal and we are going to use the same example so let's take these two tree and perform a merge on this so according to the pre-order traversal we according to the pre-order traversal we according to the pre-order traversal we are going to take the root process it then recursively process the left tree and then recursively process the right tree this is the basic pre-order reversal pre-order reversal pre-order reversal that we have already seen in our trees chapter but let's go through it step by step over here now while we see the root nodes both of these are not null and so this is the overlap condition and we need to consider the sum of the values of both these nodes so let's alter the tree one that is the tree which is in the blue color and we'll output that tree as our merge tree so we'll change its value two plus one which gives us three now once we have this process we are going to process the left subtree and the right subtree recursively and so we go to its left and again we have a overlap and so we'll add the values and the resultant will be 4 and we'll go to its left now over here as you can see we have the node in the first tree but we do not have the left node in the secondary and so we just need to consider the normal node which is 5 and we keep it as is now we need to go to the right of this root node 4 because our left sub tree has been processed for this so over here you can see that the first tree does not have a right node but the secondary has it so we need to attach this node to its right and so it goes over here now as we have processed the left tree we go to the right and process these nodes again if you see over here we have a overlap and so we do addition of both the nodes which gives us 5 and we go to its left now as we go to its left we see that the left of both these trees for this particular node is null and so we do not need to consider anything or we do not need to update anything and we can move forward and go to its right for this right node three once right is null so we are going to consider the right for tree 2 node and so that gives us 7 and now our entire tree is merged and this becomes our resultant tree so the solution here is very simple that is we are going to follow pre-order is we are going to follow pre-order is we are going to follow pre-order reversal and we are going to follow the conditions to check whether we can sum up the node values or we need to take the nodes from either of the trees so let's first write the code for this and then we will see the other approaches as well okay so we have a few conditions that is if p1 is null we need to consider t2 similarly if t2 is null we consider t1 otherwise we do sum of t1 and t2 now all this is going to happen with pre-order traversal which means we are pre-order traversal which means we are pre-order traversal which means we are going to first process the root then go to its left and then go to its right so let's go ahead and write some code for it so let's take the condition one which is if t1 is null give out t2 vice versa if t2 is null return t1 and if nothing of this is there then we update t1 with sum of t1 and t2 and recursively crosses the left tree and the right tree so t1 dot left equals merge trees even dot left comma t2 dot left and similarly with right finally our answer is going to be the tree t1 so we just need to return it and that's it let's run this code okay so let's just change it to t1 and d2 and run this code so it's giving a perfect result let's submit this and it got submitted the time complexity for the solution is going to be o of n because we have to iterate over all the nodes and the space complexity is going to be o of h that is the height of the tree to store the recursion stack now this o of h can become o of n if the tree is skewed tree now one of the questions that an interviewer can ask is tell me the drawbacks or tell me the cases where the solution will fail think upon it and we'll go back to our next solution with the answer okay the answer to that question is that particular solution can go and run into stack overflow because for maintaining the recursion stack the program is going to use your memory which is the heap memory now how can you avoid it you can use an iterative solution to avoid it now there is one more question that the interviewer will ask you if you give the solution as use the iterative approach instead of a recursive one we'll see the answer to it after we are done with this particular approach so stay tuned and let's move ahead the answer to the question is that we can use the iterative method to get away with the stack overflow issue now how does this help and when will this fail that we'll see after we have covered this method so stay tuned and let's go ahead in this also we are going to use the same example and let's start with it iterative traversal requires a stack or a queue depending on what kind of traversal we are going to perform since it is dfs we are going to use stack if it was a level order traversal we would have used q if you are not aware of the traversal methods you can check out our tree playlist wherein we have all the traversal methods explained in detail with the examples now in here we are going to first add our root nodes into the stack we are going to add both the nodes as we are going to process both the trees at the same time so the stack can contain either a pair of tree node or you can have an array of tree node now once we have these tree node into the stack now what we are going to do is we are going to start popping out from the stack and processing the nodes while the stack is having some elements in it so we are going to pop this node out and process it for processing we need to check our conditions now since we have the normal nodes over here this is an overlap and so we need to sum it up and the sum will go into the first tree because we are going to modify the first tree itself so this node over here will become 3 and then we are going to process its left and right so we'll add those node pairs into the stack now this gives us left pair which is three and one and the right pair two and three into the stack now we'll go and pop one of them out and process it so this will give us the right node out and for processing it we are going to add the values which will give me five now while processing its left and right we can see that both these nodes that is these two nodes are not having the left node and so we do not need to process it for the right one only one of them has a right node so we do not need to do anything but just add this normal node into our resulting tree which gives me 7 over here so now the processing of this node completes so we now pop the other one out and process them over here also we have two normal nodes we add it which gives us 4 and now we are going to process its left and right similarly for this node we have left for one of the tree and right for the another tree so we are only going to consider the non-null node consider the non-null node consider the non-null node and so we keep 5 as it is and we add 4 from this tree into a resultant tree which gives us our output now how do we say that we need to stop the stack has now become empty and so we can stop our processing and return the first tree that we have updated to form the merge tree so this was the iterative dfs now if you would see the time complexity for any of the approaches over here is going to remain same which is o of n because you need to go to each and every node in order to merge the trees the space complexity for the first one was of h which was going to be stored in the heap memory the space complexity for this approach is also going to be of h because we are mimicking the recursion stack but we are mimicking it in our own user defined stack so this is not going to go into our heap memory and so we won't get the stack overflow issue but we can get an out of memory issue over here if the tree becomes skewed because in case of a skewed tree the space complexity will go up to o of n that is the number of nodes that are present into a tree so the stack overflow issue can be overcome by using iterative and now the second one more question that the interviewer can ask in this particular approach is that is there a way you can increase the memory so the answer for that is yes you can configure the memory that you can allocate to the stack that is going to be used by your jvms for your programs and so this issue can be resolved or it can be leveraged now that we know the answer to the question and also the explanation for the iterative dfs let's go and code it out so in this also we are going to update our first tree the first two conditions remain the same while we are going to take a stack over here so let's take and in the stack you are going to add or push the roots d1 and t2 once we have the basic initial stack ready we are going to loop while stack is not empty so let's take that condition and inside this we are going to check for our cases before that we are going to just pop out the element from the stack so pop the element and in the stack we'll never encounter any value wherein any of the two nodes is null so what we are going to do over here is process the node so for processing this we need to add the value for the zeroth and first element of this array so we take this and we are going to update the first tree now we are going to take our conditions wherein current of 0 is null current of 1 is not null second case could be vice versa and third is both not null so in this case we are going to take the non-null element and here we are the non-null element and here we are the non-null element and here we are going to add a tin stack for the further process so we need to do this for both left and the right tree so let's go to the left tree first so here we are going to take the condition that is my current of 0 dot left if that is equal to null i am going to do current of 0 dot left equal to current of 1 dot left otherwise if current of 0 is not null and also the current of 1 is not null then we are going to add it into the stack so stack dot push new three node current of zero dot left comma current of one dot left same thing we need to do with the right tree as well so let's copy this and instead of left we'll just make it right so this will process the left tree as well as the right tree and the while loop will take care of processing the root node finally we return the tree t1 and that's all let's run this code and we have a issue we need to put a square bracket and we are getting a perfect result let's submit this and it got submitted the time complexity for this particular solution is going to be o of n as we are still going to go over all the nodes that are there the space complexity will also be of h because we are going to have a stack that can accommodate at most of h nodes at a particular time but here also there is a catch now what happens if you are only going to get skew trees as your example in that case your space complexity is always going to be o of n if and only if the trees are skewed so if the trees are going to be skewed this can be made efficient by using level order traversal because in level order traversal you are going to go level wise and at most number of nodes that you will be storing would be of two levels so let's go and see that solution that is not the perfect solution for your perfect binary tree but it is going to help you in case wherein you have a skew tree level or a traversal is nothing but bfs and this is also an iterative method so we take the same example and in this we are going to take a q now level order traversal is also a topic that we have already covered in a tree section so you can go and check out that videos for a in-depth explanation in-depth explanation in-depth explanation over here we are going to go through the process so we are going to take a queue and as an initial step we add the root nodes similarly as we have done in our stack approach we are going to use an array of tree node or a pair of tree node to store into our queue now once we have the root added this becomes the size of our current level so i have shown this current level with this particular line now what we do after this we are again going to pop these elements out or remove from the queue which will give us these two nodes and we are going to process these and add its left and right into the queue so again while processing sum this up because we are going to merge this nodes and add the left and right into the queue now once we have added the left and right now these are going to become the end of the current level and so this is marked by this particular line next we are going to pop this out process it by merging the nodes so we are going to add the numbers which gives us 4 and after processing this we are going to go to its left and right so as we know over here the left is present for this tree the right is present for this tree so we are going to just process these nodes and we are not going to add it in our queue as we did it for stack also so 5 remains here 4 gets appended to this and we have processed this particular node next we pop out the another node and do the same so for this node also we are going to add the values up and then we are going to process left and right since both the left are not there it will be null for the rights we have a right in this particular tree so that gets appended into our merge tree so the condition is that if the left or right for tree two node that is the second tree is null we are not going to require any processing because we can keep the same left tree as is but if for tree one we are not having the node we need to take the node from tree 2. so we take it and that's done because the queue has now become empty and this becomes our result so that's it with the explanation for a detailed explanation on level order traversal i'll ask you guys to go and check out the trees chapter wherein you will find a detailed explanation of what we are doing and why we are doing it for this question now let's go and code this particular approach out the first two conditions are going to remain the same over here instead of stack we are going to use a queue so let's use a queue and this is going to be a linked list instead of st we are going to do q so we are going to push this tree node and while my q is not empty i am going to remove one of the node now as we said if the right tree is empty we do not need to do anything so if my current of 1 is not equal to null then we are going to process and so we are going to use the same thing current of zero dot val is going to get updated and we are going to have the conditions for left and right so let's take it over here and then we change it as we need it so now over here we are always going to have this as not null so there is no case this that is going to appear let's remove this out and now if current is null i need to just consider current of 1 that was the mistake in the earlier approach as well in the comments and if this is not null that is if current of 0 is not null we are going to add it into our q and that's it same thing we are going to do for the right and left so if this is equal to null we are going to take this and else so we do not need this if condition we are going to do q dot add and same with right one so we are just having a if condition to check my left that is the first tree is not empty and that's all let's run this code and we have used a push somewhere let's change it to add that is the queue convention and let's run it again this becomes q let's see if we have used it somewhere else and not let's run this and we are getting a perfect result let's submit this and it got submitted the time complexity as set remains the same which is o of n the space complexity would be the maximum number of nodes that can be in any of the two levels so it goes to 2 raised to h plus 2 raised to h minus 1 which will give you a time complexity of 2 raised to h so this is obviously more than the time complexity for the dfs approaches but this will perform well space wise wherein you are only going to have a skew tree so that's it for this question guys i hope you liked the video and i'll see you in another one so till then keep learning keep coding bye
|
Merge Two Binary Trees
|
merge-two-binary-trees
|
You are given two binary trees `root1` and `root2`.
Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.
Return _the merged tree_.
**Note:** The merging process must start from the root nodes of both trees.
**Example 1:**
**Input:** root1 = \[1,3,2,5\], root2 = \[2,1,3,null,4,null,7\]
**Output:** \[3,4,5,5,4,null,7\]
**Example 2:**
**Input:** root1 = \[1\], root2 = \[1,2\]
**Output:** \[2,2\]
**Constraints:**
* The number of nodes in both trees is in the range `[0, 2000]`.
* `-104 <= Node.val <= 104`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
89 |
hey coders welcome back to my youtube channel today we will be discussing a very famous coding question that is called gray code so what is a gray code the gray code is a binary numeral system where two successive values differ in only one bit for example this 0 1 0 so for example these two numbers they are differing by only one bit 0 & 1 so this is a gray code 0 & 1 so this is a gray code 0 & 1 so this is a gray code so what is the question given a nun in non-negative integer and representing non-negative integer and representing non-negative integer and representing the total number of bits in the code print the sequence of gray code sequence must begin with 0 we can solve this question very easily by the help of backtracking and bit set it said first we will see what is bit set a bit set is an array of both but each boolean value is not stored separated bits it optimizes the space such that each will takes 1 bit space only ok so you can refer this geeks for geeks links for studying bit set about bit self so first what can we do about this problem that first B initializes a bit set of 32 digits and then we used backtracking approach for this so again what is backtracking approach backtracking algorithm is a very famous algorithm and very useful for this such problem so backtracking is basic basically consists of these three parts first part is choose we have to choose the option then we have to perform the operation on that then we have to unchoose the operation you can refer gigs for gigs this link for this backtracking algorithms now we have to see what this board looks like so now I have to initialize this my bit set that is going to be in this current value of the backtracking algorithm then I have to initialize my result vector now I have to perform backtrack that's the end result then and at last to return the result now let's see this function backtracking is a very simple algorithm yet it can be complicated in many ways so you have to practice make Samantha now if K becomes zero I'll explain to you then we have to add you to deep result by the help of itself it's now we have to perform the basic backtracking this is it so what is this whole poet backtracked so I'm assuming this backtrack algorithm as this backtracking as I said backtracking has three basically three parts so first part is this backtracked bits result K minus one I am choosing the value that can perform the recursion by the question and at last to the question is this stopped at this value when K is equal to zero and by for performing the flip is a function that can change the current value this K minus one value like suppose if we have bits or zero value and K is equal to 2 then K minus 1 is equal to 1 so we can flip the one at position that is this which set always defined in define index in backward direction like this you can see this article this is really helpful for you understanding bit set so we can change this by this is what which bits dot left is doing here right this is operation of our backtracking algorithm of this backtracking problem then we are unchosen that is this so this is all about this problem hope you find this useful these likes like and subscribe if you find it useful or helpful thank you
|
Gray Code
|
gray-code
|
An **n-bit gray code sequence** is a sequence of `2n` integers where:
* Every integer is in the **inclusive** range `[0, 2n - 1]`,
* The first integer is `0`,
* An integer appears **no more than once** in the sequence,
* The binary representation of every pair of **adjacent** integers differs by **exactly one bit**, and
* The binary representation of the **first** and **last** integers differs by **exactly one bit**.
Given an integer `n`, return _any valid **n-bit gray code sequence**_.
**Example 1:**
**Input:** n = 2
**Output:** \[0,1,3,2\]
**Explanation:**
The binary representation of \[0,1,3,2\] is \[00,01,11,10\].
- 00 and 01 differ by one bit
- 01 and 11 differ by one bit
- 11 and 10 differ by one bit
- 10 and 00 differ by one bit
\[0,2,3,1\] is also a valid gray code sequence, whose binary representation is \[00,10,11,01\].
- 00 and 10 differ by one bit
- 10 and 11 differ by one bit
- 11 and 01 differ by one bit
- 01 and 00 differ by one bit
**Example 2:**
**Input:** n = 1
**Output:** \[0,1\]
**Constraints:**
* `1 <= n <= 16`
| null |
Math,Backtracking,Bit Manipulation
|
Medium
|
717
|
994 |
hey everybody this is larry this is me doing day 29 of the october uh lead code daily challenge live so hit the like button in the subscriber and join me on discord let me know what you think and as i said these are live so it's a little bit slow just fast forward whatever you need to do i today i may be rushing a little bit because i do need to get out of here um but we'll see how it goes um okay so today's problem is writing oranges 994 medium problem okay so you have a grid you have okay any fresh diamonds four directional adjacent to a one orange we turn the num okay um well this one's a little bit weird and that well the first thing i wanted to see was just the constraints right because um i think conceptually you um you would do a breakfast search um uh um just like a distance thing from so basically maybe it's not breakfast i mean you would implement it that way with the q but basically you're doing um multi-source shortest path from a place multi-source shortest path from a place multi-source shortest path from a place um and that would be the uh yeah multi-source shortest path from all yeah multi-source shortest path from all yeah multi-source shortest path from all the run um or the wine oranges to all the fresh oranges right and then you just get the max of all the distances from all the oranges and so forth um i think that should be good but yeah but so that would be the linear way to do it um you look at every cell once and that should be good um in this case though m times n is 10 so it's a little bit easier so you can do something more brute force by literally just keeping track of all the wine tomato uh wine oranges and then just do the um what's it called the manhattan distance from the closest white and orange and that should be good um and of course that's gonna be n square or it's gonna be quadratic which is m times n um square or m squared times n squared well i like to say r squared times c squared right um and that still would be fast enough because that's just a hundred square i'm gonna do it that way because i'm in a rush um but i would recommend you doing in the linear time way which is also not that much harder to be honest so okay maybe i should do it that way see what time i have um but basically what you're gonna do is um yeah i mean i think that should be okay so let's get started then um but basically this is just general shortest path thing weber q we have a collections.deck have a collections.deck have a collections.deck because that's the implementation in python and then let's keep track of r is equal to length of grid cell is equal to length of grid of zero we have at least one so we don't have we should be able to check and then here for x is in r for y is in range if grid of x y is equal to 2 for wine oranges then we let's keep track of distance yeah let's keep track of distance is equal to let's just say infinity um times c4 my infinity i just set it to some big int um i don't like using full dot whatever uh full passing because it's a it is a different primitive i suppose but yeah the distance of x sub y is equal to zero and then we append um x y right okay and then this is standard bfs type thing of first and first out so x y is equal to q dot pop left and then now we look at all the adjacent neighbors so we have to look at the directions um well just in a weird way but okay for dx d y and directions um and x and y i use the same notation though you don't have to uh what this is just saying is that the next x and the next y uh and then we just make sure that it is inbound and distance of x and y is not or if it is infinity then we want to uh relax it by you know going to the next frame so we set this as equal to distance of x y plus one and then we push on the cube and i think we should be mostly good we can print it out the distance oops what did i click on um but really we sh um all we have to do is just take a max of uh so t is equal to zero um yeah for x and range of r for y in the range of c i know you can write this in actually much closer way but oops uh return t right i think this should be good that's uh one example cases oh this is wrong uh so we only cared the longest distance if it is um if the grid is uh it goes to one right because we don't care about empty you know the distance to the empty cells um i thought about this one i was like how come we don't use this but uh okay seems like i'm still wrong but why do i output four for the second one oh maybe i misread something hang on oh so it's not the distance because okay so i'm glad that i didn't do it the manhattan distance right because it only if it's um only if it's a fresh orange so okay so i mean but that's not that bad we just have to add it here and because you only pass from a one orange here um we can only we can do this and it'll be fine we don't have to change the grid or anything like that um okay that is just awkward then oh i meant nx and y uh maybe i'm watching a little bit because i do have to go pretty quickly um okay so that looks good um i didn't realize that there's a negative one because this is impossible but that's straightforward which is that if t is equal to infinity then we return negative one which is i think that should be good um but that means that there's an orange that is not violable um and that therefore the distance is infinity um cool uh is this all i have um i think so i mean unless i missed a case somewhere um yeah oh i think this would be a case that i would be looking at which is that there are no fresh oranges to begin with um hmm and i guess this is the other case okay so let's give it a submit then um and hopefully i don't have any oh no do i have a typo somewhere huh i guess so uh oh yeah i do have a typo in the directions so i did worse than last time um i thought just oh wait yeah i will just really funkily and i thought i did very funky but i didn't double check um but basically i just didn't go on the negative i mean that was just wrong right so um yikes whoops uh like i said maybe i'm watching a little bit too much today but uh but at least this should be right let me double check real quick uh yep okay maybe there's another uh silly mistake but this part should be okay 577 watching a little bit my bad friends uh but it is fast this is just regular breakfast search um i think that's what i have i mean this is linear because we look at each cell once uh this is linear space as well because of this distance thing um do i need it yeah i think we need a distance ring because otherwise um you're gonna you need to keep track of the state you've seen anyway i mean you're gonna there are some hacks you can do with extra space but let's ignore that for now um but yeah so linear time linear space and linear in this case is r times c which is the size of the input right so yeah um that's all i have for this one um let me know what you think about everything the video quality the code any comments i'll see you out later stay good stay healthy to good mental health and i'll see you later bye and also happy friday
|
Rotting Oranges
|
prison-cells-after-n-days
|
You are given an `m x n` `grid` where each cell can have one of three values:
* `0` representing an empty cell,
* `1` representing a fresh orange, or
* `2` representing a rotten orange.
Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten.
Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`.
**Example 1:**
**Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\]
**Output:** 4
**Example 2:**
**Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\]
**Output:** -1
**Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally.
**Example 3:**
**Input:** grid = \[\[0,2\]\]
**Output:** 0
**Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0.
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 10`
* `grid[i][j]` is `0`, `1`, or `2`.
| null |
Array,Hash Table,Math,Bit Manipulation
|
Medium
| null |
216 |
welcome back guys today we're gonna solve this lead code medium level question combination sum three total down my shoes eurostat my move i just cut the ring yeah my fingers hope on a finer thanks in this question we'll be given k and n as input and we need to find every possible combination of length k so that every individual combination summation is equal to 6 and for the combination we can only choose number between 1 to 9 both inclusive so the possible answer could be 1 5 2 4 three four two and five one right all of these make six but there are some more constraints the constants are like we can't if we have taken three we can't use three again the same list so this can't been our possible answer we have taken 2 and 4 so we can't take any other permutation of that also so 4 2 can't be in our answer 2 and we have taken 1 5 so 5 1 can't be in our answer 2. so the final answer would be 1 5 and 2 4. so by looking at the solution the first thing that comes to our mind is we can make dfs calls and we can find every combination of length 2 and we can avoid the duplicacy by using set and for the individual list we can use a set or a visited array there too but that could lead to extra space and extra time right so to avoid that we can make a use of method called pruning so for that what we'll do is the for first dfs call we'll start the loop from one to nine as we have to take numbers between one two nine only so first we'll take one so for the next tfs call we'll take the number we have taken previously plus 1 to 9 right so the next number would be 2 so by this we can avoid the duplicacy so yeah so let's see for this so first we take three here and then next dfs call it will start from four to nine so we can't take three so we have solved this and for this and this so we are taking four first so the next loop will start the next dfs score will start from five to nine here so we can't take two so this is solved and for this the next dfs call will start from six to nine so this is solve two so we have avoided the duplicacy thingy right so now we have understood this so let's just run through the algorithm what i'll do is i'll have a temporary list in which we'll check every possible combinations we'll have the result as the final answer this will this is a list of lists so we'll have the final answer here and we'll have some initially the sum will be zero and what we'll do the first dfs call will start from one to nine right and so the first fs call will start from one to nine so we'll take one and the next jfs call will start from two to nine as we have taken one here uh yeah and uh we have taken one in the first call so we'll add that to our temporary list now we move to the second dfs call and here we'll add 2 and we'll add 2 to our temporary list again now our list's length is equal to k right and the sum will be 3 so we have to maintain the sum also so the initially it will be 1 and 1 plus 2 will be 3 so the sum will be 3 right and our length is uh yeah so length is k so we now check if our sum is equal to n or not so 3 is not equal to n 3 is not equal to 6 so we won't add we want add 1 and 2 to our result right so we'll backtrack and move remove 2 from the list now so we have explored two we'll check with three and as we backtrack we'll reduce that from the sum two so sum will be one plus okay so now for three one plus three right so one and three will be added to the temporary list also now we'll check one plus three make six or not so it doesn't so we'll backtrack and remove that from the list two and from the sum two right now i'll check with four does 1 and 4 make 6 no so we'll remove that right now i'll check with 1 and 5. does 1 and 5 make 6 yes so we'll add 1 and 5 to our final answer right we found one answer we need to check for other answers too so we'll backtrack and remove that too we have explored five now we'll explore six now six is greater than n we'll just return we'll not explore any further from there and for seven yeah now we have seven we explored six now we have seven is also so one plus seven will also be greater than n so we'll backtrack and remove that too yeah now we'll check with 8 so that will be greater than n2 we'll check with nine that'll be greater than n2 so we've explored the second dfs call so we'll move back to the first dfs call and we'll backtrack and move remove one from temporary list and the sum and we have explored once we'll explore two now we'll add that to a list and to our sum right and the next dfs will move to the next dfs call so the next fs call will start from 3 to 9. right so we'll check with 2 and 3 does 2 and 3 makes 6 or not it doesn't so we'll backtrack and remove that we'll check with 4 does 2 and 4 make 6 yes so we'll add that result i mean add this temporary list to our result so we got one more answer now we'll check if 2 and 5 makes i will backtrack and remove 4 first i will check if 2 and 5 make 6 2 5 is greater than sum greater than n so we'll just return and now we'll check with 6 just 2 and 6 make 6 2 and 6 is greater than n so we'll just return again likewise when 7 2 and 8 and 2 and 9 will be greater so we'll just return back right so we have explored the dfs2 again we'll move from dfs2 to dfs1 and we have export 2 so we'll remove 2 from list and 2 from sum2 now we'll check with 3 we'll add 3 to the list we'll add to 3 to the sum and we'll move to the next dfs call which will start from 4 to 9. so does 3 and 4 makes uh 6 no it doesn't so we'll just return back likewise we'll return back from 5 6 and 7 and 8 and 9. so this will continue and we'll find that the final answer will have 1 and 5 and 2 and 4 right so for this example this is the possible solution uh now let's just look at one more example so for k is equal to 3 and n is equal to 7 for this example we'll first have temporary list we'll have sum initialized as zero will have the final result right so the first loop will start from the first default dfs score will start uh not start we'll have the loop from 1 to nine so we take one initially we'll add that to the list we'll add that to the sum two and we'll move to the next dfs call will start from two to nine so we'll add that to our list and to our sum and we'll move to next dfs call because the temporary lists length uh doesn't equal to three yet so the next if it's called start from three to nine so we'll add three to the list and three to the sum now we'll check as the list length is equal to 3 so we'll check if the sum is equal to 7 or not the sum here is 6 it's not equal to 7 so we'll backtrack and remove 3 from the sum and from the list now we have explored three so we'll explore with four so we'll add four to the list and to the sum and now the sum is equal to seven so we'll add 1 2 and 4 to our answer list right and we'll backtrack and check if other if there is some other possible answer or not right so we'll check with five likewise we'll check with six and seven then eight then nine right and then we'll backtrack and move to the second dfs call and here we'll check with as we have explored two so we'll remove that from the list and from the sum and we'll explore with three so one and three and the next gfs call will start from four to nine now so likewise we'll have to check with every possible combinations right so this was the explanation part let's look at the coding part now so initially i'll create a list of lists which we are going to return at the end and in between we'll have our dfs calls in the dfs call we'll pass k n our result list of list which we're going to populate and our temporary list and the initial value of the loop which would be one as we will loop initially we move from one to n right so the initial value will be one which we gonna change in every dfs call and at last we'll pass the initial value of sum so here we'll have the helper function and okay and then we'll have the result uh we'll have our temporary list will have the start value of the loop and the sum initially we'll check if sum is less than if sum is greater than n we don't need to explore any further we'll just return from there if sum is not greater than n then we'll first check if temporary list's length is equal to k or not if it's equal to k we'll check sum is equal to n or not if sum is equal to n we'll just add temporary list to our result but we have the reference of the temporary list so we need to create a template a list here a new list here and we don't need to explore any further so we'll return from here too and if these two conditions are not satisfied then we will have our loop which will start from one to nine initially the start value is 1 which will go to 9 yeah which will go to 9 and inside this loop will add i to our temperature less then we'll go to the next dfs call in which the start will be i plus 1 and the sum will be sum plus the number we have taken here that's i and when we backtrack will just remove the last element right so i think this should work and it does so let's just submit and test this and it works so don't forget to like and subscribe see you next time when i'm down like three me and my brother shook toe two down my shoes euros that my move
|
Combination Sum III
|
combination-sum-iii
|
Find all valid combinations of `k` numbers that sum up to `n` such that the following conditions are true:
* Only numbers `1` through `9` are used.
* Each number is used **at most once**.
Return _a list of all possible valid combinations_. The list must not contain the same combination twice, and the combinations may be returned in any order.
**Example 1:**
**Input:** k = 3, n = 7
**Output:** \[\[1,2,4\]\]
**Explanation:**
1 + 2 + 4 = 7
There are no other valid combinations.
**Example 2:**
**Input:** k = 3, n = 9
**Output:** \[\[1,2,6\],\[1,3,5\],\[2,3,4\]\]
**Explanation:**
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
**Example 3:**
**Input:** k = 4, n = 1
**Output:** \[\]
**Explanation:** There are no valid combinations.
Using 4 different numbers in the range \[1,9\], the smallest sum we can get is 1+2+3+4 = 10 and since 10 > 1, there are no valid combination.
**Constraints:**
* `2 <= k <= 9`
* `1 <= n <= 60`
| null |
Array,Backtracking
|
Medium
|
39
|
1,315 |
Hello hello friends today in this video winner discuss mother problem sombir kodan problem name sex notes with life lived reference choudhary cant see independent states that you are giving up by ministry and after 10 years the value of the notes with valid and now you must know the Diamond Club in Tricks The Con is Not Press the button subscribe and subscribe the Channel Please subscribe and subscribe the Channel subscribe Video subscribe and subscribe this Video What to do This fact and Electronics and see the flashlight of chemistry From time to time this how to tell the Submission of Values But this how to tell the Submission of Values But this how to tell the Submission of Values But Not For Which Being A Grand Parents Will Give For Pimps And Accept It And Subscribe With Nod To Solve Vidyalaya Must Subscribe Like Comment And Also Subscribe The Channel And Listen Agency For This Is The Grand 1021 10000 and subscribe the Channel and subscribe the for going up sid do subscribe to a plu kepler control in the current notice price sanju how to do how to add values for this cream and grandchildren of mind and want to give back to avoid children more benefit only for every Agri Vid Oo Agri Vid And Video subscribe And subscribe The Road That Endangered Brothers Note Witch Children And Just Relax Is Half Cup Product In Websphere Lutb Scanner subscribe The Video then subscribe to the Page This Issue Sister Mother Phase Airplane Mode Switch Acid Mother But Alternative 15 minutes from which debit the receiver check the last not exist in the language a subscribe button on the left side subscribe like subscribe must subscribe not exist this camp chapter note exit backward this china 's behavior hand folic acid left side 's behavior hand folic acid left side 's behavior hand folic acid left side include until 1999 pluto subscribe to the Page if you liked The Video then subscribe to the Right Side Par Lena Hai Ki Iten Root Right Left Challenges in Root Right Side Optimum Interests of Aapke Exam Pal Jab Check Remedy Ko Turn Left Child and Left Side Broken Cement Bill-2008 subscribe and subscribe the Bill-2008 subscribe and subscribe the Bill-2008 subscribe and subscribe the Channel subscribe our A College Kid With Perfect Wedding The Process In Slogan In Order Reprocessing The Different Types That And Good Cause Loot-Pit Commission For That And Good Cause Loot-Pit Commission For That And Good Cause Loot-Pit Commission For Scheduled On
|
Sum of Nodes with Even-Valued Grandparent
|
sum-of-nodes-with-even-valued-grandparent
|
Given the `root` of a binary tree, return _the sum of values of nodes with an **even-valued grandparent**_. If there are no nodes with an **even-valued grandparent**, return `0`.
A **grandparent** of a node is the parent of its parent if it exists.
**Example 1:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 18
**Explanation:** The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.
**Example 2:**
**Input:** root = \[1\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `1 <= Node.val <= 100`
| null | null |
Medium
| null |
823 |
hey everybody this is larry this is day 13 from the march the code daily challenge hit the like button hit the subscribe button drum and discord let's hang out uh ask me questions okay today's promise binary trees were factors oh i just woke up so my eyes are a little bit winky uh yeah so i stopped this live it's a little bit slow just fast forward and all that stuff uh okay so binary treats are fragrance what does that mean given an array of unique integers okay you make a binary tree using these integers you each non-leaf should be equal to the each non-leaf should be equal to the each non-leaf should be equal to the product of the values of its children okay um not sure i understand what it means but okay let's read this again i'm gonna make a binary tree okay each number can be used a number of times each non-leaf node should be you go to the non-leaf node should be you go to the non-leaf node should be you go to the product of the values of its children okay uh okay and n is about a thousand so we can do some n square type things which is probably what's on my mind um the value of his children yeah okay i mean this it's a very awkward uh problem to phrase but i think that should be okay basically we um and each number can be used that's a little bit awkward but maybe or maybe that's fine okay huh so okay so the key thing to note is that there's going to be some dynamic programming or not even dynamic pro i mean it is the you could call it dynamic programming because a lot of people call everything that i'm programming um but maybe memorization is the better word the thing to note is that okay um the thing to note is that uh okay how do i explain this um this is a i actually like this problem i think it's an interesting problem or see my interesting problem so okay so there so my algorithm is going to be you know uh for kind of brute force in that okay we try for each node we try putting it here uh putting a note there i'm gonna actually give me a second i'm gonna bring up uh i'm gonna bring up the paint thing so then i can show you so oh whoops oh my god too big hey hang on okay so basically the thing is that okay let's say you have uh 10 right um and 10 in this case have you know a couple of um a cup of you know like a couple of uh like ways to do it right so it actually turns out that you know you look at the example two um in this case 10 has you know given the 2 4 5 and 10 there's actually four um the three ways to do i'm using the mouse to draw says a little bit a two have 10 as the root right okay so you have something like that right um you know and you could draw it out just ten two and five on each side and so forth uh 10 being a leaf but so then the question is okay what happens well what does this mean for us to for calculation right well let's say for example now we have 20. um you know let's say we have the same numbers but we add 20. what does that mean well let's just say that for example we have you know now we have 20 on top uh you know you have two on the left and then 10 on the right so that's one combination but you can also think about it recursively or dynamic or memorization which is that okay this actually means the 10 actually means um you know to get the number of uh trees with 20 at the root the 10 side actually just you know can have three combinations as we talked about before right so that means you know i'm gonna uh this is i'm not gonna write everything but so there's three combos right so that means that now with 20 under root there's gonna be you know the two and the ten and then you do the proof you calculate you do a count on how many the ten has and it's three so then you multiply that in um and once you kind of realize that um observation then it becomes you know just commentary just counting stuff um and yeah and then just a lot of multiplication to kind of get that number i'm going to start writing the code so hopefully that explains a little better i know that i hand waved this part of the explanation but this is something that you know um i would if you do have trouble kind of uh making you know i think the key part about this problem is making the observation around um reusing the number the count of a given node um or like the count of the number of subtrees for a given node and because if you do then um the other part of the counting is just commentarics and uh or even simple commentaries counting like you know um this number of sub trees just the number of left sub trees times the number of different sub trees that the left node can have and times the number of sub trees the right node can have right um yeah and then you could do this recursively which we'll do together so as i said if this is a little confusing don't worry we'll look at it in code and hopefully maybe that's a little bit easier a little bit better okay let's go so basically we'll define a function um let's just call this this a num uh num rooted tree maybe something like that and then we have a node say right a node value or root value maybe um right let's also just set some minus above as i would like to write so that i don't have to write this later um okay actually now i'll convert this to a set actually yeah okay let's just say selection maybe do we i need that i don't know okay so then now we have you know that we could we just set the count for the for this values node right so counties you go to one uh we started with one start with one because this can be a leaf terminating right so if this is a leaf then you have one count so that's why i start with one i always like to return the value or i typed in the return value in the beginning but that's just me um and then now you know we put force on the left node and uh before it's on the left node and calculate the right node right so okay so now we do for left in selection if root value mod left is equal to zero that means you know uh yeah then right is equal to root value divided by left and then count we can just add number rooted three of the left node times number of rooted tree on the right node right on the right value that is um and of course i'm gonna forget about the model let me double i usually do it really early but i think because i was talking to farms i didn't do it so that's just too much as you go ten plus seven um and then i you know be modded every two after every time oops and that's pretty much it except for that this will be exponential as you may imagine uh so yeah but you know this is you know we'll go over real quick how do we solve that i mean i think i already gave enough hints if i would know um but yeah so the total is the uh you know let's just do calories go zero and then we just um force sum up all possible routes right so for uh is this supposed to be unique yeah i think so okay fine so for root in away um for root in a way oh i think i messed this up oh i didn't mess this up i forgot did one more check we have to check that right that is uh inside the selection of this is why i made it into a set um because if white is not in selection then we don't have to up to the other number and then we don't have to do this thing okay so for in array or maybe even selection just to keep it consistent even though it doesn't matter um we sum up num rooted tree of root and then we might we make sure we mod it again and then this should be good i mean it'll time out for bigger numbers but uh but that's it but we're going to test for correctness first before we add the optimizations cool and that looks good um yeah so the key thing to notice is just this recurrence where you know if left times right is equal to the root value then you can't do this the key thing to know obviously is that you know now that we kind of construct this problem in this way um we're going to call the number root 3 for the same number multiple times right and that's kind of why we have to fix this a little bit um because for example um well the examples they don't give they give you are not very good at demonstrating this but as we said let's copy and paste this a little bit as we said if we have something like you know let's add that some numbers uh yeah 40 is gonna call 10 times 4 um and so forth and 10 is going to call a lot of you know times right so uh well three times so just to so that we don't we use this thing we use a technique that we kind of already hinted at uh which is dynamic programming or memorization you can actually do this in dynamic programming as well obviously but let's see even six numbers oh that was actually pretty fast i thought it would be slower uh but given you know uh let me try to make this time out real quick i don't know this is just random numbers so i don't even know but and it's notice that n is okay wow this is faster than i anticipated to be honest i mean n could be up to a thousand and we're only up to 15 um so all right let's try i'm trying to get me this time now but why is it so fast uh i didn't catch it did i no okay uh hmm i mean this should be exponential so i mean i know that this kind of um i don't know i would say if i give it a submit it will fly time out and i don't but i'm too lazy to waste um a tlu so i'm gonna tell you that i'm just gonna do the memorization whoops i think maybe i would uh huh let me maybe i'm going to do something like now it's fine i'm just going to do the memorization anyway okay yeah so notice that we have repeated uh sub problems if you will uh which is a common part of memorization uh which means that we call this function the same value right um so then the key thing is just to add memorization and yeah um note that for each root value and we'll do the um we'll do it analysis later but let's put something in a set let's just call it cash is equal to um a set and if root value in cash return cash would value um cash of root value is equal to count and that's pretty much it huh i'm surprised that this is actually what went so fast and actually technically ran a little bit slower but that's fine uh let's give it a submit cool uh so what is the complexity of this right well uh it's gonna be n square um because okay we look at what are all the possible inputs to this right well there's n possible inputs to this function because each um because each input in r array can um because each possible input has to be in array right so the only oh let's say oh and possible inputs and then each chord does of n work and the o of n work is because of this uh for loop right so that means that total is o of n inputs times o of n work which means o of n and square time complexity for space complexity it's just going to be of n because as we said you know this there's only a vamp possible input so it's going to be oven right i mean that's the way i mean you know i don't think there's anything complicated in this part hopefully if so then you know maybe uh practice a little bit on dynamic or memorization um and you can also write this bottoms up uh it's a and yeah you can write these bottoms up but um i don't think yeah i guess if you do this bottoms up you can actually get designed to owe one space but um with yeah you could write these bottoms up with two pointers uh but it's a little bit annoying but definitely practice it if you're trying to really match the dynamic programming because i think that's uh i mean it's going to look roughly the same but yeah uh yeah but if you do it in a clever way huh can you do another one space no i don't i guess not but yeah uh so it'll still be all event space but that way practice or um practice the dynamic programming and yeah let me know what your bottoms up dynamic programming let me know what you think um that's all i have uh hit the like button hit the subscribe button join me in discord and hope you all have a great weekend hope you had a great week hope you have a great weekend yeah to good health to good mental health stay good stay well and i'll see you later bye
|
Binary Trees With Factors
|
split-array-with-same-average
|
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`.
We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children.
Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[2,4\]
**Output:** 3
**Explanation:** We can make these trees: `[2], [4], [4, 2, 2]`
**Example 2:**
**Input:** arr = \[2,4,5,10\]
**Output:** 7
**Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`.
**Constraints:**
* `1 <= arr.length <= 1000`
* `2 <= arr[i] <= 109`
* All the values of `arr` are **unique**.
| null |
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
|
Hard
|
2162
|
42 |
hi everybody so let's talk about chopping ring water so you're given a non-negative integer so you're given a non-negative integer so you're given a non-negative integer representing an evaluation map where the width of each bar is one computing how much water it can be trapped after running so you're giving the integer array and you're going to find out the minimum it's basically it's a difference between the minimum um it could be so if there's a zero right here and one and zero right if there's a height more than one you can actually store water over here so the concept is pretty simple so they just uh look at the diagram so this is the question of i mean this is example formal questions so the idea is you're using two pointer i and j pointer one point on the left one point on the right and for each pointer you have is maximum so left i pointer has left maximum j pointer has right maximum so the idea is you have to update the maximum if possible and add remaining water increasing the pointer whenever you can so you compare these two points first so if uh okay so we're going to say uh wow i less than j right this is definitely the first scenario case and you're going to compute the height right if the h i is less than h j then you do something right lc2 and other things so for each if statement and else statement you need to compute the maximum and add remaining water and increase the pointer so they just jump to example so zero and one right zero is less than one so you move how about so before you move you have to know your current maximum is current zero right and your value is zero so it doesn't matter the matter you cannot update the maximum so you still cannot update remaining water so you increase a pointer and right maximum is still zero okay so right now uh height is still less than equal so this is this should be listening but it doesn't matter but it should be less than equal high j right and still moving so i will keep moving so before you move you update your maximum so max means currently one and do you have water no so it increases and so on right because i still listen to it so you move but before you move yeah before you move correct before you move you can add a remaining water right since you cannot update the maximum if so you have to re add the remaining water so what's the remaining water is the current maximum minus the value itself which is one so you do have an answer which is a result it's one parallel one so you're going to compute again yeah definitely eye point uh i move right and compute again two and one right two and one and j point the decrease and before it decreases right before it decreases sorry you need to update the maximum if possible so maximum is current one and there's no remaining water so you decrease the pointer and two right two and you have to know uh you need to move i and the current maximum will become two and there's no remaining water you move right so i and uh one and two so we know the current left maximum is two and we can update the maximum so we add a remaining volume so remaining water is two minus one for the one so one plus one and you move the i pointer so on right so this is the idea so you have to update it okay and just copy and paste this is the key okay so they just folded so in okay i do have a answer which is my result is result equal to zero i equal to zero and j will become half minus one the left and right pointer and also the maximum for the height uh left and right so i'm going to say well left i mean i listen to it right so if h i is this input h j right and you do something so what you actually need to do is you need to come up to the maximum possible so uh for this one is if left one if left maximum is less than the current value you update so left max becomes the value else you are you add a remaining order which is a result plus left max minus your height but you need to know you need to keep adding right so it's plus equal and you move your i pointer now same thing for the right side so right max is less than h i j sorry then right max equal to height okay else add a remaining water write x minus i j decrease j and you return result right so that's the idea and this simply run or running the code okay i don't have error so which is high convention okay that's good and you should pass right yes so let's talk about timing space uh for space you are not using any space right it should be constant and for the time you have to traverse every single element in the array which is all of n and we are now repeating using so that will be all of them for the time or the one for the space and please a pretty challenging question for sure and good luck
|
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,942 |
hey what's up guys this is chung here again so this time number 1942 the number of the smallest unoccupied chair so we have n friends right from zero to n minus one and we have an infinite number of chairs in the party that's a number from zero to infinity so when a friend arrives at the party they sit on an occupied chair with the smallest number obviously this chair we don't need infinite number of chairs we need at most end chairs right because the entrails will be now for influence i don't know why they both they highlight this infinite okay so for example if chairs zero uh we zero one five are occupied when the friend comes they will sit on chair number two right and when a friend leaves the party so their chair becomes unoccupied at the moment they leave and if another person another friend arrives at the same time they can sit on that same on the same chair right and then given like a 2d integer right uh where times where the times have arrival and the living right indicating the right one leaving time of the eyes front respectively and an integer target friend okay so return the chair number that the friend number the target friend uh will sit down right so that's the description right so for example uh we have three persons right who will be arriving arrive arriving at different time so the first person will arrive at time one right the second person will arrive at time two and third person will arrive at for time four and we so the target front is that we want to check to so which share the friend index number one will be sitting now right so the nut obviously so for this one the answer is one because uh friend zero will come first right and then he will sit on the index zero right and then when this the index one the next one friend comes and he can only sit on the uh chair index one because the index zero has already been occupied by the first person right which has not left yet right and then here is another one right basically this one you know uh so the target friend now we're trying to look for friend in that friend zero but obviously this one the front zero will come to the end come the last because friend one will come first and then the front two and then the last one is this one so obviously uh okay so we have this kind of uh standard constraints so obviously the first thing we need to do is that we have the sort all right so we have to sort all the other times uh by the arrival time because that's the only way we can make sure right the uh each person can see it correctly okay right and then the second one is like what you know second one is the uh so when the first person when each of the person comes right we have to know right which we i mean we which chair can need sit down right i mean the brutal fourth way is that we simply just scan all the chairs from the smallest to the biggest right and then we check if this chair has been already is occupied or available right if then we just return the first one right which is available right and meanwhile we also need to uh try to release right to release the each chair right by the current arrival time but that will obviously it will tle right because that will be n square time complexity right so a simple fix is that we have we can use priority queue right because priority queue can is a it's a convenient like data structure that can convert of end time complexity into of log and time complexity if we if what we need is the smallest value or the biggest value right in this one is exactly what we need right we want to find the smallest number which is the perfect candidate of using the uh priority queue okay so what we need is actually we need two priority queue right so the first one is for what the first one is for the uh for available chairs right so for the available chairs and the second one is a used chair use chair okay available chair this one is pretty straightforward because we need to find we need to use this available chair to give us all of one uh to help us find the first available one right but for the used chair the reason we use the priority queue is that you know given like arrival time right arrival time here we can simply uh use this arrival time to pop all the uh the chairs that have already been uh freed up until this arrival time by using this priority queue right basically we simply just pop uh the chairs out of the priority until the first one is it's greater than this arrival time right so i think that's it right so it's just two priority q implementation uh yeah so let's do it um you know since we need to sort times first but we still want to uh up um obtain the original index the reason being that we want because we need this targeted friend right to find to look for to use this times index right after sorting the original index is gone but we still need to find which person is for this target friend right that's why you know we're gonna i'm going to create like an expansion right off the current time which is the rival and the leaving and then the index right for i dot arrival leaving in the numerator right times and then we have times dot sort okay we sort right now we need two uh prodigy right so the first one is available shares right it's going to be the at the beginning everything's available right that's why we have off end but we have a hippie fight right okay we have we need to heavify the uh this entire list and we have used chair okay it's going to be another like prodigy right so we simply just loop through the uh the times from the earliest to the last arrival leaving and i in times right so first free all chairs all used shares whose arrival time uh living time right is either equal or smaller than the current than this a right that's what we need to do first because at the moment the this one the chair gets freed this person can sit on it okay it's going to be we don't need a living anymore we need the index will be the hip hop of the used chair right oh because oh so here we store two things right it's going to be the leaving and then the index right and where this one is obvious this one is simply just the index right chair index that's why you know we have this one and then after this one we're going to add it back to the available shares right it's going to be heap push off available shares and then the index right so for the available chairs we don't need the any time all we need is the index itself okay oh so what i'm what am i doing we haven't even used right the while loop here so while the used chairs are not empty and these use chairs first one and the first one right it's either smaller or equal than this arrival time then we do this right now for the current index right so we have current one which is going to be the pop of available chairs right so this is the index the current person will sit okay and then if the i equal then equal to target friend right we simply return the card right and then in the end don't forget to push this you the current person's chair to the used chair which is going to be the leaving and then the current right so that's it uh run it range oh sorry i haven't i forgot to do this let's open i have times okay um yeah i think that's it right um yeah i don't know it's i think that's it's pretty standard uh priority q problem i would say that uh maybe there are other like solutions but to me the product is the most straightforward one because like i said it helps us to get the smallest value in log and time right which is exactly what we need for this problem and yeah and we just keep maintaining two priority queue yeah i think that's it for this one and thank you for watching this video guys stay tuned see you guys soon bye
|
The Number of the Smallest Unoccupied Chair
|
primary-department-for-each-employee
|
There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**.
* For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`.
When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair.
You are given a **0-indexed** 2D integer array `times` where `times[i] = [arrivali, leavingi]`, indicating the arrival and leaving times of the `ith` friend respectively, and an integer `targetFriend`. All arrival times are **distinct**.
Return _the **chair number** that the friend numbered_ `targetFriend` _will sit on_.
**Example 1:**
**Input:** times = \[\[1,4\],\[2,3\],\[4,6\]\], targetFriend = 1
**Output:** 1
**Explanation:**
- Friend 0 arrives at time 1 and sits on chair 0.
- Friend 1 arrives at time 2 and sits on chair 1.
- Friend 1 leaves at time 3 and chair 1 becomes empty.
- Friend 0 leaves at time 4 and chair 0 becomes empty.
- Friend 2 arrives at time 4 and sits on chair 0.
Since friend 1 sat on chair 1, we return 1.
**Example 2:**
**Input:** times = \[\[3,10\],\[1,5\],\[2,6\]\], targetFriend = 0
**Output:** 2
**Explanation:**
- Friend 1 arrives at time 1 and sits on chair 0.
- Friend 2 arrives at time 2 and sits on chair 1.
- Friend 0 arrives at time 3 and sits on chair 2.
- Friend 1 leaves at time 5 and chair 0 becomes empty.
- Friend 2 leaves at time 6 and chair 1 becomes empty.
- Friend 0 leaves at time 10 and chair 2 becomes empty.
Since friend 0 sat on chair 2, we return 2.
**Constraints:**
* `n == times.length`
* `2 <= n <= 104`
* `times[i].length == 2`
* `1 <= arrivali < leavingi <= 105`
* `0 <= targetFriend <= n - 1`
* Each `arrivali` time is **distinct**.
| null |
Database
|
Easy
| null |
3 |
hello guys Welcome to our YouTube channel today we will see the problem of lead code that is longest substring without repeating characters in this problem we have string s and now we have to calculate the maximum length the longest substring that has no repeating character okay fine so let's take this example but we need some variable here like some data structure map will be the one okay so let's take map and we need certain point as I starting will be 0 and J will also be 0 okay and one will be the answer variable in this we will store the answer cool initially it will be zero so we will Traverse from starting to end when so first what we have a we will check if it exists in the map or not currently it does not exist so we will post a in the map and our answer becomes answer of maximum of answer and J minus I plus 1 because we need the length and so what will be the answer here answer will be initially both I and J are 0 so 0 minus 0 plus 1 so answer will be 1. fine so here J was 0 now J equals one they will move further so V is there if V is there we will check the exist in the map or not so it does not exist we will push V also in the map and then we will check the answer so answer will be what J minus 1 J minus I plus 1 basically J is 1 I is still 0 so 1 minus 0 plus 1 so answer becomes 2 again because we have to take the maximum so one maximum of one and two so one Solutions 2 so here becomes two C is also not there in the map we will push C and sentence they it's simple now the case comes where we have repeating characters so at J equal to 3 we have a and a also exists in the map so we can't take a that's fine we have to delete this if a exists in the map we will delete this and also increase the I pointer so now I becomes 1 but we will not increase J pointer here so J will be 3 only so we will take a here so we will again check if a is there in the map now we have deleted the a so it is a is not there so we will again push a there okay and now chat answer will be js3 I is 1 3 minus 1 equal to 2 plus 1 that means three maximum of three and three answer will be three foreign then similar for C we will delete this here answer will be the same 3 then similarly for B and in this case there is only one unit there are all RB so one unit so answer will be one so let's see some code and I'll explain code then you will understand better okay initially we are given this function so if spring is null it does not have any character so answer will be 0 because there is no unique character so other than that we will go to this function solve and it will solve our problem so initially we need certain variables that is answerable answer is one of them and I J N I will have whatever cell of string okay so we need one word One data sector that is map so they will drive us using while loop so what we will do if any character does not exist in the map we will push into the map and then take the answer this thing okay and improve the check increase the check pointer so if like in this case K was already there in the map so we will execute this condition we will delete this or simply increase I plus fine that is perfectly fine and we will directly return the answer let's check our code by submitting if it's working fine or not so first level done it's working in the test cases so now we will submit yes this is perfect perfectly fine thank you guys for watching this video subscribe our Channel like this video and enjoy do coding
|
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,877 |
Hi Haldighati My name is Rohit and welcome to my channel code YouTube Channel and subscribe comment and Chocolate Chapter Question without first ingredient Usse Means Minimizes Maximizes Pair Time Hey phone, first of all read the question, you will see this cross and then we will dip the people Solve it like this Hello friends, I am on the questions page then at maximum the last included to appear for example a fair 153 then when at maximum marine maximum oneplus 5t agree for class 4 maths 968 is equal to make him in the way of events and Fear of the elements of na minute invite it appears at each element of na intense pain in maximum appears pe mile to return minimize maximum of the day what to do in the book in the past days which now input think of it so now we have done Click here on the first element and link below everything. So friends, you will definitely make a tree of the previous amount, so like see here, make the maximum of 352 maximum to subscribe, what do we do before loot here 3.23 Free pipe is given Ludhianwa ok so 3.23 Free pipe is given Ludhianwa ok so 3.23 Free pipe is given Ludhianwa ok so 350 here how to know that it is to be taken with free and here see the last moment subscribe with half an hour or with delivery share subscribe sum yes its done my Vinod will go So Kapoor and Vaibhav waste a minute against it, I invented it and it's done, we take it here, it will come even after the free trial and we fix it, first of all, subscribe to the channel and subscribe. Why would you do it with a pipe? It will be sold. The idea of party is 7766. Sorry, sorry. Here's 28th idea of party is 7766. Sorry, sorry. Here's 28th idea of party is 7766. Sorry, sorry. Here's 28th Radhe, how are you? Open a poem. First of all, we have taken a semester so that we can keep knowing the maximum and control. For this, we have come to know that whatever mail is maximum, it will become strong and more than that maximum verification will stop, finally we will unmute it, let's take v5 of like policy, turn it on mode, with this program it will automatically clear. It will happen that tomorrow what will I do in school Bluetooth first of all then first of all desi ghee has also been used or cave what 5 pro M2 camphor program but 2014 26 then he will appoint mentor and mute him first of all if he started What has happened, yes, it has become anti-threaded and looted, so how far is this era going on for us and I am facing New Zealand problems, but even I am Ankit Vivo 's congratulations 1234 pucks, not for a week, it will 's congratulations 1234 pucks, not for a week, it will 's congratulations 1234 pucks, not for a week, it will last till 2012 of any one company and Subscribe and go ahead and then turn on the oil and gas to the maximum and check it while the program is running and then submitting it so and so quickly and checking that when the subject is a very simple program and Thank you. If you liked it, please like, share and subscribe the channel. Thank you.
|
Minimize Maximum Pair Sum in Array
|
find-followers-count
|
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs.
* For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`.
Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that:
* Each element of `nums` is in **exactly one** pair, and
* The **maximum pair sum** is **minimized**.
Return _the minimized **maximum pair sum** after optimally pairing up the elements_.
**Example 1:**
**Input:** nums = \[3,5,2,3\]
**Output:** 7
**Explanation:** The elements can be paired up into pairs (3,3) and (5,2).
The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7.
**Example 2:**
**Input:** nums = \[3,5,4,2,4,6\]
**Output:** 8
**Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2).
The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8.
**Constraints:**
* `n == nums.length`
* `2 <= n <= 105`
* `n` is **even**.
* `1 <= nums[i] <= 105`
| null |
Database
|
Easy
| null |
518 |
lead code problem number 518 coin change to so this problem gives us an integer array called coins which represents the coins of different denominations and an integer called amount which represents the total amount of money so the goal is to return the number of combinations that make up to that amount and if that amount of money cannot be made up by any combination of the coins we just return zero and we can assume that we have an infinite number of each kind of point and this is just some additional information about the test cases okay so my approach this problem is to use a 1D dynamic programming array so let's say this was our test case so first again we have the DT vector which will store amount plus one amounts of zero in this case amount is five so we will have six zeros where the first one will be one next we have a for Loop which iterates through the coins right now our current coin is one and here we have a inner loop so I is one is less than the current amount so if I minus one is uh more than or equal zero and since i1 minus coin is zero so in this case PPI this value here will plus equals I minus coin which is zero which is one so this will become one I will increment now is two 2 - 1 is one I will increment now is two 2 - 1 is one I will increment now is two 2 - 1 is 1 one is more than zero so again we do the same thing one and basically it will be the same for all right just to confirm plus one again so three 3 Min - one is one again so three 3 Min - one is one again so three 3 Min - one is two so 3 - one is true so DPI 3 0 1 2 3 two so 3 - one is true so DPI 3 0 1 2 3 two so 3 - one is true so DPI 3 0 1 2 3 this number plus equals it was Zero before plus equals DPI minus coin 1us coin is 2 0 1 2 which is one so all of these are one at first at the first coin okay next I will reach the N amount so now coin will become two for the next coin I starts at one again so 1 minus coin this is1 and since this is not more than zero so we skip this now two 2 - 2 is 0er so we update this now two 2 - 2 is 0er so we update this now two 2 - 2 is 0er so we update again at two 0 1 two so this plus equals I minus point and - coin is = to - 2 this is 0 point and - coin is = to - 2 this is 0 point and - coin is = to - 2 this is 0 right so 0 1 2 this one + Zer is still right so 0 1 2 this one + Zer is still right so 0 1 2 this one + Zer is still one next I is three so 3 - one next I is three so 3 - one next I is three so 3 - 2 this will equal 1 so 3 - 2 0 1 2 3 this plus one equal 1 so 3 - 2 0 1 2 3 this plus one equal 1 so 3 - 2 0 1 2 3 this plus one which will give us two next I is 4 - 2 is 2 0 1 2 3 4 two next I is 4 - 2 is 2 0 1 2 3 4 two next I is 4 - 2 is 2 0 1 2 3 4 this plus this will plus IUS coin I minus coin in this case is two 0 one two this is one two I is now five right so if I minus coin 5 - 2 is coin 5 - 2 is coin 5 - 2 is three since three is more than zero so five 0 1 2 3 4 five this number here plus I minus coin 3 0 1 2 3 which is two so Become Three okay next we go to the next coin which is five I back to one so this will become 1 - 5 this is 1 - 5 this is 1 - 5 this is -4 ne4 is lesser than zero we skip it two3 right so this will go on until we have five 5 - 5 is 0er so 0 1 2 3 4 5 so have five 5 - 5 is 0er so 0 1 2 3 4 5 so have five 5 - 5 is 0er so 0 1 2 3 4 5 so three will plus d i minus coin I minus coin is zero so 0 is one this is four okay now when we look at DP you can see here we return DP amount is five 0 1 2 3 4 5 means that we have four ways to make a combination to make up that amount right if we will have if the amount would to be four for example then we would have two ways which is 2 plus 2 or 1+ 1 plus 1+ 1 right so basically or 1+ 1 plus 1+ 1 right so basically or 1+ 1 plus 1+ 1 right so basically that's how this uh DP algorithm works that's all I have to show thanks
|
Coin Change II
|
coin-change-2
|
You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the number of combinations that make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `0`.
You may assume that you have an infinite number of each kind of coin.
The answer is **guaranteed** to fit into a signed **32-bit** integer.
**Example 1:**
**Input:** amount = 5, coins = \[1,2,5\]
**Output:** 4
**Explanation:** there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
**Example 2:**
**Input:** amount = 3, coins = \[2\]
**Output:** 0
**Explanation:** the amount of 3 cannot be made up just with coins of 2.
**Example 3:**
**Input:** amount = 10, coins = \[10\]
**Output:** 1
**Constraints:**
* `1 <= coins.length <= 300`
* `1 <= coins[i] <= 5000`
* All the values of `coins` are **unique**.
* `0 <= amount <= 5000`
| null |
Array,Dynamic Programming
|
Medium
|
1393
|
1,238 |
so today we are doing this problem from little contest 116 so the problem is 1 2 3 8 and says that we have a circular permutation in a binary representation that's the title now what is the problem we get two integers and start and we want to return any permutation from 0 to 2 to the power of n minus 1 such that every number it has a couple of properties the first property is that the first element has to be start that we get as input here and the second property is that every element in the next differ by only 1 bit in their binary representation this last property is that every element in the first element and the last element also differ by one bit so it's cyclic and this portion here the tubeless the last properties are the exact definition of gray code and I have a video that explains in details what the gray code are and how to generate a sequence for them I will put it in the description so please watch that first and then come back to this video so the only difference in this problem is that the sequence has to start with the value start right so that's the only difference you can look at the example it just shows that each of them differ by one bit and then that it starts with the value that we have as input here right and so once you watch that video please come back to this after that I'll just use the exact formula that comes from that solution so let's first let's see how we can solve this I'm just going to get rid of moment and so the way we are going to solve this is first we're just going to generate the sequence gray code sequence using that formula from the previous loop from the video that I have in the description starting from zero right so we'd have four let's say n equal to 2 as in the example we would have starting from zero and then the bit zero one so they differ by one bit and then 1 0 and then 1 so this would be the gray code and then once we have the gray code let's say well put it in a list in order we wanted to start with the value start which is 3 right so in order to do that we can simply just get the index of that right so we would get that it starts at position 0 1 2 3 right so we will have I and in this case I would be equal to 3 and all I need to do is I can just return the portion starting from I right and so I would get and then the portion and then just before I write so this way I would have ice thoughts I would have the list of the sequence starts with the value start right and so this will basically say ok let's just put 11 right 1 here and then put the rest which is this portion here so that portion would be yeah so pretty much just the portion after I and then the portion before eyes to that to I can have this one starts first and yeah so that's pretty much it so let's write it down so first we need rest and then we need to go with eye and range of 1 to N and then we need to add to res this is just the exact formula of generating a great code from the from a binary that we have in the previous video and so we'd have one like this and then so not just print dress to show you what's in there so it has zero one and three so it says zero this volume is 1 and then 1 actually and then 2 is 1 cell right and so if we do this here what was I the index would be actually 2 and what you will get is the portion just ending at this right from I to the rest of the list so that would be like this and then after that we'll get the portion before that right so 0 1 so you can see that I still defer by 1 bit right because the final sequence all get is like this and 0 1 is still do still differs by just 1 bit 2 1 and we still have and we have the sequence correctly starting with the value start right and so let's just do that then so this that would be and we can just run this and submit okay so that solution passes yeah so next we'll look at a different solution and okay so now let's see how we can come up with a different solution so let's say we want to avoid needing to get the index here right so one trick we can do that it's just is here we want to always start with the value of start so we can just resolve with that like this and that way we don't need to return the index because it was automatically start it want to start with start because of this exalt here so let me just put parentheses and you can return rest so let me just show you first because this may be not so let's say we have the value three right let's say value three if we observe so this is let's say our cell values three right so in our sequence here we have first the value 0 so at 3 X or 0 would give us 3 so we'll get so we will get 1 first right so we'll get 1 first right so remember our sequence original sequence is like this our original gray code sequence without not starting from start necessarily is this so this is the great word sequence and now we want to start with start so you can see three with zero is three so that means that this would make our sequence be first three so one and now if I do three zero right so the next one would be zero one right so if we do 0 1 which is 2 you can see now we get 1 so we get 0 1 and then they differ by one bit right and then now we do 3 with the next value in the gray sequence which would we want to come up with this way so we get 1 which is 3 so we'd get 0 right so we get 0 because an ottoman turkish audre the sultan 0 and then 3 with the last one which is 2 so yeah - so that would give which is 2 so yeah - so that would give which is 2 so yeah - so that would give us actually I made a mistake here because the second one should be exalt with 1 which would give us 2 which would be 1 0 and then here when we exalt with 1 0 which is covering with 2 we'd get 1 so I'll get 0 1 so we'll end up with this sequence which also has all the properties of the problem diffusion here and this works because Owings any element any value with 0 would give the valley itself so that guarantees to us because the gray code sequence starts with the zero that's guarantees to us that we are starting with start and then drawing an element with itself you can see gives us 0 and then soaring with so it doesn't make it vile if you exalt with 3 its each they already differ by one bit they will still differ by one bit right and yeah so that for this solution and yeah that's it for now thanks for watching and see
|
Circular Permutation in Binary Representation
|
alphabet-board-path
|
Given 2 integers `n` and `start`. Your task is return **any** permutation `p` of `(0,1,2.....,2^n -1)` such that :
* `p[0] = start`
* `p[i]` and `p[i+1]` differ by only one bit in their binary representation.
* `p[0]` and `p[2^n -1]` must also differ by only one bit in their binary representation.
**Example 1:**
**Input:** n = 2, start = 3
**Output:** \[3,2,0,1\]
**Explanation:** The binary representation of the permutation is (11,10,00,01).
All the adjacent element differ by one bit. Another valid permutation is \[3,1,0,2\]
**Example 2:**
**Input:** n = 3, start = 2
**Output:** \[2,6,7,5,4,0,1,3\]
**Explanation:** The binary representation of the permutation is (010,110,111,101,100,000,001,011).
**Constraints:**
* `1 <= n <= 16`
* `0 <= start < 2 ^ n`
|
Create a hashmap from letter to position on the board. Now for each letter, try moving there in steps, where at each step you check if it is inside the boundaries of the board.
|
Hash Table,String
|
Medium
| null |
1,092 |
Okay so hello everyone this is Akshay here today we are going to see questions from all the other types of LCS the important questions among them are Shortest Common Super Sequence Hard Category we will cover these but before that we have two more questions which we will Will cover Delete Operation for Two Strings and Maximum Length or Repeated Sabre. Why are these three questions asked together that all three are variations of LCS? Right, so this is a sheet which I had designed and its link is also in the description and this sheet We are covering, so this sheet is designed in such a way that we cover all the basic topics to advanced topics and specifically the remaining three questions, we will see them one by one, okay, so if you have not seen the Longest Common Sub Sequence, then first First watch this is its pre-requisite First watch this is its pre-requisite First watch this is its pre-requisite video, this is the playlist of lead code solution, yes, you will get this video, now let's start with its next three variations. Okay, this is the first variation and let's say the third variation is delete operations for two strings. Let's read the question once. So we have been given two strings word one and word two. Return the minimum number of steps required to make word one and word two the same. Okay, we have to make word one and word two the same. What operations can we do? We can only delete exactly one character in this string. Okay, this is this string. Right, so C and Eet are right. So let's take it. Friend, on our one note, C and Eet. We have correct. Let us delete the minimum characters. Yes friend, so first we take out all those common characters, from these, what is the meaning of taking out common characters, we will take out the least common sub sequence from this, so S A and we have E AT right, so the least common sub sequence is which one E A and E A or because it is present in both of the strings so again the least common sequence is pretttttttttttttttttttttttttttttttttt of course so now we have got the length 2 lcs has a length to mean which characters we have to delete this s Have to delete and this t has to be deleted so can I say m + n - 2 * LCA will it give can I say m + n - 2 * LCA will it give can I say m + n - 2 * LCA will it give us the answer will give if you solve this then what will happen 3+ 3 6 solve this then what will happen 3+ 3 6 solve this then what will happen 3+ 3 6 - 2 * 2 4 What will give you 2 right So we have taken out - 2 * 2 4 What will give you 2 right So we have taken out - 2 * 2 4 What will give you 2 right So we have taken out all the common ones. After removing the common ones, we are telling the extra characters that are left to delete them, only then our string can be the same. Right, so this is our longest common sequence. Problem of In this we had discussed all the approaches Reckon Memorization and Tabulation In this we have also considered Printing LCS but today I will explain it to you and we have also discussed its space optimization, how can you watch this video I am using the same code from here I will copy paste it and bring it here. In the delete operation, I wrote the same code of LCS, just returned so much in the last that it returned m+ n - 2 st dpn1. It took one and a half minutes to solve this question, with respect to keeping our basics clear, okay. Moving on to the second question, Maximum Length of Repeated Sub Array Correct, so what does it say in this we do not want sub sequence, meaning we do not want the longest common sub sequence but we want the longest sub array. Now what is the difference between sub array and sub sequence or look at the sub sequence. What happens is you write A B C right and you have A in sub sequence, this is what happens, let me just tell you can skip characters like A is your sub sequence but A is not your sub array in sub array. You cannot skip characters. If you want to go till AC then you will have to take complete ABC. A B C, all these will be sub-arrays. How can we do this right or again, sub-arrays. How can we do this right or again, sub-arrays. How can we do this right or again, which was our matrix of LCS. How did we create this matrix, this is the DPR, you must see it, once you understand it, we have to do the same thing again. We will match only one thing here, wherever the characters are the same, we have to take rights only for those. So once we make the matrix, zero what are the elements 0 1 2 two and one right, once we make the matrix, right away, so here are the elements, these elements denote off second numbers two, this is nothing but numbers two. And this is nothing but the roses are number one right numbers one and this first and first column will be zero because if there are no elements in an array then definitely the answer will be zero. Correct, so what do we have to do here if the character is the same. So definitely what we will do is we will find the answer from our diagonal but if the character is not the same then what we were doing in the Longest Common Subsequence was taking the answer from up and down, we will not do that here because what was the Longest Common Subsequence that you can skip the character. You cannot skip correct again. You will understand what I am saying only if you have watched the video of Longest Common Sub Sequence and today you have understood correct. So, if we go back to the matrix then the characters are not the same. We will quietly go on marking zero Right so this is one and three so one again so one and one matches I will take the diagonal one and my maximum repeated sub array of length one will be the diagonal element plus 0 Now what does this mean? Hey friend, we are comparing, we know which all eras are being compared at this point, right, which all eras are being compared at this point, I will write for you 3 2 and there is two in bow and here only you have One this compare and definitely you can also check it manually the answer is sub array which has the element one ch has length equal to two so this is actually getting storing the length ok let's continue again one if there is never a match then fill it with zero similarly For two again three will not match so only two will match here so do the diagonal element take plus and similarly it does not match for rest of the thing but again for three it will match for this place so I will say the diagonal element and Is zero I will take one and rest of the elements again with b f vi zero because there is no three present anywhere here Okay for two again zero two is matching here so diagonal low and do a plus two and two zero For all the cells again for one we will do the zero for all the cells where the one came we will take the diagonal and do a PSV and everything is zero right so this way you are getting a non zero values that is again getting a non zero values that is again getting a non zero values that is again a possible sub array. Right, a possible repeated sub array, so what we wanted was the maximum. Right, take the maximum of all the non-zero values. Right, take the maximum of all the non-zero values. Right, take the maximum of all the non-zero values. What will be their maximum? If 1 2 3 is visible, then what is the maximum? The answer will be, now you will know a little. Also look at this manually what does this mean know what we are actually considering we are considering in numbers one 321 and we are considering in sorry in numbers to this is your n2 and numbers one we are considering t 321 and you see So this is being repeated that we are getting an answer, I have found zero in all these places, so definitely the answer is not going to come from there, it is not coming, that is why it is zero, correct, so the thing is that we have found a simple Wrote the code of LCS itself with two loops and maintained a maximum variable. We have seen that where the character is the same, take the diagonal element and do a plus in it and keep the track of the maximum. This will give you your answer right. But now it's okay, friend, first understand this much, then if I submit the code, it will definitely be submitted, but I want to do a little extra work from you, if in your interview I asked you to print a little bit of the sub, then how will you do it? So this solution is submitted button, a little more cache, if we have to print then how to do it, then what we will do here is that wherever the index is becoming our non-zero, we will wherever the index is becoming our non-zero, we will call print sub array in the correspondingly last. Meaning, for this particular case, what would the AND index be pointing to? And ID would be pointing to two so this is the 0 1 2 3 fur and 5 so an ID would be pointing to a my it would be pointing to four and this is the array which Is of numbers one and let's say the first array and the first array is denoting here age t1 so that is why we are passing t1 age parameter the end index and the maximum length what is happening in the helper function is that we have this so let me Write the first array with the t1 array let's say so it is 1 2 3 2 and 1 indices r 0 1 2 3 4 Now we have a for loop running from i into and index that is far minus the length Neth is nothing but the Length of your repeated subarray chvch came s the so 4 - 3 p 1 vch will give you so 4 - 3 p 1 vch will give you so 4 - 3 p 1 vch will give you age 4 - 3 1 p 1 2 and we have to go till index a lesson age 4 - 3 1 p 1 2 and we have to go till index a lesson age 4 - 3 1 p 1 2 and we have to go till index a lesson equal to and index which is nothing but 4 so I hope the screen Is visible let me just scroll it so that means from index to four I need to print the array so can I see from t to four can I say that this was actually my length of longest repeating sub array okay man so this question Also, this is an extra slight variation, we have covered this also, once I uncomment the code, I will show you the output. Great, so you can see that in STD out, we have got the longest length of repeated sub. We have done slight modification, we also kept track of the updates which we were doing and the index. Okay, finally coming to our question, in the shortest common super sequence, let's see this question or what is saying first and we do this question. How can we then see what would be the code there? So this particular question is, shortest common sub super sequence, here we have to return the actual string in the output, right, there can be multiple possible strings, the answer to any one. We have to return but if they had said just return the length right then we would have done it easily like if we have to return the complete string then first we will have to learn how to print the LCS right once we understand the question first So we have been given ATR and A2, we have to find the super sequence means that string in which whatever string of these two is present, their characters are present, meaning that this string, whatever your super sequence is coming, let's From c b a then a1 and a2 as a sub sequence should be present for this ring you can clearly see a right so a b a s1 is present atr and is present similarly c a i can clearly see c a and that is also present Right, so Y LCS, we, or LCS, how can we solve this, what we can do is that first we find out its LCS, whatever are its repeating characters, first we take them in our hands, so in A B A C A B. What are the repeating characters and what is the LCS here LCS is a right this is the longest common sub sequence and now what I do now what I wanted was to make a string in which s1 and s2 means make a super sequence right super sequence Make one in which s1 s2 is its sub sequence, then take out the least common sub sequence. Right and take the remaining length of the characters. Right, if I have taken A, then the remaining cactus length. What happened here, I write the remaining cactus length. So here the remaining cactus length becomes one and the LCS length becomes two. All we have to return is 2 + 1 + 2 which All we have to return is 2 + 1 + 2 which All we have to return is 2 + 1 + 2 which is f and this would be our answer. You can see that the output string that we have is five. Five is the length right. Similarly, now it is okay to verify for the second output. So if this query was to return only the length then we would do the same but the query is not like this, we have to return the actual string also, so we can do our work with this formula. Goes n + m our work with this formula. Goes n + m our work with this formula. Goes n + m - LCS So now let's go to printing the - LCS So now let's go to printing the - LCS So now let's go to printing the LCS, first let's see what is printing the LCS but again pieces it, first of all you should see how we did this matrix form because I am using this matrix right now. I will write and how to form the LCS in it, how to print it, they will see, okay, so we have the string kya-kya de rakha tha yaar a string kya-kya de rakha tha yaar a Clearly C A is my answer so after forming this matrix we will have to create this matrix then what we will do is we will start our pointer from here right from last and we will see that if the characters are matching using the I and jth index and definitely we will move in the diagonal why will we move in the diagonal because see when these characters were matching then we took from the diagonal and returned by plowing right then we will move towards the diagonal meaning i minus and j Mine minus let me show you the code along with Okay so we have our pointer at the last cell that is j = m and j = n and we're cell that is j = m and j = n and we're cell that is j = m and j = n and we're moving if the characters are the same we're definitely moving in the diagonal that is a my mine and j-1 at the same time you need to append that particular my mine and j-1 at the same time you need to append that particular my mine and j-1 at the same time you need to append that particular character in your answer so we have a string builder here so edge of now we will have this character z right and we moved into the diagonal in the diagonal top now what we have to Do now, how were the answers coming, I mean, remember the time of filling, how we filled, if the character is not the same, then up, this arrow is visible, up and from the left, we had taken the maximum value, we are right here. We will check which is the maximum in which direction and will move in the same direction, look, we have also checked this is the value of our up row, above row and this is the value of our left row, right top and left, so let us see which is bigger. Who is bigger on this back? Top is bigger, left is bigger, so there is one on the top, there is zero on the left, so definitely I will move in this direction, right, this is the red pointer that I am showing, this is the direction of our printing the LCS, so again I will see here the characters are not matching because this is Then I will see the characters are matching now right so I will do that character in my string builder and since the character match I will move in the diagonal direction now you can clearly see that I have reached index zero and this way The loop will stop because the index should be taken the I as the index should be given equal to 0 to have the processing now this string builder is actually having our LCS but in the reverse order so what we will do we will call a reverse function string builder d reverse sb2 sting and we will have our lcs datchi so this is in the shortest common super sequence now this is our printing the lcs once we got the lcs like in this case a was also our lcs if we got lcs If we get it then what we have to do is to traverse both the strings and pick up all the characters except those in LCS. This is what we have to do. Okay, so here is its code. Here, this is the code of the longest common sub sequence. This is printing the LCS and this is the shortest common so first of all we called LCS right and we have stored that particular LCS into a string builder and we are creating a new answer here right here which will actually store the shortest. Common Super Sequence and what we are checking here is we are traversing for each and every character present in our LCS and we are checking that we are using a while loop first of all and we are seeing that when ever the Characters are not matching with the LCS We are taking that character and we are moving ahead in the strings in both the strings right and when there is a match We are just adding that particular character here correct and we are moving the points p1 and p2 OK So, let's see a small diagram of this code. What are the given characters? s1, s2, this is s1 and the second character is s2, our C is so p1 and p2 pointer, we keep the right first character in LCS at the starting point. We have a right so we're going to have an answer string here and we're going to traverse through a wide loop here until our character is equal to the character in the LCS. We'll keep on appending but I can see that the first character it. From the self for which we were searching right then we will stop here means the wire loop will exit from here. For the first string the second wire loop will go again. For the second string I can clearly see the first character is C which is not. Equals to a so aa will add in my answer string builder this is my answer right so I will add see and now my p1 will go to first index right p p2 not p1 p2 will go to first index and I've clearly seen the current character is a and a we for a we were also seeing right so again Y loop for both end will be right end now we will append our actual lcs character so c a would be appended and p1 will be move forward and p2 will Also b moved forward so p2 will not be pointed to b p Here now the second character was b so I will search for the character which is not equal to b and keep on appending my answer string builder so I can clearly see the first character it itself the p1 index is already having been so first wire loop is exit we will go in to the second string and easily see clearly that the p2 is again pointing to be so I will not add any characters and I will just move R p2 ahead right so before moving the p2 ahead we have exited from the wire loop and answer dot append s so now will be added and p1 will be added and p2 + p so p1 will be pointed to the added and p2 + p so p1 will be pointed to the added and p2 + p so p1 will be pointed to the second index and p2 will be pointed to out of bounds it would go out of bounds right now this is the these two are actually handling that if there are remaining characters in either of the string just add all the characters right so this is because LCS was only a and b and we have Done the iteration using this for loop will exit or because the LCS characters are gone and the remaining string here is a right so we will just add a here using this for loop right so your final answer would be B.C A B A C And You Can Clearly Verify B.C A B A C And You Can Clearly Verify B.C A B A C And You Can Clearly Verify That This is Also Present in a Given Output Okay So Either That Is It We Have Just Returned Answer to Answer That String That Variation of LCS Was Ask Right So This Was Also a Good Question Okay So Okay I hope you are able to have a good graphs of all the three questions we have discussed and we have now covered all the variations of LCS here according to this sheet and let us meet again tomorrow in the next video and if you like The Video Please Like Share And Subscribe Do Support Our Community And The Social Media Links Should Be Given In The Description For Any Updates And So Till Then Keep Learning Keep Going Bye And Take Care Let Us Meet In The Next Video
|
Shortest Common Supersequence
|
maximum-difference-between-node-and-ancestor
|
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them.
A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`.
**Example 1:**
**Input:** str1 = "abac ", str2 = "cab "
**Output:** "cabac "
**Explanation:**
str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ".
str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ".
The answer provided is the shortest such string that satisfies these properties.
**Example 2:**
**Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa "
**Output:** "aaaaaaaa "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of lowercase English letters.
|
For each subtree, find the minimum value and maximum value of its descendants.
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
1,838 |
hey and welcome to today's daily lead code challenge today we'll be solving question 1,838 frequency of most frequent 1,838 frequency of most frequent 1,838 frequency of most frequent element let's get straight to the drawing phase or the drawing portion um I want to read this carefully the frequency of an element is the number of times it occurs in an array well very obvious you're given an integer array nums and an integer K so we're given two parameters in one operation you can choose an index of nums and increment its element at that index by one so if we're given a array of 1 2 3 4 at any point uh I can choose one index let's say I choose zero and increment the value by one so from 1 to two at any point uh by one only return the maximum possible frequency of an element after performing at most K operations okay so we can't per perform this operation any number of times we can only perform it K number of times and what it's really then asking us to do is uh choose a number that's going to appear most frequently given that we have this ability to increment some other numbers before that K times so um this definitely will require us to um to have the numbers in the array uh arranged in some way where we can I would say um we can structurally decide which uh in indices to potentially increment so for example if the array isn't sorted and it's given to us in a unsorted fashion then we will never know which uh which one of these indices to choose and try to increment in order to get to some certain value for example let's say that we have this array 1 4 and 2 and the K that's given to us is equal to 5 well um to a human eye it's pretty obvious that you will not be trying to get the most frequent integer to be the one because there's no way that we can get either the four or the two to be equal to one same goes for two we can't get the four equal to two so there's no point in even trying to get um two to be the most frequent number because the only value that we will be able to increment is the one well what about four in that case well if we were to try to get four to be the most frequent then we would have to increment this guy three times to get two a four and this guy twice to get two a four and all of a sudden yes we see that we can actually have four be the most uh frequent number and I believe that the that this is also the first example here so um very good to notice that however what I'm saying here is that you can see a slight difference between the input array one to 4 and 142 and the difference is it's not sorted 142 and what that allows or doesn't allow us to do is know hypothetically which numbers or which indices do should I be working with here's what the um here's what an ordered list uh here's what sort of insight an ordered list could give me if I'm looking at a number one I know which numbers should be potentially increased and that's everything to the left of it same goes for the two same goes to the four basically this whole long spiel was about me indicating that the first step of this problem should probably be to sort the array uh given that it's not in the constraints that it's that the input is a sorted array we should first sort the array what happens after well after uh let's try to visualize some potential um some potential examples or problems I'm going to say that this is a one this is a two 3 4 five six and let's just draw out what a potential input could be um four let's have the rest be six and let's have the number K and I'm no longer looking at this example the number k b uh this is what 1 one 2 3 4 6 the number K let's have it be equal to uh I don't know five as previous well the way that I would like to visualize this at least is as I'm potentially ex uh looking at all of the numbers that are possible to be the most frequent which are one two basically just all the ones that appear here 1 2 3 4 and six uh 1 2 3 4 and six I'm going to be I need some sort of uh maybe like start and finish start being at the start and finish being at the Finish um if I'm already looking at a specific number in this case one I know that there are no other potential ones that I can that I have encountered because one is the first number so I would say that something like uh some Max that I'm keeping track of is currently at two then I could start looking at uh the next value I could move um I could move end to a new position this new position indicates also a new number uh and what do I do now well the way that I want to visualize this is by having this sort of like um this like water this body of water taking up some units of unfilled ples in this case I can see that um oops sorry I can see that my units of space that the water needs to occupy this being the total amount of water that I have at my disposal is going to be two and what does this two give me well if two gives me uh two gives me a Max of now three why well because now this one is at a two this one as is at a two and this one as it is at a two so I would have the total frequency of the number two um pushed up to three now that's my new Max what do I do next well next I would like to uh step up my potential uh number to the next possible one which is going to be three let's look at what a oops let's look at what a start and an end that's at three at the number three would look like well I know what sort of body of water would be needed to fill up the extra space and I can see that would be one 2 3 four five well there we go my ma my new Max is probably going to be five Max of three and five is five um y5 1 2 3 4 five there we go with this new approach what I'm with this approach what I'm doing is each time I'm um I'm setting this boundary the left and the right the start and the end to some position in my input array which are actually indices and I'm trying to use up as much K as possible to fill up the space needed this space will later be called maybe something like div like difference between the between what is between the volume that is this and the volume that is actually the current sum so something like the difference between let's say what is in the yellow box versus what is covered in the green um something along those lines you see the point though right so I'm now next step one wanting to move up to the next um to the next possible value which is going to be now four I see that my uh start and end are still at uh or my start is still at zero but that could potentially change let's see what sort of box I have to fill up if uh I'm looking at four as my potential well it's going to be 1 2 3 4 5 6 * 4 it's going to be 24 uh 5 6 * 4 it's going to be 24 uh 5 6 * 4 it's going to be 24 uh minus or no let's just keep it at 24 and what is the current sum that I have 1 2 3 4 5 6 7 8 9 10 14 so my current sum is at 14 so 24 - 14 I get my current sum is at 14 so 24 - 14 I get my current sum is at 14 so 24 - 14 I get uh 10 which means that the space oops the space that needs to be filled up is 10 in this and this yellow which I know that I can't do with the amount of water I have five so I'll have to compromise I'll have to start moving up my um I'll have to start moving up my uh start potentially and I can move it up a little bit I can move it up to here and see and recalculate what my uh area is going to be 10 minus uh the difference of uh 1 and 4 is just going to be seven so that's no good too either uh so seven is no good I'm going to move up one more time and subtract from Seven another uh another three which puts me at a four what does this four mean this four means that the body of water that I have to occupy is now 1 2 3 four can I do this yes but is my Max going to be bigger than and five because now I have these four uh numbers included in there no it's not and so my Max keeps up being five and I pretty much end up with a uh with a Max of five the later on you can see that since the difference between the four and the six uh is greater than anything here there's very low chance that uh anything here is going to be more than five and so I'm stuck with these with the 1 2 33 being my Max numbers that I can squeeze out so what this process really is doing or the analogy that I drew with water is um is me having this range knowing how much this range needs to or what this what the volume of this range is because it's almost two dimensional over width and over height and then I know what the current sum is and the current sum is what I use to um figure out how much I need to fill which would be either greater than or less than uh the K uh let's try to code this up see if there's any um see if we can actually put this into code uh I'm going to have a couple of variables I said already that I want the current sum I want my start equaling and end equal oh actually end I can do um and I can use from my for Loop and uh let's have a Max frequency also equal to zero for n and in range Len of nums I'm going to uh I'm going to now what well I have to figure out what my what my possible Max width is and that would be me having conditionally moving up uh start to the position to the lowest possible position lowest possible valid position uh let's have the width or the range width be equal to end minus start + one uh let's have the height be equal + one uh let's have the height be equal + one uh let's have the height be equal just to the uh the value that we're currently exploring which is going to be nums of end we know that the um volume is just going to be width time height and now what well now we have this difference that we care about which is going to be the current sum or no the volume minus Uh current sum and while this difference is greater than K I'm going to say start plus equal 1 and also at the same time from current sum remove the nums of start uh all good there now what well now that we have all of these things in place we can simply say Cur Max frequency is equal to Max of Max frequency and the width now I'm also going to be I also kind of have to recalculate the width each time because as start is moving up so is the width so I'm going to try to squeeze this guy into the uh condition here um let's see uh let's have K is smaller than the difference which is just volume which is end minus start plus one times uh this guy right this is my width times height which is just the volume so I don't need volume minus current sum here so this is my diff is volume minus current sum and I no longer need this guy okay uh let's see would this so very clean and small let's see if this works Max frequent um might be forgetting something Max frequency width is not defined it's not defined because I removed it entirely from index out of range okay so I could potentially also be running into an issue where start is leaving it's allowed premises um let's say uh start is less than Len of nums and what am I doing here something is off I'm oh I'm completely I completely forgot about current sum has to be equal to the nums of end because I'm iterating as I'm going up uh okay closer to the truth what is the problem here let me actually do one more thing I want to uh I want to print no I don't want to print that did I not I didn't sort I was talking about having needing to have the aray be sorted the whole time and forgot to sort uh um this should work let's submit awesome cool well um yeah hopefully you learned something whoa not well not doing too well I wonder if there is significant difference between what I'm doing and what they're suggesting here with the better solution Solutions or faster Solutions it seems like we're doing sort of the right thing here with the start and the end renamed to left and right we have a sorted array and then K is just am I doing an operation that doesn't need to be there what I don't understand here is where's the while loop and how did they avoid H needing to use it entirely K seems to be like the not just the yeah they're using current sum as if it's in K which I'm confused about because I mean I totally see where they're what they're doing with the K but it might just be uh might just be more hard to read how are they all avoiding using the how are they avoiding using the while loop is what I don't understand okay this one looked good enough uh I want to understand the situation with the current I want to understand this situation so this is the width the target is the height uh and they're doing everything as I expected they're watching that a um they're watching that the volume minus the current sum which is just the difference is greater than K and if it is greater than k then they are um then they are shifting the start by one but how are they able to um to not have it be in a while loop because what if the uh start needs to be moved up more than just once what if the start needs to be moved up maybe two or three times how are they getting away with that um also Len of nums minus left huh Len of nums minus left oh this is confusing how does this work for them how is this possible wait what was the previous thing it was length minus left so it's the difference of the of where left or where the start is finalized minus the largest Val so the so they're claiming that left is only going to be moved the number of times which is equal to length minus the solution pretty much so length minus the solution is equal to left minus the most frequent occurrence of a string is equal to left how is that possible what guarantees them that left is only going to be moved up that number of times here the condition is the condition makes sense you know what I'm not going to oh there's a solution that's similar almost identical actually and it's in a good place let's instead of trying to understand how that other unintuitive solution works I'm just going to try to optimize this guy a bit I've definitely don't need to have this here I don't understand why it was why it wasn't working uh I can use the target to look at the number that I want and start is going to be moved up slightly f faster 61% good enough up slightly f faster 61% good enough up slightly f faster 61% good enough this is way more intuitive and easier to understand than the previous one I don't understand how they were get able to get away with an if and how um moving the left boundary up uh that number of times indicated that was actually the difference between the uh solution and the uh or the total length in the solution so I would much rather recommend this uh it's way more intuitive it's visually uh understandable which is crucial when you're under stress like I am right now so thanks for watching um I'll see you in the later videos please like And subscribe thank you bye
|
Frequency of the Most Frequent Element
|
number-of-distinct-substrings-in-a-string
|
The **frequency** of an element is the number of times it occurs in an array.
You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`.
Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_.
**Example 1:**
**Input:** nums = \[1,2,4\], k = 5
**Output:** 3
**Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\].
4 has a frequency of 3.
**Example 2:**
**Input:** nums = \[1,4,8,13\], k = 5
**Output:** 2
**Explanation:** There are multiple optimal solutions:
- Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2.
- Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2.
- Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2.
**Example 3:**
**Input:** nums = \[3,9,6\], k = 2
**Output:** 1
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 105`
* `1 <= k <= 105`
|
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
|
String,Trie,Rolling Hash,Suffix Array,Hash Function
|
Medium
| null |
122 |
what's up guys Leeds is elite called 122 there's time to buy and sell stop to say you'll have been already prices or which a I've element is the price of the given is talk on a day I design an algorithm to find the maximum profit you may complete as many transactions as you like for example buy one and sell one share or they stock multiple times note you may not engage in multiple transactions at the same time for example you must sell they stock before you buy again so the example one we have an array with a bunch of stock prices they output is seven and it is seven because we are buying on a day two with price one and selling on a day three and selling on a date videos with price fight so the profit is the difference between these two prices and after that we are buying on a day for with price three and selling on add a file with price six and again the profit is a difference between these two prices and yes as the output is seven it's clear that we are adding both profit here example two it seems to be pretty much the same and example three the output is zero and Israel because they stock prices here are going down so the prices are decreasing and there is yes there is no way we can get any profit here yes we already did and an exercise pretty close to this one the difference here is that here in this exercise we can buy and sell a stock four times during drink this dream Albert ethanol our for loop maybe so we can buy and sell multiple times and as we can do these it's like we are not being holders we are being like traders I can buy a stock today and so they stopped tomorrow and it get some profit here and to solve these exercise the only thing I have to do is to compare the current price with the price of two marble so I have to compare with tomorrow's price because if tomorrow's price is greater than the price the different price I can assume that I can buy it today and sell tomorrow and get some profit with this transaction and as I can do this more than one time I need a terrible to save the profits so I can just if we can get an out if I can get more profit I can just add the new profit into this variable and I think that's the solution so let's try to write some code you can start by checking if the input is valid so if prices bling the question zero we can just return zero otherwise we can start to iterate through the prices array and yes we can start at the zero index so our y equals to zero while our and pricing table and my clothes books so as I said before here we have to compare the correct price with the tomorrow's price and if Paige Morris price is greater than the price if the current price is less of the tomorrow's price we can just yes we can get the difference between these two prices and add into a Max profit variable so we can first declare this variable here we can check if the current price is less than the tomorrow's price and yes as we are doing these some here PI plus one we have to stop our iteration on the night of the last item boiling the last but one I can in this array and yes if we can get some profit with these prices the today's prices and tomorrow's prices we can just add this into over max profit variable prices of tomorrow - prices variable prices of tomorrow - prices variable prices of tomorrow - prices today and when we get out of this loop we can just return next project and I think if we do not have any typo this is the solution so let's try to run any column let's try another example let's try to hit submit and that's it so time complexity here is Big O of n where n is the length of prices they are ready prices and memory complexity here is constant because it doesn't matter how big your prices get we always allocate the same amount of memory so that's it guys thanks for watching
|
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
|
145 |
Hua hai Hua hai Hua hai Hello hello everyone wearing today Solve mindtree poster traversal problem So let's understand what is most wanted poster Means post office has to add printer and factory Printed salwar at this time Creams and finally you printing Very soft ware Printed fruit full length find the best to travel from this point postorder traversal beans first for beginners loot adv1 life in the present for after days left for president will go to strike price apni points 1540 fence safe rickshaw the first friends slapped it subscribe this channel subscribe this Light this Channel pimple so they can the left and right in this fruit and phase left and right direction 25v print enemy 100 laptop reasonable to this write-up 3483 it means write-up 3483 it means write-up 3483 it means 243 left parties of this did not find a different is heroic Son Dihi Printer and Poster Driver of Binary Tree Them All Life is the 331 After This Position After Redeemer Dad That Surya Se Police in This State Power Solution We Are Doing His First of All We Are Going to Our Left Shift Loop Under Edit Post Product I Invent Metabolism Installment Vir Root Speedy N Apne Voice Mail Pass Condition Foundation Will Have For Old Rivals Silence On Tv Channels Including Simply Return Without Printing And E Will Not Printing Unit Video 55th Left Turn Free 3D Printed Laptop Window Will Printed Subscribe Our Daily Life And You Will Know how to live without oo that I sulk value latest boot value ablative I poster traversal of mind witch two not lose fat driver railway call entry level slow not liquid fluid product top wash left with no network it is Channel Subscribe Must Result 40 Channel Subscribe My Channel I Will Always Right Here Right Balbir Post Difference 5299 Tunnel Is Not A Lens For Its Right Left To Life Is Six Video Channel Subscribe My Channel And They Will Promptly Remove The Picture Subscribe This Channel press The Amazing spider-man more looted and tried to know what will return that they will print nothing and left and right in this root tarf n ps life in this app are also in the world will remove than life image of him 1000 RS Poddar Inverter Poster Traversal And What Is The Time Complexity Improve Time Festival Of All Universe Will Be Of Adverse Effects For The Native Should Address Contact You Will Offend Because Of His Personal Costs Nothing Is Illustrating Another Is More Functional To Step Up How To Set To Know After Sending Failed To Prevent And River Pollution It Is Very Straightforward From Zinc Water And Inorder Traversal Planet Is Nothing New Suv Let's Understand It A Few Lessons Which Were Looted Complicated And Its Relationship That Nodi Solution Developed Position Behind File Open Signalman Must Like Post Expert Every Month Old Is Gold Channel Must Subscribe And Subscribe Idioms Doing This Often Visited The World Will Be More In The Middle Of We Inorder Traversal Investigate Step Which Will Help Of Wins Travels In Northern Railways Must 1st And Take My Phone To Connect with point to migrant minister for railways 123 li budget android if this current and this must be disseminated stand till pilot basis in live video channel entertain superintendent points driver shift 23.23 li bottle debit jis current you will put current 23.23 li bottle debit jis current you will put current 23.23 li bottle debit jis current you will put current affair no i will make In correct form of the collective that channel for pyun and navmesh that I want to quote don't forget friends and tap side in for hair in quest of maternal novels where and international that dysfunction verification Edison not able to attack him of elements from element 15170 And check withdraw its snow deposit is available to tide over all rights reserved for you if you spread to answer the right time to develop this into a result the native may result in more benefit from fear in the middle of taking one more last seen apne In Voice Mail Points And Which Will Help You If You Want Middle Solution For The Last Not At All But He Know This Last Year Poster For Date In This Is Life In World Tour 90 Villain Chat Our Conditional Now Current Null But Thank You For This Went On For This 512 123 Right Side Yaar This Reference For Newcomer One To Three Idiot Last Month When You Will Enter Like Comment Share And Don't Forget To Subscribe My Channel And Subscribe Now Channel Like This Element Androided App That Minister Yaar Kuch A Girl For This Month Editor Of The Given During Every Day Of Wave Top 10 Current Questions What Like Share And Live Dance Is Different From This Vansha Jisme Current 231 Middle Age 60 Subscribe No Fluid And Friends I Last Updated To Take Off But You Will Not Stop This Is The Name Of The Main An Anime Result ₹5 Nine Nidhi 9 If You Like This ₹5 Nine Nidhi 9 If You Like This ₹5 Nine Nidhi 9 If You Like This Video Back To Do Not Meet R Site Is Valid Notes Will Not Be Able To Stop This Will Not Rise In This Country But I Know It's Already Driver 900909 Pradeep On How To Make Sure Vitamin C Nagla Vishnu Life Mein Last Not Lost R Last Date For Dividend Vo Abeer Value For This Entry Was Posted In And Tagged Thursday Subscribe Indian Boys 2151 That Newly Formed Month Mike Every Mother Will Be Like Comment Me Current Aa Na Ugly In The World Which Is True For This Very Soon Second Fancy And Points Laker Top 10 Setting Shift In A Pot Na Setting Is This Point To Have Worked As A Great Friday Mobile Me Current Cosmo to front meeting do to 9 its internal no current normal 1857 end share don't left national convention against vital grind them 80 little police in front for international debit card maze north to notes2 220 help's at right nine e two not have nightmares profit end Addictive that not mean that you say against CRISIL so I will just point is just checking staff butterflies yes behave like but now last updated to us last updated to you have tried but this tower bihar state taylor swift from them and make hair power stocks and e Wasted and Current in this year's very condition the act will return disawar answer Surjeet Singh and poster and that I hope you understand it solutions will prove what is the time of president for the time objective of this position found and fungus country is the solution also found all Information before you reduced if I understand what it won't regret the formation of its formation of a little bit complicated as compared to the inventor and post or free mode on more just a minute gone to hit the like and subscribe button thanks for watching the do it do it
|
Binary Tree Postorder Traversal
|
binary-tree-postorder-traversal
|
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,776
|
1,007 |
all right let's talk about the minimum dominant rotation for equal rule so you are given a top and bottoms array and then you have to return the minimum number of rotations so that all the values in the top are the same all the bottom are the same so if you cannot do it then you'll turn it on one right so uh i'm gonna just draw just bigger all right so uh we know two we know one we're not two we know four we know two right so probably like i just have to fill out the value for two right so which is right over here right so how do you know that which value should be the one i think i need to pick right so i need to keep track of the value in the tops and bottoms up so there's a counter so i'm saying from the top and then from the bottom right so i will store all the value so the dice is going it's going to be from 1 to 7 right uh i'm sorry one two six but i need to give extra space for zero index so it's set of seven so this is new in and then sets of seven right and this is the same mac and then i need also i also need a another array for the same so if they are the same i need to also keep track of the counts so i will be able to know uh when i traverse the iteration from one to six i need to know like if uh if counting top ai plus something button ai minus the same a i if this is equal to the length right we need to know like this is uh this is what the total is what four right accounting bottom is three right one two three and this the same is gonna be one same is gonna the same is gonna be one so four plus three minus one is gonna be what six is what the length of the array right if they if this is equal to the length of an array and then i need to what i need to return uh the length of array minus the maximum between the top and bottom so this is four or three right so maps between four six so uh net equal to six minus four is actually equal to two so you return to so this is a little bit mad so you just have to make sure that um you need to keep track of the value and then you also need to keep your oh keep track of the same so you will be able to understand what is the best value you can place for the final solution right and then this is uh pretty much it right so i have a pump for top new in size of seven again y size of seven this is because you only uh have a value between one and six but in cooler index zero right and also what on the bottom is right all right so i need to traverse but before i traverse i prefer making sure my end can be neutralized and from the top i need to say same equal to topic all right now i need to know my replace value so i will traverse 1 2 right because you have to know like uh you want to find out something about top and bottom and send to be exactly uh the value you need to replace right so if you're talking i plus how many top that i sorry plus something bottoms ai minus the same at i this is equal to n so this is a map so a plus b minus the same so they are unique right everything is unique if they are the same i need to return minus the maximum between on top of i from following that so uh this is supposed to be easy so at the end just return the other one because you cannot find it and let me run it submit all right so let's talk about time in space this is going to be a space so it's all of seven constant i think and then this is gonna be a time all up n and all of six i think so it should be the worst case all the way and this is the solution and i'll see you next time bye
|
Minimum Domino Rotations For Equal Row
|
numbers-with-same-consecutive-differences
|
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6`
| null |
Backtracking,Breadth-First Search
|
Medium
| null |
253 |
hey everyone welcome to another video in the algorithm and dash structures series um today we're going to be taking a look at another weak code problem this one's a medium and it's called meeting rooms two so the problem statement we have today is given an array of meaning time intervals where intervals sub i equals start and end return the minimum number of conference rooms required cool and it might be easier if we kind of take a look at an example case together so here our input intervals consists of these three blocks of time from 0 to 30 5 to 10 15 to 20. cool we want to be outputting two it looks like because we need basically two rooms to satisfy this schedule um so we have one for this meeting from zero to thirty and for this meeting room five to ten because there's an overlap between times we'll need to allocate another room in order to accommodate the schedule cool and then at this 15 it looks like this room is done so we should be good from there another example here real quick seven to ten two to four we can schedule a first meeting in one room from two to four that's going to be done before the start time of this meeting so we only need one room in total so go ahead and pause the video at this point and see if you can come up with a solution on your own and pull up whiteboard good old trusty right board to kind of better visualize this question so just going to put an example case here one to five two to three obviously in this case we need two rooms to kind of accommodate both meetings because they overlap and really when i first kind of tackle any kind of coding question like this i like to imagine how i would go about it just in my head like how would i personally solve this question if i didn't have a computer right and really visualizing this it seems very similar to almost like scheduling a meeting on google calendar if we take a if we kind of imagine these numbers right are just hours so let's say this first meeting starts at one ends at five we can kind of like create some sort of google calendar from the hour 0 1 2 and this will keep going technically to the highest number present in the array for this let's just say 5. i can block off a time space right from this one to five and that basically represents the first meeting and then when i get to this meeting i can see if i try to block out a time two to three it actually overlaps with the current meeting time so i'll basically need two rooms at this point and we can continue this logic with another room let's say one to four which should be kind of represented like this and we can see like the max intersection is three meetings which means we'll need three rooms and i think we can really take this logic and design our own kind of algorithm to solve this question so we would kind of iterate or create a some sort of hash map right where the key is the hour or whatever unit of time we decide to use and the value is actually going to be probably represented as an integer so i can just default it to zero all every single time so let's say i have this hash zero one two three initialize everything to zero and then let's say i have a meeting one two three i can basically increment all those keys by one and if i have any kind of overlap like right if i have another mean that comes in that's two to three i would just increment this and end up getting one two and then my answer will just basically be the largest key or sorry the largest value present in this hash map or dictionary i guess in python's case we can kind of talk a little bit about time and space complexity here um we're going to run into possibly an issue with timing out and i'll explain why so first off right we have to construct this hash map or dictionary based on how many elements are present in the actual schedule or lists actually more than that in this example one to five two to three we're not just creating four elements or four keys in this hash map we're creating the range from one to five so one two three four five so if there's a large range so let's say i get some sort of time that's like 1550 to something like 10 to the fourth and i haven't had a chat um chance to check out the constraints but that's very possible that we get something like this we basically are going to be iterating from the start times the end time and each iteration which can really e our time complexity but assuming best case or a simple case like this one five two three i think this answer will be more than sufficient so why don't we code this out and then we can kind of take a look at how we can optimize the solution cool so just to iterate um we want to kind of create a dictionary that represents this overall schedule so for each interval um we want to increment the power and i'm just use our just for simplicity here the hour range so basically this like list zero to the last index um by one so for one three or zero thirty will be basically creating a hash map with 0 to 30 as the keys and 0 as the value cool after that we can kind of look at each interval again um oh sorry once that's done right we already have a populated dictionary all we have to do is find the highest value in the dictionary and return cool so let's see how that looks like in code i will need to import default dick from collection from collections import default cool and so basically our schedule map or hash um will be equal to default bit and then we'll pass an interior so it will initialize everything to zero cool and now let's iterate so basically this step right here let's iterate through all our intervals and we want to basically go through the range and increment our map so we'll say for hour in range and our range will be starting from interval start time all the way up to interval and time we will want to update our hashmap accordingly so this will be plus equals to 1. cool let's just print out our schedule map at this point see what we're working with so we get five two six so we can see there's two overlaps at the hours of six and seven and that is our answer so we're on a good track so at this point let's just find the max value um i can do that by saying max hour use a max method um pass in um schedule map and our key will actually be schedule map dot get i believe so we'll actually compare all the values in our map or dictionary return the key so we actually want to be returning the value schedule map at the max hour hopefully that syntax is correct cool looks like that passed um we can maybe throw in an example test case here cool that looks great um i see that we have some constraints here so if i submit this it will probably run into some timeout issues because we'll get those like super large ranges and yeah it looks like it is kind of timing out and we can see yes makes sense this test case completely destroys our solution based on time so how can we kind of optimize this right um so if we take a go back to the whiteboard real quick and if you haven't come up with the optimized solution yet feel free to pause the video and kind of think about it and see what ideas you come up with that's really the best way to get better at this um but yeah we can kind of take a look at what we can do right so we hit let's just say one to three two to five to seven so a hint i like to use for like some sort of like indication that you can use for a lot of these problems is if they're asking you for a min or a max at any point so for example at this point right we really care about how late or basically what the end time is and we want to compare that to the start time and that will basically tell us the number of intersections or extra rooms we need so whenever you need to find like the minimum value right at any given point a min heap is usually a good way to go so obviously a min heap is just basically a form of tree in which our root node is going to be always the smallest element in the collection or list so if i have one right here or sorry i'm gonna want to let's say i append the end time as the root node so obviously the smallest element we have in the list right now if i take a look at this two sorry this five um if i say look at this five right it ends after actually no this two is what we care about this two ends basically is less than this three or basically my smallest element right now and when that happens i know that a new meeting is starting before my last meeting had a chance to end so that's when we want to kind of create a new room for them so what we can do is actually append two to our min heap because it is now the smallest element and of course that operation takes logarithmic time so this will end up looking something like 2 3. cool and now in this instance where we have this five and sorry once we compare we actually don't care about this too right we care we always care about the end time we're comparing the previous end time with the start time but we only want to append the end time to our heap so this would actually be a five cool so we have a five and three basically representing the end times of our first two meetings now when we take a look and sorry this would be three obviously because the root is going to be smaller than all its children so this is actually what the heap would look like after this iteration so once we get to this iteration we're comparing the start time with our lowest element actually ends before the start time so what we can do is actually pop out this three so after this we would just have a five and actually append this new end time to our heat so we get five and seven at the very end of our iteration our answer is really right the length of our heap representing how many extra rooms we have to allocate if that makes sense let's kind of jump into the code so we can just keep this for now this is kind of solution one for our solution two what we can actually do is create a heap that will keep track of the smallest end time or basically the earliest end time iterate through all the intervals in each iteration we basically want to compare our keep.pop which will basically be our keep.pop which will basically be our keep.pop which will basically be that very last or smallest element in the heat and we'll compare that with our interval start time and this will tell us whether or not we need to allocate a new room and there are basically two paths we can take here right um if the interval start time is greater than or equal to my earliest end time that basically value we just popped up earlier we can pop out this time and basically append interval end time right because that basically represents the earliest time that a room is now available and real quick we'll want to just check the last element or the first element here instead of actually popping it because if we pop it out at this step um we're basically popping twice when we only want to pop once um but cool so then obviously the other path we can take is an interval is actually less than my earliest end time if it's my early end time i know that i need to actually allocate a new room so i can just push in interval one and i'm gonna have to push in yeah so we push cool and i think that concludes basically what our algorithm is doing so let's go ahead and see how this looks like in code so we'll start out with creating a heap um and i might have to import heat but let's see what they say so we'll say or we'll say schedule heat use array and then basically just only use heap built-in heap methods on it to replicate built-in heap methods on it to replicate built-in heap methods on it to replicate the functionality of a heap and we'll iterate through all the intervals so for interval and intervals let's compare keep zero actually once up i did forget let's just assume we've been assuming if i go back to the whiteboard we've been assuming in this case that the elements are kind of sorted by earlier start date which i don't know is guaranteed so there might be one extra n log n step in which we have to search or sorry sort through the array um in ascending order based on start date so let's sort so we'll say intervals let's sort and basically what we want to do here right is just sort based on my first start time cool so now that's sorted we can assume um that my first end date or end time can be just pushed into the array so i can say heap cue dot push key push sorry and then we'll push into the schedule heap which we obviously have to initialize before and we'll push in right intervals first interval end time so now we only have to iterate through all the intervals starting from one and basically this is where we do the compare so let's just say earliest end time right just to name our variables earliest end time is going to be equal to our schedule heap first element if my earliest end time is less than my interval i'm sorry if my is less than is greater than my interval zero i'm just going to switch it up so it matches this so my always end time is ends later than my current start time i just can i can just push an interval because basically i'll need to allocate an extra room for this so we'll say keep you dot push special heap and we'll push in my interval and we'll make sure to push in my interval end time cool else basically this conditional we will pop out my earliest schedule and basically replace that with my next earliest end time so we can say heat cue push schedule keep interval one cool and just looking at this um we can simplify this right by just kind of so we can say if earliest end time less than or equal to interval that's when we want to execute this um but looks like we're going to be kind of doing this push action on each condition so we might as well just put that outside the conditional cool so once that's all done all we have to do with this step is return our heap length so we just return length of my schedule cool um so to reiterate before we run this code real quick create a new heap you want to sort the current intervals based on start time and push in my first end time into the heap for each iteration um we're comparing my earliest end time or basically that root node of the heap to my current start time if it's less than or equal to my start time um i know that i don't have to schedule another room so i'll just heat pop my current room curly's earliest end time and push in an updated end time returning the length this syntax is wrong let's see that's pretty sorry like that release end time is equal to schedule heap earliest and time cool looks like that was accepted let's try submitting it and see if we could pass that and there you go um faster than 99.12 99.12 99.12 of python submissions cool thanks for watching and if this was helpful for you in any single way um it'd be great if you liked and subscribe really helps out the channel um and stay tuned for more videos you
|
Meeting Rooms II
|
meeting-rooms-ii
|
Given an array of meeting time intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of conference rooms required_.
**Example 1:**
**Input:** intervals = \[\[0,30\],\[5,10\],\[15,20\]\]
**Output:** 2
**Example 2:**
**Input:** intervals = \[\[7,10\],\[2,4\]\]
**Output:** 1
**Constraints:**
* `1 <= intervals.length <= 104`
* `0 <= starti < endi <= 106`
|
Think about how we would approach this problem in a very simplistic way. We will allocate rooms to meetings that occur earlier in the day v/s the ones that occur later on, right? If you've figured out that we have to sort the meetings by their start time, the next thing to think about is how do we do the allocation? There are two scenarios possible here for any meeting. Either there is no meeting room available and a new one has to be allocated, or a meeting room has freed up and this meeting can take place there. An important thing to note is that we don't really care which room gets freed up while allocating a room for the current meeting. As long as a room is free, our job is done. We already know the rooms we have allocated till now and we also know when are they due to get free because of the end times of the meetings going on in those rooms. We can simply check the room which is due to get vacated the earliest amongst all the allocated rooms. Following up on the previous hint, we can make use of a min-heap to store the end times of the meetings in various rooms. So, every time we want to check if any room is free or not, simply check the topmost element of the min heap as that would be the room that would get free the earliest out of all the other rooms currently occupied.
If the room we extracted from the top of the min heap isn't free, then no other room is. So, we can save time here and simply allocate a new room.
|
Array,Two Pointers,Greedy,Sorting,Heap (Priority Queue)
|
Medium
|
56,252,452,1184
|
1,282 |
hello everyone welcome to another video now in this video we are going to look at this question which is of medium level difficulty and this is quite easy if you know like what if you know the concept that we have covered in our easy level question if you are a regular solver of uh easy level questions then there is nothing new about this question you can easily do it you just need to you know connect the strings and uh not in literal way like connect the links if I may say connect the links between the Logics and you will be able to solve this quite easily but if you are not able to do that let's jump into the question and understand where you are getting stuck okay so um the question let's jump into the question first what it says so let's say for example uh we have this array we are given an array okay and we need to group that according to the size what is size this value that is given inside our array okay so if I consider size 2 that means um I will have like let me say this there's a result okay this is going to be a list of list okay and uh it is going to have indexes of which of values which are similar to the size given so in this case the size is 2 what is the index here 0. so this is going to be 0 and after that 0 1 2 3 4 and 5. after that what is the another place that we have two it is the fifth position so this is going to be 5 okay similarly for one we have only one right so it is going to be just like this and for 3 we have 2 3 and 4 at 3 positions and we have the size of our uh group that is going to be 3 so this is going to be 2 3 and 4 and we have to return this as result okay this list of list now um there are other cases that you need to consider as well that will consider so first thing is um order doesn't matter well whatever you are returning in that case the order doesn't matter how is how what do I mean by that is let me take here this example the example number one that we have okay so if you will see here 0 1 2 3 4 5 and 6. okay there are so many threes okay we can create so many different types so we do so many different combinations of uh groups with three uh people inside that right so we can have zero one and two okay zero one and two we can have zero one and three that is also fine otherwise we can have 0 1 and 6 etcetera so we can have any type of combination it is fine your answer will be accepted so how are we going to solve this basically we'll be taking um two different approaches first there's going to be a Brute Force approach and second is we are going to tweak that Brute Force approach a little and we will be optimizing that approach okay so first of all let's get started with the Brute Force approach here so how are we going to do that so first of all let me take this example three one three okay at the end we need to return this result area result list okay that is a list of list now um what are we going to do here is that laughs first of all we are going to um go through this Loop in a nested manner okay so for the outer loop we are going to go like from let's consider that is added as if Loop okay for that what we'll do is let's say this is given as group size right um okay let me write it as GS group size okay so this what we'll do is GS of I will assign it not this way we will assign uh to a different variable GS of I the group size of I that is in this case it is three okay after that what we'll do is in our inner loop that is the jth loop let's call that um we will check what um if this group size at J if that is equal to size okay then what we'll do is we will add this jth index because we need Index right we'll add this index to our temporary list uh let's say dot uh pushback and this is going to be J okay and after this is pushback right so right now let's say it is zero okay after uh let me do one thing let me create this temporary list here okay foreign so first of all I have added zero uh sorry uh the zeroth index so it is going to be like this and after that what we'll do is um this value at jth index will convert it to zero so that we do not encounter it again because the outer loop is going to start is going to go uh go normally but jth Loop is going to start from 0 every time and we don't want to encounter uh the first three or whatever the values that we have encountered at the beginning multiple times so for that what we'll do is we'll change this to zero okay y exactly zero why not negative you can change it to negative as well but uh you know for the minimum value that we are going to have in this array is going to be 1 right so the any value below one is fine you can take negative as well so yeah so after this uh we can continue with this uh whole process again so this is also uh equals to 3 like the GS of J is right now here and now it is here it was here now it is here uh is this equal to size yes so we'll add this and at this index and then we'll convert this to zero again J is now here is it equal to size yes so we'll add it here now if you will see here we will check if temp dot size if that is less than our given size or not because we need to return this size this temporary list as soon as that is equal to the size that we want I'm sorry in this case it is 3 okay so as soon as it can it reaches the size of 3 what we'll do is we will add this temporary list to our result.pushback result.pushback result.pushback temp okay and since after this as soon as this condition is reached our Loop will end and this is going to be zero and I will start from here so as soon as we go on we will slowly have 0 1 2 then we will have um 3 4 and 6 and at the end we will have five so the answer is going to be 0 1 2 three four six and five okay this is going to be our answer I hope you understood this is very smooth process you don't have to uh there is no big deal here okay but if you did not understand um let's jump into the code it will be easier for you to understand over there otherwise if you understood um you can try coding it yourself okay so let's jump into the code here I'm sorry so first thing that we need here is that other uh Vector right a vector of vector the list of lists let me name it as result and we want the length as well right length that is equals to group sizes Dot now the Outer Loop okay here we need to check what if G group size at index I is equal to 0 or greater than 0. we will only continue if this group size is greater than zero because otherwise we know that we have encountered that position and we have worked on that index so it doesn't make any sense to continue on that right so what we'll do is we'll check here if group sizes at I is greater than 0 only in that condition we will continue otherwise we will skip this Loop okay so it is going to be like size that is equals to we want that uh we want to remember that uh value right the size of uh the temporary uh Vector that we are listed that we are going to have okay now size is ready let's create the temporary list as well or array why don't know why I keep saying list okay now we have temporary our Vector as well now uh for the inner loop what we'll do is J is less than length we will be going through the length of our whole um group size right and we will have one more condition here as you can see we need to quit from this loop as soon as we reach this condition like if the tab dot size is greater than or equal to size okay so basically we don't want to go more than the size of our uh the group size that we have assigned here so what we'll do is m dot size it should be less than size okay and here we will check if group sizes at index J if that is equals to size what we'll do temp dot push back will add that index to our temporary vector and we'll reassign at jth index to 0. okay after this we need to check if um our temporary array if that is temporary Vector if that is greater than 0 or not because let's say we have um created this temporary Vector right but we did not add anything and if without checking we add that to our result it will give us wrong answer so here we will check if Cam dot size is greater than 0 if it is then we'll add this to our result at the end I will simply return this result okay let me submit this okay it's really good we are able to solve this but as you can see it is taking a lot of time like 45 m is the submission is almost at the end of our bar or graph right so we don't want that so let's optimize this so how are we going to optimize this let me remove all this code I hope you have taken note of this code okay um let me remove this code and let's jump into the optimized approach how is that going to work so uh for optimize what we are going to do is uh one thing that is going to remain common is that our result list okay the other thing is that we will be taking another Vector okay whose size is going to be one more than the size of our given uh group right because if you can see if you will see here the group size is going to be equals to n okay and the values that we have are going to be less than n less than or equal to n okay so we'll be creating another vector 2D Vector okay because y i I will show you why so let me create this temporary okay and let's say we have right now what do we have let me take this example of um let's see okay let me take three one and three okay this is our uh not result this is our group okay this is group okay and at the end this is going to be our result okay uh okay so temp so what are we going to do is that what is the current uh size of this it is uh one two three four five six seven okay so what are we going to do is zero one two three four five six and plus one that is seven okay it starts with 0 plus 1. so it is going to look like this we are only giving the size of the rows our size of columns is going to be dynamic right so we'll go through this Loop okay uh the group okay and what we'll do is at uh at this particular index uh whatever this uh three whatever the value we encountered in group okay so right now let's say it is 3 okay at third index it thought this is this one we will add this index okay so this is what uh right now this is zero again it will continue it is third so that third index it is going to be one again it is I it is going to be 2. now as soon as this is equivalent attempt of I size okay temp if dot size as soon as that is equals to the size of our ith term right we will push this to our result but as you can see it is not possible to normally push that uh we cannot like just do pushback and add this list or add this Vector to I'm sorry to our result so for that what we'll do is that first of all uh add result what we'll do we'll push back an empty vector okay and at the end what we'll do is we'll swap the um result dot back that is this will give us the final value in our result array okay so at this point it is empty array empty Vector I am sorry okay and it will we will swap this with temporary of uh temporary Vector at is index okay so after this what will happen is that this will become empty and result will have 0 1 2. okay and so on we can continue it's really simple I hope you understood this it is not great that great big of a deal okay let's jump into the code and uh if you did not understand then you will be able to understand over there so the first thing that we require over here is that our result right so let me create that picture and result okay and the second thing that you require over here is that our temporary Vector so let me create that as well and we are only going to provide the row size right the column size that is going to be dynamic so let me provide the column size here group sizes dot size plus one why is that as we you know see that the group size the length of the size is going to be n and all the values that we have in our group array okay that is going to be less than n okay so this is the maximum that we can go so now let's go through our array yes then let's say group sizes dot size and I plus so now here uh we need uh the size first okay size is going to be group sizes of I okay and technically this is also the index right because at this particular index we are going to have uh our group size right so let me give the same to index as well for clarity purpose okay now this is simply for clarity purpose you can avoid this as well uh I will show you at the end how we can remove this and all that okay so now uh at this particular index what we are going to do is that we are going to add index I okay and our so by giving this our temporary error will get filled okay uh so next is we'll check if this index dot size okay if that is equals to size in that case what we'll do two things first of all we'll need to add okay we'll need to add an empty list in our result why because we need to swap uh the last element of the result with the value we have in our temporary array so that whatever the final result that we get in our temporary array we can push it to our final result array okay so what we are going to do is reserve swap result dot back this back function will give us the last value the final value the ending value of any array any Vector okay you can we have front and back two values front will give us uh two functions sorry uh front will give us the first value in our vector and back will give us the last value in our Vector okay this we need to uh get like temporary of uh at the list that is at index uh index in our temporary Vector okay and by doing so we are filling our result vector and at the end we simply return our result okay now let me submit this sorry I forgot parentheses so as you can see it's really that simple uh the code was really short and sweet and simple okay now this index we can obviously remove this index from everywhere okay and we can instead of index we can put size over here so wherever I found index I will put size okay um this is also like it's going to run its variable just nothing else but that was for readability purpose okay so I hope you like this video and hope you learned something new and enjoyed it and understood everything that I said okay uh so yeah that's it for this video thank you for watching uh do suggest me if you have any other um problems for me to solve from any other platform do give me your suggestions uh okay I will try my best to cover as much ground as possible based on your suggestions okay so yeah I'll see you in the next one till then keep coding
|
Group the People Given the Group Size They Belong To
|
number-of-valid-words-for-each-puzzle
|
There are `n` people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from `0` to `n - 1`.
You are given an integer array `groupSizes`, where `groupSizes[i]` is the size of the group that person `i` is in. For example, if `groupSizes[1] = 3`, then person `1` must be in a group of size `3`.
Return _a list of groups such that each person `i` is in a group of size `groupSizes[i]`_.
Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.
**Example 1:**
**Input:** groupSizes = \[3,3,3,3,3,1,3\]
**Output:** \[\[5\],\[0,1,2\],\[3,4,6\]\]
**Explanation:**
The first group is \[5\]. The size is 1, and groupSizes\[5\] = 1.
The second group is \[0,1,2\]. The size is 3, and groupSizes\[0\] = groupSizes\[1\] = groupSizes\[2\] = 3.
The third group is \[3,4,6\]. The size is 3, and groupSizes\[3\] = groupSizes\[4\] = groupSizes\[6\] = 3.
Other possible solutions are \[\[2,1,6\],\[5\],\[0,4,3\]\] and \[\[5\],\[0,6,2\],\[4,3,1\]\].
**Example 2:**
**Input:** groupSizes = \[2,1,3,3,3,2\]
**Output:** \[\[1\],\[0,5\],\[2,3,4\]\]
**Constraints:**
* `groupSizes.length == n`
* `1 <= n <= 500`
* `1 <= groupSizes[i] <= n`
|
Exploit the fact that the length of the puzzle is only 7. Use bit-masks to represent the word and puzzle strings. For each puzzle, count the number of words whose bit-mask is a sub-mask of the puzzle's bit-mask.
|
Array,Hash Table,String,Bit Manipulation,Trie
|
Hard
| null |
729 |
hi guys we are live today and we continue with binary search uh so let's share our screen okay so we have today the next task that calls my calendar and the task is the following so uh we should Implement a program that called my calendar uh in this program we can add new event and uh what does me event uh double booking okay so we are adding some events uh into our calendar we have start and end time uh we see that uh we have some uh start and end time would be end will be always greater than uh start and we should Implement my class and book uh method where we should return true if we can book new event so we have some example here we have 10 20 um that would be start and we can add this then we have 1525 we cannot because it's like in the start position like the pre like more less than the end position of the previous one so we actually should um yeah return false then we have 232 we can end it because like 20 here it's uh and it start and end so yeah we can add this okay nice we have some constraints start and end so start can be zero and can be 1 billion and we have 1,000 calls to our 1 billion and we have 1,000 calls to our 1 billion and we have 1,000 calls to our book method okay so let's think about some solutions so the first solution that come to my mind that for example we can have a list of events and when we have empty event we just add this event here uh when we have new event for example 1525 we first check if our uh yeah we can like basically do check with every element if it's valid or not uh so for example we are checking with this well is if it's valid then we actually add this element uh we are checking valid okay valid uh valid okay if it's here we checking okay it's not valid that we return false in this case uh so the solution is the following we are check uh if Val it then we add or we return false and sort our array every time because we need to sort it start from the beginning and till the end uh to check if it's valid uh yeah it's a question if do we need to sort it so for example if I have first 1020 uh then we have in our array uh let's say 4 five right and then we uh have event that uh that's 46 event five uh seven so we are checking with this EV it's 1020 um it's 1020 so we can end it so it's right and for this one is not valid so we just return false in this case uh so I think uh if we have at most 1,000 calls it's not really have at most 1,000 calls it's not really have at most 1,000 calls it's not really much we actually can do this iteration over here for every elements in our array and to check if it's valid or not if it's valid we just add this to array and then to this check once again so maybe we don't need even to sort um so check it valid add or false in this case uh time complexity would be all of M and space complexity would be also all M um we have n calls so it will n squ mhm okay because um because if we have sort in we have another n calls and N Lan operations so here we also added log so let's try to implement actually this uh solution without s first so we have our list of events it will be empty by default so let's even have it here um okay then we have our book method uh here we do the following we are going by our list of events here it will be event events and we are checking okay so let's take this example so what we should check so here we have some event that is common and 20 and our uh our events is now empty so if it's empty we just add events and new uh start intent and we uh return true in this case uh if it's not then we just uh do the following we take our current event so let's imagine that we have 1020 right and we have 1525 uh so we are taking the start of current event and this um so if we have start is less than this the finish of the previous R and start is so it's right and start is um greater than events zero so in this case 12 and what will be in T 10 so 10 is also I think not correct because in this case we cannot have event yeah so it would should be greater or equal so if it's even equal uh if it's zero nine then it's correct so we should return false okay so let's imagine we have nine but here we can have 11 for example so it's also not correct so we should also check if our end um so in this case uh this event is greater so yeah so let's imagine so if we have um so now we check that this event is over here with start position now we want to check if this events over here it means like when start event is less than uh you zero right and end event start event is less but end event is greater uh greater than event start so it's also we should also return false in this case uh yeah so we check this thing we check that it's here I think we also should check uh this so this is checking like this so we have uh start event that is greater uh your stent that is greater than if start is greater than uh the previous one and is greater than newent start and is less than event mhm we return false so we are doing all these checks and we check with all events our start and end position um so let's write right th that's okay nice so it's working solution I think uh what will be without this one can work well yeah it also work with this one I okay so it's even faster but um what is the most faster solution okay so here we can use also yeah I think binary search uh so we have our book method let's check how it works okay we have note event notes okay so they are trying to um use some mhm some events yes set of events uh we are book this new event in our set of events ah and they are comparable okay so we just have like set of event and this actually build us this comparable thing so if yeah this start and start minus and return okay yeah this was comparable is nice also we have internal n no I think it's more complex one um here I think we have this uh binary search approach if pointer end is less than start pointer start is more than end okay book Left Right root insert okay left and right okay let's check another one my calendar reset okay so if it's empty we return then we do previous selling yeah was map lower event start it's three set as well um yeah let's check maybe with another one dream map okay so I think should work something like this so we have our root right root would be now root is like start and end left and right so we have like link list something like this then we uh trying to insert so if parent start is greater than e parent left is equal to null we just insert we just return otherwise we are going to the left uh yeah we going to the left and we check if we can add to the left mhm parent end try to insert okay and we have book so if our root is null we just return through otherwise we return we try to insert but uh do we update our root actually or it's always the same yeah because we can like build uh Its Over N yeah but I see that we have some root and we are building some kind of tree from this rout so some events is going left some events is going right and we are building kind of three it's not balance three so uh but it still works fine so we have root and we have start and we try to insert okay so we have parent we check if parent start so parent start it mean parent start yes yeah if parent start is uh greater or equal than n so it means that we should go left we have left and we check if bur like we have null then we just return through if not we are going here uh and let's imagine that we uh we don't have par yeah so we have uh we have parent left right we uh we insert it okay yeah and we are checking okay start so we have not don't have so we end this okay then we go here root right and check it yeah okay I think this is really nice approach and so let's check editorial so editorial is doing the same so here we have like our N squared solution it's our Brute Force solution sorted list and binary search so yeah we have our tree map uh floor s okay yeah I think yeah I sold it with Brute Force let's check our submission yeah I've sold it with Brute Force but yeah and Brute Force even can be done better so for example if our uh end is less yeah so if our end the end is less than and start is less than i1 M I returned through otherwise I just okay so here it can even rewriting uh faster so if our event Uh current event link yes if our start current event is less then and let's this one and so it's less right so we have like start some start position here and um if our start is great is less than uh event yeah so we have this one is greater than this one so it's for sure then should go here but this one is less than this one so it's somewhere here right um yeah so in this case I actually yeah I actually solve it this way but yeah not optimal okay thank you very much and see you next time
|
My Calendar I
|
my-calendar-i
|
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**.
A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.).
The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`.
Implement the `MyCalendar` class:
* `MyCalendar()` Initializes the calendar object.
* `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar.
**Example 1:**
**Input**
\[ "MyCalendar ", "book ", "book ", "book "\]
\[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\]
**Output**
\[null, true, false, true\]
**Explanation**
MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.
**Constraints:**
* `0 <= start < end <= 109`
* At most `1000` calls will be made to `book`.
|
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
|
Design,Segment Tree,Ordered Set
|
Medium
|
731,732
|
108 |
version 108 converted sorted convert sorted array to binary search tree given an integer array noms where the elements are sorted in ascending order so an array of integers is given to us and these numbers are sorted in ascending order the question is asking us to convert this array to a height balance binary tree so what is a height balanced binary tree is a binary tree in which the depth of two sub threes uh of every node never differs more than one so as you see like the this is a completely uh height balanced binary but if we had another node here like from the right side of -3 node it was still the right side of -3 node it was still the right side of -3 node it was still height balance binary because the difference was only one but if we had one node from 10 minus 10 then it wasn't a high balanced binary tree so and also the question is saying if we return the high tiles binary tree like this or like this they're both going to be accepted uh and um this is another example it says three two one two three they're both accepted as long as it's the balance a high balance binary tree when we talk about uh graphs binary trees and uh this sort of like traversing first thing that comes to our mind is bfs or dfs for traversing a tree or an array to build the tree there are different ways that we can traverse dfs it's going to be pre-order it's dfs it's going to be pre-order it's dfs it's going to be pre-order it's going to be in order and it's going to be post order so in this question what we are going to do we are going to use uh dfs to traverse this array and build those three first thing that we are going to do we are going to check if noms is not empty and if it is empty we are going to return none right if the noms is empty we are going to return not then what i'm going to do let me explain it using this example uh so what i'm going to do i'm going to find the middle of the this array and build a node from it and use the left side for building the left nodes and for that root and using the right side to building the right nodes of that root and i'm going to use a recursive function to recursively uh call this function and make the left side and right side let's see how we can do that first thing that i'm going to do i need to find the middle number so it's going to be the length of nums divided by 2 because we don't want a float number right so for example for this one m is going to be uh length is going to be five is one two three four five divided by uh two is going to be it's going to be 2 right so it's going to be index 0 1 2 so 0 is going to be the root note so let's make that i'm going to say root is equal to i'm going to call this uh class here so it's gonna be three note and what it needs a value i'm going to give the value to it i'm going to say norms at index m right and then i need to make the left nose and the right nose for doing that i'm going to say root dot left and i'm going to say root dot right so what i'm going to do i'm going to call this function recursively but this time i'm going to call the function for the left side of the value that we use for the root.left and right side of the for the root.left and right side of the for the root.left and right side of the value that we used uh the right side of the root value right so what i mean by that i'm going to say self i'm going to call the function itself sort array hopefully we don't have typo b s t and i'm going to give instead of noms i'm going to give uh from the root node to the beginning so it's gonna be to the end because this is uh exclusive so m is not going to be included and i'm going to do the same thing sorted array hopefully no mistake or typos and i'm going to say nums from n plus one to the end right so this is how it works and then what i'm going to do i'm going to return root as a result so let's see what happens so after making the root which is going to be zero what will happen i'm going to say what is uh build so far so zero is built i'm going to call this function when i call this function it's going to be called for minus 10 and for minus 3 right and then it comes here it divided by 2 the length is 2 divided by 2 is going to be 1 so it's going to be minus 3. so it builds the minus 3 one right and it reaches to here it needs to build the left node again so it will call this function and it will call the minus 10 one only right it calls this one it comes here divided by two is gonna be zero it's the minus ten one so it's gonna build the minus ten here and what it does now it's gonna be an empty right so what it happens it comes here and the knobs is empty so it's going to build a knot here right and then the con we are using a stack because we are calling this recursively right so it goes all the way back after this is done and it's going to start to build uh the um right side five and nine and then it's gonna build um nine and then it's gonna build five and then it's going to be uh empty right so this is how it's happening and it builds the tree this was just for illustration purpose so you can better understand let's run the code and see if we don't have any mistake or typo and there you go it was accepted so the time complexity for this is linear because we need to go through every single item that we have in here and the space complexity because we are using recursive stack it's going to be logarithmic thank you
|
Convert Sorted Array to Binary Search Tree
|
convert-sorted-array-to-binary-search-tree
|
Given an integer array `nums` where the elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** nums = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** \[0,-10,5,null,-3,null,9\] is also accepted:
**Example 2:**
**Input:** nums = \[1,3\]
**Output:** \[3,1\]
**Explanation:** \[1,null,3\] and \[3,1\] are both height-balanced BSTs.
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in a **strictly increasing** order.
| null |
Array,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Easy
|
109
|
1,465 |
hey guys how's reading this is Jay sir in this video I'm going to take a look at one four six five maximum area of a piece of cake after horizontal and vertical cut we're giving a rectangular cake with a high height H and width W and two arrays of integers horizontal cuts and a vertical cut and we're her wear horizontal cuts is the distance from the top my horizontal be cut right okay and yeah the vertical cuts this is from left this is vertical return the maximum every a piece of cake after our cut at each present on a vertical position provided by Ray blah since the answer could be a huge number return the modulo and that's number right cool so the piece of cake are generated by two adjacent cuts right the area green area here is generated by cuts to and cuts for with cut one and cut three so it's really straightforward all we need is to get the maximum distance between two adjacent cuts right both vertically at her horizontal horizontally and then we just multiply them up and it gets the answer remember the first the zero flying would be the zero line and the ending line would also be a cut right because it's like the border its each with this line and the cut you will generate a piece of cake also so yeah we just do that so we're so two to get there the distance between two adjacent we just look through the cut and divide the current cut with the previous cut right but that needs the that requires us to get to have the sorted cut our input of Wow on the other hand our input are not guaranteed to be sorted so we need to sort it first after we sort we can just loop through top to bottom and get the distance between two adjacent cuts like here is one two one and vertically one-to-one so maximum up with vertically one-to-one so maximum up with vertically one-to-one so maximum up with two baguette the area for so that's our solution let's do it first with sward and then we saw the vertical well and remember the last one when we are getting the distance between two adjacent numbers we need to get the prief right brief a cut and the last cut is that the border should be counted also so I'll cut the brush edge and vertical cuts we need to push W then nets gets the maximum distance okay so the okay let max wrangle toe but in each size from 0 and the pre f1 is H less 0 and for that cuts both horizontal cuts max edge with the math max edge cut - prick and that press equals cut - prick and that press equals cut - prick and that press equals cut right by this will get the max horizontal max distance from top to bottom and we will get the max V it would be a saying it should be cut of vertical cuts and yeah by this we will get the maximum distance vertically which is 2 here 1 3 and then return the max v mod by this number right okay let's try run the code oh we led two times run code cool yeah we're accepted so that's all for this problem let's analyze the time and space complexity for time we used to we're here let's suppose that both of them have the meant of n okay both at noon and January I a birch Lee so that time would be the sorted so the sword cost us the O log n right this o log n right and we push it push constant and this for should be oh and this is Big O pen and then this is constant so the time complexity will go and lock and then the space we're not using extra space mm-hmm so custom space okay so mm-hmm so custom space okay so mm-hmm so custom space okay so that's all for this problem hope you helped see you next time bye
|
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts
|
maximum-product-of-splitted-binary-tree
|
You are given a rectangular cake of size `h x w` and two arrays of integers `horizontalCuts` and `verticalCuts` where:
* `horizontalCuts[i]` is the distance from the top of the rectangular cake to the `ith` horizontal cut and similarly, and
* `verticalCuts[j]` is the distance from the left of the rectangular cake to the `jth` vertical cut.
Return _the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays_ `horizontalCuts` _and_ `verticalCuts`. Since the answer can be a large number, return this **modulo** `109 + 7`.
**Example 1:**
**Input:** h = 5, w = 4, horizontalCuts = \[1,2,4\], verticalCuts = \[1,3\]
**Output:** 4
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
**Example 2:**
**Input:** h = 5, w = 4, horizontalCuts = \[3,1\], verticalCuts = \[1\]
**Output:** 6
**Explanation:** The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
**Example 3:**
**Input:** h = 5, w = 4, horizontalCuts = \[3\], verticalCuts = \[3\]
**Output:** 9
**Constraints:**
* `2 <= h, w <= 109`
* `1 <= horizontalCuts.length <= min(h - 1, 105)`
* `1 <= verticalCuts.length <= min(w - 1, 105)`
* `1 <= horizontalCuts[i] < h`
* `1 <= verticalCuts[i] < w`
* All the elements in `horizontalCuts` are distinct.
* All the elements in `verticalCuts` are distinct.
|
If we know the sum of a subtree, the answer is max( (total_sum - subtree_sum) * subtree_sum) in each node.
|
Tree,Depth-First Search,Binary Tree
|
Medium
|
2175
|
71 |
now let's move on to the actual coding if you remember from the previous video where we talked about the intuition behind the static I said using a stack may not be the optimal solution so why is that in this case if you are given a input ring let look like that looks like this your final result should be ABC right now if you are using a stack and presume presumably you are using a stack data structure inside a language that they give you stack let's visualize what the stack will look like if you actually use the stack so when our record rest until here we push a friend's into here we put be friends in so here we put C then we stay there do nothing so this is what our stack looks like after the iteration now the reason why using a plain and naive stack is not good is because our result is ABC we do not get the result from the stack immediately we have to use a while loop to pop every elements off out of the stack and while we are popping we need to declare a separate variable in order to store them we ate a stray be a string or an array we need a separate variable and when we are storing them they will be in the wrong direction right because we are popping from the talk we got CBA right but our desired result is ABC which is from bottom to the top you see we want bottom to the top but we get top to bottom so you need to reverse it now due to all these reasons let's just not use this tag at all list instead use an array to simulate this tag why because array pushing and popping behaves the same as a stack so you push a you push me you stay there or voila you get the final result right so let's use a array let's call it V now given a input string let's use a slightly more complicated example so this shirt gave you if your input looks like this you should get a because doctor is a valid right treating stay there and you pop that dirt so you get a so let's use this as a test-case so let's use this as a test-case so let's use this as a test-case now what shall we do in order to extract all these elements or tokens that are living inside in between these double slashes one amid one function that immediately come to mind is split right if you are using Python or JavaScript now you C++ the equivalent of that is now you C++ the equivalent of that is now you C++ the equivalent of that is string and get line do not be scared if you're not familiar with C++ all I'm doing is the same as split so let's split by slash so let's print out what this code actually does in order to make printing more explicit and I am adding the guard to make the token more explicit and see what is exactly Brendon you are as you can see a doctor dot-dot-dot are as you can see a doctor dot-dot-dot are as you can see a doctor dot-dot-dot these are expected now just to make it more explicit let's make input has to be something like this you all right the first and the last are empty string why is that because there's nothing on the left of Ruth right so when you are splitting you get empty and there's nothing in between these two slashes so you get empty as well that's why when we are dealing with the so can we need to deal with the case where token is an empty string so if celkon is or token is a single dot we do nothing right you elves we push when we are not doubled up right you so we push else meaning we are Tom oh God but we need to track if is not empty then we pop you right the let's print out the content inside V after these while loop you okay so our vector only has a right because tartar is a directory in state and pop so this should be correct then all we need to do is to generate the result so let's declare the result as rest you now our result will look like a slash plus token now in the case where there's nothing inside ve we need to handle that as well right so I believe this will pass you okay what am i doing you okay so it looks correct let's tidy up the code and prepare to submit you can squeeze out some performance by doing reference because you are avoiding copies okay so this will pass let's move on to JavaScript in JavaScript since we are using an array to simulate a stack let's make the stack an array and we are splitting by / now this e is each element that is living in between we that was lashes now if E is that we need to pop else if E is not dot or E is not mg frame stack dot push e let's just console.log what staff let's just console.log what staff let's just console.log what staff looks like by the way you can pop a stack you the pop in our empty array because it will just return undefined is not an error okay let's look like what this will log you okay I need to use end okay this looks correct let's generate the final result by using template screen you always have route then followed by elements that we can get from stacked I'll join you okay just to make sure you all right they submit and see is all right so that's it
|
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 |
190 |
welcome back to our adjust today's question is leak code 190 reverse bits so all this question is asking is for us to reverse bits of a given 32 bits unsigned integer so as you can see in example one we have this 32-bit integer example one we have this 32-bit integer example one we have this 32-bit integer and we need to reverse it to give us this output and we will be using bit manipulation for this so we have this 32-bit integer and we need to have this 32-bit integer and we need to have this 32-bit integer and we need to reverse it and usually with bit manipulation we always look at the least significant bit which is a good place to start because just like reversing a string with this we're going to be taking this and adding it to the front and we'll do that for each one until all the bits are reversed so how can we tell whether this bit right here is a zero or a one well if we compare zero and one or zero and zero what operator is always going to give us these values but it's going to be the and operator so if we compare 0 and 1 we will always get one if we compare zero and zero we always get zero so using the and operator we can easily find that least significant bit so step one find the least significant bit step two now that we have the least significant bit we need to reverse it right we need to add it to the front here and what operator do we know that will shift that zero to this position over here that would be the left shift right so we could use left shift but how many are we going to shift it by well for this first one When We're looping through this string we want to add it to the first position right so we're going to shift it by 31 because it's a 32-bit unsigned integer but we it's a 32-bit unsigned integer but we it's a 32-bit unsigned integer but we also want to subtract I and the reason for this is so if we move this to the front when we move to this bit we want to add this here we don't want to be adding it to the front so we need to subtract I from this because I is going to be incremented and then that will allow us to reverse these bits correctly so step two left shift so now that we've shifted this the significant bit to the front we need to create a result from this run so if we initially set our result today zero when we shift this bit over alt operators do we know but can compare to this and always give zero likewise if we add a 1 here what operator would we use to return us to over one here well we could use the or right so zero or zero is going to give us zero or one is going to give us one so for step three we're going to update the result is going to equal result or the value of 2. so the value of this actually what we'll do is we'll call this X and we'll update this to X so this will update result and the last thing we need to do for is we still have this last bit here the least significant bit we need to remove this right so that we can get this as our next least significant bit so the simplest way of doing this is just to shift right if we shift the least significant bit it'll remove it from this 32-bit integer and then we can from this 32-bit integer and then we can from this 32-bit integer and then we can just repeat this process right and time complexity for this one is going to be a 01 and space is also one let's code this up let's declare result set it equals zero then we Loop through 32-bit integer so then we Loop through 32-bit integer so then we Loop through 32-bit integer so it's going to be I equal to zero I is less than 32 I plus we need to get the last bit and we said that the operator would use is the and operator then we need to reverse that bit and we can store it in the variable let's call it red bit so it'll be last bit left shift 31 minus I so that we reverse it in the correct order and then we need to update result right so result is going to be equal to result and we're going to use the pipe so the or operator and we're going to or the red bit then lastly we need to remove that least significant bit so we need to shift right and one thing I forgot to mention in the code is that we need to convert the result to an unsigned 32-bit convert the result to an unsigned 32-bit convert the result to an unsigned 32-bit integer and in order to do that we're going to shift right and we are going to return this let's give this a run submit it and there you go don't forget to like comment subscribe and I'll see you in the next one
|
Reverse Bits
|
reverse-bits
|
Reverse bits of a given 32 bits unsigned integer.
**Note:**
* Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
* In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`.
**Example 1:**
**Input:** n = 00000010100101000001111010011100
**Output:** 964176192 (00111001011110000010100101000000)
**Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**.
**Example 2:**
**Input:** n = 11111111111111111111111111111101
**Output:** 3221225471 (10111111111111111111111111111111)
**Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**.
**Constraints:**
* The input must be a **binary string** of length `32`
**Follow up:** If this function is called many times, how would you optimize it?
| null |
Divide and Conquer,Bit Manipulation
|
Easy
|
7,191,2238
|
378 |
okay so lead code practice time uh so there are two goals in this video the first one is to see how to solve this problem and also we are going to do some coding work on top of it and the second goal is to see um how to behave during interviews suppose this is um a question given real interview so let's get started um so remember the first thing always is to try to understand the problem and also if there's anything uh unclear to you please bring up the question to the interviewer uh and at the same time think about some edge cases so let's see case smallest element in a sorted array so given a n by n matrix where each of the rows and columns are sorted units and the other so find the k smallest element in matrix so note it is a case of smallest element in sorted order not the case distinct element okay so okay makes sense let's see um so i think i kind of understand the prob i pretty much understand the problem um i don't really see any ash case at this time so it says that n square is larger than one then it means the matrix is not going to be empty so the next thing is about trying to find this solution so how to solve this problem so since each row and the column are in sorted order i mean of course we can so we can keep a i think one thing one solution is we can keep a mean keep uh and we have n pointers uh all the pointer so for example the first pointer pointing to the first element of the first row and the second pointer pointing to the first element of the second row so on and so forth so we manage a main heap um with the size of k and each time we pop the top element is going to be the smallest among the at the end pointers and we find the corresponding pointer and then move the corresponding pointer to the right by one so for example we have three pointers uh we have three pointers and k is equal to eight so we are going to pop the smallest element from the mean heap which is one then we are going to move them the pointer the first pointer to the right by one so the next element which number is five then we push the five into it and the next time uh five is still the top element then if we move the first pointer to the right by one again and then it is nine we push nine and then uh so on and so forth until uh we popped uh k we popped k times uh from the main heap so that's the that's one solution so the run time for this is gonna be uh so it's gonna be k log n so yeah this is k login uh using the main keep solution so i'm thinking because it says that so far we have leveraged the uh the characteristics which is each row is sorted but we didn't make use of the information which is each column is sorted as well so yeah so this is just the solution one i'm not sure how to use the information that each column is sorted well it's really sorted if it is going to get us some more optimization on top of the current approach um yeah so because so we know that the for example for this element the element on the right is larger than that the element to the bottom of it is larger than it but we don't know the relationship between this element and this element so that's the thing we don't really know uh so i think mostly this would be a very good approach to start with let's do some coding work on this approach so after you find the approach and you do some runtime analysis and you talk with your interviewer about um about the approach and you get the agreement to step into the next step which is doing coding then it's time for you to do some real code so here we care about the speed of the code and the correctness of the code and of course the readability of the code so let's do some coding work um first of all we need to define a priority queue let's define a class so let's define the class as okay so let's define it as let's say class um let's say node private so we have several different things the first one is the row number and the second one the column number third one it would be the value of it so let's give it a constructor let's say the node so insert that value is equal to value all right so the small it's priority key of the node let's say this is the main heap you pray alright q um yeah it's a new priority queue this is uh yeah so we need to have a comparator i think you can pass the comparator here so new comparator uh this is node all right so comparator like overran this is the public compare uh into compare so it will be node one and node two say we return node one dot val minus node 2.ll all right so this is 2.ll all right so this is 2.ll all right so this is the main heap and we should have essentially have um so first of all we need to initialize the heap by uh dumping all the first uh all the first number in each row so in i is equal to zero smaller than um i is smaller than i actually start let's just define the n as matrix dot lens right so i smaller than the n and plus i yep um okay so now we have it you're going to have many dots at the new node which is uh i is the row number zero is a column number and also the matrix high zero okay so um this is this finishes the initialization of it let's see so well uh let's say let's do this one so let's say um so in i is equal to zero i smaller than well k minus one i think okay minus one the plus i so this one um each time we are going to do a pull from the mini so uh node is equal to main heap dot pool yep so um so if we pull it is the end of the element so if it is the end of the element uh if it's the end of a row then we need to then we cannot actually add anything new into it so if it's if that's the case okay so we need to see if um node dot uh column is smaller than uh n minus one then we need to have um inhib dot uh add a new node what is that this would be the um this would be the uh node.row node.column plus one and then this is matrix um no dots row and now the column plus one so that's the node we are going to add into it and then finally we just return uh min heap.4 uh min heap.4 uh min heap.4 all right so it seems to be fine um so next one after coding it's time to do some testing so first of all um we need to go through some same sample test case explain how this piece is gonna work um uh and uh at the same time you do some sending check on this piece of code to see if there is any bug and after that we will need to come up with different task cases to make sure we have good enough test coverage so let's give it a shot by running this piece of code so it's case smallest matrix okay so we have the priority queue defined so we initialize it with um all right so i think priority queue should have how many elements should we have so it should be and right i think there are two primary theories to initialize the first is the capacity and the second is the uh comparator yep so now we add everything which is 1 10 and 12 into the main hip and we pop it for seven times so we pull it every time we pull it and if no dot com is smaller than minus one so what we would do is we get the row of it and the if since this is not the last of the column so we are going to get the next number so for example for the first one when we get it you're going to see okay so the current column is 0 which is smaller than uh so this one should which is smaller than n minus one is equal to uh three minus one so zero is smaller than two then um we need to get the next number which is five with a real number as zero column number is one and the corresponding value as five and push it push the new node into the main heap i finally just pull something from it and so this one actually need to be value okay uh i think it should be good let's give it a run okay so it looks good let's give it a summation okay it seems like uh we should be good about the solution um so i'm not sure currently uh about if there is any better solution than this but if you know this feel free to leave some comments below so if you have any questions about the solution or about this coding puzzle please leave some comments below as well if you like this video please help subscribe to this channel and i'll see you next time thanks for watching
|
Kth Smallest Element in a Sorted Matrix
|
kth-smallest-element-in-a-sorted-matrix
|
Given an `n x n` `matrix` where each of the rows and columns is sorted in ascending order, return _the_ `kth` _smallest element in the matrix_.
Note that it is the `kth` smallest element **in the sorted order**, not the `kth` **distinct** element.
You must find a solution with a memory complexity better than `O(n2)`.
**Example 1:**
**Input:** matrix = \[\[1,5,9\],\[10,11,13\],\[12,13,15\]\], k = 8
**Output:** 13
**Explanation:** The elements in the matrix are \[1,5,9,10,11,12,13,**13**,15\], and the 8th smallest number is 13
**Example 2:**
**Input:** matrix = \[\[-5\]\], k = 1
**Output:** -5
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 300`
* `-109 <= matrix[i][j] <= 109`
* All the rows and columns of `matrix` are **guaranteed** to be sorted in **non-decreasing order**.
* `1 <= k <= n2`
**Follow up:**
* Could you solve the problem with a constant memory (i.e., `O(1)` memory complexity)?
* Could you solve the problem in `O(n)` time complexity? The solution may be too advanced for an interview but you may find reading [this paper](http://www.cse.yorku.ca/~andy/pubs/X+Y.pdf) fun.
| null |
Array,Binary Search,Sorting,Heap (Priority Queue),Matrix
|
Medium
|
373,668,719,802
|
424 |
hi everyone today we are going to solve the readable question longest repeating character replacement so you are giving a string s and the 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 operation so let's see the example so you are given like a b and the K is 2. output should be full because the place are two A's with 2B or vice versa so let's say if I change this a to B and also this I change this A to B in that case we get the 4B that's why our output should be full or if I change this B to a oops root a and uh this V also change it to a in that case we get like a 4A so that's why output actually before so to check the longest substrings we use like a left pointer and the right pointer but how can we know that this range is valid or not so that is the most important point of this question so let me explain how to solve this question okay so let me explain with this example so you are given a b a and the k equal to so first of all I initialize the left pointer and the right pointer with index 0. so this freak variable is the most frequent character number between left pointer and the right pointer so I'll explain how to use later so first of all initialized to be zero and this is our return value result variable and this is a hatch so basically I get it through all characters one by one and every time I put the current character into hash and what we are trying to do is that we get the arrange with the range um between left pointer right pointer every time why is that because uh okay let's say right winter is now here so what is a max range between that pointer and the right pointer it's obvious from index tarot to index 3. so if I change this B to a so we get a 4A so in the case we successfully get the so max range which is full so how about a this right pointer is now index 4. so in that case what is the max range between that pointer and the right pointer it's obvious from index 0 to index 4. so in the case if I change this to be to a we get the successfully like a 5A so in the case we can get the max range between left pointer and the right pointer yeah it makes sense so actually there is a formula to calculate the range between left pointer and the right pointer so formula is right minus left Plus 1. so this is a formula to get the range between left pointer and the right pointer so for example now um left pointer and the right pointer is zero so zero minus zero plus one is one so now uh we only find that a so yeah this formula does this formula should be should work um so how about this so right pointer is now here so index one so one minus zero plus one equal to so now um length range between left pointer and the right pointer is now two so yeah this formula works so we use this formula to calculate the range between left pointer and the right pointer okay so let's start iterating first of all we find a so up a to hush one so most frequent character is now one okay so result variable also one it's obvious and then move oops move light to next so again we find a so add a to hash and then most frequent is a so now two and the result of the variable also too and then move next we find B so RB to Hash but still a is the most frequent character so I don't apply frequent variable and for result variable so we can change the character twice at most so if this be if I change this B to a we get a 3A so that's why uh result variable should be three and then next now we find a so other way to hash and the most frequent character also three and again if I change this V to a we get a 4A so result variables should be four and then move next we find the B so RB to hush and the most frequent Capital still a so we stay three and these are the variable if we change these two to a we successfully get 5A so result should be five and then move next so actually this is an interesting point so now we find B so I'll be oops RV to hush and then now the range between left pointer and the right pointer is now here and then now we have three a and then 3B but we can only change the character twice at the most so in the case we cannot max range between that pointer and right pointer because uh if I change a it's like a 1A and a 5B or if I change it P to a it's like a 5A and a 1B but the range between that pointer and the right pointer is now one two three four five six so six is either longest substring so in that case um we need to shorten the range between left pointer and the right pointer and there is a Formula where we need to shorten the range between left pointer and the right pointer so we know that like minus left plus 1 is a formula for range between left pointer and the right pointer and then minus frequent is greater than k in that case we need to shorten the range between left point right pointer because so usually we change the character that is not most frequent character so if this condition valid we cannot get max length between index pointer and the right pointer so in the case R is there one two three four five so five minus zero plus one minus most frequent is three thousand two so in the case six three so this is a three is greater than two in that case well we need to uh shorten so how can we do that it's simple um move left pointer to next and then remove most left character in this case a so we need to reduce the number that will add minus one to a so now a is two so again so five minus 1 plus 1 minus three is 2002 in the case too so this condition uh doesn't read so in that case compare a little bit messy but now length is like a here so current max length substring is now five and then and the current Max length is now one two three four five actually um right minus six plus one so okay so in that case so now we have a 2A and a three B so we can change character twice so if I change this A to B so we successfully get 5B so that is a longest substring um between the left pointer and the right pointer so yeah now looks good so about a five so current length is five and uh yeah now we have a file for the longest substring so it's same so I don't update the result variable but I keep going move next and now we find the a so of a oops again um we have C A and three B so okay it's the same situation so we have a uh we have a chance to change the character like that twice at most so in the case so now yeah a little bit messy so let me change the color so now left pointer is index one and the right pointer is uh neither at the last index so we need to shorten the range between that pointer and the right pointer so update left pointer till next and then remove the most left character a so now a is two and then the range between left pointer and the right pointer is now here so now so current max length should be right minus left plus one so zero one two three four five six minus two plus one and five so and it's same so I don't update the um uh result variable and then go to next button there is no character here so that's why uh five is a data value longest substring yeah that is a basic idea okay it's a long explanation yeah um but I hope you understand the concept in terms of discretion and time complexity is um order of n because I get to all characters that go one by one so with that being said let's jump into the code okay so let's write the code first of all inside this point the result variable with zero and the most frequent character number initials with zero and the character count with empty hash so start looping for right and ranks of string so first of all add the current character to Hash so hash is in the right equal one plus okay get try to find the current character if we don't find therefore the value is zero and get the most frequent character number so freak Creek buses and most frequent character should be the character we just added here so compared to numbers and then do you remember the formula to shorten the range between left pointer and the right pointer so we check here so y right minus left plus one minus frequent is greater than k so in that case we cannot the max rank substring between index pointer and the right pointer in that case first of all remove the most left character from the hash so yes left minus equal one and then up to date left pointer to next so after that just uh compare current length versus new links so write minus left plus one yeah okay that's it and then return result variable so Ram is a limited yeah it looks good this solution works so I told you the time complexity is order of n but I forgot to say is complexity space complexity is also order of n because I use hash here so basically I put all characters into hash so that's why our linear order of n so let me summarize step by step algorithm this is a step-by-step algorithm of this is a step-by-step algorithm of this is a step-by-step algorithm of longest repeating character replacement so step one initialize the result variable left pointer right pointer the most frequent character number variable and hash and the step to start looping at the plus one to Hash for current character and get the most frequent character number between direct pointer and the right pointer step three shorten the range between direct pointer and the right pointer until we don't meet right minus Select Plus 1 minus frequent is greater than K step 4 compare current to longest with the range between left pointer and the right pointer so that's it I hope this video helps you understand this question well if you like it please subscribe the channel and hit the like button or leave a comment I'll see you in the next question
|
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
|
11 |
hello everyone welcome to harsha lectures in this lecture i am going to explain you about container with most water given and non-negative integers a1 a2 so given and non-negative integers a1 a2 so given and non-negative integers a1 a2 so on n where each represents a pointed coordinate i comma a i and vertical lines are drawn such that the two endpoints of the line i is it i comma a i and i comma 0 find two lines which together with the x axis forms a container such that the container contains the most water so here coming to example one we need to find out which two container is having maximum water here 0 1 2 3 4 5 6 7 8 okay so here if we measure 8 to 6 or 8 to 2 these are many containers available in this graph so which two container is having maximum water that we need to find out here the given heights 1 8 6 2 5 4 8 3 7 and here we need to show the output by finding maximum water between two containers okay now i'll explain clearly here first we need to create variables in max water variable i am initializing 0 and i'm creating left variable here also i'm initializing 0 and here i'm initializing right height dot length minus 1 okay now for int i equal to only to mention for loop okay directly we can mention while i is less than shade if i is less than j then here max water math drop max of here in this i will mention max water comma write minus left okay and multiply with math dot mean in this i will mention height of left comma height of right okay in this if height of left is less than height of right if left container is less than right container then i need to do any agreement left okay left increment else if height of left is greater than height off right okay if height of left is less than height off right then i need to increment left if height of left is greater than height of right then i need to decrement right so right decrement okay and here i am going to written max water now i will run this code any error is there or not will check here cannot find symbol okay while it okay here instead of i can mention left comma right now i will run this code okay accept it now i will submit this code success so the logic behind this case here this is 0 1 2 3 4 5 6 7 8 so here in this step what it is doing i am doing just right minus left means here this is eight minus one seven multiply here i am finding out the minimum height here the minimum height is seven so the seven multiply with 7 is 49 this is the maximum water we can find out through this logic if you have any queries you can mention your doubts in commentary session and please do like and subscribe for more videos thank you
|
Container With Most Water
|
container-with-most-water
|
You are given an integer array `height` of length `n`. There are `n` vertical lines drawn such that the two endpoints of the `ith` line are `(i, 0)` and `(i, height[i])`.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return _the maximum amount of water a container can store_.
**Notice** that you may not slant the container.
**Example 1:**
**Input:** height = \[1,8,6,2,5,4,8,3,7\]
**Output:** 49
**Explanation:** The above vertical lines are represented by array \[1,8,6,2,5,4,8,3,7\]. In this case, the max area of water (blue section) the container can contain is 49.
**Example 2:**
**Input:** height = \[1,1\]
**Output:** 1
**Constraints:**
* `n == height.length`
* `2 <= n <= 105`
* `0 <= height[i] <= 104`
|
The aim is to maximize the area formed between the vertical lines. The area of any container is calculated using the shorter line as length and the distance between the lines as the width of the rectangle.
Area = length of shorter vertical line * distance between lines
We can definitely get the maximum width container as the outermost lines have the maximum distance between them. However, this container might not be the maximum in size as one of the vertical lines of this container could be really short. Start with the maximum width container and go to a shorter width container if there is a vertical line longer than the current containers shorter line. This way we are compromising on the width but we are looking forward to a longer length container.
|
Array,Two Pointers,Greedy
|
Medium
|
42
|
1,359 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem count all valid pickup and delivery options this one is a hard but it's actually easier than you would think especially if you are good at like discrete math and more specifically if you're good at like combinatorics and like stats and probability I'm not the best at that but I'm familiar enough with it that this problem was actually pretty trivial for me to solve and I'll kind of explain why that is we're given n orders and to be honest this problem is worded not like very well you won't understand it at all from reading the description I would just go straight to the examples so we're given n orders in this case n is one now that's a little bit misleading because for each order we have to pick it up and then we have to drop it off the catch is that for any particular order like for the ith order we have to pick it up before we can drop it off that makes sense but now what if we're given like 10 orders well we'll have pick up maybe I Plus plus one and we have to drop it off after as well so the drop off for I plus 1 also has to happen after the I plus one pickup but other than that there isn't any restriction like we can pick up the first order and then pick up the second order and then pick up all the other orders and then drop all of them off we can't of course drop off an order before we've picked it up so that's literally the only restriction and the only thing we're trying to do here is count the number of possible ways that we can do valid deliveries in my opinion the best way to think about this problem is not in terms of n but actually in terms of n times two let me show you what I mean let's consider the example where n is equal to two so then I'm going to draw four slots one for each pickup slash delivery so I'm gonna call these P1 and D1 P is for pickup D is for drop off and this is one valid way of doing things pick up one then drop off one then pick up two then drop off two so that's just one valid way and in total if you look down here there's actually six valid ways of doing it and just to like very roughly show you that uh visually we know we have to either start with P1 or we have to start with P2 you can't do a drop off before you've done a pickup that makes sense but consider when we choose P1 first how many possible ways can we arrange the rest of these well we can either start with P2 or we can start I think with D1 we can't do D2 unless we've already picked up P2 so we have three slots to fill I'll quickly just go over this decision tree just to show you but here we can either choose D1 or D2 and then whichever one we end up picking then is going to be the opposite of what we pick next so there's one two valid ways and then here is pretty straightforward here we can't pick up D2 We can only pick up P2 and then we do a drop off two so there's three ways of rearranging these starting with P1 similarly there's going to be three ways of doing that starting with P2 so in total there's going to be six ways I didn't show you all six ways but I think it's reasonable enough that we can assume there's six ways now that doesn't necessarily help us arrive at the best solution but it gives us a bit of the intuition of how we are rearranging these variables these pickups and these drop-offs there's many solutions to this drop-offs there's many solutions to this drop-offs there's many solutions to this problem but in my opinion the simplest one is this like this is the thought process of solving this problem we have this many slots in this case it's four but it's going to be some arbitrary number n times two whatever n happens to be that's going to be the parameter for us now if we were just doing raw permutations we would say okay well four times three times two times one or in other words two times n Factor tutorial that's how we count permutations but we know there's actually a restriction here it's not that simple because if we put like D1 here we can't do that we can't put the drop off before the pickup it doesn't work so what's the Restriction here well how about we place that pair P1 D1 at the same time like at least mathematically we're going to place these two values at the same time so we have this many slots two times n slots and we are trying to place two values in those slots what is the math formula for that do you happen to know it's not super complicated because you can break it down into well the first choice we can put the first one in any of the positions in other words and I'm just going to start using a new variable for like the length of this because I don't want to keep saying two and let's just say it's X that's the length that's the number of the slots so we have X choices when we make the first choice so let's say I put P1 here now the next choice we have x minus one choices we can put D1 in any of these positions but we're going to end up with a lot of ways that we placed those two values half of the way we place the values is gonna put D1 in front of P1 they're going to look like this is one valid way this is one way we could place those this is also another way we could place those both of these ways are invalid now the Opposites are also going to be true the Opposites where P1 was first and D1 was after half of the combinations are going to have P1 coming first half of the combinations are going to have D1 coming first so we can take that math formula x times x minus one and just divide it by two why not we're not looking to actually create all of the unique paths all the unique delivery sequences we're just looking to count them so this tells us after we've placed two of those things I don't even know what to call them at this point P1 and D1 we place them this is how many valid ways we could place them and now we have a new sub problem we started with let's say x slots we had four of them to be exact now we only have two slots so we would just repeat this repeating this equation just updating the X every single time and every time we calculate this we would multiply it with the previous result because that's how you kind of count the number of ways now even if you're not like a math person I still encourage you to sometimes think about problems in a mathematical way because especially the dynamic programming problems really are just discrete math under the hood so if you can kind of understand it from that perspective solving the problems definitely becomes easier I've been planning on making like a discrete math crash course for a long time if you think that would be helpful definitely let me know but without further Ado let's get into the code it's going to be pretty easy coding it up and these are just some comments that I had for myself I guess I'll kind of finish them in case you didn't understand the previous part of the explanation but remember there's two times n slots we want to First count the valid number of ways to place any particular pair and we know that this is how many ways we could place the pairs but to get the valid number of pairs we take that n times n minus one or I guess we were using X originally so I'll switch it up to that but taking this number and then dividing it by two this is going to be the valid choices that's pretty much it so let's get our total number of slots pretty much just following the comments here while the number of slots the unfilled slots is greater than zero let's calculate the number of valid choices we have which is just going to be the number of slots to be honest X is in this case the number of slots multiplied by slots minus one and then divide that by two which will be the valid number of choices this should be an integer regardless I don't know even know why I'm putting double slashes here but this is going to be the number of valid choices and we probably should declare our results somewhere so I'm going to put output here it's initially going to be one because that's kind of like the base case if n is one is going to be the result and also it's a neutral number so when we here put output is going to be multiplied by the number of valid choices then like the computation will work out because when it starts out as one it'll end up being replaced with this value and every time we fill some slots we should probably also decrement the number of slots by two now after we're done with that don't forget that actually in the prompt they told us to return the output modded by 10 to the power of 9 plus 7 and in Python I can get away with doing that at the end because integers or numbers are arbitrarily large in Python but you might need to move this mod over here but in any case let's run the code to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neatcode.io thanks for check out neatcode.io thanks for check out neatcode.io thanks for watching and I'll see you soon
|
Count All Valid Pickup and Delivery Options
|
circular-permutation-in-binary-representation
|
Given `n` orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation:** Unique order (P1, D1), Delivery 1 always is after of Pickup 1.
**Example 2:**
**Input:** n = 2
**Output:** 6
**Explanation:** All possible orders:
(P1,P2,D1,D2), (P1,P2,D2,D1), (P1,D1,P2,D2), (P2,P1,D1,D2), (P2,P1,D2,D1) and (P2,D2,P1,D1).
This is an invalid order (P1,D2,P2,D1) because Pickup 2 is after of Delivery 2.
**Example 3:**
**Input:** n = 3
**Output:** 90
**Constraints:**
* `1 <= n <= 500`
Given 2 integers n and start. Your task is return any permutation p of (0,1,2.....,2^n -1) such that : p\[0\] = start, p\[i\] and p\[i+1\] differ by only one bit for all 0 <= i < 2^n - 1.
|
Use gray code to generate a n-bit sequence. Rotate the sequence such that its first element is start.
|
Math,Backtracking,Bit Manipulation
|
Medium
| null |
377 |
hello hi guys good morning welcome back to the new video so basically in this video from combination some four although like it's an easy problem so you should be able to do it if you have seen the last videos or if you have been watching us for the last month so like last one month so you should be able to solve it but if not like there is a slight catch in the code itself many people are confused on why this is happening why this is specifically there so I highly recommend to watch this video because if you just go by a specific code format so you will just see okay here you are using something different but why something else is being used you should be able to know let's see the problem is like logically it's very easy we are having an array of distinct array integers called as nums again it is same we have distinct integers in my input itself I will have like integers all will be different which means I have one two three four so I will have like I can't have one two three four like this like which means integer will not repeat and I have a Target in TJ called as a Target if it's my final Target which I have to actually make off now what I mean by that is I have to written the number of possible combinations that add up to my target so from my nums I have to pick up some numbers and again I have distinct numbers so if let's say I ask you to make a Target as 3 and I have input as one two three so I can just say okay just in just get three or just maybe get one and two or you can also say get a one thighs so again you can just repeat the number itself and also you can get that particular Target as let's say the example itself we have uh nums as one two three we have a Target as four so my ultimate Target ultimate aim is to make the target sum as four so again when I'm trading on my Ali itself I can just say okay at this point of time I want to have a sum as four so okay if I am standing if I'm landing at one I can take it or not take it okay let's say I take it I'm landing at two I can take it or not take it okay I did not take it I'm landing at three I taking it I can take it or not take it so you can easily see it's just a take and not take problem which means like at this option you have an option okay you will take it or you will not take it but uh the difference is that as you will see in the example you are taking 1 again which means although in the standard take a not take you are just going on from initial index to the end index but here in this example we saw okay I can take it and not take it again I will start from the very start index itself and I can again repeat the same process as in I can again start from here and we'll again say okay can I take it can I not take it again can I take it cannot take it and also I can just go on forward also I can just start from here itself and I can go on forward also which means after taking it again it will start from here also and it can go on further here also which means for two also it will ask can it take it yeah it can take it and then it can again start from one itself then it can take it so you saw it can be a one to one combination also which is actually here itself it which means I was here I then went again start from here and then came here or what happened earlier I was here and then took care and then again here so there came multiple combinations but again it's just a slight modification of just going forward is just that as we simply in a recursion with DP what and again if you had not known okay why is this RDP it's just a taken not take right take a notice to for sure we would be having repeating sub problems for that we will just be having a memorization criteria so as to not repeat that's a problem but again but earlier what you should do was okay we were having at index I and then I was having a Target okay if I just say I just take this particular element one then I will just try on from index I plus 1 and my remaining Target will be Target minus one because I have just consumed this element one so now I have to search for Target -1 as a new value Target -1 as a new value Target -1 as a new value but in this case I will not be going from I plus 1 I'll be starting from the very start itself which means my index would not matter as such because I have to start from index 0 always so in my code itself what I will lose I will start from the index 0. it's inside my recursive code I will start from let's say the function name is solve and the standard base case and stuff we will handle it later and the memorization case will hundred later but just a thing I will start always on the index 0 and we'll see for sure if I'm subtracting as you saw I was subtracting the value Target from the existing Target right so for sure uh the value should be lesser than the Target right so I just say okay if my nums of I is actually less than equal to my target then only I can subtract that number five from my Target and then I will go and solve again call the same function solve from a new for my new Target value which is Target minus thumbs up I and then I can just simply store this in my DPF Target or any other variable let's say Val and I can ultimately also put that variable valve value in my target my tokens simply get this sort cool uh so that's the reason like you just have to relate it with an existing problem and just see okay what's the difference in this problem and we related that okay we can just move on but here it's itself we are starting from the very starting it's and then moving on again so firstly I'll just initialize my DP simple initialization and then called my nums the only thing in this is the target which actually is the main target value and it can actually keep on changing according to what input we are giving it so we just call this sum and for sure as soon as my target is exactly equal to 0 which means okay I have got the perfect numbers combination to X to actually exactly match to this target sum so I can just simply say okay as soon as my target reaches 0 because you know that I am subtracting my nums from Target so that okay numbers will add adder and it will ultimately add up to my target so as soon as my nums sorry as soon as my target reaches 0 I can simply say okay I have found one such combination so please add one in my answer and for sure a memorization simple memorization that okay if you're deep your target is on to minus one simply return the deeper Target now as we saw earlier also that we will just simply add on all the number of combinations for that specific Target and we'll go on for every of those num value which means from very start up till very end I will have to go on and try for every value again and again we will try only when the num value which means thumbs up I is actually less than equal to my target if yes then I can simply call the solve function for that specific remaining value of Target and I can simply keep on adding in my Target and ultimately I just simply return that DP of Target so that is a simple top down approach which is very easy just a simple extra a simple bottom approach again is exactly same as you saw I was going on for every Target value and for every Target value I was just calculating my for every of the nums same for every Target value which means from one target I am going on to my all the nums and again checking okay if that num value is less than my target which means current Target because here also it is the current Target which will come in from the recursive call uh so if it is less only then I will just add that in my current Target consisting of the okay what is the current Target minus num's value that's the exact same bottom of code but the only thing which you will notice is that okay here I have used unsigned enter rather than the normal End by if you will use a normal int you will see that there is a uncyclic there is a int overflow why is that the case because if you will have this test case let's say example then for sure it will have to go and try for all the target values again it is going and trying for all the target values which means from one as you know the main value of Target is 99 so it will go and travel 1 to 99 which means it will go and try for one two three up to 99 which means it will go and try for all the target values for sure and if it is the case then you will see that it will go and find the value for all the target values and these values are more than the integer limits and RN why was this not happening in the above case of this one because when I would be starting from the very end for the very end starting I will go and subtract these values 10 20. so if I will subtract the 10 so it will be 989 the next value what recursive code will try off is 989 and it will never go on to these values ever that is the reason in the recursive case into was more than sufficient because I knew that my answer will for sure behind so every value it will go on which means the input is modified or basically input is given in such a way that every value would go on will always be an INT but here in this case when we are doing a bottom approach so we are going on specifically to every Target value and because of this going on to every Target value I am actually going on to every of those values even if it is not required to actually solve it that is the case it can become more so usually in these cases just it's given okay do a modulo where the money nine plus seven and stuff but if it is not given which means okay the input is in such a way that it will always be in the integer limit but for sure you are going on to every integer from one to Target so you have to handle it by yourself by taking a unsigned long end or basically unsigned it into itself depending upon how big you see that it can go and then ultimately so get this sort cool that's the only thing that's the specific only thing which fits why I specifically put this case of a bottom up cool uh the time as you can easily see is just going on to every Target value and for that going on to all the numbers on the very beginning itself space is nothing but of Target because you saw that we are using only DP of Target itself bye
|
Combination Sum IV
|
combination-sum-iv
|
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
| null |
Array,Dynamic Programming
|
Medium
|
39
|
1,710 |
Hello guys, today we will leave Delhi question because if you keep maximum units omelette then what is the giver in the head of this question, we have life in which I show any person that I can market you, as if in this effort What is the giver that we have been given a boxer, meaning in every studio, every girl is single, her religion has a box, what is there in it, first of all, the number of boxes is right and how many boxes are there in each box per unit. Meaning, every number is time, life is evening, we have this advertisement that box on number of units, how much time is one, just so many units, we have only one and as we have shown here, first of all, let's hit zero which is our number option. After that, what we have is box on unit like this is one, this is the number option but one box cute three silk Malviya if you take drops then each box will be unit so by doing like this and along with Mukul was giving the size means that means one The truck has empty 4G in it, a lot of meaning, how much is its limit, the employees can be multi years and that's it in this, so let me give you a little advice to improve you on everyone, so before that, first of all, a minute, what do you have to do in deep life. Is for example one MP3 I am just become two and you even thinking of wrestling as this question building Admit sorry in this common man that west some ghee salt wounds how to do thing I one more ko itne me kya bole hain spoken in this way That we need the maximum Total number of units We need the maximum Now this is a given Message on this We will take out dry ginger We will dry ginger but on which specific unit will we joint it On the specific unit which is already married Start with a jerk What will we do? This saver has been started. Okay Olden, first of all what will we do, we will see that first of all there is one, its truck is less than the side. What will you do, now we will celebrate the answer 501, we will keep our answer and the pain of that answering machine. Superhit film and truck size kitna hai tera khun ko pehle T20 World Cup and karta hoon and Prakash Raj mein kitna hatefully ok phone hai par when I add one, I used to cancel it so it is tractor which was ok And coming to the second edition, I am the number opposite here, which is how much is my given size, the previous one and the unit is green, someone's is fine, so this is what I answer, what will happen to me, only the answer, I have put an off invention in it, answer is mine. What is it like a chameleon is 3 ki * number of boxes chameleon is 3 ki * number of boxes chameleon is 3 ki * number of boxes is ok Yoga now what will be the answer my husband is already a giver of thriller plus what will I do number of boxes which is a doob multiple of each ki that unit electricity bill how much is my answer Saivan Yatra will come, agreed and I have to reduce the size of my truck, so I lifted it and reduced it in size. Now this Jatin is cement for free, so how high is the forest from here, so tell me what does it mean that the dead size is empty. There is no more left and the rest now look, now it has come as it is, so here I have number option 3, so I will take 300, okay, what should I do with time, I will not take it here also brother, now I will see Amit, here I have made a distraction on this. Lagi means three which is very attractive, so what will I do, whatever breast size I have become that the robber is the answer is the man attractions, how much is it a minute which is my old one is closed A+ my old one is closed A+ my old one is closed A+ I am one * * how much is it So Ajay is there, so come Om told Bigg Boss that he is completely healthy, you will understand better, I will hand it over and show you, so what did I tell you before that, I have to do this, it is short, so let's start the shot, I thing, I gave you half a lot. How would I shoot from Giridih if I had ₹ 40, if How would I shoot from Giridih if I had ₹ 40, if How would I shoot from Giridih if I had ₹ 40, if you don't get it, then I will show you this is our box type, this box type song is so many and you just have 500 trends on the app on Android and match khela banaunga compare mera kaun naam diya now I Do it here on the low that I got it done in a strategic school, now we took the pan, so I found my two, a tree, it here, I have to grind for the steadfast, and the song here, I have to message to wish me a cigarette of this I want that the duty is always bigger than this, if this happens then do it immediately, it is of the phone and you need time, then you bathroom falls, I just tell you while you make the words at less, wires for video, do nothing. Do you want your condition Rani, what do you want this, you put the vacation in reverse, you want, do you want this, you put the vacation in reverse, if you don't want it, then do the chords, now one more on this movement, my jovi has reached the rosy, now I make the answer, in which I am according to you. And what I do is this is vibrate so when I put it on the side now what will I do forms which is stretchy so first of all how will I do Tubelight up if my that if my truck Shahjahan if it is zero then I will give to play it As soon as I hit the brakes, I will give you India. You have been chatting with me from here. My answer is ok, this is my acting, I will chat in the furnishing channel, which is my truck, is it bigger than the size of a tomato, is it bigger than my story, unit 781 What is the meaning of currently in my ID the particular one Mahendra address is known articles Meghvanshi this exam has been done deceased and investment I took one means I took first minister 13131 delivery man is sorry I took rear box Amazon so what if my peer got up from given for If it is not the biggest then yes it is small then what will I do? First of all I will do it with my truck - I will do this as per the knowledge of the size - and now I do it with my truck - I will do this as per the knowledge of the size - and now I do it with my truck - I will do this as per the knowledge of the size - and now I have to increase that answer. Now the answer is these two phone numbers are boxed * phone numbers are boxed * phone numbers are boxed * for phone number off. If by mistake it happens to any of my kalim that the track size has become less and the number is the same meaning tree, that condition of ghee and walli that when I have a big truck size is small and my life box size is more then message. What should I do at that time? You see the video of pizza, I showed you the footage, there is little in it, I don't have to do anything, I have to take the answer, keep a minute, tell me how much is left, I have tracked the Rajdhani, I have multiplied its unit in it. I don't give you three options but a box. The girl said, 'When don't give you three options but a box. The girl said, 'When don't give you three options but a box. The girl said, 'When I do this, I will make the truck size zero. When I make the track size zero, then look here, it will make it different from the pictures. I show it in my code. I have run.' It is running and I will show it by moving some other finger, so I am going to show it by moving these fingers, if it is working, it will also work, I will try it now, before making the video, this is another 400, I will hit submit to Amit. I am yes, if it is going on then Ayodhya will have to be understood, if you want a little son, please send the video twice, you will understand and today's Delhi question of the Commission will be yours. Thank you, new post has been posted as soon as the instructions are received.
|
Maximum Units on a Truck
|
find-servers-that-handled-most-number-of-requests
|
You are assigned to put some amount of boxes onto **one truck**. You are given a 2D array `boxTypes`, where `boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]`:
* `numberOfBoxesi` is the number of boxes of type `i`.
* `numberOfUnitsPerBoxi` is the number of units in each box of the type `i`.
You are also given an integer `truckSize`, which is the **maximum** number of **boxes** that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed `truckSize`.
Return _the **maximum** total number of **units** that can be put on the truck._
**Example 1:**
**Input:** boxTypes = \[\[1,3\],\[2,2\],\[3,1\]\], truckSize = 4
**Output:** 8
**Explanation:** There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 \* 3) + (2 \* 2) + (1 \* 1) = 8.
**Example 2:**
**Input:** boxTypes = \[\[5,10\],\[2,5\],\[4,7\],\[3,9\]\], truckSize = 10
**Output:** 91
**Constraints:**
* `1 <= boxTypes.length <= 1000`
* `1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000`
* `1 <= truckSize <= 106`
|
To speed up the next available server search, keep track of the available servers in a sorted structure such as an ordered set. To determine if a server is available, keep track of the end times for each task in a heap and add the server to the available set once the soonest task ending time is less than or equal to the next task to add.
|
Array,Greedy,Heap (Priority Queue),Ordered Set
|
Hard
| null |
1,944 |
here is the question 1944 we have n people standing on Q and they numbered from Z zero to n minus one and the height are like distinct integers and high represent the height of I personis you can see another person to the right if everyone is shorter than both of them like okay so we return an array answer of the l n so we can see like if we look at a certain point looking on the right side to see like how many people we can see so for the height is 10 then we can see like three people um which is like one two and four so this one and four so we ski the number three and for like one we can see only two so only this guy and three we can see like two we can see three and four and for number four we can see number five and for number five we can see nothing thing okay so I think we will use like monotonic stack so we put a like stack and in this way I going to refresh the page okay so we got a stack and in this way we're going to Traverse from the right side to the left side so in range learn Heights - one or - 2 - one and - one Heights - one or - 2 - one and - one Heights - one or - 2 - one and - one so we Traverse from the right side to the like left side so we do wire St s St since here everything is like distinct integers so we don't need to worry about if they have the same value so the previous one is greater than the current one smaller okay if that's the current is greater then that one then we can like set up a count so also we do st. pop we can do aand appar the count and there's one situation if we are have the previous one then we do not like skip anything but we will not pop anything but we will like see one more so we can see if we already if we have at least one then we can see at least one so we plus Q oh here's not Qs St and we see what's going on okay is that's do okay I see what's going on so after here we need to do st. append like and we submit okay great
|
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,844 |
foreign so we're going to continue our 1844 question replacing all digits with characters now in our last uh video I was not able to figure it out now after looking into it I realized there is couple things that we should have done or should change um for instance there's multiple way of doing it however in this instance we need to look into our for Loop where it iterates through each character array with the steps of two to process forward right and then we need to calculate within the body of the for Loop the new characters by adding the uh the Asic values and the numeric value of the current digit and in order to do that we need to get the Char I and we need to have um add into the char with the index I minus one minus character Zero and then return our what converted character array back to the string and we need to remove this so in a sense if we run it would um character I minus 1 0. 6 as it showed it should run smooth now uh just to iterate inside the loop it calculates the new character for the odd index by performing The Following with the uh adding plus two where we get the odd values and it takes the Asic value of previous character uh I minus 1 which is the lowercase letter using the subtraction zero character Zero this converts the numeric value into integer value and it adds this integer value to the current character to the current I character effectively shifting it by the calculated amount in essence the code replaces each digit in a string of the character obtained by shifting it by numeric value of processing characters now this aligns with the problem requirements to use the shift function to replace digit in the string and in order to explain in Uzbek let me translate it is no return statement may he beat the return is uh with the character array uh for Loop Yoki indicator uh Thomas e foreign even again um characters um or Lopez another character boys e was a I uh I plus I but I please um character shoe uh array character index Olive shoe character index solid ozone ass character I index minus integer our mess he can return Yankees drink uh character clip heteromis case yeah foreign
|
Replace All Digits with Characters
|
maximum-number-of-balls-in-a-box
|
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
|
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
|
Hash Table,Math,Counting
|
Easy
| null |
1,706 |
hey everybody this is Larry this is the first of November hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem we'll be doing it all week or all month until whenever I don't know if you're new here I have a four uh 944 day streak hopefully 9 55 after this and we'll just keep going so come hang out maybe we'll get to a thousand and yeah let's get on it today's problem is 1706 where will the ball fall okay so what are we doing here so you have a 2d grid okay something like this and then you just kind of go to do and then do it for us and then you kind of see where it falls okay it's kind of an odd problem I think this is a kind of one of those Prime that I mean it's what known as a simulation problem I think conceptually it is not hard in the sense that there's nothing um you know like there's nothing hard to understand maybe there are a couple of edge cases you have to think about and consider but that's pretty much it we have to figure out how to get to the bottom okay so I think the idea here is kind of just um you know one at a time simulate and simulate means just do what they tell you really and pretend you're the boy and the idea is going to be that if you go down and you see a disc then you go one to the right and if you see this you go one to the left um and then when you go to the right um it's kind of almost like navigating through a maze except for yeah I mean I think this is a the hard part is going to be to just how to get it right but I don't think it is tricky per se so let's um it's kind of just start coding I don't think there's anything that we have to you know we'll see um because I think you just have to solve the two things right one is which direction you're coming from meaning that given one of these things it matters where you're coming from up you know coming from top to bottom or from left to right or right to left in some cases and then yeah so that's pretty much the idea and okay so then first of all Let's uh say for I in range of is it n by n or n is the constrained so okay so let's just say oh he's got a link up with C is a good link up quidup zero and then now we start each one right and okay yeah I mean I think and then I don't know if I is um let's just say x-ray so then now um let's just say x-ray so then now um let's just say x-ray so then now um Y is equals uh maybe the other way yeah okay let's say we start Y and X is equal to zero and then now we just basically let's talk about true Loop we can kind of change the condition later I just like to kind of set it up and then here um okay so previous direction as you go to how do we say it so maybe say up we can use some genomes uh left is you got two right is equal to three someone like that right um and Maybe not maybe there definitely is going to be queen of ways of writing it but um there's definitely gonna be queen of ways of writing it but I am going to just at least begin with doing it the stupid way and then we worry about um and then we worry about uh cleaning up the code later right as I always say um oh I guess the form is a keyword but um so I'm just still thinking but you know um so I got distracted because someone keeps messaging me uh what I was gonna say but yeah uh having the right solution is key and then we'll optimize the code later if you'd like but okay so then now it is just going for the cases right which means that okay so now if grid of X Y is equal to right we might have to add an extra this because to escape it oh wait did I miss okay huh that's really weird okay that's why I got confused maybe we can handle this a little bit away okay I was just looking at the inputs down here and I was like oh that doesn't work okay so which one is one again one is the one that top left to bottom right okay fine so that means that if this is one and we're coming from Up then that's good and we move to the right um so then f is equal to uh left meaning that we're coming from the left um X we keep X the same we increment by one and then we continue right if grid is X oh uh this is only if f is equal to up um uh else if f is coming from left I guess coming from left is fine too actually if f is equal to left then I'm just looking at this oops I'm looking at this example and just kind of going through it if f is equal to the left then now you know we just go down right so f is equal to up and then what uh we move when command we go down one and that's it and then uh this is an outsef and then otherwise if it's coming from the right that means we try to go up which means obviously it's going to be wrong so we do a pen negative one and then we break maybe we could put this in a function or something so that is a little bit easier to handle but that's fine um okay uh and then else if grid is I think this should always be the case so but I just want to type it out but now here and then now it's just if f is equal to up then we go to the left so yeah of course we actually should keep going so let's do that and also I guess we only continue we just end up using control loops and then f is equal to right we're coming from the right at 50 go to left what happens right that means that just goes uh bounce negative one break uh else um this is coming from the right and wrap this so then now it goes down so X and command by one f is equal to up um yeah okay so we have one way of working but then we need another way right so if this is on the last if x is greater than um or yeah actually if it's equal to or you get down so then we break right so here now um there are a couple of things that we have to do which is that you know um if y can we go bounce I don't know but if Y is greater than uh or you go to C then we also this is very yucky okay let me rewrite this from simulate uh let's just saying why and then yeah something like that right and then now we can just put this in there even though it's really yucky right now but at least it's something and then now we can clean up this code by just uh yeah we turn negative one we can actually clean this up even more but I just wanted to uh yeah actually don't care because that's part of the loop here uh if Y is less than zero we turn negative one right again we don't need to continue this is just return negative one this is also just return negative one this kind of like I said this product could be queeno and we can think about how to optimize this but that's okay we can actually for example optimize this by saying uh if not we turn negative one so then we can off shoot it to the next thing um yeah I think that should be okay because that only changes on whatever right um okay so yeah so then now we can return why right because I think that's the case I think this is mostly good in theory um the layout is good it's very possible with missing some random things and get uh time limit exceeded or get never gather hmm is my internet down let me check another website I guess my internet no my other internet's good I'm getting temporary weight limited when I pull out liquor so like I don't know is this website helpful not really um okay this is doing something maybe we went down a little bit and then everyone's hammering that's how you get the way Limited but this is not great I might just kind of go AFK for a little bit because uh foreign because people are actually asking if lead code is down it seems like the code is having issues so um okay well that's a little bit sad uh okay well hi friends uh I am going to take a break just because well if it's down I mean we can probably test this at least for the input but I'm a little bit lazy uh at least I don't know how to do it on stream and I don't have a setup for that so I'm gonna be back you know that I don't like editing and cutting but I mean I don't know I also what are you gonna do just sit here and watch me do nothing with the bad decote for however long I don't know right all right fine I'll be back I mean for you it would take no time so all right but I just want to give you a heads up because I don't like cutting it like I'm cheating or something but it is what it is so you see it all right hey everybody I'm back it might seem like no time has passed at all actually it uh it took an hour I probably took a shower or something like this but uh hopefully it just actually works okay so I would read the wrong answer and that's okay but um yeah I mean the idea is right now we're gonna think uh did I put in order code I don't know okay yeah so okay hmm that is actually a little bit I don't know if it's surprising maybe I just missed something uh oh huh no I think this is mostly what I want to do to clearly something is off though uh let's see I mean do you think about simulation is you what you can do is look at every St um every step of the way and then you can yeah see what happens and then see if they match what you expect uh hmm who doesn't print which is kind of uh hmm it's on complete why would it not print anything though um I miss something let's try again real quick or maybe I just missed something really obvious for example that's why this is not a oh whoops I think I meant to put this as the termination Loop so okay well maybe that solves the problem of why I just was just wearing still one two three four where you use these silly mistake to make um and then okay so this one looks good and two three also looks good um okay fine I'm just trying looking at this very quickly I wish there was a way to visualize this um to at least um I guess they all just go diagonal because so that's what this is trying to do um I don't know that there are damaged cases so let's click on submit like maybe there's a I was gonna say maybe there's an edge case on you know like one row one column type thing I know that's one of the inputs but maybe there are the weird cases with that but looks okay so yeah 945 day streak um yeah so what's the complexity of this one right in the worst case um we look for each so for each column which is here so it's for you to see what is complexity at the worst you can only hit each row twice right in fact you have to hit each well twice so that means that at first it's going to be two times R which means that um this is gonna run for each y v one all of R so this is on total gonna be over or times C time and this is of course linear time because that's the size of the input in terms of space I think we just use all of one space but I don't think we do anything just variables and oh well I guess the answer away so that's all of CSI line but that's the size of the output um yeah you can also write something like all of K space where case the size of the output but in this case this K is C's and that doesn't change so yeah so I lie about over one space but it of one extra space maybe if you want to play around with saying that but yeah um did I click on submit sometimes I forget and I won't forget okay yeah it's a medium Farm that's all I have for today let me know what you think uh did I have a queen of code last time yeah wow what uh I don't know that this is greener to be honest uh I think this WOW dynamic programming okay past Larry is a little bit uh I don't know this is it's not super clean you can probably optimize this to be a little bit shorter a bit uh and also yeah but um yeah but that's fine that's what I have for this one I think this is pretty okay you know like I said a good code that works is still you know better than pretty code that doesn't work so yeah let me know what you think stay good stay healthy to good mental health I'll see y'all later and take care bye
|
Where Will the Ball Fall
|
min-cost-to-connect-all-points
|
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides.
Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left.
* A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`.
* A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`.
We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V " shaped pattern between two boards or if a board redirects the ball into either wall of the box.
Return _an array_ `answer` _of size_ `n` _where_ `answer[i]` _is the column that the ball falls out of at the bottom after dropping the ball from the_ `ith` _column at the top, or `-1` _if the ball gets stuck in the box_._
**Example 1:**
**Input:** grid = \[\[1,1,1,-1,-1\],\[1,1,1,-1,-1\],\[-1,-1,-1,1,1\],\[1,1,1,1,-1\],\[-1,-1,-1,-1,-1\]\]
**Output:** \[1,-1,-1,-1,-1\]
**Explanation:** This example is shown in the photo.
Ball b0 is dropped at column 0 and falls out of the box at column 1.
Ball b1 is dropped at column 1 and will get stuck in the box between column 2 and 3 and row 1.
Ball b2 is dropped at column 2 and will get stuck on the box between column 2 and 3 and row 0.
Ball b3 is dropped at column 3 and will get stuck on the box between column 2 and 3 and row 0.
Ball b4 is dropped at column 4 and will get stuck on the box between column 2 and 3 and row 1.
**Example 2:**
**Input:** grid = \[\[-1\]\]
**Output:** \[-1\]
**Explanation:** The ball gets stuck against the left wall.
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\],\[1,1,1,1,1,1\],\[-1,-1,-1,-1,-1,-1\]\]
**Output:** \[0,1,2,3,4,-1\]
**Constraints:**
* `m == grid.length`
* `n == grid[i].length`
* `1 <= m, n <= 100`
* `grid[i][j]` is `1` or `-1`.
|
Connect each pair of points with a weighted edge, the weight being the manhattan distance between those points. The problem is now the cost of minimum spanning tree in graph with above edges.
|
Array,Union Find,Minimum Spanning Tree
|
Medium
|
2287
|
1,610 |
today's question is maximum number of visible points let us see what is the question so we are given with an array of points an integer angle and your location so this is an array and then we have an angle and location is um also an array which contains position of x position of y so these are coordinates x coordinate and y coordinate and points is also an array of such points where the first part of the array says x i and then y i so this is quite clear both denote integral coordinates on the x y plane initially you are facing directly east from your position you cannot move from your position but you can rotate so we are at some position and we are looking at each direction we cannot move from this position and we can rotate rotation is allowed in other words position x and position y cannot be changed your field of view in decrease is represented by angle so at one point in time the thing that is visible to us is going to be defined by a certain angle and this angle is given in the question so um degrees is represented by angle determining how wide you can see from any given view direction let d be the amount in degrees that you can rotate counterclockwise then your field of view is the inclusive range of angles this and this yeah obviously so once we move in certain direction then um our view also changes so let's say that we moved here so our view changed from this to this um yeah that makes sense so what do we need to find here you can see some set of points if for each point the angle formed by the point your position and the immediate east direction from your position is in your field of view right so yeah we are looking here this is the angle that is given we move in this direction so our field of view also changes right so there can be multiple points at one coordinate there may be points at your location and you can always see these points regardless of your location rotation points do not obstruct your vision to other points so we need to return the maximum number of points you can see oh so let us see from this example uh this is our location cannot change but what we are seeing here is um in our current field of view there are three points right so three would be answer in this particular case uh let us take a few more example so um let us say this is the graph that we are given with and there are some points on this graph here and this is the location that we are given with now um there could be more points at our location itself and this point whatever points are there on our location itself are always going to be visible right so that is always going to be a part of our answer let's say there is one point so we know for sure that at least one point is going to be visible always visible so the answer would be 1 plus something now let's say that this is the angle that we are given with let us call it angle and then and we are free to move this angle anywhere so this can change ah this was not a good rotation this should have happened well so let us say that this changes and this changes from this point particularly and the new angle that it makes would be this one something like this um and well it is not clear here but the angle that it is making we are assuming here that is going to be the same so in this case there is just one point which is visible in our field of view and in this case there are two points which are there in our field of view so our answer is going to be 2 plus 1 that we got from this so the answer is going to be 3 so as it seems it feels like a sliding window question where we need to change our direction of view we have to rotate and in whichever direction we find the most amounts of points that is going to be our answer and it seems like there is some mathematical background also needed here because there are angles and we'll probably need to calculate angles or do some calculation over these comparisons over these angles so we should probably understand uh some basics of from elementary mathematics as well so let me see if i can tell you something so let's say that we are given with ah this point and this point this is our graph so this is 0 and this is another point that is going to act as reference for us so um let's call it one two this is also one and two and well just to make sure that we are at a nice place um let me make this here so three so we need to find out this angle this angles um so the first step in our algorithm is going to be sorting all the points according to the angles that they are making with the x-axis x-axis x-axis and obviously if you want to sort something according to their angles we need to understand what is the angle that they are making with the x-axis that they are making with the x-axis that they are making with the x-axis right and this is going to be uh with taking a reference from this particular point that we are given with location so here the coordinates of this particular point are going to be 3 comma 2 this point is going to be 2 comma 2 and this particular point is going to be 2 comma 1 so uh we need to find out this angle and then we have to find out this angle and if theta is going to be smaller than theta dash then this point will appear before this point in the list that we are going to sort so how to find this theta this is where some mathematical background comes into the picture um so from your mathematical classes back in the days would you remember that if there is a triangle this is hypotenuse this is opposite side and this is the base or we call it adjacent side so 10 of theta is equal to o divided by a in our example see this is making the same structure so if we want to find out theta uh we can do a tan theta of o so o is going to be the perpendicular height um perpendicular height of this uh this triangle and that is going to be 2 minus 1 right so 2 minus 1 and that is divided by this length and this length we can see 3 minus 2 and that is going to be 1 divided by 1 so 10 theta is 1 so we know what 10 theta is now we want to know what theta is going to be so theta would be arc 10 which is the inverse function arc 10 of then theta this value we know a we know o we know a so we should be able to calculate arc 10 as well and r10 is usually a part of all the libraries um all the language libraries so for example in javascript we are provided by uh provided with math dot arc uh sorry it is uh a tan i think math dot 8 10 2 and then y x so with this thing clear we can go to our drawing board and we can start coding and okay let me also give you a brief of the algorithm that we are going to follow so first of all we are going to calculate all the points which are same as our as the given location so that we can calculate at least the number of points the least number of points that is always visible and we'll initialize max with that point uh points at origin then second thing would be we'll calculate all the angles that all of these points are making with respect to the origin that we are given with so from the list we'll map it to the angles and then we are going to sort this list of angles right so that means we would know this point comes before this point comes for this point something like that and after that this is going to be a typical sliding window um question so we let's say this is the sliding window then we move the sliding window all around all right so let's go and start coding let us start with looping through all the points and making a list of angles there so for that we'll need an empty array of angles and then we'll start with looping so uh but it's going to be the list of points and from each point let's take x and y coordinates so x is going to be points uh i and zero and let y is equal to points i and then it's my coordinate uh in case if uh it happens to be the x and y coordinate happens to be the origin we should skip it so if x is equal to location and y is equal to location 1 then add it to a list of points on center so i'll call it on center initially it is 0 and i increase it by 1. so at the end of when we are returning result uh we'll be adding this on center there and um we're going to skip it from our list that we are going to build right after it and then otherwise add it to list of angles so it is going to be angles dot push and i'll create a function and call it angle and it will be needing x and y and the location for reference and the return value will be directly pushed to angles and it is going to return angle let's quickly build the function with angle x comma y and then reference we could call it origin as well i think relation will be better so um we have already discussed about uh how to get angle we are going to use inverse of tan theta uh to get theta and ten theta because we have y and x which is going to act like opposite side and adjacent side in a triangle so let opposite is equal to y minus origin 0 that adjacent is equal to x minus sorry this is going to be zero here and one here right and then we know that angle is going to be math dot eight and two is the function that we use for getting uh angle from ten theta opposite comma adjacent and um so this returns angle in terms of radiance and we'll need to convert that into degree because this angle that you see here is going to be sent in degrees so we should have the same unit everywhere so in order to do it we'll add it to uh multiply it by 180 and divide by pi yeah and then we can return angle there's just one quick thing that we should remember here the angle that we get this is the range is between minus pi and plus pi and that's in radian that we have already converted into degrees uh i think it'll be better if we can just have a list of these angles in terms of degrees from 0 to 360. so convert it to 0 to 360 range yeah and it is going to be quite easy if angle is angle that it calculated is 0 less than 0 then we just add 360 to the angle and if this is not clear let me quickly tell you about the diagram so let's say this is our x coordinate x-coordinate this is our x coordinate x-coordinate this is our x coordinate x-coordinate y-coordinate and y-coordinate and y-coordinate and pi is 0 to pi is in this region and then minus pi 2 0 is here so if we want to convert all of these angles which are going to be in minus ah into their positive angles what we can do is let's say that there is some angle here we add 360 degrees so the value of the angle doesn't change but the sign changes sine becomes from minus to plus right so i think that's easy i hope you understood so yeah let's continue angle is there return angle yep so i think this part is done and we have already pushed all the angles here so we already have a list of angles then what is left is yeah we can sort on language and angles will be salted according to the angles themselves so it is nothing but just a simple numeric sort so angles dot sort a comma b and a minus b so this should sort in ascending order yeah uh now one more corner case that we need to take care of is that um so again this is going to be our graph and we start searching from um here like this so this is the window that we take and then we take a complete circle and we continue this until it reaches here right so in the beginning this is the portion in the end this is the portion now see if there are some points which are going to be like this then we should also take this theta in such a way that these points are also covered but we are going to miss that in this current scenario so these additional points should be added to the list of angles and these should be added in such a way that the angle that they make for with the center is not um less than 360 but more than 360. so just to give you an example let's say that this point is making an angle of 30 and this point is making an angle of 270. so in order to check whether they are forming they are in the same sliding window it will be easier if we can make this 30 into 30 plus 360. in the second round in the first round 30 is fine but in the second round it should be 360. so what we are going to do is we are going to add all of these points uh the angle that these points make with x axis and add it to our angles array in 30 plus 360 format so angle plus 360 format yeah so that's what we are going to do now this is going to be easy how to do that um so first of all let us figure out what is the largest angle um that our array of angles have largest angle is equal to angles angle start length minus one so because angles is already sorted the last angle of this array is going to be our largest angle right and let's also make a temporary list of these additional points that we're going to add let's loop through our angles array and we need to continue this loop until um the current angle plus 360 minus the largest angle uh the value is going to be greater than angle so while the value is less than or equal to angle we'll continue the loop and we'll stop the loop when the value of the current angle goes beyond the angle that is provided here so if angles i plus 360 goes beyond angle so angle then we break the loop otherwise we add this to our to the temporary area that we have 360. and then at the end just concatenate this with angles so i think all the pre-processing is so i think all the pre-processing is so i think all the pre-processing is done now comes the meaty part where we actually run these sliding window algorithm and figure out the maximum number of points um that are covered by the given angle right so let max is equal to zero and for let's start is equal to zero and is equal to zero so we start with the from the beginning itself and we need to run it until end reaches the end of angles uh array and n plus um and we need to increase start pointer when angles and minus angles start is more than angle the given angle that's when we increase start and yeah that's okay and then we update the value of max and value of max is going to be um maximum of max itself which is initialized at 0 and n plus 1 minus start so this value here is going to tell us the size of the current sizing sliding window and at the end we just add max and on center both on center is the value that we calculated in the very beginning and these are the points which are at the center at the location itself the reference location itself i think this should give us our answer let us try and run it oh we got it let's try and submit it um seems like the answer is not right there is some error is it and we'll send minus a good start and this looks okay angles.concat temporary angles.concat temporary angles.concat temporary this is also fine i guess angles 360 more than angle yeah this is also fine oh i did not subtract the largest angle yep that's the issue use the example test cases oh one more so this is when the angle submitted is going to be zero and there are obviously two hmm okay so this was one problem um we have sorted the angles here this looks okay zero to angle start length i plus and that's fine then here we are doing angle start push with respect to location and that's okay x is location zero y is location one that's when we add to center um x is zero y minus one what about get angle x comma y comma region opposite is going to be y minus origin one yeah x is going to be x oh this was supposed to be minus hmm yeah this was accepted this time that's all thank you so much
|
Maximum Number of Visible Points
|
xor-operation-in-an-array
|
You are given an array `points`, an integer `angle`, and your `location`, where `location = [posx, posy]` and `points[i] = [xi, yi]` both denote **integral coordinates** on the X-Y plane.
Initially, you are facing directly east from your position. You **cannot move** from your position, but you can **rotate**. In other words, `posx` and `posy` cannot be changed. Your field of view in **degrees** is represented by `angle`, determining how wide you can see from any given view direction. Let `d` be the amount in degrees that you rotate counterclockwise. Then, your field of view is the **inclusive** range of angles `[d - angle/2, d + angle/2]`.
Your browser does not support the video tag or this video format.
You can **see** some set of points if, for each point, the **angle** formed by the point, your position, and the immediate east direction from your position is **in your field of view**.
There can be multiple points at one coordinate. There may be points at your location, and you can always see these points regardless of your rotation. Points do not obstruct your vision to other points.
Return _the maximum number of points you can see_.
**Example 1:**
**Input:** points = \[\[2,1\],\[2,2\],\[3,3\]\], angle = 90, location = \[1,1\]
**Output:** 3
**Explanation:** The shaded region represents your field of view. All points can be made visible in your field of view, including \[3,3\] even though \[2,2\] is in front and in the same line of sight.
**Example 2:**
**Input:** points = \[\[2,1\],\[2,2\],\[3,4\],\[1,1\]\], angle = 90, location = \[1,1\]
**Output:** 4
**Explanation:** All points can be made visible in your field of view, including the one at your location.
**Example 3:**
**Input:** points = \[\[1,0\],\[2,1\]\], angle = 13, location = \[1,1\]
**Output:** 1
**Explanation:** You can only see one of the two points, as shown above.
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `location.length == 2`
* `0 <= angle < 360`
* `0 <= posx, posy, xi, yi <= 100`
|
Simulate the process, create an array nums and return the Bitwise XOR of all elements of it.
|
Math,Bit Manipulation
|
Easy
| null |
791 |
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is custom sort string so in this question we given two strings order and S all the characters of order are unique and were sorted in some custom order previously so order will give us the order in which we have to sort the input string s and this is the condition of the sorting and our task is to permutate the characters of s so that they match the order that the string order was sorted in and more specifically it means that if a character X occurs before a character Y in order then X should occur before y in the permitted string and we can return any permutation of s that satisfy the above property now let's take a look at example one and see how we can solve this question so the input string given to us is a b c d and the order is CBA first C should occur if C is present yes C is present so let us build our result so C is present so first C should occur so this is done now we have to check for B yes B is present so add B here check if a is present yes a is present so add a now we finish the order and whatever is left will be appended in theend so this is a one kind of peration which satisfies this condition mentioned to us and CB a is the expected output so let us implement the same ideology in code we are maintaining the number of occurrences in this string s and based on those occurrences we are checking if that character is present inside order if it is present we are first printing those characters inside a result so let us form our logic since we have to deal with the number of characters present in s I'll create a map which will store Key and value pairs so the number of characters present inside s so we iterate through S which is the input given to us and find the number of characters a is uring so add it and set this frequency to one B is appearing so add it and set it frequency to one C is appearing set it frequency to One D is appearing in set its frequency to one now we have the characters of map now inside this map we have the characters of s now we iterate through the order now first we start with this character CH is equal to C we check if the C is present inside the map yes it is present so all the occurrences of C present inside s should be printed in our result so if first I create a string Builder C is appearing one time so print it inside the result and now remove the C because we added it once and that many times it was occurring now go to the next character in order CH is now B check if B is present inside the map yes so get its count is one so print B one time and remove it from the map now CH is equal to a check if a is present inside the map yes it is present so get its count it is present one time so print a one time and now remove it from the map and we finished processing all elements inside order now we have to check for rest of the elements present inside the map D is present one so printed one time so D will be printed and we finished processing all the elements inside uh the map and so we can end the iteration no need to remove the leftover elements from the map we just print it how many other times it's occurring and here as you can see we are getting the expected output cbid which is matching here and finally the return type is a string but we filled a string Builder so convert the string Builder into a string after converting whatever is present inside the string cbad will be returned as the output now let's take a look at the code and do a dry run for the second example now here as you can see first we have started with creating a map so I create a map and now we iterate through the string s let's take the second example string s is equal to a b c d now we iterate through the stringles from starting to end and fill all the characters a is appearing once B is appearing once C is appearing once and D is appearing once and now this we are filling the map now I create a result string Builder so I create string Builder which is empty and now we are iterating through the order so converting this order into a character array so order is equal to BC C A FG so convert order into a character array so that we can access one character at a time b c a f g now we access one character at a time we pick the first character now we check if that character is not present inside the map it is present here so this will be skipped we get the count of that character that count of the character so count is one so we are running the loop count number of times zero to count so we have to run this Loop one time in that Loop first we are appending that character CH so this is ch right so append that character into the result and remove it from the map so B will be removed and this for Loop will end we go to the next character is C so CH is now at C we check if it is present inside the map yes CH is present so C is present so skip this and get its count is one so count is now one we use a for Loop to iterate one number of times in that we append that character CH so CH into the result so c will be added and we remove that uh CH from the map so c will be removed and now the for Loop will end we go to the next Loop the next iteration we are at a we check if a is present inside the map yes it is present so this will be skipped get its count it count is one so we iterate one number of time in that time we add that character into the result V A and remove it from the map the next character is f we check if f is present inside the map no it's not present so this will be executed and we skip the current Loop so we go to the next Loop so CH is now at G check if G is present inside the map no it's not present so this will be executed and we skip the current Loop and now we reach end of the order array so this is finished and now we have to iterate through whatever is left inside the map yes D is present so get its count is one so add 1 D into the string Builder and this for Loop will end and we reach the end of the map and no more characters are present so here the character set was just D and we processed that and we added that and we came to end of the key set so we are done with this Loop two and we come out and we convert the string Builder into a string so b c a d will be returned as a string because the return type is a string and this bcad is the expected output which is matching here the time complexity of this approach is O of n because we are iterating through the character array and the space complexity is also of n because we're using a map to compute the output that's it guys thank you for watching and I'll see you in the next video
|
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
|
1,743 |
hello shangi I hope that you guys are doing good so as in this video we're going to see this problem restor the array from adjacent pairs it has been asked by Uber Capital 1 Robin Hood so let's see this problem statement itself it's going to be a bit tricky but as soon as you got the solution you can just relate it right so we have an integer AR called as nums now in that it consist of basically an unique elements again Mark the words unique elements it has unique and unique elements but you have forgotten the nums entirely okay however you do remember every pair of adjacent elements in nums now if I say I have a b c d in my nums then I remember the adjacent pairs which means I remember I have a Ab pair I remember I have a let's say ba pair I could remember that also I then because AB pair and ba pair are both same and then I'll remember I have a BC pair or a CB pair then I'll remember I have a CD pair or a or I can say a AC pair so anything I can say I just have to say the pair itself now I am given a 2d integer adjacent pairs which is of size n minus one as you saw I had n elements so I will get Adent pair element as n minus one right so I will get that now when I have that it indicates that from UI to VI basically these are two adjacent element in my nums now it is guaranteed that every adjacent pair of elements num of I and num of I + 1 will exist in of I and num of I + 1 will exist in of I and num of I + 1 will exist in adjacent pairs which means every adjacent pair will actually always exist in this adjacent pairs Vector which will be given to us now uh the pairs can appear in any order these pairs it can appear in any order which means it can be possible that BC can come initially or it can be possible that CD can come initially and it can also be possible that DC can come initially so it can appear in any order whatsoever so that is also a good condition that it can appear in any order so you will see that some things are highlighted so they are actually important for us now we have to return the original array nums if there are multiple Solutions you can return any of them so just imagine we will be given these stuff which means these pairs and we have to return this original array now it can be possible that okay for sure uh when you are saying are in firstly they are seeing that if they can multiple Solutions so first think is it POS to have multiple Solutions let's see what if let's say I know that it is a b c d right what if I start and make something like okay I know that b is there so I'll make something adjacent to it which means I know that b is here so I'll make something adjacent to it which is a because b and a are adjacent okay then B and C adjacent okay B A has already been there so I have to play C somewhere else I'll play C somewhere else which is having space then I know that I have a c uh I can place adjacent to C A D I know adjacent to C already one B is there so I can place a d here so you saw that one thing I can make something like this or I can just go ahead and make okay I have a then I play adjacent to a b I placed adjac to B I can place a c whatsoever is empty then I can adjust to C I can place a d I can make this so you saw either I will be making this format which is you will see is the reverse is exactly the reverse of the input or I will make exactly the input itself so these two are the only possible solution which you can have and why is that the case it is the case because these two numbers these A and D have both of their other ends as empty so for sure I will have a space to actually put up something else but for the other elements which is B which is C they are bounded by two neighbors they are bounded they will for sure have these two neighbors beside them they will have for short these two neighbors beside them so we cannot just uh say that BNC can occur in anywhere while I can just say that the order will remain same which means a b c d it's just that I can for sure any time just simply reverse it because still the pairs will remain same so these two can be the possible solutions now coming on to that if I have given these pairs how will I have to make this now as you can easily see that it's a connection okay I know that I have an A it is connected to B right because you know that it's a because you'll see it's a sequence is just a connection I have a which is connected to B I have a b which I know is connected to C right because I have I know a is a pair so a is a connection so I have two nodes let's imagine I have two noes I can just connect them right so I know that I can connect AB with two noes I have a BC I can connect them now I have a CD I again connect them so you saw that if you just imagine these adjacent pairs as the nodes of the graph and this AB as just saying okay it's an edge between those two graphs those two nodes of the graph and then I can simply build the graph if I know what is the root node and root node can be any node whose like whose neighbor is only one so root node having neighbor only one so that's a root node so I know this is the root node for me and I can simply Traverse do a simple DFS or a BFS to actually get the entire array because you know a simple DFS is or a simple BFS is just a traversal now if it is a traversal you will simply Traverse okay I will Traverse a and then after a I can just go to B and then C and then d as I'm traversing to every element and for sure it will be just a single line because I know that every element occurs only once and if every element occur only once one element can have maximum of two neighbors that's it so for sure this will be always a straight line so you will always know if I will start from the very start I will keep on pushing elements in my answer Vector whatsoever I have then I'll simply get my answer so you will see that you can just convert this entire problem adjacent pairs grab the adjacent pairs convert that to a graph travel the graph from the start node now it can be a it can be D also if you travel starting from D itself you'll get a d c b and a that's also a correct answer for you but you will see that time complexity will actually be o of N and it's for sure because you have toate on the entire adjacent pairs are that is for sure obvious it will always occur because you have to Travers the entire input area itself space will also be offn because if you even use a DFS or a BFS uses a q DFS uses what DFS uses a recursive stack so for sure any way even if you use a DFS or BFS might be a bit less in space because for sure if you just input this element in the queue then if the child comes in so the previous element will go out it will only come in now when the next element will come in so this element will go out it will again come in and so on and so forth so space wise DFS will be actually o ofn but BFS will kind of tend to O of one so that is very okay for us so but still um can we do it in some other way or because like it just seems a straight graph can't we just get the property of that straight graph and maybe try to find the answer for it let's see so what we have done is that okay we know that for sure if a has just one neighbor or like B has so like for now let's imagine just one node okay I got a which is having only one neighbor so for sure it is a starting node now for sure if it is a starting node then I will know it for sure it will start from a now I should know very well and very fast what is the neighbor of a and what all possible neighbors of a are there right now it's just one which is B so which means that I the concept of graph keeping the track of neighbors I have to make sure I will use that itself which means I know that I have a graph for the a I know the neighbor is only B for the graph which is B I know the neighbors are A and C it's just I'm making adjacency list of this graph for the C I know the neighbors are actually B and D for D I know the neighbor is only a c it is nothing but the adjacency list made for the graph and it will and you will have to make it either if you go via the DFS way or if you go via the uh this way of our finding answer now again you can just go VI the BFS also it will also be same uh please don't keep track of the visited you will keep track by the parent if you keep track by the visited then again you will actually end up having a complexity of ofn a space complex ofn so keep track that visited thing not just by seeing okay my parent was this so I will not take this element so keep track that parent also meanwhile uh what we will do is uh we'll just simply Traverse it and try to use it sequentially without using the graph entirely in indirectly it's graph concept but not directly cool now uh what we know that we have got these pairs which means in very less time I can just find out and for sure you know his length will either a one or a two if it is a one which means the these are the end nodes if it's actually a two which means it's a middle node now I know okay I have grabbed a and a b because if I am saying that I'm starting off with a node with a pair because as I grabbed this I know that A and B are the notes which means a is having a neighbor as one so for sure a is the starting note and the next pair is B now as I'm on to B I can go and check okay I on to B now I know that my in my answer is built so far like this I am on to B now I have to just increase my I have to build my entire answer so I am on to B I'll go and check okay what's the previous element okay it's a so I'll go and ask bro what are the neighbors of me bro your neighbors are A and C so I'll just go and ask hey bro is a this number is a the bigest number of me it is the last number if the if my answer is built up till here it is the last number and it is the second last number so I'll ask its adjacent pairs of B that bro uh what's your first adjacent pair he will say bro I am a I ask bro a are you equal to my second last number yeah bro I'm equal oh sorry my next pair cannot be in a then I'll ask next number bro see are you my second last number he will say no bro I'm Different oh bro then it's great then you just push back in my answer okay I just push back you in my answer then I'll just land on to this number which is actually again the last element if it's the last element I'll again go and ask bro and for sure I know this is the second last element I going ask bro uh who like I'll go on to you bro now bro uh for you my second last number is actually like my first encountering neighbor is actually a b bro are you equal to my second last number yeah bro I'm equal so please bro please don't take me I'll go to next number which is b d and for sure these will only be just two numbers now I'll go to next number which is D bro uh are you equal to my second last number bro I'm not okay cool bro no worries just you are my this answer D so just push back in my answer and as you know that your answer dot size is actually have become equal to your graph size which is this and as soon as it becomes equal you know for sure that you have computed your answer and that's how in just simply o of n time you can simply solve it and O of one space o of one space again as we showed that we can use Simple a DFS or again a BFS if you use a DFS strategically for sure we will have to use o of npace if we strategically use a BFS we can actually get it done in O of one space it's just that we have to explain the interviewer that why it is o one again we will not have to use visited and for sure there's another way to solve it that we just simply use the concept behind the graph and just simply check okay I know it's a straight line I know for sure the previous neighbor and with that concept I can just simply get okay I this is my last if my array is built something up till here this is my last number this is my second last number I'll go and check the neighbors of B and check okay the neighbor of B which is not the second last number is my next number that's it cool uh let's quickly jump onto the code uh so basically what we will do is we'll just solve it the way we saw the O of n time and O of one space so firstly I need to have my answer and as I also showed that I need to have a graph kind of structure because of the adjacency list as I showed below so I'll just have the um My Graph now for this particular graph um I'll just know that first I have to iterate on the entire graph itself so I'll just go and iterate on all of my pairs uh in my adjacency list which is adjacent pairs now for all these pairs I know I have to build the graph so let's name it as a p itself so I know that P of0 I need to push back um the P of one which is just a UV pair and also the graph of P of 1 dot push back uh P of0 now when this is done I know that my graph is made uh but for sure I need to get that starting node so I'll just simply go on to all of my node pairs in My Graph because graph is nothing but a map so this is a pair of node and the adjacency list which is the vector of neighbors so I'll just say if uh node pair doc do size which node pair do second is the neighbors if that neighbor size is one oh bro for sure I have got in what I have gotten that particular neighbor which is actually start node so I know that I have got the start node so although if you were start to doing a DFS and stuff so you would have taken a start node here let's name it as a Min -1 E6 now why -16 let's name it as a Min -1 E6 now why -16 let's name it as a Min -1 E6 now why -16 because you know that your nodes are from -15 to5 so you can take the other from -15 to5 so you can take the other from -15 to5 so you can take the other values now you can just mention a start node here and that will be nothing but node pair DOT first if you would have done a DFS so you would have known okay I will start my DFS from this node and I'll will get the answer but right now you don't need DFS so you can just ignore this part and what you can do is you can just push back these first pair first combination in your answer now what is the first combination uh first combination is simply uh the first node which is node pay first because it has just one neighbor and also the uh just neighbor of this which is actually again stored in node pair. second and that node pair. second only had one value again it only had as you will see it only had just one value which is B so I just pushed back this value and I'll just push back it's a first value and for sure I have got the first pair with me so simply break because after getting this first combination I will now build my answer now while my answer do size if it's actually less than my graph do size because my graph also says the same thing uh number of elements in my entire answer so while it is less so firstly as I know that I will have to find my last element which is nothing but answer and answer do size minus one and also I have to find the second last element now that will be nothing but answer of answer do size minus 2 right so that will be your second last and last element now what I have to do is I will have to find the all the neighbors of your last element so I'll just go and find the neighbors of my these uh last element now when these last element uh because you know that last element's neighbors it can be the previous one and this one so I've got the neighbors now I'll just ask uh bro if neighbor zero if it is not equal to my second last element so bro for sure this nebor zero is my next element so I'll just push back um push back this neighbor zero in my answer else for sure the next number which is the neighbor of one because I know I will only have two Neighbors at Max will be the uh next element which is neighbor of one and with this you will easily get the answer and ultimately you can just simply return the answer now for sure you can just initialize these two inside also uh but if you are doing a you know DFS way then you it's good to actually initialize outside because your DFS regive call will actually be outside now quickly run this and just submit it and that will be done cool thank you for watching good take care bye-bye it beats time and space too bye-bye
|
Restore the Array From Adjacent Pairs
|
count-substrings-that-differ-by-one-character
|
There is an integer array `nums` that consists of `n` **unique** elements, but you have forgotten it. However, you do remember every pair of adjacent elements in `nums`.
You are given a 2D integer array `adjacentPairs` of size `n - 1` where each `adjacentPairs[i] = [ui, vi]` indicates that the elements `ui` and `vi` are adjacent in `nums`.
It is guaranteed that every adjacent pair of elements `nums[i]` and `nums[i+1]` will exist in `adjacentPairs`, either as `[nums[i], nums[i+1]]` or `[nums[i+1], nums[i]]`. The pairs can appear **in any order**.
Return _the original array_ `nums`_. If there are multiple solutions, return **any of them**_.
**Example 1:**
**Input:** adjacentPairs = \[\[2,1\],\[3,4\],\[3,2\]\]
**Output:** \[1,2,3,4\]
**Explanation:** This array has all its adjacent pairs in adjacentPairs.
Notice that adjacentPairs\[i\] may not be in left-to-right order.
**Example 2:**
**Input:** adjacentPairs = \[\[4,-2\],\[1,4\],\[-3,1\]\]
**Output:** \[-2,4,1,-3\]
**Explanation:** There can be negative numbers.
Another solution is \[-3,1,4,-2\], which would also be accepted.
**Example 3:**
**Input:** adjacentPairs = \[\[100000,-100000\]\]
**Output:** \[100000,-100000\]
**Constraints:**
* `nums.length == n`
* `adjacentPairs.length == n - 1`
* `adjacentPairs[i].length == 2`
* `2 <= n <= 105`
* `-105 <= nums[i], ui, vi <= 105`
* There exists some `nums` that has `adjacentPairs` as its pairs.
|
Take every substring of s, change a character, and see how many substrings of t match that substring. Use a Trie to store all substrings of t as a dictionary.
|
Hash Table,String,Dynamic Programming
|
Medium
|
2256
|
202 |
first of all there is no such thing as a happy number it is just a problem statement and we have to solve for it i am talking about the problem happy number on lead code let us see what is it all about hello friends welcome back to my channel first i will explain you the problem statement and we will look at some sample test cases next we will see how you can approach this problem and what is the efficient approach so that you can arrive at a solution on time going forward we will also do a try run of the code so that you can understand how this code actually works so without further ado let's get started let us quickly make sure that we are understanding the problem statement correctly you are given an integer and you have to determine if that integer is a happy number if yes return true else you need to return a false right the first question that should come to your mind is what exactly is a happy number in terms of mathematics and arithmetic there is no such thing as a happy number but according to this problem statement a number is called to be happy if you take each digit of this number and square them and add all of them and you keep on doing that until you get the final answer of 1. if you get a 1 you just stop over there but if you're not getting a 1 you need to keep on repeating this process to understand it better let us look at our two test cases first of all let us look at our first test case and the number 82 right so what do you have to do over here you take 8 and you square it then you take 2 and you would square it so that will give you 64 plus 4 and that equals to 68 correct this is not yet one so what you have to do is take the digits again and square it so this time you get 6 square plus 8 square and that will give you 36 plus 64 and that will give you 100 right now what happens if you square it you get 1 square plus 0 square so this will change to 1 right and that is where you have to stop because no matter how many times you square 1 you will still get 1 right so in this case 82 is a happy number and you have to return true as your answer correct similarly let us look at our second test case that is the integer 2. now it is not a case that you have to stop at a single digit you still have 2 right so 2 square will be 4 but you don't stop over here since you haven't received a 1 4 square will be 16 right moving on you have 1 square plus 6 square that is 1 plus 36 and that will give you 37 correct similarly you will keep on doing this process 3 square plus 7 square that is 9 plus 49 and that will give you 58. so this is how you will have to keep on doing this and for this particular test case if you keep on doing this again and again you will never reach a one so what you have to do is in this case you have to return false as your answer so now if the problem statement is clear to you feel free to try out the problem once again on your own otherwise let us dive into the solution okay so how do you start to approach this problem what is the most naive way let us say you are given the number 65536 and you have to determine if this is a happy number what will you do what you can do is you can start taking each of the digits then square all of them and then you get the final sum as 131 right now you have to repeat this process because you have not encountered a 1 correct so once you start repeating this what will happen is you will get 1 square plus 3 square plus 1 square and that will be equal to 11 right you still cannot stop over here because you haven't got a 1 yet so you're just gonna proceed ahead this time it will be 1 square plus 1 square and that is 2 and then you will keep on doing this operation until and unless you reach 1 right and yes that is the way to approach this problem but think about it when you are writing code for this problem how do you know when you have to stop it is not necessary that every number will be a happy number right so what happens if you keep on doing this there will be a chance that you might get stuck into a loop and you never reach the number one correct it would also be possible that you receive the same number again and then you are stuck in the same loop trying to achieve one but you will never get it so what happens then how do you solve for it so let me show you first how you can get stuck in a loop so let us say i am taking another example of the number 61 correct so now when you start to apply your algorithm on this number what will happen is 6 square plus 1 square you get a 37 right next you get 58. similarly you will keep on doing this now look at it what happens when you apply the same algorithm on the number 16 what will happen you will get 1 square plus 6 square that is 1 plus 36 and that will give you 37 again right and if you look closely we already got a 37 in the first place right so if you keep on applying the same algorithm again further to this you will keep on getting the same numbers and you will get stuck in this loop right you will never reach a one so somehow you need to determine that okay this is the place where i have to stop you cannot just decide to stop after let's say two seconds or five seconds hoping that you have achieved your result you need to stop when you have encountered the same number right and that is when you need to take the help of a hash fit what a hash fit can do is it can determine if you have encountered this number already so if we do our same calculation but this time with the hash fit what we can do is we started with 37 right so what you can do is you can put 37 in your hash fit next you get the number 58 so put 58 in your hash fit then you got a 89 so put that number similarly just keep on adding all the numbers to your hash fit now when you encounter the last sum again that is 37 check your hash fit if this number is already in the hash fit that means you have already calculated for it and you did not get a one so that is where you need to stop and break out of the loop and this should help to achieve your answer in a very efficient manner now if you have understood all of this let us look at the dry run of the code and see how it actually works on the left side of your screen you have the actual code to implement this solution and on the right i have a sample number with me that is passed in as an input parameter to the function is happy oh and by the way this complete code and its test cases are also available on my github profile you can find the link in the description below proceeding on with our dry run what we do next we create a hash set that is used integers and this will contain all of the numbers or the integers that we have already encountered right so now what you do is you start a while loop notice that this loop is an infinite loop because we do not know when we will reach our solution so moving on what do we do is we find the sum of squares for the actual number that is n so what will happen is you will find this sum and then if the sum is 1. right now what is the sum of digits that is 6 square plus 1 square and that is 37 right so what you're going to do is this sum is not 1 that means you have to continue so you will reach the else part of your loop right since this number is not 1 this is a new number that we have to work with again correct but at the same time what we can do is we can add this number to our used integers that mean we have already encountered it so what we'll simply do is we will add 37 to our used integers now what will happen is this loop will run again and this time we have to work with the number 37 correct so you will square each digit and add them right once you add them this time you will get a 58 correct so once again you check if this one no that means you have to continue but what you will do you will also check have i already calculated things for 58 earlier no right that means this is a new integer so i will simply add this integer to my used integers right so this loop will keep on running again and again until you get a unique integer in this hash set either you will eventually get a one or you will get one or the other number that already exists in this hash set and then you can simply break out of this loop while returning a false this solution will work in a constant time and space complexity that is order of 1 for time and that is order of 1 for space because no matter how big your integer is even if it is 2 to the power of 31 you will never have the sum of digits that is more than one thousand so you are doing all of your calculations in a limited space that is order of thousand and that is constant space i hope i was able to simplify the problem and its solution for you as per my final thoughts i just want to say that i know you are thinking how the time complexity of this problem is constant time well if you think about it if you read the problem statement correctly the range of integer is between 1 and 2 to the power of 31 right so that would look like a very big number correct but if you look at 2 to the power of 31 and then try to calculate the sum of all the squares of all the digits even then the maximum sum that you will get will not exceed more than three digits so the maximum number that you can get is 999 and hence you could have to fall for 999 numbers in the worst case but then again that is equivalent to order of 999 and that is constant time correct and hence we say that the time complexity of this solution is constant time right and space complexity is obviously order of one because you are not taking any extra space i hope this will help you understand why the space complexity was very important in this problem to analyze what other similar problems did you find what problems did you face tell me everything in the comment section below and i would love to discuss all of them with you also tell me do you want to know more hacker rank problems or more lead code problems or do you have any preference of the type of problems that you want me to solve you would be also glad to know that a text-based explanation to this content text-based explanation to this content text-based explanation to this content is available on the website a pretty handy website for all your programming needs as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where i can simplify programming for you until then see ya
|
Happy Number
|
happy-number
|
Write an algorithm to determine if a number `n` is happy.
A **happy number** is a number defined by the following process:
* Starting with any positive integer, replace the number by the sum of the squares of its digits.
* Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1.
* Those numbers for which this process **ends in 1** are happy.
Return `true` _if_ `n` _is a happy number, and_ `false` _if not_.
**Example 1:**
**Input:** n = 19
**Output:** true
**Explanation:**
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
**Example 2:**
**Input:** n = 2
**Output:** false
**Constraints:**
* `1 <= n <= 231 - 1`
| null |
Hash Table,Math,Two Pointers
|
Easy
|
141,258,263,2076
|
398 |
all right so today's question is 398 random pick index we are given an array of integers with possible duplicates we ask you to write something to write some code to randomly output the index of a given target number you can assume that the given target number must exist in the array so less corner case with either hander there is a note that the array size can be very large solution that uses too much extra space will not pass the judge will not be okay so the example here we have array1 2 3 if we ask it to return the index randomly return the index for the number 3 appears three times in the ray at indices 2 3 & 4 the ray at indices 2 3 & 4 the ray at indices 2 3 & 4 so you know these three numbers have a equal chance of being returned if we call this method if we call pick one we only have one double here at the index to zero so the zero has a hundred percent of the chessmen return if we call pick one so that's the problem here so this that this question has more down votes than upwards that's something you can note and I guess the reason is this is super unclear what it means by too much extra space so you better ask if the interviewer serviced at you front you're lucky you can ask him for clarification what exactly you mean by too much extra space if you tell you anything above constant is too much then you might have some thought you might be able to you know give him the idea so things that he would you know the fact that it's giving you an array of integers and the signature here is giving you directly a reference to a physical list kind of making you even more confused why there is the such thing as too much extra space so if you are allowed to actually store the numbers of this array meaning that you have you can afford order n space then a simple order n space solution would just be let me just quickly coded this up it's pretty fast collections or index no so what I'm gonna do is to create a hash map to store the indices for any given number that appeared in this array so this hash map will basically store the number two in this is mapping in this is the list of indices mapping and will be order of n as the same lens of this Nam's right so when you ask her to pick one so we just returned random and then of choice and staff down target so you just look up that all the indices for this target number in the array and just randomly return one this is a order of and space solution and the pick master is constant in time and space as well and in terms of space complexity the constructor also have to go through the numbers once that's order of n so I think this works yeah but the real purpose of this question is to you know and you are not allowed to use any extra space so actually your any extra space are higher than constant and that's the better way of asking this question if I were for the interview I would say that instead of a physical array I'm giving your iterator that you can you know call next to grab the next value and you are only allowed to you know what once I'm running out of number I Searle you a nun and after that the next time you call you try to call I will basically refresh this I starting to throw numbers out of you again so there is indicator where you basically reach the end of the sequence of numbers you know streams and maybe I some other yeah I would just say that I would just give you a literature instead of a physical array and I will ask you to solve this without using anything that's any space more than constant so then you still only want to go through the array of the integers only ones and when you see a target value you have to make a choice basically you have to make a choice whether you want to remember this index number and the next time you see this target number again you have to decide whether you want to update your memory and in the end you want to make sure that all the indices of the target value that you see throughout the whole string of numbers is equally likely so the way of doing that is actually quite easy so the first time you saw number the target number you definitely want to keep it so that you've got a one other one probability of keeping that in this index number as your return value the second time you saw this target value again you basically have to reduce the first your previous memory to be 1/2 and the your previous memory to be 1/2 and the your previous memory to be 1/2 and the current of on current index has 1/2 of current of on current index has 1/2 of current of on current index has 1/2 of the chance be becoming the new memory so you basically just sort of run a store sort of flip coin if it's a head you don't change your mind if you it's a tell you update your memory to be the second time second indices of the target number so the third time you saw this number you have to decide whether you want to update your memory to return this current the third in the system whereas the final result and the way you do that is you if there are anything that's a 3-sided if there are suicided that's a 3-sided if there are suicided that's a 3-sided if there are suicided dies let's just say that you have a suicided die that is basically if it's a with the number like 1 2 3 there if I know only if that's three shows up you update your memory if it's a one or two you don't change your mind so the way it works is let me draw a picture here so if you see the first time that something is coming up but it has probability of 1 being returned right the second time you see the target value 2 for the second time you want to reduce the first one to be 1/2 so your serial the first one to be 1/2 so your serial the first one to be 1/2 so your serial coin and if it's how do you forget and if it's tell you don't forget right so you reduce the first whomping be memorize the first indices being memorizes 2 by 1/2 and the second one memorizes 2 by 1/2 and the second one memorizes 2 by 1/2 and the second one has naturally 1/2 of probability become has naturally 1/2 of probability become has naturally 1/2 of probability become the new one you know memorize the one so the third time you saw a new thing the target value you have one third of the chance to memorize that index that's so that number has one third of the chance and if you choose to not to update your memory that's too certain of the probability right and you have to multiply this by 1/2 to forget the multiply this by 1/2 to forget the multiply this by 1/2 to forget the probability that you actually returned the first occurrence of the target volume in the end and these works out to be you know what sir as well so the strategy is when you go through the string of numbers you keep a track of the you know the location that you memorize for the target value and you also keep track of the number of occurrence for the target value and when you see the target value you know new target value here new indices for the target value you basically do a 1 over the total occurrence probably the updates to whether to use that new index as the return value otherwise you don't change your memory that guaranteed to have to be you know make sure that every occurrence of the target value have equal probability I guess I'm done doing a really bad job explaining this anyway you just finish this coding real quickly so in the constructor here we only keep track of reference to the num that you can now get that's arguably just a constant space because we only store reference and for here we can have a return to be minus 1 initialized to be minus 1 or none or anything doesn't matter and we keep track of the count of the number of occurrence of this target value we just start to be zero and we iterate over these stream of numbers knows what are we gonna do is when we in call her the target number we will make a choice whether we update another memory or not so this check can be anything it could be anything that seemed between integer that's in between zero and count but just for the sake of my previous example you know when I saw a surface to die I don't know if that exists if the number is a three I choose to update my choice we update the you know return value to be the index of this new occurrence and we have to increment the counter for the number of occurrence and easy and we just return this so yeah so that's an that's another way of solving this just looking at the time and space complexity for the overall we don't have any extra space it's constant for the reference gear and for these variables it's also constant for the time complexity the constructor takes constant time we're just initializing a variable and that takes but for the pick master here we have to actually go one pass so the numbers so that's order of N in space complexity and in terms of time complexity or are there but four spaces constant yeah so I'm really tired today I hope that I'm not schooling up at the analysis but yeah it's just an it's a the packets are more expensive if you do have to call this multiple times compared to the you know previous hashmark dictionary implementation solution so yeah I guess you should ask the interviewer how many times you're gonna call this big Messer and exactly is given to you is it fix the array that's always gonna be the fixed array it's just too big to be loaded into memory in one go you know there are some mechanisms of in the background to handle that you're reading in chunks and appears to you as a physical array but it's not so that so in that reason you can not afford for a hashmap or is that it's really a string of numbers you know you have to ask those things to clear out the things but either way if the pic should be called multiple times and the numbers fixed there go for the hashmap solution if you know if it's okay that is out of hand here and you don't want any you know beyond any space that's beyond constant go for this one and the you know just work so a cup of this examples and hopefully you can convince that this will guarantee to be unified uniformly Rendon yeah let's submit this as well okay so that's the question for today
|
Random Pick Index
|
random-pick-index
|
Given an integer array `nums` with possible **duplicates**, randomly output the index of a given `target` number. You can assume that the given target number must exist in the array.
Implement the `Solution` class:
* `Solution(int[] nums)` Initializes the object with the array `nums`.
* `int pick(int target)` Picks a random index `i` from `nums` where `nums[i] == target`. If there are multiple valid i's, then each index should have an equal probability of returning.
**Example 1:**
**Input**
\[ "Solution ", "pick ", "pick ", "pick "\]
\[\[\[1, 2, 3, 3, 3\]\], \[3\], \[1\], \[3\]\]
**Output**
\[null, 4, 0, 2\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3, 3, 3\]);
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(1); // It should return 0. Since in the array only nums\[0\] is equal to 1.
solution.pick(3); // It should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `-231 <= nums[i] <= 231 - 1`
* `target` is an integer from `nums`.
* At most `104` calls will be made to `pick`.
| null |
Hash Table,Math,Reservoir Sampling,Randomized
|
Medium
|
382,894,912
|
86 |
Hello gas I am Lalita Agarwal welcome you who is owner on coding channel the trick is made by you so late na start today this lead card problem actually late ki problem kya bol rahi hai achha before going tu tours have problem na 1 minute session par Those who understand this problem well and have six to try, look at this question, literally, it is a very easy question, for today here, what is the easiest and most simple trick, what is the power of that trick, it is the power of ji. You reduce one by two and make a new link list, I am fine, what will you do in that link list, all those who are smaller than I am going to add all the saree notes and all the bigger ones in the second list and go to the last list and make these two lists mine. The final answer will appear in front of you. Think a little about this and why this trick of yours. They are doing it because what is the range here, tell me the range is only 200, literally it was a very small range, hence there is no need to put any more options here, there is no need to sleep much, space etc. redemption. There is no need to take it, just focus on the implementation and finish the question. He said ok, I have understood this. Anju bhaiya said, I have understood. Okay, those who have not understood this problem, there is no need to take tension. First of all, we are going to understand very easily what is meant by a question, after that we will build its approach and give the final bill, the most wide sets implementation, see here the question, I had done my life, the question I have given to myself is the head node. Jeevan Thi said ok, now what is this here, this is the clinic list in which what is the value of the notes you have, one is four, give three, say ok, you are den, five is give, you said ok, this saree is What is the value of all the notes? What has to be done is to reduce it to a simple one that whatever value is given is Equal or to the right, where will we write the one that is bigger than it? Will we write it to the right? After the first, double is ok, so now which value was smaller than that one is 3 to 41, it is said that 440 is three, it is said that three is smaller, but It is not small, he said ok, then tell me 2 here, the value is small, then five, he said no, then yours, you said, yes brother, your value is small, ok, very good, now yours have written this here, this is on the front side. Saree Chhoti Value Now whatever children are there, the saree values of the saree will come here. Which saree values of the saree will come here. Which saree values of the saree will come here. Which value is the girl? He said, he has 4 children and then he also has three daughters, after that he understood this and said, Yes brother, there is no sorting here. Understand carefully what is happening here, like the three which is three, was it smaller than four, so my friend asked me to take this first, no one is starting, I have to maintain the order, just my Reduce it by so much while maintaining the order that whatever small value you get, brother, you have to write it on the left, just see, this is where you get your answer. What did he say, yes brother, 12243 5 understood, call this thing brother, have you understood? I have solved my question literally, that was all, now here I have explained something about what is solve, that is, I have explained the question from the approach, you are going to solve it with this and literally you can also tell how the question has been solved. We will not do anything, we will run the look of one of ours on top of this error, we will run the look of one of our four, we have said, it is okay, we have made one of ours in English with the name A and we have made the pen of A with the name of B. It is okay now. What will we do here? Simply give the condition that IF now we are standing on note 1. If we are standing on 1 for supposing then what is 1 then let us give Will we push it or will we push it to the note, that of the stick, what is the A inside A, has already been made, if this IF condition of Apna is not Pro and goes in Else, like it will go in Four, if it is Bullet, then this At the point of time, what will you post in your B? Will you push the female? Bullet's four A is gone, then yours is on top of 3, then put it back on yours. If petrol is not done, then back in service. Story: is not done, then back in service. Story: is not done, then back in service. Story: Three is pushed in front of four, it is okay. It is very good and then 2P 2p came on your own as soon as you came to your condition, then it went to its condition, then you have been in front of the forest, then you have gone in front of the forest and then you have to retreat on the five above the five We used to retreat, its condition was fulfilled, here we got five, then we came back, what is our trade on you, suddenly this condition became true, then we pushed us here, very good, our Puri's condition is done. The look of Hai Four is over, now what will you do? What is the name given? First step is ok. Yes, now whoever gets your trade done on top of this, name the trade as your current. First, there should not be any problem, brother, it is a simple thing, then you have created a new list note which you can name. Named it second and also gave current second to the tractor, ok, you can name anything, there is no add in first rule, just named it so that it can be understood a little, it is very comfortable, isn't such a name our own? Why did you give it? He said, okay, it's a simple thing, then what about this one which I had in the list note, on top of that, what is the IT rate on the whole, till the time the next one is taped, it is fine, father. First let's go here and check that the value of its head is if it is Add on its value, which you had just understood with great ease. But after the health condition is bypassed, what will you say, what happened? If you have to check on the next value, then what will you say that head = head's. Do next say that head = head's. Do next say that head = head's. Do next because you have to study yourself for the next value. There should not be any problem. It is good to be clear on biology. After that, what did everyone say? All the mobiles have become looped, the look of the four has ended, which is theirs. Brother, we were talking about four people, it is only one thing, it is a simple thing, there should be no problem, first thing should not happen, Mulayam ji, it is clear to me, after that, what is happening to me, which was the next of the current was the next of the first, the next was the current. What was the first road in which the saree of the saree from Apni Kya Gayi Second Note Gayi Says, It's a simple thing and what did you do, then opened the first one, next one, got the first one returned, got it returned. Hope you must have understood, still if you have any doubt then comment box. Whatever your friends, you tell me, what will be its time complexity and space city? First of all, if we talk about our time complexity, then here we have paid off because the entire note above is absolutely correct and if we talk about our space. So that will also be off N only because Apne Kya Hai, we are creating a new completely new link list, so Apne Kya Hai Space Complexity Thank You
|
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
|
132 |
hey everybody this is larry this is day seven of the august league daily challenge hit the like button hit the subscribe button join me on this call let me know what you think about today's problem pattern drum petitioning too so how's everyone doing hope uh this august month has been treating you well we'll weekend congratulate yourself about like a quarter of the way through so let's uh let's keep the streak going shall we i give an s give it a string as petition s such that every substring of position is a palindrome return the minimum cuts needed for a palindrome position of s okay so yeah so i usually solve these live so if um yeah so if it's a little bit too slow for you skip forward watch on 2x whatever speed you need uh maybe 1.25 x whatever speed you need uh maybe 1.25 x whatever speed you need uh maybe 1.25 x i don't know whatever you need um okay um so the reduction about this problem is going to be that it is uh the shortest path um it's the shortest path problem from the beginning to the end and if you know hmm the tricky thing is that there can be a lot of these quote edges um so for example if everything's the same then you like if it's all a's then you can definitely just go for all of them but yeah i don't know because there are just a lot of different techniques of doing it um you can also do dynamic programming again but kind of like a shortest path by looking each node one at a time but you might have many edges and in that case i guess in that case it's actually only n squared and n is only 2 000 so maybe that's okay hmm um and then the other thing then maybe that you have to figure out all the palindromes and i guess you can also do that from n squared right so maybe everything is just n squared i don't know if that's gonna be fast enough um given that 2000 square in python is a little bit slow but if needs be i could use another language can i do better than that i don't know i think i don't i mean other than having like shortcuts with heuristics um i think in the i think that you can construct and a graph of maybe n square maybe you could shortcut that i don't know maybe you could do greedy not sure can you do greedy yeah i mean i don't think you could do greedy in a good way because this is um without looking at all the edges once um and there are potentially n square edges so i think that's why um yeah so we can start by building out the edges uh by you know so what i know that i already used uh graph terms so what do i mean right let me pull up a drawing thing hang on uh to kind of talk about what i mean i think i don't i sometimes skip over this a little bit too quickly um but yeah but basically for example you have a word that's i don't know um let's just say hey something like that right okay and then it crashes for some reason let me try again sorry friends hmm all right let's just write it out then draw it out let's say you have you know a uh b a c a or something like that right just any word um and then so what i'm saying by shortest path is that we're trying to go from the beginning to the end in the shortest number partition and each partition um and each partition you can think about as one cost in the thing um so you may have something like this for example uh where did where there exist an edge like this edge exists if and only if the word is a palindrome right uh the sub word so that's basically the idea and you can construct all this in n square time and then you can just do the dynamic programming and square time as well um i don't like a lie i'm not super confident that this is fast enough but we can you know it's a good starting point and i think to be honest if i was using like java or something like that i would actually be super confident but i am using python today so we'll see if uh delete code you know thing uh is fast enough the reason i say that is because for one test case four million is going to be fast enough because i have no constants but it depends on the number of test cases because python is a little bit slow on neat code and they use something called the sum of execution time meaning they take your total time of all the edge cases to see if it's time limited instead of per test case which is why um there's a lot of uncertainty because i don't know how many test cases there are anyway all right let's start by constructing the edges um okay so now let's start by uh okay how do we want to think about this so let's just say we have edges we have uh default list and here or default take of a list um here uh i think we kind of did it out a little bit uh on a drawing but you know let's say that we have a word like this our indexes means that this is a zero this is a one so we're actually using the spaces between the string as our nodes um or the empty spaces between the characters as our notes so sometimes i get questions about like how do you know if you use plus one or minus one or whatever for indexing well in this case as long as you kind of draw a clear picture you should be able to reason that out whether like for example in the last one then it should be um it should be end then right yeah good so yeah so that's an as an example um and yeah okay so then now let's do the odd uh length pattern drums first so yeah so now n is equal to the length of s and then and we start by for index uh yeah that's just to start in range of n so this is the starting index and then we have four offset and range of n something like that but not really um because we'll early terminate so here in the odd length we basically is trying to say let's say we have a string of uh let's take this one again say something a little bit lazy we're just essentially starting from the middle by one and then we expanded by uh three and then so forth right so that's basically the idea behind this uh or by another one so that now is length three and so forth um okay so so this is how we construct a pine drum is because if well uh a word of cat length one is always a boundarium and then the word of length three is a palindrome if they're equal to each other and then the next one and as so as soon as they're not equal to each other then it's no longer pendulum right so that's basically the idea um so now we can do edges of so let's say we're at start so let's say we're here at the start then the space is actually the start so we can so then the space that we're adding is behind between these two so that is equal to um actually we want to do the other way so that's pointing backwards so okay and you could do it either way but these are just my edges um yeah hopefully this makes sense basically what i'm saying is that there's a an edge pointing uh connecting start and start plus one you can make it bi-directional if you can make it bi-directional if you can make it bi-directional if you like i'm keeping it directional um so that i'm going in one direction with my dp you'll kind of see it later on uh hopefully yeah and then here okay so if s of star plus offset is you go to ester star minus offset um so let me run the opposite of this to break so basically if start plus offset is greater than or equal to n or star minus offset is less than zero or this thing this is you know if this is not true then we break otherwise then we can do another edges of again in this case let's see right if we move to offset by one we have oops how did this happen okay so let's say now we have move it to left by one and then we move it to the right by one right so then here this should be um plus one i want to say yeah uh dot append start minus offset okay so that's basically doing all the construction of the list and then now let's do the even length pattern drums next um and this is the same idea um but now we have to be a little bit clearer of okay now we just have to look at you know these things two at a time so let's be a little bit careful i may be a little bit sloppy on this one but here we actually start to offset immediately because and we can do a little quick copy and paste um do i have to double check this um okay so what does this offset mean or rather what does this start me now um okay start means okay i mean and you get to choose to be honest so i'm just trying to figure out which one is easier um let's say okay let's say we have this is that okay maybe yeah so now so guys so if offset is zero oh yeah i have to double check that this is not zero so whoops because we only did this here um okay if and here we can okay with zero if it's zero then it's you can it compares stone and star plus one so i think this is good so then here we do the same thing yeah okay let's just type it out otherwise we do this oh wait this could be wrong because now this is the character so we want to do the right of that uh the space to the right of that so that's why it's h of minus plus two sometimes i write this as plus one twice to be more clear on why um but yeah and you can kind of uh maybe i should have with an available you could look at this as the right and then this is the left and so forth um okay so then now we should be good with all the constructions of the edges so let's kind of give it a spin to kind of see whether we did it okay and uh let's just do a b a maybe a c a or something like that i don't know that's just a random example you and i sound like i know what i'm doing but yeah here so aft this means that after the one space it goes to zero two it goes to one and zero which is true three goes to r3 uh four it only goes to three because only b is a thing five it goes to four which is just one space and then two which is three spaces so i think we're good here um i think one thing that i did notice and i was kind of bad about is that you actually don't need a default dictionary you just need to you just need a list of uh length n plus one but you don't want to do that yeah no but i'm just going to leave it like this because i'm lazy but it's something that if you're at home you could fit you can actually optimize a bit but for now especially for me whenever i try to do it first i worry about correctness and then we can make optimizations afterwards um yeah okay now we're going to use dynamic programming and you can actually use to do the same thing but use breakfast search to um yeah i think you use by first search i'm going to use dynamic programming it doesn't at the end of the day um the reason why both of these work is because this is a dag or you can construct it as a dag um a direct uh yeah directed asynchronic graph um and because it is a dag um the shortest path in a dag it can be solved using dynamic programming and also by first search at least in an unrated graph you can use that for search um you can use other things you know or sorry breakfast search um but you can you know use daiso or something if it's not you know uh generals general shortest path things um so yeah so now that we have these two things uh now we have all the edges and i am wearing slow and deliberate but now we have edges now it's just dynamic programming so yeah so i should say best is you go to um let's say infinity times n infinity is just some big number fine uh i'll do this because people keep on telling me to um even though i feel like every time i use it i mess up somehow so yeah so okay and then we have to set best of zero is equal to zero um because this is basically the space before the one before the string and then now we just go through it um yeah and then this is i think i plus one if we want to be i guess it doesn't yeah just to be consistent um with the spacing because we're now dynamic programming on the spaces so we there what the spaces go from zero to n meaning that there's n plus one spaces uh but yeah uh okay so now we want to go through the edges so the previous edge and edges of index um yeah so this is you go to best of the previous plus one or well min of this and that's basically it is going to be n square like i said so i don't know if this is hopefully this is going to be good enough but uh oh yeah hmm i do have a index of whoops i knew that i said m plus one and then i typed it incorrectly i knew that the entire way of course i mean you don't have to believe me it's fine i'm just telling myself uh okay so i think i'm off by one because i miss um because we're looking for the minimum number of cuts not the number of words and the number of words relate to minimum number of cuts is just that the number of words is just the number of cuts minus one right oh sorry the number of words is the number of cuts plus one so we can uh subtract one from here i think that should be good because what we actually calculate is the number of words not the number of cuts um but i think the number of words is more intuitive because otherwise you have weird ad cases maybe so yeah so this looks okay uh do we have random bigger cases i don't know let me just bang on the keyboard a little bit so this is going to be like not that good because i don't think that much that many um that many whatevers but okay it looks good enough for me to give it a submit so let's give it a summary the only thing i worry about is tle and i know that uh how to generate the 2000 n case but like i said at the end of the day whether this gets accepted is determined by the number of test cases and that is something that i cannot test for so that's why i yolo'd a little bit because i knew that 2000 square was going to be fast enough but it's in one test case but it's about the sum of the test cases at least in terms of leak code um okay so what is the complexity i think we already talked about this but yeah but it's going to be adverse n square how does an n square well the worst case is going to be if it's all the same character at least the way that i did it you could have some shortcuts there sure but why is this because in this case the um because you can imagine huh oh right that's right you can imagine that in this case there's you could draw an edge um like from every point to every other point before that and because of that you can say that on the first space there's one edge and the second space there's two edge on the third space there's three edge dot so you get one plus two plus three plus four plus dot to n or n plus one i don't know is equal to n squared effect or o of n squared i know that it's not at exactly n squared it's again square over two roughly speaking i'm hand waving a little bit so excuse me but yeah so it's gonna be n squared number of edges and because the number of edges are n squared um this is going to the shortest path on that is n squared and yeah um and for example because for here for every index you can have f at most n edges uh so therefore this is an n squared loops and this is n squared time um and as a result because they're n square edges and we do store each edge it's going to be n squared space as well um you can actually maybe do a little bit smarter but that's all i have for today let me know what you think is shortest path dynamic programming how did you do it uh let me know what you think stay good have a great weekend everybody you know welcome larry back stay good stay healthy take your mental health i'll see you later bye
|
Palindrome Partitioning II
|
palindrome-partitioning-ii
|
Given a string `s`, partition `s` such that every substring of the partition is a palindrome.
Return _the **minimum** cuts needed for a palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab "
**Output:** 1
**Explanation:** The palindrome partitioning \[ "aa ", "b "\] could be produced using 1 cut.
**Example 2:**
**Input:** s = "a "
**Output:** 0
**Example 3:**
**Input:** s = "ab "
**Output:** 1
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters only.
| null |
String,Dynamic Programming
|
Hard
|
131,1871
|
883 |
welcome to about the training difficult solution if you want the best knocking of your experience in North America feel free to check us out and above the training door org so we provide the most real mock interviews from all the top interviewers from all these top companies so today we are going to talk about this problem it's supposed to be an easy one it's called a projection area of 3d shapes this is just I randomly pick up this one and then this problem is so bad described that it tooks me like it took me really like 15 minutes to understand what it means it's really the kind of interview question that I really hate but anyways so the problem is so it's a like all my n times and greed so it means every time it will be a square so later you will figured out why what the input means so we placed some like one by one cubes on this axis so it's like this three-dimensional graph right like this three-dimensional graph right like this three-dimensional graph right and then each value V equals two grid IJ represented tower V cubes placed on top of a grid cell IJ so what that essentially means is if you see an input like this so that just means that's a three by three matrix two dimensional arrays that's it so essentially you can say okay I have great like one what if it depends on how you wanna call which one is a row which ones column normally what I do is so this is just row and then here's column like this is a column 0 column 1 column 2 and then this is a row elected to it like a row one that's right Rosie Row 1 and Row 2 something like that so it basically the 1 that means element is 0 and then so it's basically asking you to do a 3 view like projections so if you're not familiar what this projection means this is like if you are I called it like a ton view it's likely from top you look down it looks like this and I called like a direct view so normally people let's say you could your viewpoint here so this is direct view and then it would basically result in this but this is the other way around so he was like looking through from here to here and then you see this view and then the other is the side view video see from X to Z like X Z and they okay this is the area and this area so the question is to find all the areas from this review so essentially this is called the mountain view projection right so if you're not familiar with that easily in the graphical graph engineering graphical graphics so if you are if you ever go undergraduate study in China you hope you will learn this course called engineering graphics it's called the control Cuccia so you will know like the three view what are the three view means director view down view and then also side view and then the problem is now translating into okay well how do you capture the area so you just do this review separately so for the down view you directly look from top to down and then because it's a square so each one comes for what so it doesn't really matter what the value is so the value is basically the height right of each of the things so each of the q and so in this case for the tongue view all you need to do is so essentially this is a two-dimensional array and a this is a two-dimensional array and a this is a two-dimensional array and a further down we all need to do is counter the nonzero element so if the element is a zero then you don't come too bad for example I think they're having example rate yeah like this example so you can only count the dumb view counted it's like H because the middle one 0 so there's no element when you look at top from loop from top to down and then we will look at the director view so the direct review if you look at it this way this is the Y Z is what I mean by two actually it's literally in a two-dimensional array you literally in a two-dimensional array you literally in a two-dimensional array you will find the largest element of each row so each row the largest adamant and then because the shadow will cover each other so think about if you were here and then you look at it here and then this is row so for each row the largest element will be the height yes will be the height of this thing and then it is a side view to the side view sorry this is a column I think yeah so if you're here you look at this way the largest view of each column for this row and then for each row you want to look at the largest column and then the side view is from here to here is in this two dimensional array you want to find the largest element in each row so basically you go through each column and then you find the largest element in each row and use something together and then you basically put the total sum and then that's it so it's very simple three for loops but this problem I really I don't think you will get anything from the interview because it just takes so much time to understand the question and then the coding part is actually pretty easy so it doesn't really it's not a really good II give you a question so okay alright thanks a lot for watching
|
Projection Area of 3D Shapes
|
car-fleet
|
You are given an `n x n` `grid` where we place some `1 x 1 x 1` cubes that are axis-aligned with the `x`, `y`, and `z` axes.
Each value `v = grid[i][j]` represents a tower of `v` cubes placed on top of the cell `(i, j)`.
We view the projection of these cubes onto the `xy`, `yz`, and `zx` planes.
A **projection** is like a shadow, that maps our **3-dimensional** figure to a **2-dimensional** plane. We are viewing the "shadow " when looking at the cubes from the top, the front, and the side.
Return _the total area of all three projections_.
**Example 1:**
**Input:** grid = \[\[1,2\],\[3,4\]\]
**Output:** 17
**Explanation:** Here are the three projections ( "shadows ") of the shape made with each axis-aligned plane.
**Example 2:**
**Input:** grid = \[\[2\]\]
**Output:** 5
**Example 3:**
**Input:** grid = \[\[1,0\],\[0,2\]\]
**Output:** 8
**Constraints:**
* `n == grid.length == grid[i].length`
* `1 <= n <= 50`
* `0 <= grid[i][j] <= 50`
| null |
Array,Stack,Sorting,Monotonic Stack
|
Medium
|
1902,2317
|
1,609 |
hey everyone today we are going to solve theal equation even or3 okay so let me explain with this example so we have to check if even index level has integer value with strictly increasing order from left to right on the other hand we have to check if what index level has even integer value with decreasing order from left to right so we have to check like a level by level right like this so that's why I think U breast fast such is easier than death F suchar right so I'll show you two ways with like a breast such and death F suchar but uh since breast F search is easier than best F search first of all I'll show you a breast F sear solution okay next let's break down the condition so we have to separate even level and OD level and we know that this level is zero this level is one two three right so that's why simply if we can divide um level by two is zero so in that case this is a even Revel on the other hand if we cannot divide Revel by two is not zero so this is a auto level right very simple okay so let's see the condition when we are at even level so description said the values should be a integer with increasing order from left to right so we have two condition integer and increasing order so let's think about the false case that's because if we meet the false case we can immediately return false so false case should be node value and divide two equal Zer so that means this value no current node value is even right but we need a value right so that's why if um this formula is zero in that case we should return false immediately this is a one condition the other condition should be U check if increasing order or not right so in that case we have to know previous value right so that's why we keep the previous value so previous value exist and the previous value is greater than or equal current node value so if we meet this condition that should be decreasing order right but we want the increasing order in this case so that's why if we meet this condition we can immediately return false very easy right and let's think about when we are at O Level actually it's opposite of even level so that's why node value divide two equal one in that case we should return false so we want even integer value for autel but if we meet this condition so current value should be o integer right so that's why we should return false and uh another case is um so we want a strictly decreasing order from left to right so that's why um previous value exist and uh previous value is less than or equal current no current value so if meet this condition so that is a increasing order right but we want a decreasing order so that's why we should return false in this case yeah that is a main logic and other than that actually a typical breast search so I'll show you how to implement in the next section yeah so let's jump into the code okay so let's write the code so this is a bre first search solution so we use a Q and d q and first of all we append root node with Rebel so Q do append and V is a t and root and level Zer right and then y q so every time we start a new level so do you remember so we have to keep previous value right so that's why initialize PR equal no and then we use a one more for Lo for underscore in range and length of Q and uh take the most left data so node and level equal Q do op left and then let's implement this main logic so if um level divide two equal Z in that case this is a even lbel so in the even level um if node value divide two equal zero in that case we should return false and another case should be if PR value exist and PR value is greater than or equal to node bar in that case we should return false right so you can combine uh this condition but I separate these three condition uh to make you guys understand easy and then um another case should be if our level uh divide two equal one in the case if node baride 2 = baride 2 = baride 2 = 1 we should return false and another case should be if PR value exist and pre value is less than or equal node do value so in the case we should false right and then after that um we have to update uh pre value for next iteration so that's why pre equal um node. value and then check if current node has children so if node so we have to check from left to right so that's why we have to append left child at first then right child so uh Q do append and uh we need a node do left and a level right so next level should be current level plus one and let me copy this and change left to right and the level should be same level plus one and then after that so out of white Loop return uh true yeah so let me submit it yeah looks good and the time complexity and the space complexity should be order of n where N is a number of nodes in the tree yeah so I'll explain the solution with SP search okay so for this SP sear solution we can use some idea from breast such I think we can use this idea and this idea but we cannot use this idea why that's because in breast SE solution basically we move horizontally right so that's why we can keep previous value with simple variable but this is a depth F solution so we move up or down right that's why every time we move a Next Level so previous value should be changed right so how can we deal with this problem so my idea is to keep a previous value with array and first of all empty array and every time we reach new level so we in that case we append zero to previous array so first of all we start from root node right and check length of previous array is less than or equal to current Rebel so now they are same right in that case append zero to previous array so this zero will be a previous value and then in the end so we have one at level zero right so that's why uh in the end update um index zero with one and then move next so um check length of previous array is equal to level one right one so in that case I'll upend zero to previous um array so uh yeah this Z is also um previous value and then in the end so our index one will be update with 10 right and then move next so we find three and this is a new level so that's why append zero to previous variable I mean previous array and then in the end so index two should be three right and then move next so we reach level three so length of pre array should be three and level three so they are equal so that's why up and zero to PR aray and in the end um so previous value should be 12 right so now we have 1 10 32 so that's why so let's go back to three and move right so in the that case we find eight right so and we are at level three so um key of PR array should be reel so that's why PR and the key is three so that's why uh I mean index three so 0 one 2 three right so that's why we can access 12 and 12 versus um current value eight so I think level three we need a decreasing order right so that's why that's fine so that's why update um index three with current value eight so that uh eight will be a previous value when we reach six right and then at six uh so we are at level three so that's why again we can access like a p and three easy right so I don't explain everything but uh we do the same thing for all node and then uh if uh we Traverse all node successfully so in that case we should return true if not we should return false okay so let's WR a code first of all create a pre array and then return de for search and passing the root node and L is zero and let's create a def F search as a inner function so death F search and then let's say node and level so first of all this is a base case so if not node in the case return two and uh next so if length of a BRI is less than or equal level in the case we append zero to Bri array and then if level divide two equal Z in that case if node baride two equal Z or PR exist so PR level and PR level is greater than or equal node bar in the case we should return false and uh else if node baride two equal 1 or so PR exist and uh PR level is less than or equal node bar so in the case we should return false yeah this is also um you can combine the condition and then after that update pre and level equal node bar and then is U left b equal so move left so def for sear and node do left and the level should be so we go down so level plus one and then let me copy left side and uh change left to right and then right and level is same level plus one and then after that is left B it and is right B it we should return to true if not we should return false yeah so let me submit it yeah looks good and the time complexity and the space complexities are same as solution one order of n where N is a number of no in the tree yeah so that's all I have for you today so please support me with the action such as comment and hitting like button I'll see you in the next question
|
Even Odd Tree
|
find-all-the-lonely-nodes
|
A binary tree is named **Even-Odd** if it meets the following conditions:
* The root of the binary tree is at level index `0`, its children are at level index `1`, their children are at level index `2`, etc.
* For every **even-indexed** level, all nodes at the level have **odd** integer values in **strictly increasing** order (from left to right).
* For every **odd-indexed** level, all nodes at the level have **even** integer values in **strictly decreasing** order (from left to right).
Given the `root` of a binary tree, _return_ `true` _if the binary tree is **Even-Odd**, otherwise return_ `false`_._
**Example 1:**
**Input:** root = \[1,10,4,3,null,7,9,12,8,6,null,null,2\]
**Output:** true
**Explanation:** The node values on each level are:
Level 0: \[1\]
Level 1: \[10,4\]
Level 2: \[3,7,9\]
Level 3: \[12,8,6,2\]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
**Example 2:**
**Input:** root = \[5,4,2,3,3,7\]
**Output:** false
**Explanation:** The node values on each level are:
Level 0: \[5\]
Level 1: \[4,2\]
Level 2: \[3,3,7\]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
**Example 3:**
**Input:** root = \[5,9,1,3,5,7\]
**Output:** false
**Explanation:** Node values in the level 1 should be even integers.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 105]`.
* `1 <= Node.val <= 106`
|
Do a simple tree traversal, try to check if the current node is lonely or not. Node is lonely if at least one of the left/right pointers is null.
|
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
563,1005
|
116 |
hello everyone hope you all are doing well so i am back with another lit code daily challenge and it is lit code number 116 populating next right pointer in each node and it is a medial medium level question and i also feel the same so the question is you are given a perfect binary tree where all leaves are on the same level and every parent has two children the binary tree has the following definition of a not content value and left point the right corner and the next pointer populate each next pointer to the pointer to its next right point on next write note if there is no next right not the point the next pointer should be set to null initially all the next pointer are set to null so here they are given an example like one there is no right child for one so it is null two for two it is three and for three it is null then for four it is five for four five it is six for six it is seven and four seven there is no right side so it is not and this is the output okay so what are the constant the number of node in that tree is in range of 0 to 2 to the power 12 minus 1 and node value can go up to minus thousand to plus thousand there is a follow-up question you may there is a follow-up question you may there is a follow-up question you may all only use constant extra space the recursive approach is fine you may assume implicit stack space or does not count as extra space for the for this problem okay so you can solve it with extra space and without extra space so i am going to explain you both the uh case okay so this is the code for the extra space one where you can use an extra space so this is a bfs approach okay so it is a bfs approach oh what i have done here is i have taken in queue and i put the root element here okay so i initially a q only contain a root for this example uh there is only one value so i have put it there then i have taken out the size of the queue so the size value will be one so the size is also one okay and now i have i taken to point f from n2 now i iterate uh from zero to size minus one means uh zero two like here it is size is one so one minus one is zero so i is less than zero so the loop will not iterate so the motive here is to take size minus one is when the loop is over uh when the loop is over then there must be one element present in the queue okay so that we can perform this force i will explain it in the further explanation why we need uh this one okay so let's see for this condition q is empty so our current from i will write f and t is null and here also t is also null okay this loop will not execute so if not two means if two is null here that t is here the two is null okay so we will take out the last element so we will take out this element okay and i will put it in two so i just what i just do is i just remove this element and put it here so one is here okay and this is empty now and what i will do and we pop it also in the this there and then i will do i just uh take out the left and right if it is exist and put it into the queue here the left and right child are two comma two and three so i will put it two and three okay so now the while loop again get iterated and the and now the queue size is two and uh okay so what it will do the loop execute for the for one time okay because two minus one is one and the loop will execute for zero only so now the four the two will pop out and we'll put we will put it here and this will pop out and then uh we just simply take the front element so the queue saw the front element we take and put it into the two section and the three we will not pop out as you in you can say that i will i have not written any pop condition after executing this q dot friend okay we just simply put the left side and right side for this element which we have pop out okay so we have pop out two so we'll push that uh element but four and five okay so for we just simply push four and five here okay so that so this means that the you can see that from to from next equals to two so the two next is four so this will point like this okay and then initially this will like this okay this will point to this and after this i will i have checked if 2 is null if it is null then we just simply uh perform q dot front and pop out and take the front element but here you can see that the two is not null so this condition will not get execute okay this one will not get executed so now what we'll do we just simply push all the element of which is on the left of this two element left and right okay for the like it is six and it is seven okay and we just simply pop out now okay so i think you have noticed that we always pop the last element outside this loop or this is because like uh okay for though you can see that for this example means for this well null okay for this example the size is four and we again initialize this for from n2 to null so let me put here and for null okay so what we are always to doing now we just simply uh pop out the last element outside the loop so what is the profit of this like if i pop out this element here only so there is a risk that i execute this form of from part and i also execute the two part but when i puff after performing this for from part okay this from part there is no element left okay when we perform this from part on the last element because this already get uh this 456 already get popped out so we have to check here again that if the queue is not empty or not so again it will uh we can pop four and in place of null we can perform we can put four and we popped out this four okay then we just uh take the front element now the front element is fine just simply put it here so the four will point to five now okay as i have right here that from next is equals to two uh after we perform this loop will again uh iterate and now we just now the front is of this one and the two is six and we just pop the front okay so now this will point this now again it is six and it is seven okay so we'll pop this and now this is pointing to this okay so you can see that all the link from left to right is okay so now only this last element uh is there so we just popped out from the loop and if two is null but it is here it is not null so we do not perform anything okay we just simply pop this q again now the while loop break because the queue is empty okay and we just simply and it will indicate to null and we just simply return the root so it will form this okay so here we have we are the time complexity is often and the space is also of n uh but here um there is again another approach that we can do for uh in of one space only okay so this is the second approach and it is a dfs one and its space complexity is of one okay so as there is a follow-up question okay so as there is a follow-up question okay so as there is a follow-up question they asked to do it in often space so this is an uh recursive approach here what i have done is like you can see that if not root then return it is obvious thing okay now uh i have checked if the root there is a no root left for this example there is a roots left okay so we know that if there is a root left then we have to simply point it to the that roots right element okay so i have done the same thing the root left next will point to the root right one okay so this is the root right one okay then i have check uh take the right part like if there is root right and if the if it is and if there is root next what this root next mean i will explain you in this level when we explore these two level because it is not possible to explain it here so for now we just simply ignore it or i can say that this will uh initially uh pointing to null so it will remain null okay and we just call the left and right now again i check if there is an root left yes there is root left and is there any root right yes it is root right so we can point it there okay if there is no root light like if there is no phi okay then still this code will execute and this four will point to null okay because if there is nothing there is there will be null so this line can execute and the four can point to null okay but in our case there is a five so let point to the five let it point to the five okay now i check for the right side also for these twos right okay so it is yes it is exist and the root next is exist or not yes it is also exist okay so what is this now if there is no or there is no right part for this one so the root right is null okay so we need not to perform this part okay because if we try to perform this now then what will happen to root right is there okay but if i do not check this condition then what will it get like you know then it will try to access the nulls next okay because the root next is null if there is no this uh this part so it will try to uh try to get the nulls left and it is not possible then it will create a segmentation fault so it is necessary to check the root next part okay so in our case there is a root next okay so we just simply go into it and we just point root right next to roots next left okay root next left okay so it will point to this and again we call for left and right so it will go there but you can see it's left and right is not there so it will simply return and here also it is left and right is not there so it is simply written then again it will return okay then we come here and we can see that it is already pointing to the next and the and now it's left and the right will again perform the same thing we check if it is uh roots left is there okay it is there so we just simply put it to the root right and i'm gonna check for the right and now we can we have to check if it uh if this is next means it's parent next like this three is next is there or not the three next is not there so this condition will get false and we did not perform this it means this will point to null as initially elements next pointer will point to now then again we can call left and right and again return the root so i provide you link for both my solution and the question also so you can check it out there and for now i am going to run this code only open space to show you okay this is the same code and let me submit it okay it get accepted so see you tomorrow goodbye take care bye
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
150 |
hello guys and welcome back to lead Logics this is the evaluate reverse polish notation problem from lead code this is a lead code medium and the number for this is 150 so in this problem we are having an array of strings tokens that collectively represent a reverse polished notation of a expression so we have an arithmetic expression in its reverse polished notation and we have to evaluate the expression and return an integer that is the value of the expression that is the solution of the expression so and we have some points that there are only four operators that is plus minus multiplication and divide and each operant may be integer or another expression okay division between two integers truncates toward zero there will be no division by zero it is confirmed input represent a valid arithmetic so all the arithmetic expressions are valid and the answer and all the intermediate calculation can be represented in a 32bit integer so we have these notes which uh going to help in solving the problem so let's see uh what the problem is so we have a token 2 1 + 3 and star so uh if you know token 2 1 + 3 and star so uh if you know token 2 1 + 3 and star so uh if you know the nature of the reverse polish notation so you might be knowing it is also known as the postfix notation so in this you might be knowing that whenever we encounter operator in the reverse polish notation what we do is that we apply the operator to the last two operant so suppose we get a plus here so we'll take the last two oper operant that is 2 and 1 and we'll apply this operator plus so 2 + 1 Become apply this operator plus so 2 + 1 Become apply this operator plus so 2 + 1 Become Three so this entirely becomes three okay now we have again three and next we have an operator star that is multiplication so this was evaluated to be three then we have again three and we encounter operator so we'll apply this operation on the previous two operants so 3 into 3 becomes the answer so the answer is N9 so this is how we are going to solve the problem this is the nature of the uh reverse polish notation and to solve this question a stack would be the perfect data structure for evaluation as it allows to keep the track of operant as they appear and apply uh by we can simply pop and apply and then push again the results so how we are going to do that first of all let's see for this example only uh we take this example uh we take an uh stack uh we take a stack or a list we can take that will act as a stack then you iterate through the tokens uh suppose you have a token so if we have a token that is a number you don't have to do anything you simply push it to the stack so first token is two which is a number so we simply push it into the stack then next number is one uh next token is one that is also a number no need to think anything just simply push it onto the stack so the stack becomes two and one now third token is an operator now whenever we have an operator we have to pop the last two operants and then apply the operator on the first operant and the second operant and then push again the result so we simply pop the first U the second operant first and then the first operant so we have the two as the first operant and one as the second operant we apply the operation which is 2 + 1 equal to 3 the operation which is 2 + 1 equal to 3 the operation which is 2 + 1 equal to 3 and this result will be posted onto the stack so now the stack becomes only three now the fourth token is three which comes from here so this is a number simply push it onto the stack so the Stag becomes three and three next the fifth op token is star so this means we have to apply multiplication ation so we pop the second operant and the first operant and multiply and then store it in the result so three is popped and then three again so we simply multiply 3 cross 3 answer is n we simply push it onto the stack so yes this is the answer because we have do not have the any more operations we can return the answer St that is top of the stack and this is how we are going to solve the question so let's come to the coding section but before that do like the video share it with your friends and subscribe to the channel let me just clear the solution first because I want to tell you while coding so first step is to initialize the stack so we can initialize in the tokens. length size so yes and we can create a variable stack top equal to 0 now we have to iterate through the tokens so we'll use a for Loop meanwhile if you have not subscribed to the channel or like the video do like the video and also share it with your friends and classmates so we'll extract one character from the string s now s is the token now if uh this top uh I mean the character everything will depend upon this so if this character equal to Plus then what we'll do we'll take int b equal to stack of minus stop and then in a equal to stack minus stop so this is the we are trying to pop The Operators operant so in this way we can get the operant so we have to repeat this so we can simply copy this first and the next stack do top Plus+ will top Plus+ will top Plus+ will be a + b so we can copy this as a be a + b so we can copy this as a be a + b so we can copy this as a whole copy else if c equal to minus simply we do minus here else if this is multiplication we do multiplication L if it is division we do division and store it onto the stack otherwise it would be a number it would definitely be a number so we simply push it onto the TX stack toop Plus+ equal to it onto the TX stack toop Plus+ equal to it onto the TX stack toop Plus+ equal to integer it is a string so we have to convert it into integer. pass in and uh here will be the string s and at the end we can simply return the stack top uh not top it will be zero actually the top will be zero after this full iteration so there's been some error let's see I think there has been some error let me just recheck the code you can also check the code from here and yes there has been a condition missing here so we need to check one more condition that is while checking division you have to make sure that there are two elements and not one so s do length should not be equal to should uh should be equal to at least one to perform this operation and we can copy this put a end in between here SCH now let's see so yeah it runs fine so the time complexity for this solution is O of N and the space complexity is O of n also you can see it passes with a good run time you can also check the C++ uh Python and JavaScript Solution by C++ uh Python and JavaScript Solution by C++ uh Python and JavaScript Solution by going into the solutions panel and check this solution this is my solution here you can see the intuition the approach the complexity the code Java code C++ python JavaScript and yes Java code C++ python JavaScript and yes Java code C++ python JavaScript and yes do remember me to upad so I hope you like the video and I'm sorry for that error in between the code so I hope you do understood the logic please do like the video share it with your friends and subscribe to the channel if you're new to the channel thank you for watching the video have a nice day
|
Evaluate Reverse Polish Notation
|
evaluate-reverse-polish-notation
|
You are given an array of strings `tokens` that represents an arithmetic expression in a [Reverse Polish Notation](http://en.wikipedia.org/wiki/Reverse_Polish_notation).
Evaluate the expression. Return _an integer that represents the value of the expression_.
**Note** that:
* The valid operators are `'+'`, `'-'`, `'*'`, and `'/'`.
* Each operand may be an integer or another expression.
* The division between two integers always **truncates toward zero**.
* There will not be any division by zero.
* The input represents a valid arithmetic expression in a reverse polish notation.
* The answer and all the intermediate calculations can be represented in a **32-bit** integer.
**Example 1:**
**Input:** tokens = \[ "2 ", "1 ", "+ ", "3 ", "\* "\]
**Output:** 9
**Explanation:** ((2 + 1) \* 3) = 9
**Example 2:**
**Input:** tokens = \[ "4 ", "13 ", "5 ", "/ ", "+ "\]
**Output:** 6
**Explanation:** (4 + (13 / 5)) = 6
**Example 3:**
**Input:** tokens = \[ "10 ", "6 ", "9 ", "3 ", "+ ", "-11 ", "\* ", "/ ", "\* ", "17 ", "+ ", "5 ", "+ "\]
**Output:** 22
**Explanation:** ((10 \* (6 / ((9 + 3) \* -11))) + 17) + 5
= ((10 \* (6 / (12 \* -11))) + 17) + 5
= ((10 \* (6 / -132)) + 17) + 5
= ((10 \* 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
**Constraints:**
* `1 <= tokens.length <= 104`
* `tokens[i]` is either an operator: `"+ "`, `"- "`, `"* "`, or `"/ "`, or an integer in the range `[-200, 200]`.
| null |
Array,Math,Stack
|
Medium
|
224,282
|
430 |
hey you out of there let's talk about today's liquid in China question it's called flatten a multi-level called flatten a multi-level called flatten a multi-level doubly-linked list so we have this thing doubly-linked list so we have this thing doubly-linked list so we have this thing that's called a multi-level doubly that's called a multi-level doubly that's called a multi-level doubly linked list what makes this multi-level contrasted what makes this multi-level contrasted what makes this multi-level contrasted to the textbook doubly linked list is that in addition to the next and previous pointers the node inside this multi-level doubly linked list that can multi-level doubly linked list that can multi-level doubly linked list that can also have a child pointer which can be either no or you can point them to a head node of another multi-level doubly head node of another multi-level doubly head node of another multi-level doubly linked list so this is looking at this picture here it's a realization of this multi-level doubly linked list if you multi-level doubly linked list if you multi-level doubly linked list if you ignore all those child the pointer fields then you would just be three different doubly linked lists isolated by themselves but once you introduce this a child pointer you become a whole thing and they have this kind of a nested relationship the double linked lists the starter with 1007 is nested within the first doubly linked list so you have this kind of a multi-level nested structure there the multi-level nested structure there the multi-level nested structure there the question is asking us to flatten the list so that all the nodes appearing a single level doubly linked list so the one obvious question that we want to ask is to what's gonna be the output when we flatten it so we definitely have a lot of choice we can explore the first level first and then we put all the second level to the back of that or it could be in this case actually whenever we visit a node that has both directions you can either go to next I'll go to the children we actually visit to the children first so the output will look like this so 1 2 3 because 3 has bows the next and also the children in the final output in the flatten the result go to the children first so yeah so that's a the order and we can see here once we went to the children route connecting three with seven we keep going visit eight have the same choice we have to visit the children first we visit eleven twelve and go back to nine ten once we finished all the children you know all the doubly-linked lists are know all the doubly-linked lists are know all the doubly-linked lists are from this children pointer we go back to the next visit four five or six so as you can see it's a TFS surge kind of a pattern we keep going whenever we have two choices whether either next or child we go to the child route after we finish all those we go back to the next and what are we going to do is basically connecting the previous node and the current node when we do this DFS search and to solve this iterative living which is going to use a stack to keep track of the node and use two pointers one is the previous node the other one is the current node that we are looking at and yeah and basically just rewiring those next and previous pointer yeah so that's pretty much it looking at this example you can clearly see that you want to do DFS search you want to go as deep as possible us deep into the multi-level as possible us deep into the multi-level as possible us deep into the multi-level as possible before you go back to the previous level finishing the work there and go back to the top level so that's the that's why this order has 1 2 3 7 8 11 12 and then go back to 9 10 and then go back to the top level 4 5 6 yeah so that's pretty much it let's solve this number of nodes will not exceed a thousand so it doesn't it does tell us whether it can be empty then we're just gonna do a DFS search starting with the stack and obviously the initial the only node inside the stack in the beginning will be just the head node so we will need a sentinel node to be in our initial previous node so let me actually do a little bit Animus animation so this is the example copied over here and we're going to start with initialized a sentinel node previous here and then just gonna do this DFS search with a stop initially we pop this node one out which is the head node so the traverse will become damn node and then what we're gonna do is to establish the previous and traverse kind of a back and forth relationship once we do that we can look at the next end child because this case we only have an X so we push the next node onto the stack at that time we can advance the previous over to this node and then after that we go to the next iteration will pop the top node out of the stack and moved the traversal node onto to there and then we're gonna do the same thing establish the next and previous connection between these two node previous and traverse after we've done that we look at do we have a next do we have a child we do have a next so we push down next onto the stack once we update to the stack we move the previous to the current to traverse and then go to the next iteration in the next iteration we're going to move the traverse onto the top node of the stack and pop it off and then establish the two bi-directional linkage between these two bi-directional linkage between these two bi-directional linkage between these two nodes after we do the rewire we - do we have a next do you have a child - do we have a next do you have a child - do we have a next do you have a child yes we do have a next we push it onto the stack first but we also have a child so we push the child onto the stack after we push the next so that once we move the previous over and enter the next iteration we're gonna pop seven out and then we're going to move the traverse over there so we start to explore the nested doubly-linked list explore the nested doubly-linked list explore the nested doubly-linked list before we do actually go back to resume on the very first level once we do that we establish the bi-directional we establish the bi-directional we establish the bi-directional connections as usual and then move previous over here and then push the next onto the stack and then enter the next generation in the next iteration we pretty much just rinse I repeat all this process so yeah that's a little bit animation about how to solve this it's pretty standard DFS search so we're just going to do a while loop pop this node out and then we establish the relationship between previous and Traverse once we've done that we look for the two possibilities the next and child we push the next on the stack first before we push the child onto the stack so that way because we popped the stuff that's last again we're going to explore the children before we explore the next so if we do have the children we've pushed on over there and after we've done that we advance previous to be the current to traverse so to initialize this previous node and also be able to plunge back to the starting node we're just going to do a sentinel dummy node here which is initialized with the value B I don't care the value the previous can be none the next is the header and the child node is I don't care about that it does not have a child so in the end I will just return dummy done next which is pointing to the head node and I will also make sure that I set the previous node for the original head node to be a node pointer so that's them about it let me see if it works my result is one two three seven eight eleven twelve nine ten four five six it's not a valid to doubly-linked list why is that why they seem to be the same thing oh I see I have to clear the child pointer okay that makes sense because in the picture here shows that the child note of those three is cleared that's a null pointer okay so let's see yeah this time it works all right so that's a that's this question today that's not the FS search and you just have the previous node and the current Traverse note just advancing them make sure the order when you're advancing them of the correct and whenever you move to the next position you establish this previous and next relationship bi-directional links yeah so that's it bi-directional links yeah so that's it bi-directional links yeah so that's it for today the time complexity is order of a.m. but because we visit every node of a.m. but because we visit every node of a.m. but because we visit every node exactly once so that's this
|
Flatten a Multilevel Doubly Linked List
|
flatten-a-multilevel-doubly-linked-list
|
You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional **child pointer**. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a **multilevel data structure** as shown in the example below.
Given the `head` of the first level of the list, **flatten** the list so that all the nodes appear in a single-level, doubly linked list. Let `curr` be a node with a child list. The nodes in the child list should appear **after** `curr` and **before** `curr.next` in the flattened list.
Return _the_ `head` _of the flattened list. The nodes in the list must have **all** of their child pointers set to_ `null`.
**Example 1:**
**Input:** head = \[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
**Output:** \[1,2,3,7,8,11,12,9,10,4,5,6\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 2:**
**Input:** head = \[1,2,null,3\]
**Output:** \[1,3,2\]
**Explanation:** The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Explanation:** There could be empty list in the input.
**Constraints:**
* The number of Nodes will not exceed `1000`.
* `1 <= Node.val <= 105`
**How the multilevel linked list is represented in test cases:**
We use the multilevel linked list from **Example 1** above:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
The serialization of each level is as follows:
\[1,2,3,4,5,6,null\]
\[7,8,9,10,null\]
\[11,12,null\]
To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:
\[1, 2, 3, 4, 5, 6, null\]
|
\[null, null, 7, 8, 9, 10, null\]
|
\[ null, 11, 12, null\]
Merging the serialization of each level and removing trailing nulls we obtain:
\[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12\]
| null | null |
Medium
| null |
1,510 |
hello everyone welcome back to decoding on this channel we discussed problems which are frequently asking programming interviews and today we are going to solve a problem from lead code VT contest the name of the problem is stone came for so let us see what the problem statement is Alice and Bob they take turn playing a game with LS starting first initially there are n stones in a pile on each player's turn the player makes a move consisting of removing any non-zero square number of stones in the non-zero square number of stones in the non-zero square number of stones in the pile also if a player cannot make a move he / also if a player cannot make a move he / also if a player cannot make a move he / she loses the game we are given a positive integer n we have to return true if and only if Alice wins the game otherwise we have to return false and both of these players are playing optimally so in the first example n is given to be 1 now Alice can remove one stone winning the game because Bob doesn't have any stones left to make any move when n is given to be 2 then Alice can only remove one stone and after that Bob will remove one stone and no stone will be left in the pile hence Alice is going to lose the game when n is given for and is already a perfect number so LS will take all the 4 stones and 0 stones will be left so when the number of the stones are 0 that means that the particular player who is getting this and s 0 is going to lose the game so let us try to simulate one example and try to create the tree using this so let us say the example that we have is 17 now this will be given to LS is having this number s 17 what all are the moves that Alice can make at this particular point so Alice can choose 1 because 1 is a perfect square then 4 then 9 then 16 so these are all the possibilities that Ellis can have so when Ellis is choosing one the number of the stones that will be left are 16 in this case it is 13 in this case it is 8 and here it is 1 now these it was Ellis making the move now it is Bob so let us see when someone is getting 16 the possibilities are to choose one from this to choose 4 again then 9 okay these n n16 also in case 13 we have the possibilities as 1 4 9 so these are all the possibilities here so in this case the stones left in the pile will be 15 haled is going to be 12 here it will be 7 and in this case it is going to be 0 so when someone is getting 0 as the number of these stones he is going to lose the game so in this case when the next player loses the game that means that we are going to win the game so this is the player this pair is going to win the game and if this play is going to win the game that means that the player who played the game just prior to this is going to lose the game so that is what we have to think and when Alice is getting 17 as the number of these stones in the pile she should make such a move that Bob loses the game so she have all the possibilities and among these possibilities she is going to choose that possibility in which the next player that is Bob will lose the game so we see that when Alice's choosing one Bob is going to add 16 stones on the pile and ultimately Bob will win the game because he will use all these 16 and he will pass on 0 2 LS and then LS will lose the game so that means Bob is going to win the game that means that we should not make this particular choice of choosing 1 again when we choose a 4 over here then we will be getting then Bob is going to get 13 and Bob will have so many choices to make among these choices let us say the choices are he's going to past 12 then here he's going to past 9 and in this case he is going to pass four when he passes 9 he will lose the game when he passes for he will lose the game because a perfect square when someone is getting a perfect square he will win the game when he's passing 12 so in this case Alice can have the choices as one of choosing 1 then choosing 4 then 9 so in case of 12 she's going to pass on 11 8 and 3 to Bob now using these 11 Bob is going to pass 10 then 11 minus 4 is 7 and 11 minus 9 is 2 so this way the recursion will move on and ultimately anyone who is getting a perfect square is going to win the game so we see that there are so much of repetition in this 16 we see 16 is going to repeat then we see 7 is going to repeat over here as well we will be having 7 so there is so much of repetition so instead of making all these branches we should try to store whichever branch we have already calculated so that we will do using memoization now once we are clear with this concept we can try implementing this so what we discussed over here is if someone is getting n and if n is smaller than equals to 0 that particular player is going to lose the game else we have so many choices to make among these choices the number that we are choosing should be a perfect square so starting from the 1 till the point this I square is smaller than equals to the given number n I plus so among these choices we should go with our choice which is going to defeat the next player so if the help of n minus I into I so this is the amount of stone that we are passing to the next player this is actually the next player making the move and if this is equals to 0 that means if choosing if passing these many stones to the next player defeats the next player we are going to go with this choice so we will return 1 in this case because we are going to think the game ultimately if even after choosing all the even after going through all the choices that we have we are not able to win the game that means that we have no option but to lose the game so this is what we have to do and then we have to simply pass on the total number of stones to LS I think this should work it is giving this correct answer but if we try to submit this solution I don't think that it is going to pass because ya see it is giving us time limit exceeded that means we are recomputing a lot of work here we should try to store that so we will have a DP array I only show you how there are so many repetitions so we see that we are getting 8 here then it again over here so this tree I have drawn just to represent just to demonstrate you that there is so much of repetition in this so instead of computing everything again and again we should try to store it in a dynamic programming manner and we are going to min set this with minus 1 if it is already computed that means that if the value which is present at this index is not equals to minus 1 we have already computed that and then we will simply return it in case we haven't computed that earlier we will store it here also so now it should work it got accepted now let us talk about the space and the time complexity of this particular solution we see that the space complexity that we are using is Big O and because in the constraints n is given to be 10 raised to the power 5 that is what I have used here talking about the time complexity let us see so we have n loop running so that is for the recursion and inside recursion we have another for loop that is from I is equals to 1 to I into I is smaller than equals to n so this loop is under root n loop so the time complexity will become n raised to the power 3 by 2 or n under root n so this is the time complexity that we have it will simply pass the constraints that are given to us so this is it for the solution if you liked the video please press the subscribe button and please leave the comment as to what suggestions would you like to give me for my future videos thank you
|
Stone Game IV
|
find-lucky-integer-in-an-array
|
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are `n` stones in a pile. On each player's turn, that player makes a _move_ consisting of removing **any** non-zero **square number** of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer `n`, return `true` if and only if Alice wins the game otherwise return `false`, assuming both players play optimally.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** Alice can remove 1 stone winning the game because Bob doesn't have any moves.
**Example 2:**
**Input:** n = 2
**Output:** false
**Explanation:** Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
**Example 3:**
**Input:** n = 4
**Output:** true
**Explanation:** n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
**Constraints:**
* `1 <= n <= 105`
|
Count the frequency of each integer in the array. Get all lucky numbers and return the largest of them.
|
Array,Hash Table,Counting
|
Easy
| null |
350 |
Ajay Ko that welcome back to day today they are going to solid problem 30 intersection of tourists and the see tomorrow office problem 350 intersection of tourists to solve this problem now they are going to discuss and solve into a session before I started liking details into this Problem He Want To Mention The Type Of Create List Solution Videos And Java J2ee Interview Related Videos So You Will Find Your Love To Play List On My YouTube Channel Like It Sonu Shades Of Computer Science Staff Like You Knower For Your Research Please Attention Deficits Dynamic Programming So please check the play list listen subscribe The Channel Subscription really help solve Please subscribe to the Channel Honor 9 light started discussing problems one by one so let's one is the giver 2ND year name Sonam Tourist Darkness of the intersection Delhi maintenance result Strong Unique And Tumors Return You May Return Result In Your Order Shoulder Matter Birthday Elements More Unique Example Clear *Addition This More Unique Example Clear *Addition This More Unique Example Clear *Addition This Is The First And Second Patients And There Support To Return The Common Element Intersection Of Admission Form Elements Such As You Can See A Grade 2nd Bluetooth of commerce in the recent but as you can see here VR only supports to return unique number price boiled twister one to front units do to you only alternative which caused unique song how to solve this problem solve your problems through the implementation of This will create alarm set up in tears from this edit software reading of terror and creating a set of interior and you will read second sharing and quality set to and merging half limits in to send to solve what they are doing there solutions hui hai she se 2182 Software Will Have Elements Like One Hand To Here And Schedule Will Have Element To Write Only One Element With A Renunciation To Sonth Yudh Creator The Earliest Here Frontiers And Will Get There Through The Two Main Elements And Wherever You Will Find Correspondingly Match Insat-2e Illegal Correspondingly Match Insat-2e Illegal Correspondingly Match Insat-2e Illegal element in to our list and the end villagers convert date list * ad villagers convert date list * ad villagers convert date list * ad frontiers using arduino this is the method in java list screen dot print grnw20 loot convert suddenly stopped in tears into an unfaithful continuous and vijayshree internet solid state forward 100 grams wear going to Unitech gave examples better give voice to example sirvi * example sirvi * example sirvi * she said yet vikrant and mix and is giving correct answers that you can also see two also a grade result hair and north cleared coffee normal different matter 100 solution is correct 340 submit this code a Solution Got Accepted As This Way You Can Solve Intersection Of Tourists In Java Using Set Has Shrinked Of This Problem Share The Different Share It From Problem Difference Element In Result Exam Time In Both Are You May Return Result In Order To Which Means That You Have one element appear multiple times for example Wash Share and Subscribe To return to three years Middleton Basically sure elements of British universities and it's OK to duplicate elements To listen to this example for example The one's Ruby just like they should have been going to solve this problem with The Help Of Is Time Pride Busy Us App And Will Define Has Map Contest Celebrities And Comments Must Interior Is The Number To You Have Any Other Interior Is This Is The Frequency Of The Number Into It Is The Frequency Solid Waste Create A Guide Training Appear And Will Just Go Through This Example Dhoop So As You Can See Wherever They Find Any Number Of Villages For Entry Into His Mouth With Frequency He Cleared 504 506 420 Hui Internal Entry Care For Them One Right Its Frequency This Day Norms Will Increments Frequency From One to Vikas Nine is Coming to Times Now Sunna and Gyanpeeth's Egg Superhit Loot Enter Atavan Vikas Frequency of S8 150 Grams Fennel Will Again Find Element for Already Existing Villages in Treatment His Wits Frequency Here Right 34 Hai Samay Puge and What We Will Do It is a will be getting through the second whole and will create one list right only place with great and you will want to this wherever you find any element hair oil check-in and have time to update element hair oil check-in and have time to update element hair oil check-in and have time to update this elements present such as you can see floor for It is present in power house map so we will improve internet earliest fried and one for entry into here going to reduce its frequency of 21000 we have already used one norms and norms will enter nine to our list and they will reduce its frequency of form 2018 5.5 for 2018 Is Not Dare Show Hui Will 2018 5.5 for 2018 Is Not Dare Show Hui Will 2018 5.5 for 2018 Is Not Dare Show Hui Will Not Do Anything Like That To You Don't Have Any Corrupt Political Mess Will Not Do So Will Convert 49 List Into The River For Its Poise Faces Day To You Will Return Basically 133 Or Men We're Going To Have They Solve This Problem Should Meet Like Explain The Java Solution Sutra Hai Samay Appear In Danger Comments A Koi Share Trading Through The Number One And They Are Creating Apps Loot Hui Just Create This Have Samay Explain Clear So This Is The Map Hui Created Fear And Hui Creator Link Clearly Stated Of Interior Name They Are Going To Interest Crying Norms To Edit And You Will Keep Checking In Power Center In Our Time Pipe The Number Kiss Present Her With Number Is President Dher Din Hui Set The Number Interver List Will Get The Prevention From The Map And Difficult See Welcomes One Menu Sachin Hui All Have Used Rather Number Here With Phone Frequency Should Be Rich Nothing To Keep In The Map Subah To Remove The Number Basically After Its Frequency Vikram Sirohiwal Remove It Is Pages Greater Than One Mins YOU HAVE SHOWN FREQUENCY LEFT DAY WILL JUST THE SAME NUMBER WITH ONE REDUCE FREQUENCY WILL REDUCE IT'S PREVENTIVE WE HAVE ONLY ONE WHO HAVE Told YOU THAT YOU FROM 2ND YEAR BOY'S HAIR CUTTING LIST SUBSCRIBE BUTTON LIST IN 2ND YEAR BOY DISTANCED JANU002 SECOND CONVERT LIST AFTER Enters into clear interior right and will have written test result share some little things modi example show what you have been given and just twitter annu hai to s you can see to clear also and for not and share also for native with good very Do Research 10 Related Articles 200 Solutions Not Accepted By Its Own This Is The Way You Can Solve Intersection Of Tourists Using Her Face Map Ashwamedh 09 Concrete Videos Related To List Solutions Using Java J2ee Technologies And Have Created Under Couple Of Good Playlist Educated At Earliest Solution Seater Uniform Drop Electronic and Print and Other Hridaya Ali Sardar with Dynamic Programming in the Deficit and Research Institute subscribe The Channel with Health Channel and thanks for watching this video
|
Intersection of Two Arrays II
|
intersection-of-two-arrays-ii
|
Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2,2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[4,9\]
**Explanation:** \[9,4\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000`
**Follow up:**
* What if the given array is already sorted? How would you optimize your algorithm?
* What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better?
* What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
| null |
Array,Hash Table,Two Pointers,Binary Search,Sorting
|
Easy
|
349,1044,1392,2282
|
402 |
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you not like the video please like it subscribe to my channel and hit the bell icon so that you get notified whenever i post a new video so without any further ado let's get started so problem is remove k digits very interesting problem so uh in this problem we are given a string uh and that is representing a non-negative integer so this string is non-negative integer so this string is non-negative integer so this string is given to us and it's a non-negative given to us and it's a non-negative given to us and it's a non-negative integer and until an integer k is given so we need to return the smallest possible integer after removing k digits from num so from this num from this number we need to remove k digits that is three digits we need to remove from this number so that smallest number smallest integer is created so see if from here we remove four three and two so these three numbers because k is three now so we need to remove three numbers so if we remove these three numbers the number we will get will be one two one nine so this is the smallest number one two one nine which can be created by removing three digits right so this is the uh problem in the second test case if you see here we just need to remove one digit so if we just remove this one we will get what zero two zero and this leading zero has no benefit obviously so 2 200 we will get remove the leading one we are removing this one because we need we can remove one integer so we are removing this one and zero because it is leading zero so that we do not need to have output must not contain leading zeros so that zero we removed and then rest of the number 200 which we get similarly for this number 10 we have to remove two digits so we will remove these two digits and we get like empty string then we number becomes empty because we have deleted both the integers so then we just return zero right so this is a problem see this is the problem now see when we see this problem for the first time now what we like quickly think we think that okay we can try removing all the digits like uh we have to remove three digits now so what we can do is uh either we can remove this or this like let's see over here so what i can like what i thought initially was what i can do i have to remove three digits now i have to remove three digits so what i'll do is i can remove this one or i can remove this or this anything i can remove any three days any three digits so that will lead to all combination all combinations will be there now this and this could be deleted so this will be the number left or you can do what you can delete this and this so this will be number left but see guys we are not there is no need to generate all the combinations in this case now like if we do like this so every combination will be generated where we are deleting the three number three digits and the rest of the four digits will have so if i delete these let's say i delete this four i delete this 4 this 2 and this one so then the rest of the number will be 1 3 2 9 this will i get i will get this but see there is no need to generate all the numbers all the combinations there is no name why because there is a easy way we can do this entirely let's see that so what after that i thought like maybe there could be another way there is if because see if we do not if we generate all the combinations that will be uh not efficient approach because c k could be very large if you see the constraints k could be 10 raised to power 5 also so there will be no benefit of generating all the combinations because that will be very huge those will then recursive calls will be very large that is not what we need to do over here we here see what we need to do we need to find the smallest number now after removing k digits from this test case from this first test case just see this test case again and try to think if you're able to think of any approach see we need to remove three digits and what are what we are removing four three and two that is these we are removing and these are largest numbers see these are some largest number four three two so see here we get 2 and these all numbers are larger or equal to 2 see 4 3 2 are greater than this 2 so see what we can do is we what we observed that when we are here these all numbers these three numbers are greater than this 2 or equal this 2 is equal right so what we can do over here is if we remove these because these are greater numbers no and they're coming in the starting they are coming in the starting you will say 9 is also a greater number but see it's at the end it's at the zeroth place so that is not contributing to making the number largest these are the at the more significant places now so if i remove these larger numbers so what i get one will be as such two one and nine right so this is the smallest number which i can get if you say that no i do not agree i if i want to remove 9 because it's the largest number i want to remove that so if you remove this 9 what you will do is you will uh remove the largest number and then the second largest and then the third largest so you remove nine you remove four and then you remove three because this is the largest and then this is the second largest and this is the third largest so what number you will get then 1 these will be removed 2 and this one so they see this is 1219 and this is 1221 so this is smallest now this is more this is greater than this number so answer should be this one that is why it does not depend that which number is the uh the greatest it depends which num which number is coming first which is greater like see 4 3 2 these numbers if they are greater than this number so if we remove these numbers then we could have that could be beneficial for us right if you see this test case also i hope you are understanding what i'm trying to like get to here so let's see this test case also one zero two zero we have this now we have this and k is one so over here if you say that remove the largest number which is two so i remove this two because i can only remove one digit so i am removing this two so number which i get will be one this thousand this two will be removed and one zero this will be the number but if we start from the starting we go from here we go here then we go here and we see that we are at zero but this one was greater than zero similarly like here now here it was same case now that here we have our add this two and these four three two were greater than or equal to this two so we remove those similarly here this one is greater than this zero right so if i remove this one i will get this number zero to zero and we do not need uh require this leading zeros so this will be the number so see if you remove the largest number then you are getting this number but if you start from the beginning and compare like this then you get 200 so this is the smallest number which we need to return all right so the approach which we will use here see guys it's very important approach we will use is c what we will do let's write this test so it's 143 one four three two one nine right one four three two one yeah and k is three so what we will do we will start from here we will traverse this string this ring this is a string right this is string we will traverse the string and whenever like we are here we will check if there are numbers greater than this 2 before it so for example here before this 2 we had these numbers now so if you see for this 3 also when we are here so this 4 is greater than 3 now so we will remove this 4 then we go ahead now this 3 is greater than this 2 so this 3 will be removed and then we go here so these are equal so we can remove this one so then we get 1 2 1 this approach we will be following but now how we will do this how we will check uh whether or how many numbers are like uh greater than this for example we are here so we are here how we will know that this is greater than this it could be see it could be this also now uh so yeah we'll see the test case afterwards so for this now for this we will use a stack to know how many numbers are greater than like this two how many numbers are greater than uh it before it so see how we will use a stack how we'll use the stack let's see that so see it bits bit of complicated but don't worry once we are done with the dryer you better understand so see we use a stack we have the stack initially we are here at one we just push it because stack is right now empty so when just check is empty stack is right now empty so just simply push nothing to check just push so one is pushed now we come here we check four we have the we have four and we will check whether this element which is currently at the top of the stack that is top of the stack top of stack is top of the stack greater than the element current this is the element no like 4 is greater than this one 1 is not greater than 4 so we can simply push this 4 then we come here at 3 now argument is 3 element is 3 right now see now this top of the stack is what 4 is greater than this element 3 means we can remove this 4 just remove this 4. it's not because see guys why we are removing this 4 because if we remove if we do not remove this 4 number will be what like 1 4 something but if we remove 4 and we add 3 in place of it then number will be what 1 3 something we need to find smallest number so that's why when this 4 the top of the stack is greater than the element we remove that top because if we do not remove it we get this thing 1 4 and then 3 something like that but if we remove it we get 1 3 so this is 13 something and this is 14 something so obviously this is smaller so that's why when the top of stack is greater than the element we will pop from stack pop so pop four is popped i hope you're getting so three we will be add we'll add three right i hope you're understanding so let's dive in further let's go ahead so here we get two element is two now again check top of stack is what three is three greater than two yes so one could be possibility we get a number one three something if we do not pop this three and if we pop this three we get one two something so obviously this is better now so that's why we'll pop it just pop it and add two so we popping it and we are adding element we are pushing the element in the stack right so we go ahead and then we get 2 element is 2 again so this is element is 2. so see now these are equal right top of the stack and this is equal so what we can do is we can remove this so just remove it and we will get this too or let's do one thing let's not remove it we can keep it like that only so um or we okay we can just remove it so we need to move this two right we remove the two uh and then we go ahead and we get one so element is now one so top of the stack is two which is greater than 1 right so which is greater than 1 so what we do is over here oh yeah so we see let's not pop it we will keep this two again so now we get one and this is greater than this uh no so we'll pop it and we'll add one so we'll keep this like greater than only let's keep the greater than condition because that is going in sync with our dryer like this and then what will happen we get 9 so top of the stack is 1 which is not greater than 9 so we will add 9 simply so see after the after hold reversal of the string we get number which is if you pop it from the stack nine one two one so one two one nine we get the number which is the smallest number right don't worry we will let's again uh dry iron on another test case so let's take this one 1 0 2 0 all right now let's make the stack so the condition was that if top will be greater than the element will pop from the stack and we will push into the push the element push element will be pushed every time right so see we are here currently stack is empty we will just add one go ahead now we have element as zero top of the shack is what 1 is greater than element so what we will do we will pop this one from the stack and we will add 0 right then we go to the next number element is 2 now to pop up the stack top of the stack is 0 and element is 2 so 0 is not greater than 2 hence 2 we will push in the stack then we go ahead we get 0 so element is 0 now element is 0 and top of the stack is 2. so now you might be thinking that now 2 is greater than 0 means we have to pop this 2 but no we will not pop why because see k was what k was 1 k was one given so k is one so that's why uh we have already removed this one we already removed this one digit so now we will not remove anything so k is now zero so we will not remove anything and we'll just push these numbers in the stack like this so then what we will do we will pop the from the stack so 0 to 0 we get and we'll check whether there is a leading zero if there is a leading zero we'll remove it this is a leading zero we'll remove it and this will be the output so every time when you are popping from the stack now when you're popping from the stack here one thing you need to do we just saw that if we do not decrement k n we do not decrement k we will be again popping unnecessarily but we have to only pop k elements now so whenever you are popping from the stack you have to decrement k also so here we have to do pop and decrement k because you have removed one element so this is one test case see we are thinking and we are improving l algorithm right now let's see one more test case so let's do one thing let's take this test case right let's take this test case so let's do one thing now let's take this test case and see one more uh thing which we have to improve in our algorithm so here k is nine means we need to remove nine digits right let's take a stack and condition was that if top of the element is greater top of the stack is greater than the element we will pop from the stack and we will decrement k and push we are every time doing right push so see what we do first uh we start from here currently stack is empty so when stack is empty we just simply push in the stack one is pushed we go ahead now we get two element is what two what is top of the stack one is one greater than two no so just push in the stack similarly we go ahead element is what 3 top of the stack is what 2 is 2 greater than 3 no so just push 3 in the stack similarly we go ahead so here element is what element is four and top of the stack is what three so three greater than four no so this will not uh these steps will not do and we just simply push so four is pushed similarly it goes ahead we go to 5 element is 5 top of the stack is 4 greater than 5 no so just push 5 in the stack then we get to 6 element is what element is 6 top of the check is what 5 greater than 6 no so just uh push in this stack six is pushed in the stack so there is no space six we go ahead similarly see same steps now seven is there six is the top of the stack seven not greater just push 7 similarly we push 8 and then now we go ahead and we get element as nine top of the shack is eight not greater than nine so we'll push nine also now see now we go to zero so now top of the stack is what nine and the element is what zero so element is here zero element is zero right this is true so we will pop but now the question is how many times we will pop will it will there be if here or will there be a while so that means like until this loop will continue until top is greater than the element that we will do or will we you do just this only one like we will have if only like once so see guys from this test case we can see that we will be using while because here we will be popping we will be keeping keep on popping until there are no greater elements before this zero so right now nine is greater than zero this condition is true so we will be using while here right just like i've taken this test case so that you can understand why we are using y not if so uh this condition is true line is greater than zero we will pop nine line is spot line is formed and kb will decrease so k will decrease it will be eight similarly now top is what this again while loop will cut again it will go it will again check the condition top is what eight it is greater than 0 again this will get removed and k will decrease so see this will keep on happening now top will be 7 and 7 is greater than 0 so what will happen is until k is not equal to 0 until k is not here we will write k is not equal to 0 just keep on popping until we have uh this stop greater than the current element so what will happen 6 will get removed 5 will be removed 4 because 4 is greater than 0 then 3 is greater than 0 2 is greater than 0 1 is greater than 0 now i am now we got stack empty so now we cannot pop anything and also these will this will reduce k will be equal to zero whenever we are popping we are decrementing also okay so here also one condition until stack there is something in the stack because then only you will be able to pop now so if stack is not empty that condition also you need to add and at last we will push this 0 in the stack so now this is only the number left so 0 will be the output for this test case because what we are doing we are removing 9 integers all these 9 digits will be removed and the rest number which will be the smallest number left will be 0. so guys i hope you understood from these test cases we discussed three test cases now let's see the code so before that uh yeah let's see the code so see what we are doing is we are just like this is the edge case that if the size of the string is less than the digits we have to remove then obviously answer will be zero because for example let's say we have this um we have one two three but k is given to be five that we have to remove five digits but the string is only of three digits so how we will remove five now so their answer will be z zero all right and then what we can do is we'll be having this for loop in this what we are doing is if you remember what we were doing we were going to each digit in the string going to each digit and into the stack was empty we just simply push so when the stack was empty we just simply push the first element and after that we have this while loop here that if stack is not empty and the top is greater than the current element if the top is greater than the current element and k is not 0 that is k is greater than 0 pop from the stack and decrement k this is the while loop right this is the while loop and uh this every time we are pushing in the stack whatever the element was so that we were pushing if you remember these are same steps which we did so right after this what we were doing was we were checking uh we were just popping from the stack so see we are popping like this we are not doing this answer plus is equal to whatever s top is why we are not doing this thing because we need to uh like if you remember here we have to have elements in the correct order now so if you generally remove from the stack 0 will be there 0 to 0 this will be the number but we don't want this now we want it in the correct order so that's why whatever we are popping we are inserting it in the beginning that is we pop 0 then we pop this 0 so this will not come here it will come here 0 then we pop this two so two will not come at the end it will come in the beginning and then this zero so like this so this we are doing that and this answer string is the string which we are making and after that if there are any leading zeros there are leading zero so here leading zero was there now so we were removing it we removed this leading zero all right we removed this leading zero we taken this i pointer until there is zero in the starting just move on uh keep on incrementing i and at the end if your answer is empty so just return zero otherwise return substring from that so like over here i will start from 0 but here 0 is there so i will go to this one and now there is no zero so what we will take substring we will take string substring from this i index from this so 200 will be the answer all right so guys this is c simple very simple approach right one thing which we left was is this thing let's discuss a test case for that because it's very important to understand that case so let's see that let's take an example um let's take we have one four three two zeros uh no not zero seven eight and a is four we have this thing right now see let's dry run our algorithm so i hope uh just do one thing first pause this video and try to dry iron by yourself and then see what is happening in this case right so what we will do is we will have one first of all in the stack then we go ahead and what was the condition top should be greater than the element and if it is that then we pop and we decrement k so now our limit is four so top is one which is not greater than four so four will be pushed then we go ahead we get element as three and now top is what four and four is greater than 3 so we'll pop it from the stack so we will do this all right now 3 will be pushed we go ahead element is 2 top is 3 is greater than 2 degreement k and pop from the stack so three is pop from the stack and we get two then we go ahead element is what seven element is seven see these guys it's very interesting test case element is seven and uh seven is greater than sorry top is two and two is greater than element is with 7 no this is not the case so what will happen uh 7 will just push in the stack and 8 then element is 8 top is 7 is not greater than 8 so 8 will also get pushed in the stack now see guys this for loop is completed but still k is not reduced to 0 we haven't removed all the digits we have to remove k digits we have only removed 2 which are 4 and 3 we have still k left still we have k left right so now what we will do see now while k is greater than 0 we will remove the largest elements so that what our strategy is to remove the largest so right now number is one two seven eight this is the number so guys what you will what you do you think what will be the ben what will be beneficial if we remove these or we will remove these last nut so what we will do once we are completed with the for loop and we are outside and still k is greater than zero we will keep on popping from the stack it will remove so 1 k is reduced by 1 still k is not greater than is not 0 it's greater than 0 so again we will pop from the stack 7 and then it will go to 0 so see now our number is what 1 2 so then we will just uh store it in answer string and then we will check for the leading zeros and then we will return it so answer will be 12 for this test case so 1 4 3 2 7 8 if you check here let's take this test case 1 4 3 2 7 8 this is a test case of 1 4 3 2 7 8 and k was 4. so if you run this we will get 12 as the answer so we get 12 here all right so here i just remove this i have written this we get 12 right so if you submit this is getting accepted so i go guys i hope you understood the problem and approach very interesting problem it was let me know in the comments if any doubt if you found the video helpful please like it subscribe to my channel and i'll see you next video
|
Remove K Digits
|
remove-k-digits
|
Given string num representing a non-negative integer `num`, and an integer `k`, return _the smallest possible integer after removing_ `k` _digits from_ `num`.
**Example 1:**
**Input:** num = "1432219 ", k = 3
**Output:** "1219 "
**Explanation:** Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
**Example 2:**
**Input:** num = "10200 ", k = 1
**Output:** "200 "
**Explanation:** Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
**Example 3:**
**Input:** num = "10 ", k = 2
**Output:** "0 "
**Explanation:** Remove all the digits from the number and it is left with nothing which is 0.
**Constraints:**
* `1 <= k <= num.length <= 105`
* `num` consists of only digits.
* `num` does not have any leading zeros except for the zero itself.
| null |
String,Stack,Greedy,Monotonic Stack
|
Medium
|
321,738,1792,2305
|
51 |
hey everybody this is larry this is june 4th uh of the lego day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's prom today's bomb seems to be a classic prom and queen so i guess we're no longer doing that prefix thing uh yeah end queen is a classic problem we turn all distinct solutions okay so one thing about this one is that is it really today's problem okay um because yeah it is just backtracking right there are all these cases and you just have to do it because um and you can really do better than that because uh because literally you have to put you have to print them out you have to like have to configurations right so you can really do faster than just iterating them i mean obviously um there might be some optimizations that you can do to make it faster but in the in that case it's gonna be backtracking it's still gonna be exponential so let's just get started and the idea is just what you think it is right it so the naive backtracking maybe just put a queen in a place and then go to the next cell you can go the dot and then you know like for example if you have a 4x4 right you might first try just put a queen here and then try to put it on here and then no good right and then so forth and do a for loop like that and here no good right and here or something like that right um of course then the second optimization that you can notice here is that well each row is not good and i mean once you use a row you can just go to the next row because well that was no good is it occupied by queen and then the second thing is that you could do the same for column and then next is you can do the same for diagonals um i feel like i did a i was going to say make a comment about diagonals about we did recently but i think i was just practicing a little bit on code forces by myself just to kind of warm up uh so i don't think i have it on video but the idea here is and this is something that you get from practicing a lot uh or maybe just a little bit and but for me that's what i get for practicing a lot because i you know it takes time for me to figure these things out um but the idea behind diagonal is that and let me put up the paint brush i'm drawing so give me a second to set that up we have something like this right nope you don't have something like this huh why is this not pasting am i not clipping white there you go that was weird so you have something like this and then the idea behind these diagonal uh behind the diagonals is that um you know you could draw these things in many ways but like you could have zero index of one index but that's your zero index so you this is zero one zero two zero three right ugly three one two and so forth and then the idea about labeling the diagonals is that i'm just trying to find out common pieces right well going to this diagonal what are the common pieces well is the x is equal to y um in this diagonal uh this would be what is it one two uh oops two three right that means that x is equal to y uh minus one and then dot right you can see the pattern here and this way is the other way as well it's going to be x is equal to y plus 1 and so forth and then also the other pattern that you can think about so then these are diagonals going this way but then obviously you're also want the other diagonal going this way right and then you try to figure out the pattern here is that true actually maybe i made this up actually uh maybe i'm just wrong here so yeah okay that should be right but just wanna make sure right and then the other diagonal is the same idea um and that you know uh well here it is gonna be x is equal to y still um and then here um what is here i think like it's like is that true i don't know about this one but yeah it's something like negative x is equal to y minus one or something maybe uh oh no this is whoops i remember now sorry this is uh i don't know how phrase it but i mean this is right actually but right or maybe minus one i forget but whatever direction is um the way that i think about it i know that i'm writing it just to kind of demonstrate the pattern but the way that i have it is that for these diagonals it's going to be x minus y is equal to some c right and the c will be the diagonal name i just see for constant but and then going to this direction you can think about it as x plus y is equal to c and this is just like an observation you know you're doing that uh yeah if you do enough you'll notice it so that's the thing and having this what's the point right having this will allow us to quickly check whether a diagonal is used the same way that um you know uh a quick the way to check whether a column was used i'm gonna go to the column first uh and then we'll go over how you know things are together so let's get started uh yeah and let's just say we have some recursion or try row of uh let's say the row because we know we skip each one so then now we have a row number we have a current board maybe and then let's say a column used right column used columns used yeah uh and yeah um and the two ways you can do about it one is have um kind of have solutions and then aggregate it up or you could just do it as you please um that's the way that i'm gonna do it is that with ro is equal to n then we um just because technically uh i think in theory i would like to keep it you know each um each function call returning everything that had um returning all the possible sub states but i also but this is actually i think uh faster and so it's a pretty much optimization but it is for me so then answer that a pen board the reason why i have this is because it makes a copy of it versus making a thing because otherwise i think i see this a lot which is that and i get this as a comment sometimes but what happens is that if you have let's say b as you go to some you know one two three and then you do end up b and then answer that b right then what happens right and then now b of let's say you change the element to five what happens is that answer is now actually you go to one two five technically references to well answer contains vb but when you print it out it would actually looks like one two five right because now b is pointed to an array so what you wanna do is actually you wanna make a copy of it every time you append it so that now there's they make a copy right so then you don't have the same thing so this happens a lot i even i with my experience i make this mistake from time to time just because it's very easy if i don't pay attention um but without paying attention i'm usually pretty okay about that so yeah um and then now we go uh yeah so for i so now we try to do a column right for uh the code cell is in range and so if columns use them we'll just use a uh a boolean here maybe but we'll use a set just because it's easy to think so if column is not in the used then we want to use it right so port of row of column is this is actually may not be sufficient even because of what we said but uh but for now that's okay uh is you go to um queen maybe i don't know how do you want to win and we might have to fix something but that's fine we just get a general feel uh so then now we do we try next row uh wordpress one board uh columns used right so this is just standard uh you know we change the state and then we change it back you know leave think better than you use it and this is removable uh all right i know that this isn't right just to be clear but let me try running it real quick just so that i um uh just so that i uh do what this is also y by the way this the thing that we said about this and this is why we write this way because if you just write times n times uh and again i guess in this case you would have all the pointers but yeah and then just a new set right i just want to run this real quick i know that this is wrong we don't even return anything i guess we can return it a bit but just to see um just want to see if i have any type posts or something like that and of course we didn't really would answer but yeah the reason why i just have so many is because i messed up i suppose that's weird actually i mean this is fine um yeah the reason why there's so many more than we expect is because we don't take care of diagonals and this is intentional and just that like we want to talk about um why do we need a diagonal optimization i mean well i mean you still have to take care of it otherwise you might have a you know in this if statement you could check whether you know you check whether um you know given an i uh a queen in row and columns then now you have to look at every other row and column just to see if uh they are at the same place or something like that right but if you want to do diagonals then that makes it just easier to do it in all one that's basically the idea um yeah and we have two diagonals as you probably just know visually so then one is row minus column and then the other is wordpress column as we kind of used yeah and this should be a little bit better though i think i don't allocate the space correctly here so uh oh and i don't recurse correctly here anyway uh ideally here we have the right amount of answer but not the correct answers so yeah we will see oh did i oh wait no did i do this incorrectly add remove rule minus column why would this be wrong because this can only happen after this right oh wow i forgot to check that's why uh so it was just removing stuff um yeah not in diagonal one used and row plus column not in diagonal 2 used so therefore it's just removing stuff before adding huh that's a silly mistake but yeah that's the check um and here like i said i'm just looking for uh well this is wrong just because i have a way of strings instead but i was looking for the having the right number of answers if you will um and it looks like that is the case we have two answers you know none of them got filled in but uh but yeah so here maybe we don't need to do all this thing but we do need to do something like for row for our import um okay so current is equal to and then enter that append current um and here we don't need to i mean you could do this as well but we don't need it because we allocate this memory um right there so yeah i mean you could copy it again but that just makes it slower okay so that's pretty much it uh i mean there are only nine cases so that's you know uh we can proof force and you could just saw me prove first typing it in just to see if we're right and this looks good so let's give it a submit let's give some love see if it's fast enough and that's pretty much it yeah much slower than last time but 795 days uh but yeah let me know what you think uh hit the like button hit the subscribe button join me on discord let me know what you think i did the same thing last time okay uh yeah i had a better abstraction last time though huh but uh yeah that's pretty much it so yeah stay good stay healthy take your mental health i'll see you later go rangers and yeah i'll see you later bye
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
1,091 |
In this video we will discuss this problem in the shortest lesson in binary matrix. In this you have been given a binary matrix. Binary matrix means that the value of each of your cells is either zero or one. In this you have to go from the starting to the last cell. And you have to go to minimum staff, what is the meaning of the steps, the number of cells you will visit from the beginning and in life, you will have that many steps and we have been given some rules of Tribalsal, what are the rules, we will move from one cell to its 8 just like if This is a cell, this one, you can go left and we can go only to the cell with zero value, like from this zero, I can go to this zero, where I can't go, that should be blocked for me. So if we give the example, what can we have, how many degrees Celsius can we have and what can be the second term? If we go from here to here, then how much is our shortest text, 4, so we have four. Whenever you find the shortest text in any matrix. When asked to find out, the first thing that should come to your mind is BFS because what is BFS? To find out the shortest path, it is generally our BF. What is it on the graph? What are your vertices in the graph? And this is what happens between them, what do we do, we start from the beginning, why do I put its neighbors, then visit their neighbors, travel like this, in our matrix we can tweet every cell like this There is one ahead among them, from this you can tweet like mother lo, I am on this cell, there will be diagrams of this cell i.e. what valid location do I diagrams of this cell i.e. what valid location do I diagrams of this cell i.e. what valid location do I have, these are three, out of these also zero, which one is mine, there is only one location. I ca n't go to one so I have direction but where do I go only on this i.e. there is this vertex i.e. there is this vertex i.e. there is this vertex only in the middle of it there is no further place in the rest and so on how can we find out if I have to go to my So I don't have to actually make a graph. If I have the coordinates of a cell, I can easily find the adjacent neighbors. I have to consider 8 neighbors and see whether they are valid or not. If it is valid, then I can find it in my I can enter it brother, what do we do in this, why do we enter our bus, then whatever sales are valid for us, why should we enter them, what will we do, if we ignore them, then what can we simply do, from here our B Let's start F, which of these is the only one that is not valid, why should we give this one as ours, then we have to give this one here, which one is this, so why should we give these two as I, then we will do this one of these. This is this was this, we had already considered this one, this is one, we have already considered this, when we had considered this, then we will have no one for this, then if this has not happened to us, then we will push this, we will see that we Enter our last one, which was our destination, then we will return it to whoever came to us on time. No, how will we be five in general, what do we do in BSF, what do we push in ours, after that what do we call it off. Similarly, then we come to this level and first scan it, i.e. and first scan it, i.e. and first scan it, i.e. ours which I push, then we come to the next level, so how many levels do we have? One level is this. There is only one, so in the same way, when we complete the entire level, we will update our steps on time, like this is your answer, our answer is done, our answer is three, so in this way we will update our answer. We can do this and because what we have to do is to count this one from the beginning like how many steps we took, one to three four, the number of cells we visited was equal to the number of steps we took and we had to count this also from the beginning. Generally what happens to me is that we start from here, then when we visit, I count this type, but in this problem, you have to account for this also from the beginning, when we finish one level, we will increment the step. And as soon as we make the last one, we will return our answer, whatever steps we have taken till now, we will return one more thing, when we traveled to this cell, we had pushed this and this is our reason. Then when we popped this cell, this was its end and why did we not push it again because what happens in BSF is that one of your cells is pushed only once, only then its time complexity has reduced if we repeatedly- has reduced if we repeatedly- has reduced if we repeatedly- What will happen to us if we keep pushing the note from the bar? It will increase. So how do we know that we have already stored this cell in our side i.e. we have already visited it? i.e. we have already visited it? i.e. we have already visited it? What can we create for this? We can make it widgetized. Whoever we push our price to, we will mark it as visited, then once we upload this whole thing on this example, we get this life matrix, zero, one zero. We have created a widgetized matrix. Took a note of this size to note that we have not started all of us from zero, that we have not visited any cell yet, why will it appear that the initial is YouTube and what is our answer, it is zero, then what will we do from the beginning. And we had to go to but if we ca n't go to the starting then what do we have to return. Minus one key we can't drive by definition but our example is zero so what do we have to do. Why do we have to push the starting cell? We have to push it for this reason. How will we push K into K? Basically we will push its Why did it go to zero? Answer: I went to Why did it go to zero? Answer: I went to Why did it go to zero? Answer: I went to one. We marked it. I turn off the frontmost element. After that, the adjacent elements are there. This is our element. What is its addition? It is three here. This part is outside my boundary, so if I can't go to this one and this one, then why should I will push it and this is my pop and after it is popped, I have not sent this here, basically after every level, I am putting a center note that you have to update the answer, my level is one level from zero to one level is complete. When it is done, what will I do with the answer and my image is zero, this one is my cell, my answer has been done, we have marked it as visited, then what do we have to do with it, no, just basically, what is it, these are the five of them. Have already done this is one and both of these energies are fine, this was our last note of this level, so we will have to increment the answer by three, so now our straight A is gone, so there are two notes in our time, the answer is our three. The rest is our required matrix. Now we will change it to zero comma tu i.e. Now we will change it to zero comma tu i.e. Now we will change it to zero comma tu i.e. what will happen if we prop up this cell, for this we have already visited these three. Here, looking at our visit matrix, we came to know that we have already visited it. This one is this one, we have already considered how if there is one in our widget, then we will not do anything, we will just pop it, now our data is one element, our answer is still free and the rest are our requirements, we have made it one comma you. Ours is this is also one mark and here we will do it, so now what is our state, this is our destination, so what do we have to do, return our answer. So we will return four that we will take minimum forceps in life here 000, so in this way our BF of matrix is K will so in this way our BF of matrix is K will so in this way our BF of matrix is K will do no, we could have done without it also, so what can we do in this, what is there in this in our life -What is valid is zero in our life -What is valid is zero in our life -What is valid is zero and one. Only this value is zero means invalid cell. If we are allowed to modify the original matrix, then we can reduce the error in our life by doing this without modifying the original matrix. How can we reduce the error whenever we find a cell? What do we have to do, Jeevan Beti, you put its value in it, what will you represent that this is my sale already, I have already considered it and will reprint me, zero will represent my valid sale which we have already considered, like starting. When we do something to this, what we would do normally but we will not visit this, then what will we do, when we do this, we will have to store the truth of our why, then when we visit this, we will do this, what will happen to us in this visited matrix. It will not be required, rest of our whole process will be done just when we had to mark visit one, we mark it there in the life matrix and while considering our neighbour, we will also add this condition in it, first we check that Is it one or not? Now we will see that in the life matrix, cell one air is not one of these. One means invalid cell. If you do not want to do it, then our further process will be from the rest. We will mark it because it is We will start turning off and then those who will do ours and when we reach the last step will return our step, how many will be in ours, then a matrix is given in my total, first of all if we cannot reach the destination then we will return minus one. After that, what we had to do was to go to the direction. For the coming direction, we had seen what would be our 8 numbers. There would be one increase in the other room. There would be one decrease. Similarly, there would be 1 increase in the pen. There would be one decrease. So, 18 was used to represent that. We put codes that in our current coordinator, we have to remove it by doing plus one x plus one by doing this plus one What we also have to do for the office is that we will do the life matrix, then what we have to do is add it and before that what I had to do is that when we have this, we have to do answer plus this, then we will do every level like this. After our A, Answer Plus, we will travel the entire K level in this four loop and as this level ends, Answer Plus, that is why we have taken zero here in the beginning, so that after coming here for the starting sale, it happens that brother. In our single look, all the levels are considered and the next level of that level gets added together so that after that we can increment our answer. What we do in this world is that we pop from the front, we check this. That element is our destination, then return our answer, then what do we have to do, so we took one of these, I went through the loop for the combination that our auto should consider the bus, in our current tax, we entered this We will make one side like this and add it in the front A in this way so that the code of our knee becomes net A. Then what we had to see is whether that knee is our inner boundary or not and if it is also within the boundary then it is zero. Or if it is not there then we have written a function for that to check whether this is our never valid cell, if it is a valid cell then why should I push it and mark it. What have we done in this function, we will check that these corners Is it our range or not? If our mount is less than zero, what does it mean that this is not a valid code? Also, we have checked that if our grid express is not zero i.e. it is not a valid cell, then not zero i.e. it is not a valid cell, then not zero i.e. it is not a valid cell, then now we are in four. Turn from here that we don't have to drive here, as per our rule, this is a valid cell to turn. In this way, after complete BSF travels, if this condition of ours is ever satisfied and we reach the destination, then we will return the answer from here. Will give but our distance never came and our BF is the first one who got terminated, such a situation was created that all our cells were one, we were not able to reach the definition, so what will happen to him, take this, he will be terminated from here and Mines one will come here we can't go on definition thank you gas
|
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
|
32 |
hey what's up guys welcome back to this video in this video we're going to solve this query interview question the longest valid parenthesis the difficulty level of this question is hard in this problem we are given a string the string contains opening parenthesis or closing parenthesis we have to return the length of valid parenthesis we have to find out the longest valid parenthesis and we have to return the length of longest valid parenthesis for this string this is the longest valid parenthesis the length is four so we have to written four for this input for this string we see the longest valid parenthesis is this opening bracket closing bracket so we have to written two the length of this longest valid parenthesis is 2. for this string the longest valid parenthesis is this and we have to written the length of this longest valid parenthesis that is 4. now how do we solve this problem now let's talk about how to solve this volume first let's talk about the brute force approach in brute force what we will do will generate all possible substring and we will check whether the substring is valid or not if the substring are valid we will keep track the longest valid substring that means the longest valid parenthesis but the name approach will takes off in queue time complexity we have to validate each substring so the space complexity will be of and we have to use a stack data structure this is the name solution can you improve this solution yes we can improve this solution we can solve this problem in linear time complexity and in linear space complexity now let's see how to solve this problem in linear time and in linear space when we encountered parenthesis problem the common data structure we use is stack we're going to solve this problem using stack data structure we're given a string not an array of character we're given a string we're representing each character as a box so that we can understand the indecent okay now first thing what i'm going to do i'm going to create a stack data structure let's create a stack data structure right here this is our stack and we'll have a variable the answer equals to initially zero answer is the length of longest valid parenthesis initially we have zero before we traversing this string we will insert minus 1 what does this mean here we have minus 1 here we have nothing ok by -1 i mean we have by -1 i mean we have by -1 i mean we have uh we will see if we find it in a valid order then what i will do will insert and will puff so here at this point we will have the length of valid parenthesis is 1 minus 1 that is 2. that is 1 minus 1 that is 2. we will see why we are inserting here minus 1. now our current character is opening a parenthesis if we find it opening parenthesis we will insert the index of opening parenthesis let's insert here zero the index of opening parenthesis now let's move to the next this is our next when we encountered closing parenthesis what will the first thing will remove the top element from our stack that is this element zero now we see we have minus one our stack is not empty at this point what is the longest valid parentheses when we when you encountered closing parenthesis we will check we will remove the troubleman from stack and we will get the peak if the stack is not empty and will calculate the length upon longest valid parenthesis that is minus 1 that is 1 minus the index of this current 1 and minus 1 minus one is the peak so we will have two at this point we have two so we'll take max of answer and two that is two let's move forward this is our current character is closing parentheses when you have closing parenthesis what you will do will remove the top from our stack let's remove it our stack is empty if our stack is empty we'll insert this index the index of this current character that is 2 what it means we have 2 right here it means that if we find out valid combination of parenthesis on the right we'll have nothing here when you move to this we will have on our stack only two so we to we can keep track the immediate left of our valid parenthesis that is this okay now let's move forward this is your closing parenthesis uh now let's move forward this is our opening parenthesis let's insert the index now let's move forward we have opening parenthesis so let's insert the index for let's move forward this is our closing parenthesis so let's remove the top home stack and let's calculate the length of our current longest valid parentheses which is three the top three which is the boundary here okay we have just removed this so we have the boundary here five minus three that is two so max of two and two is two will not change the value of answer let's move forward we have closing so let's remove it we see now our boundary is this okay this is the uh this is the first character upper valley this is the first character of our valid parentheses of this substring so this is the boundary with this we can find out our length the length of our current a valid parenthesis so 6 minus 2 that is 4 so max of 2 and 4 is 4 so answer equals to 4. now let's move forward we have closing let's remove it we are closing so we removed now we see our stack is empty there is no boundary for this closing that means we have no valid group for this closing parenthesis so we are done we reached at the end we reached the end we are done so we will written this answer this is how it works let's take another example for a better understanding let's assume we're given this string initially we'll have minus one on our stack now we have opening if we have opening we'll insert on our stack now we have closing when we have closing will remove the top from stack we see we have a boundary we find out a valid parenthesis so 1 minus 1 that is 2. so max of 0 and 2 is 2. let's move forward we have closing so let's remove 12 now we see we have no boundary for this so this is not a part of a valid parenthesis so we'll in we'll insert the index of this character that is 2. now we're done we reach the end so we'll return this 2. let's take here another example let's assume we're given this a string initially answer equals to zero and on our stack we will have minus one we have closing at the first position so we'll remove the top now we see we have empty means this is not a part of a valid parentheses so let's insert the index 0 this is uh this will be treated as the boundary okay now this is opening let's insert the index one let's move forward let's remove it now we see that we have zero it means we have a uh it means that this is a part of a valid parenthesis and the boundary is this so let's find out the length 2 minus 0 is 2 let's move forward this is our opening let's insert the index 3 let's move forward this is uh closing so let's remove 12 and here we see that we have 0 this is the boundary so this is a part of a valid parenthesis so let's find out the boundary this is a boundary so 4 minus 0 is 4. so let's add this value with 4 now let's move forward this is closing so let's remove the top now we see we have nothing in our stick so this is not a part of a valid parenthesis so let's insert 5 we might have some element on the right so this will be treated as a boundary since we're done here at this point we'll just straighten this four this is how this algorithm works this algorithm will takes off in time complexity because we're traversing the string from left to right where n is the length of the given string and it will takes off in space complexity for the word sketch we'll have in item on our stack data structure so it will takes both in space complexity if we have input like this we will have five item on our stack that's why the space complexity is off in for the worst case now let's write out the pseudo code let's call the function longest valid parentheses longest valid parenthesis this function takes one parameter a string let's call it h now i'm gonna check if the length of the string is zero will return zero if this is the base gate if the length of the string equals to 0 we will return 0 this is your base sketch now i want to create a style data structure so stack equals to let's assume this is our stack at the first position we will insert minus one so stack dot push minus one this is for initial boundary now let's run in low for int just let's say here i equals to zero while i is less than the length of the string then here i plus now let's find out the current character so ch current character equals to is dot char at zero sorry here we should have either in this edge now we're gonna check if ch equals to uh opening bracket what i'm gonna do i'm gonna insert our current index onto the stack so stack dot push i okay if our current character is not opening bracket that means closing bracket if our current character is closing bracket first thing what i'll do i'll remove the top element from stack because we'll have a match here we might have a match so stack dot pop we just remove the top element so we might have something like this we'll have that minus one zero one will have minus one zero so we'll remove this we have a match and this is a boundary so you can find out the length okay so we remove that tough now what i'm going to do i'm going to check the length the stack can be empty if we have something like this a string uh if we have something like this so in our stack we'll have minus 1 then we'll just remove -1 okay now stack is we'll just remove -1 okay now stack is we'll just remove -1 okay now stack is empty so you have to check if stack dot size uh style size equals to zero if standard size equals to zero that means it's empty if the stack is empty we'll insert the current index on our stack the current index will be trading for this case zero will be treating as our boundary so let's insert our current tower stack so stack dot push i okay otherwise else will calculate our answer uh we should have an answer variable somewhere here uh let's activate an answer variable to keep track of our answer so answer equals to zero uh stack equals to this is your stack dot push minus one okay so ils here we're gonna calculate our answer so answer equals to max of answer and i minus our peak stack dot pick the top from stack so stack dot peak okay so this is our uh logic to find out the answer so max of answer and i minus stack p we might have mean that we might have uh string something like this so for this string we see that here we have max so we have to keep it the maximum okay uh at the end we are done with this loop we will written the answer so return the answer this is your algorithm this algorithm will takes of in time complexity and of in space complexity hope you have understood this video explanations this is not super difficult to understand if we try with couple of examples it will make sense i think you're understanding thanks for watching this video i'll see you in the next video
|
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
|
999 |
So hi friends, in this video we are going to talk about the problem number 999 of elite code, its name is available capture for ruk, ok so this problem is very simple, what is given to us in this, what is a ruk, ok elephant that walks plus directions. OK, what we have to return is how many number of pawns are killed, OK, so in this case, how many numbers of pawns are being killed, and OK, so we will give three in the output, now there is a condition that Bishop which is Camel, he is also coming in the middle, if he comes in the middle, then he cannot kill the pawns. Okay, this is the condition, so in this case, in example number two, you can see that the bishop has surrounded the pawn from all sides, then that bishop. surrounded the rook I'm sorry so he can't kill any pawn if it was not a bishop then he would have killed it we would return one in the output but in this case he is not killing anyone so for this we would return in the output Will give zero, okay and in example number three you can see that three is hitting it, here it cannot be hit because there is bishop here, so this is a problem, we have to create a function which we will get this in the input, we will get a board, okay. And we have to return how many number of balls can he hit, so here is the solution, okay, this is the function solution, my solution is my approach, now I will explain it, okay, first of all, I declared an array named ruk inside it. I have run this one power loop, it is ok according to the board and it is running fine, something like this and what am I looking for in it, what is the position of the stop, where is the hatch in this board, so after finding that position, I brake. I am fine, it is as simple as we can find the solution to the problem, I did some approach, you can get the optimal solution from this too, but okay, this is my solution, so here I found the position of the stop, the answer was declared a variable which is zero. Which gives us the number of how many po's hit, it will return, it is giving the answer in the return, okay and which is the first for loop, or for loop, I declared okay, here I am going from where to where, up to down means up to down. Give this direction now so four directions are ok Rani so it is this otherwise charge direction is like this direction first direction so I am checking first from up to down the zero aa position is this from position to length of the board means it will go something like this Aa plus will happen, okay, I am checking if board off aa board off, how much aa means this direction and stop ka which is j direction, j means from here like this, inside the stop board, I am traversing something like this okay start where I am doing this from where the rook position is from here and I am checking that first I am checking whether the bishop is there, if the bishop comes then simply the for loop will break because he will not be able to hit even a single pawn. No, then I am checking that check position means check on my track, is there a pawn on this track, what is that, if I talk about this condition, then it went like this, I got the pawn, so I answered plus and At one time he can hit one punch, then for this, directly break, so this is also very similar for loop, okay, in this I am going down to up means it is the same logic in the direction, in this, from stop of zero, I am going to come. It will traverse something like this: a greater than equals to 0 and traverse something like this: a greater than equals to 0 and traverse something like this: a greater than equals to 0 and a minus will be okay in that plus in this minus after that this board of I is doing something like this I'm doing Chuck Car Bishop is not there so in simple it becomes plus It is following in the truck and after that, left to right means 'y' left to right means 'y' left to right means 'y' direction, how will we make it something like this plus, j plus, aa is fixed in it, okay whatever aa is in it is fixed, ru ka se. We are starting from y and going to k something like this direction is fixed, the direction of y is fixed and the direction of Same is the hope, so you understood the solution to this problem and in the end I am returning my answer. It was simple, there is not much in it, I could have probably found some optimized solution but I chose this approach because it is time saving. I don't want to spend much time in the problem, it's okay, so hope you understood this, I will run it and tell you the answer, I have also submitted it, I have also checked whether the answer is coming or not, I will see after submitting it, the answer is coming, still you are a little confused. In red but still the answer came, the matter is over, thank you so much for watching, see you in the next problem.
|
Available Captures for Rook
|
regions-cut-by-slashes
|
On an `8 x 8` chessboard, there is **exactly one** white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`.
When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered **attacking** a pawn if the rook can capture the pawn on the rook's turn. The **number of available captures** for the white rook is the number of pawns that the rook is **attacking**.
Return _the **number of available captures** for the white rook_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "R ", ". ", ". ", ". ", "p "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** In this example, the rook is attacking all the pawns.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "B ", "R ", "B ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "B ", "p ", "p ", ". ", ". "\],\[ ". ", "p ", "p ", "p ", "p ", "p ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 0
**Explanation:** The bishops are blocking the rook from attacking any of the pawns.
**Example 3:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ "p ", "p ", ". ", "R ", ". ", "p ", "B ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "p ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\]\]
**Output:** 3
**Explanation:** The rook is attacking the pawns at positions b5, d6, and f5.
**Constraints:**
* `board.length == 8`
* `board[i].length == 8`
* `board[i][j]` is either `'R'`, `'.'`, `'B'`, or `'p'`
* There is exactly one cell with `board[i][j] == 'R'`
| null |
Depth-First Search,Breadth-First Search,Union Find,Graph
|
Medium
| null |
134 |
hello everyone i hope you're all doing really well so today in this video we'll go over this question which is generally being asked by amazon in their coding interview rounds the question goes by the name of gas station available on lead code and it's defined to be a medium difficulty problem so we'll quickly go over the question what it says and then we'll move on to its explanation as well as the coding part all right so the problem says that there are n gas stations along the circular route where the amount of gas at the ith gas station is given by gas i and you have a car with unlimited gas tanks so there is no limit on the mount or the capacity of gas you can store at one point of time and it costs i cost of i guess to travel from ith gas station to its next one and you begin the journey with an empty tank at one of the gas stations so you are given these two areas the amount of gas and the cost to travel and you need to find the starting gas station if you can complete an air circuit in the clockwise direction otherwise if there is no such gas station available you need to return -1 you need to return -1 you need to return -1 and it says that there is only one such unique gas station available so for example in this particular test case these are the amount of gas available at every station and this is the cost to travel to the next one so the explanation just says that you'll be able to start from this particular station and then complete the entire tour from four to five then one two and three and you will be able to make an entity starting from this particular gas station so we need to return the index of that which is index number three so in this test case it says minus one because you can't start at station zero or one obviously you won't be able to move to the next one and that's why there is no such a gas station from where you can start to make complete circuit so our answer should be -1 so let's understand the different be -1 so let's understand the different be -1 so let's understand the different approaches to solve this question and then we'll code it out all right so let's quickly discuss the explanation part now so i have drawn these gas stations here in orange and the blue represents the distance between two gas stations so we are given this list of gas stations as well as the cost to drivers from one gas station to the other and we are required to find the gas station to start with in order to complete a full circuit a full two so the first approach that can come to your mind the easy approach is to simply take every gas station as a starting point and try to check if starting from that gas station we can make a two so this one was actually the brute force solution as uh this is a naive approach so this takes n square time because what we do here essentially is we consider every petrol pump as the potential starting point once so in the first loop we'll iterate through all petrol pumps to consider the starting point and then in the next loop we move to all petrol pumps ahead of that to make sure that we are able to complete a circuit so this takes n square time and in terms of space this is going to be constant because uh we are not using any auxiliary container here to store any information so this is a n square time and constant space solution but this solution is pretty easy to come up with and pretty much everyone with little to no experience can think of the solution and your interview probably won't be too happy with this one and there does exist a much better solution which is which can be done in linear time but it's pretty tricky to come up with by yourself but once you do understand the intuition and the logic behind it then it's amazing how it just comes together so let's quickly jump onto the optimum execution okay so i have drawn this diagram once again to explain the optimized approach and in this approach basically we try to do this in two different parts or two different phases so in the first phase what we do is in the question we are asked to find if there is a petrol pump then return its index and if there are no such petrol pumps from which we can start to make a complete tool then we need to return minus one so let's handle that case first so we first basically try to check whether such a petrol pump even exists or not from which we can actually start and take a complete tool and how do we do that so let's say we have something like net petrol required so this is a variable which will store the total amount of petrol it is required to make this complete do that is when we are speaking about total petrol we don't really care where we start from we can start from any single petrol pump and we just need to make sure that we are able to complete this tour that is all we are dealing with here so to explain this part let's say we start from this particular pump randomly as i mentioned it does not matter where we actually start from we just need to go over all the pumps and reach that particular pump once to check what is the net petrol that is going to be required so basically if we start from this pump so currently we will have two units of petrol that we see from this now in order to reach this pump we have to travel this distance which requires 4 units so our net in this path will be 2 minus 4 which is negative 2 now actually this negative 2 distance travelling is not possible but we are not bothered by that we're just trying to calculate the total petrol so currently we have negative two when we reach this pump so three more will get added so we'll have three plus negative two which is one units left and now to traverse this distance will require 5 units so 1 minus 5 gives us negative 4 which we have at this particular pump now with this 4 gets added from this pump and then we have nothing left but we need to travel this particular distance so basically we have 0 and 0 minus 1 gives us negative 1 so we'll have negative 1 units left at this particular index so we are just trying to calculate the net petrol that we require now to this negative 1 5 gets added so we have 4 units and we require 2 units to traverse this distance so we have 4 minus 2 which gives us 2 when we reach this index now from this pump 1 will get added so we'll have 2 plus 1 which is 3 and then again 3 minus 3 during this part will give us 0 when we reach this particular pump once again which is where we actually started from so with this what we found that starting from any particular pump let's say this one in order to complete the entire circuit we need a net petrol of zero units now the value zero does not really mean anything but if it's if the net value required is anything zero or greater than 0 then it's actually fine because that means that it's possible for us to make a complete circuit otherwise had this net value been negative then that would have meant that it's not actually possible to start from any pump and be able to cover the entire circuit so with this we know that it's possible and now all we are left with finding is the index of that particular pump from where we should start for us to be able to reach that pump again with some petrol left so now we come to the second phase of this algorithm which actually finds the particular petrol term from where we need to start so let's say again we can start from any gas station to check for the correct gas station so let's say again i start from this one randomly chosen one so what we do now is we always maintain what is the current amount of gas available with us so we can have something like a variable which stores the current petrol available and this value also will initialize with zero because before we start we don't have anything with us now what we do is whichever point we are starting from we try to consider that itself as the potential starting point so we are not sure if this is actually the correct starting point or not but for now let's just consider this to be the potential starting point so if i assume that my answer is this particular gas station so currently i'll have two units of gas here and then i need four to traverse to the next gas station so in this path i'll have 2 minus 4 which is negative 2 now as soon as i find my value is negative which means this is not the correct starting point because obviously from here i cannot reach this particular gas station itself so there's no way i can make a complete door and now since this is not a gas station we'll simply move on to the next one so i'll now consider this to be my potential uh starting gas station so here i will have three units of gas available if i start from here now to reach the next one i require five units so the gas i'll have after that is three minus five which is minus two again this is negative so this also cannot be my answer because starting from here i cannot reach this particular gas station itself again we move on to the next one we consider this to be our potential starting point so here i start with four units and then to reach the next one i require one unit so that is four minus one which gives me three units left so once i reach this particular station starting from four i will have three units left to that three i'll get five more so i'll have eight units and then to reach the next gas station i'll require eight minus two units that is the distance which will give me six units so here i'll have six units of gas to which one more will be added from this particular station so i'll have six plus one seven so here i'll have seven units available and i require three more to traverse to the next gas station so i'll have seven minus three which is four units and i reach this particular gas station from where we started checking for the current starting point so once we complete this entire loop and reach back so at this point of time the last gas station that we consider to be our potential starting point is our actual answer because we already know that it is possible to make the entire tour and starting from this particular gas station our net current petrol never became negative because at any point of time if it was becoming negative then we were simply dismissing that as a starting point and considering the next one to be the potential starting point again if it became negative we considered the next one to be the starting point and after this during this entire path the petrol never became negative so starting from this it is actually possible to make a complete tour and reach this back again without ever having negative gas or negative petrol in the middle of the tool now to talk about complexities so for time complexity of this algorithm uh basically what we are doing is we are starting from one particular point and then we are iterating over all other pumps and reaching that gas station once again so we are only iterating over all the gas stations only once and it does not matter where we start from but we once we reach that once again we stop so the time complexity for this one will be linear itself because we're only hydrating over all the gas stations only once and to talk about the space complexity so in this one we are not really using any container or any auxiliary array or list to store any information we're just using two or three variables so space complexity will be constant for this one so this is a constant space and linear time solution so i think this is a pretty optimized solution although a little tricky to come up with by yourself but once you understand the logic behind it's amazing how it does the job in linear time so that was it for this explanation and let's quickly move on to writing the code so the code should be simple we have a vector of gas representing the gas at every station and cost representing the cost to move to the next station we need to return an integer denoting the index of the station from where we can start to complete the entire tour so let's move on to the first part which is to check whether it's actually possible to start from some station or not so we'd have a variable called net gas required as we discussed so this will be initialized with zero and now uh let's start from the first one we can start with any one but let's just start from the first one so we'll traverse the entire uh area of gas stations and we'll keep on adding the transaction amount to this one that is the amount of gas that i acquire from the station minus the cost that i need to reach the next station so to this value i can simply add the transaction that is the amount of cash that i get from the station minus the cost that i need that is the amount of gas that i need to use in order to reach the next station so once i'm done with this the leftover value this netcast acquired value should be some positive value or zero that is it cannot be negative if it becomes negative that means no matter from where we started during some point in our journey we will have a negative value which means we will not be able to move past that particular station so if net gas required so this is just calculation of the total gas required we don't care where we start from but if the gas required is a negative value then there is no way we can make the entire circuit so we need to return -1 no matter where we need to return -1 no matter where we need to return -1 no matter where we start from if we reach this point and the function does not return anything then that means that there is indeed an answer possible and we just need to find the index of that particular gas station so now what we'll do is we'll have another variable called let's say current gas available so this will keep on holding the gas that i have at every particular transaction also i will need the index from which i need to start so we keep on storing the starting index our potential starting index that we discussed so let's consider it let's call it start index and we start from the first one you can't take any one but we just start from the first one the reason i'm saying you can take anyone is because they have guaranteed the answer to be unique so starting from any let's say we start from this and then we move to this and then again to these values in a circular fashion in an array you will find the answer so it does not matter but let's just start from the first one so if we start from the first one so what we'll do is we write it over all the gas stations so gas dot size and at every station we'll again make the transaction that we want so from current gas available we will simply uh make the transaction that is gas of i what amount of gas do i get from this gas station minus cost of i the amount that i need to reach the next gas station so once we make this current transaction i can simply check if my current gas available is becoming negative or not and if it becomes negative then that means that whatever we considered to be the starting point earlier potential starting point was actually incorrect so we have to consider the next uh coming gas station to be the next potential starting point so we can simply make the start index to point to the next particular gas station's index because we know any gas station till this index will not be the correct starting point because somewhere in between the path my gas is available will become negative and once we're done with this also since we are starting again from the next gas station i need to make my current gas available as 0 again since we're starting afresh so this becomes 0 and i think that should be it because once this loop completes i will have the correct start index stored in this value because i know for sure that there is an answer so we can simply return that particular start index which is what we want so i think that is fine and let's run this code for the sample test cases so it's working for the sample test case let's submit this to check if this gets accepted and this is faster than 94 and gets accepted so i think this is an overall pretty good solution so yeah that was it for this particular video and if you like the video do hit the like button share it with your friends subscribe the channel for more such coding interview problems and if you want me to take up another problem please do recommend it and if you have any doubts any suggestions put them down on the comment box and thank you so much for watching share with your friends i'll see you guys soon in the next one
|
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
|
920 |
hey everybody this is Larry this is day seven day six of the liko day challenge hit the like button and subscribe and join my Discord let me know what you think about today's Farm 920 number of Music uh music playlist musical playlist music playlist all right uh your music player contains and different songs you want to listen to Go songs not necessarily distinct on necessarily different during your trip to what bottom you will create a playlist so that every song is played them at least once a song can be played again if only K other songs have been played and it is a mod thing so okay uh let's do it my mind okay so yeah so okay uh so this is a commentatorial problem obviously uh so let's see um and of course with that it's gonna be DP but it doesn't seem like I mean I don't know for me these DPS are sometimes kind of tricky uh and is and go and all these other things only up to 100 so that makes it I mean that we don't have to be I mean it's still gonna be tricky but uh okay so let's see right um how are we thinking about this so I mean I let's see uh man I just woke up so uh so it's a little bit slow okay so what's the hand again just end different songs and go is the number of total songs in case the repeating thing okay so let's say we have something like this um how are we counting this so let's say there is um I'm gonna call everything index but that's just like everything but uh song index and then maybe left maybe that's the third dimension uh and here of course we want to Define this to be honest I'm still just thinking if uh okay so we have songs left okay that's terrible it's almost to pick from and we have left number of songs to put on the playlist right someone like this and the idea I think the tricky thing is that and some of this I think I greatly remember some of something about this Farm or something similar to The Spot uh that's why I'm trying to be a little bit more careful is that I think the naive first way is just for every song you know like okay for the first song on a playlist rather for the first song in the playlist oh you know like stop with one on the first one and then and start with two and then three and then so fourth dot and then and try like okay so for one we well you know look at K and it means that you cannot be one but it could be one two one three and then dot and then get kind of generation right um but that part is tricky because then now you have to remember State and what I mean by that is that um the thing about this kind of uh dominating programming and memorization in general is that you're trying to uh well the core idea of it is that given a certain set of inputs things are memoryless right and stateless uh status do I work but memoryless right meaning that you know everything you have or everything you want to know about a sub problem is already given to you by the input right like the input uniquely defines a situation um and here if you have to know the last case songs that is not very terrible right because K could be a hundred then you have to like have an array of 100 and then that state is like n to the K or some something ridiculous but uh it gets exponential in terms of the possibilities of last case so we have to think about in other way to think about it um and for me uh for me I think the only like well the only two Dimensions other than K if you want to call that I don't even know okay it's a dimension but the only two other Fame right which is um which is the end part the number of songs and we have to try to think about you know maybe do one song at a time right like instead of thinking about you know each slide on the playlist um instead of thing thinking for a playlist each slide at a time we think about the order numbers at a time right uh I don't know right now I still don't have the full definition yet to be honest just to be clear like I'm not trying to uh I'm still kind of working it out on my head but basically let's say you have five songs as a goal is equal to five and N is equal to say also uh yeah essay let's say go is 15 and then n is five right then we want to say okay where do we put all the ones it could be here and then we just kind of skip and you know and someone like that so right no maybe not that but and you know factors given K so we have to figure out I think that's the way that I would think about approaching it but I have to figure it's not easy um the key thing to note is that every song has to be um every song has to be picked once so that's a thing uh this one's hard so hmm let me think about it yeah so basically the um there are a couple of ways to think about this that's why I'm trying to think which one way makes more sense combatorically uh it I mean we definitely want to do this kind of thing but then the thing I'm thinking about is do we pick the first number or do we get to pick skipping and is that easy meaning that here we choose the first number as a one or is it mixed and then we Brute Force enumerate all the other order whatever all the first numbers or is it does it make more sense to kind of um skip to like did it like where the first number is undefined necessarily and then do it this way right and it's not immediately clear to me which way is um easier without you know we uh double counting and all this other stuff so um so yeah so for me I don't know okay maybe I think I'm gonna do it this way where I enumerate the first part because then now we first because the reason why is this way is hard to uh enforce that every song has to pick once at least in my current frame of mind and I don't know that's true but um so we'll do something like this so then now we have to put first the first song um because then now sorry friends I usually do these live or I always do this live as you can see but I'm trying to think about this one because this one is uh yeah so and if you're watching at home definitely feel free to fast forward or whatever you need to do to you know efficiently used your time but right now I'm thinking through it and maybe I should have been uh I just woke up so maybe I should have warmed up my brain a little bit first didn't expect a hard problem but okay what does that look like when before the first one right um I mean that would look like something like this um there's something like okay so we have total zero that's how we restructure it generally um and then we might have some like but then what is this other part um okay so then well we have to choose the thing where this the current elevation is the only once or so minus one enough minus one maybe um yeah I mean that one hopefully this one makes sense it's just we put in the first song otherwise we have to put a song I and then this is so awkward um and then the idea here is that I mean so here we the first okay so then the idea here is that um sure I'm sorry I'm trying to think about it that idea is true before rephrasing it but the thing that I'm trying to do is that we're trying to skip case slots before going so it should be something like this but it feels the way that I'm writing this is a little awkward for sure um and also now this one doesn't make sense actually I think this one makes sense when left minus one for this is brute forcing the first possible song but then now I'm not doing the recursion quite right also this I don't think this is I this is song minus one um and of course if you come with that then this means that we don't really need to maybe like this or something like that right um but I'm trying to think okay so then now how do you select possibly with the other ones so it's this past the number of uh I'm gonna say someone like this but that's not even quite right because that ignoring the off by one uh aside because I'm just my head stuck you now you're able to skip some stuff right huh and this one is hot I feel like I'm in um but the thing that I'm trying to think is that okay um let's say we and maybe I'm doing this really weird but let's say the first um song is one then now given K we were forced to block off these things and that's how we get the suffix right but um I mean alternatively maybe we can't do the skip thing okay maybe this is not the way I want to do it okay let's say then now we have at uh goes right and then now maybe we put first the first where to put the first song and then yeah I think the tricky part with what I want to do is that we have to put the song at least once right you can't just skip the song um so you have to kind of enforce that and that is a little bit tricky Maybe um but maybe I could just write I was trying to avoid this but sometimes like this maybe you have to uh or you can um like two functions right uh and stuff try to put everything in one function uh and yeah the way that I would think about that is so this is maybe the function where um we need to put song at least once man so then now we're trying to think of the first slide right count uh naming things is hard uh including maybe right then now we maybe we Brute Force where to put the one for the first one and we have to do it right so then now for I and range of uh there's only left songs so yeah it's just rare to put the first one and then now we do count um not including so the oh is that the server this oh yeah that's right basic now if you play in the first slide it you're blocking out the first slide minus uh or the first the so you have left minus one is the number three starts but then you also lose K minus 1 because that's the Gap right or just minus k sorry yeah so it's something like this right and then here this is optional meaning that we same idea for count including but we're not forced to pick this song Maybe and just to be clear I don't know that I'm going the right direction uh so uh but you know you're looking at someone who is actually working on this one that helps basically okay we have left so then now we're saying okay pick on the Zero um the same thing or not right so just the same idea um we have to make sure that this is uh yeah with left is zero to zero then we just return left is less than zero then we turn uh zero otherwise if left is zeros zero then if song is equal to zero then we'll return one otherwise we'll be times zero because we have songs left so it's not a valid playlist um yeah okay this is not sufficient right so this is um so then we also want to add it to do an add or multiply hmm account including a song minus one so now we pick a different song um off left and yeah and I don't know that I'm so not confident about this is a look this is wrong for sure I'll explain why in a second this is wrong because I'm here with skipping like here we're skipping right so we cannot like we put in the gaps and here we don't use the gaps um so that's not quite right is it maybe something like this and even that's not right because now you're trying to make sure that you're counting all the lefts right so this idea I think is just wrong um yeah this idea is wrong because we're not we're stopping these are two as in two states but we're not doing it quite well because um because basically we're not you know like this podcast and used up like four uh songs on the playlist and this plug would know about it I think maybe the trouble I'm having is that I'm missing a dimension I'm trying to do it this way but if I have a dimensional what um so maybe the extra Dimension is that we need a position or someone like this where position is the current position to insert someone like that all right what does that mean if that's the case I don't know that this is um I don't know that this is good either but man this one's hard I feel like I another one um I don't know that makes sense maybe I have to think about it backwards Let me let me think about it for a second let's say uh okay so let's say we have one song and go as you go to one then we'll talk um and then if go is two and we have one song what does that look like no I'm just trying to get an understanding of it goes two you have one song so it just throws it out but uh so maybe that is one base case but is that good enough Okay so um okay let me think I get it ah geez I think instead of this um because I think I fooled myself a little bit I think I was thinking of another problem where you have to do something like this and it makes it really hard um I because I basically have my collection that this Farm was hard and I think I just kind of psyched myself into it uh let's go back a little bit of um okay let's say we have you know what's the first yeah okay I got it uh I'll be some respect 26 minutes all right let's say uh yeah so okay so that's the first song by definition will be the first song there really is no um like what purpose whatever song you pick it's gonna be number one right so without loss of generalization um yeah it's just gonna be all one and then the second song it could be either one or one two for a new song so basically I think now I'm uh okay so then basically um when you have a new position you ask do I want to choose a song from the previous um so we have two choices we rather choose a new song or a song that we have seen but not in the last K uh slots because okay because the definition here is that the last K slots um are gonna be distinct right I think that's the observation that I kind of missed in my building this DP and it's kind of hard um is that the last case slots on the playlist will be distinct so this allows you to kind of not remember the last K as long as you kind of do it intelligently um and okay so then here the idea is that okay well then here we start with zero songs on the previous okay so here uh this is hard so song is the number the total number of songs we've seen or listened to so far and love is the number of songs we have to populate left right and then here so we have two choices right we either more than two choices so okay here we go we pick a new song right um if possible basically if um if some plus one is less than n or is it less than or equal to yeah let's just do this for now maybe I'm off by one right then we pick the new song and then and this means that we have a new song that we've listened to so far and left minus one right um okay we pick a song with a very listen to oh and here we pick a new song this is a new song but we have n minus song or something or maybe something plus one to choose from right uh so it's gonna be something like this um so it came in zero you have all n so I think this is right maybe it's off by one but um so yeah otherwise if some minus K is greater than maybe greater than zero okay basically here we have to pick a song we listened to but not the last K songs right because then otherwise you repeat so yeah so we have um so minus k I guess greater than zero because otherwise if this is zero then and um times count of just the number of songs we haven't changed and then left minus one I guess that's good this is so hard to come up with if this is even right up uh I didn't do the memorization point but um oh I have a base case okay so if left as you go zero um then if some if we had played all the songs at least once then we return one otherwise we'll Return to Zero uh okay yeah I mean that's pretty much it uh I mean we're gonna do the memorization part for sure um this took a while and I think I kind of had a light bulb but like light bulb moment I'm like oh wait I could just kind of uh this observation was the point that I kind of um ignored even though that's you know that I thought about it very briefly but I don't know what to say about this one other than that I kind of wasted like 20 minutes of your time so but uh yeah all right let's do the memorization uh well song can obviously go from zero to n inclusive uh and go um oh sorry left can go from zero to go so yeah so we can say you know uh has cash as usual uh I do get cautioned as to why I write it like this I think it's just easier to see the your space and time allocation um feel free to if you feel like you already know what you're doing uh feel free to write it however you like uh and if you kind of see my contest code you know that I write them in some particular ways anyway but so this is just for teaching purposes yeah uh give a submit this is a hard one yeah and I this is so hard that like it's been like four years and I still have a wake recollection of this one and I did this a different way last time I guess I mean it's the same idea though but maybe I just count down and stuff coming up or something do I even use shoes no I end up not using this I thought that I could probably do it that's why that code looks and this code looks infusing but yeah um this one is a very hard one for sure I think it's just about yeah I mean I think to be honest these things um I mean I said this on the last Q4 on the bi-weekly um for me how I came to this is because I just ran out of possibilities right like if it wasn't someone like this then I would have no idea what to do uh I think that's made the honest uh answer um so I'm just trying a little in my head I'm just trying everything right and we kind of talked about all the possibilities not all the possibilities but the possibilities I was considering and how do you solve this um the idea is just me thinking okay if this is the case can the other stuff you know kind of match up and make sense right meaning what I said right like I was trying okay what if we just you know who first the first number and then kind of count the number of gaps and something like this right um and then maybe you know doing some weird way of counting you know with gaps and stuff like that I was trying that for a while okay I even talked about how to prove first the before saying the first number but I think one the thing that I kind of um well two things that I didn't really uh take advantage of as I said is that uh oh no the last case down the playlist is distinct so that actually makes it so that we don't have to worry about State as much because we don't have to care about Rich songs that we did in the last K just not any song on the last K which allow us to reduce um the thing to this thing right yeah I do Wonder because I think the other part I was a little bit um thing is kind of mixing this the items into the same item uh meaning you know picking a new song and then just be like okay this is numb song that we've seen versus uh if we have like the last song is three or something like this um can we kind of simplify it that way or something right and that requires the state that we talked about which is making so tricky is that in this way by so this is one distinction but the other thing is also that um foreign you can treat all songs or you have to in fact as you know same not the same item that's not quite the right way to say but like the same um like the same as in that yeah I don't know how to say it uh I don't know that I'm gonna take it but you basically have to treat this other song the same in the way that you know they're like almost interchangeable in a way versus you know um because I think the idea that I was thinking of is okay maybe like you can think about song and love and then maybe the last thing that we insert or something like this right and then you know the last song is the song one song Two song three and I think the thing I'm trying to say is that I think I have this idea of okay well now you have n songs let's label them one two three four five n and then now let's put one of them into the first one and so forth but the actual and but if we had to say something like okay the first song is one and then the first song is two first one is three dot um and actually for the K component uh this Cave Part we have to think about well what's the last K until we could use the three again um instead of this other thing where we have to treat them like I wouldn't say the same but like I said uh in a weird interchangeable way so that okay well look this there's one song that we played before but um but it could be any of the end songs right which is kind of a that's a tough Dimension to figure out and uh something that I don't know maybe just get with more experience but I think it's like a you have to have a strong deep understanding of dynamic programming and then kind of thinking because this is almost like a derived Dimension versus like a more direct dimension on the constraints that they give you this is almost like uh a dimension board out of looking at the constraints and the observations of the problem and then creating a dimension of thin air almost right which is kind of uh just hard all right uh it's been long that's all I have I need to get some food and all this stupid stuff so yeah stay good stay healthy to good mental health I'll see y'all later take care bye
|
Number of Music Playlists
|
uncommon-words-from-two-sentences
|
Your music player contains `n` different songs. You want to listen to `goal` songs (not necessarily different) during your trip. To avoid boredom, you will create a playlist so that:
* Every song is played **at least once**.
* A song can only be played again only if `k` other songs have been played.
Given `n`, `goal`, and `k`, return _the number of possible playlists that you can create_. Since the answer can be very large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** n = 3, goal = 3, k = 1
**Output:** 6
**Explanation:** There are 6 possible playlists: \[1, 2, 3\], \[1, 3, 2\], \[2, 1, 3\], \[2, 3, 1\], \[3, 1, 2\], and \[3, 2, 1\].
**Example 2:**
**Input:** n = 2, goal = 3, k = 0
**Output:** 6
**Explanation:** There are 6 possible playlists: \[1, 1, 2\], \[1, 2, 1\], \[2, 1, 1\], \[2, 2, 1\], \[2, 1, 2\], and \[1, 2, 2\].
**Example 3:**
**Input:** n = 2, goal = 3, k = 1
**Output:** 2
**Explanation:** There are 2 possible playlists: \[1, 2, 1\] and \[2, 1, 2\].
**Constraints:**
* `0 <= k < n <= goal <= 100`
| null |
Hash Table,String
|
Easy
|
2190
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.