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
395
hello gas field under consideration for subscribing character subscribe and subscribe this Video subscribe button video tenders 59 click the absolute subscribe button city pin code will also subscribe modification in president appointed election subscribe and subscribe Video subscribe and width shrubs And - Video subscribe and width shrubs And - Video subscribe and width shrubs And - Da Indian Isse Z2 Subscribe And Lies Between subscribe and subscribe the Video then subscribe to the Page That Frill Is That Album Acid Add E Will Convert String Into Indirect Taxes In More Staff Against A Length Of The Day Who Is The And - Start So That The And - Start So That The And - Start So That this remedy of fuel must be subscribed to that Twitter account from phone number Right way will find the forest Invalid value Effigy of votes will start again soon Middle-aged youth Subscribe to that Sindhi's checkup poverty To fold Next point Oil oo will find value addition Meantime hai tits latin ke soogi ki in the exact point split string find the value of aaj tak children adh ka disrespect mithila will be that me quickly and that find any invalid value plans in a video will be easy and - just near vid oo value plans in a video will be easy and - just near vid oo value plans in a video will be easy and - just near vid oo Pimples Ko The Software's Title Track Related Code To Crisis Time Find Gambhir And Subscribe
Longest Substring with At Least K Repeating Characters
longest-substring-with-at-least-k-repeating-characters
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`. **Example 1:** **Input:** s = "aaabb ", k = 3 **Output:** 3 **Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times. **Example 2:** **Input:** s = "ababbc ", k = 2 **Output:** 5 **Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times. **Constraints:** * `1 <= s.length <= 104` * `s` consists of only lowercase English letters. * `1 <= k <= 105`
null
Hash Table,String,Divide and Conquer,Sliding Window
Medium
2140,2209
1,758
hello guys and welcome back to lead Logics this is the minimum changes to make an alternating binary string problem from lead code this is a lead code easy and the number for this is 1758 so we are given with a string in the problem there's a string s consisting of only characters zero and one that is it is a binary string and in one operations we can change either the 0o to one or the 1 to zero and uh we have to make the string alternative and what uh alternating string is uh like if it starts with 0o so it should be in this sequence 0 1 and if it starts with 1 then it should be 1 0 so no two consecutive characters should be same so that is what we have to make out of the string and we have to tell the number of operations needed to make the string alternating and in one operation we can only perform a single character to 0 to one and 1 to zero so let's see through an example suppose we have 0 1 0 so if we change the last character to one the string becomes alternating yes so this is a possible answer and uh this is the actual solution so let's see how we are going to do so what we are going to do is that we are going to consider two cases once when the input string is starting with zero and second when the input string is starting with one so if the input string is starting with zero we'll count the number of possible flips that we need to make and if the count starts with one uh that means the character starts with one we'll count the number of flips in that case and whichever is minimum we can return that so for this example 0 1 0 uh we have initialized the count of zero with uh we will be initializing count one starting with 0 and count two that will be for the string starting with one as one because the string start the string starts with zero so we need to flip this bit also if we want to start with one so that's why we have initialized with one and count one is zero because this is already zero so we need not flip it so okay so this is the initializing of the counts now let's Loop through the characters now for character one uh for starting with zero we need not to flip because after zero comes one and this is the uh correct character that should be come coming after that but for starting with one so if it starts with one so the next character is also one so we need to flip this also so the count two will be added by one so it becomes two now at index two we have already have zero and for starting with zero again we need not to flip it because the string is becoming 010 so the count one remains same zero and for starting with one we need to flip it again because we have 1 zero and it should be one and it is zero so we have flipped that also so the count becomes three now for the last character for the string starting with zero we need to flip it because it will be 0 1 and it is zero and it should be one so we have count incremented count one becomes one and there is no need to flip uh this zero for string starting with one because uh the string is becoming 1 0 so that's why we need not flip it and the count becomes count two becomes three count one is one as already told starting with zero it will be in one operation starting with one it will be in three operations so we have to return the minimum out of these and with and we have returned the minimum that is one will return one and this is the possible answer and this is how we are going to solve this so let's come to the code section but before that do like the video share it with your friends and subscribe to the channel if you're new to the channel so first of all we'll be taking the starting character so character at index Z 0 = to character so character at index Z 0 = to character so character at index Z 0 = to S do car at zero okay we have taken character at the zero index now we'll take the count one we'll make a custom function now we have to invert the starting character so if starting character was equal to0 then we need to give one otherwise we need to give a zero and we have to do a plus one and return the minimum out of this so now it's the time to write the count function to count equal to Z now we'll iterate from the I = to 1 to the length of from the I = to 1 to the length of from the I = to 1 to the length of the string now with the current equal to the pre that means we need to do the count Plus+ that means we need to do the count Plus+ that means we need to do the count Plus+ because it is that case where we need to flip so the count is done plus otherwise and C of pre will be also changing in this case C of pre is becoming C of three if it was Zero then it will become one otherwise it will become zero okay else part is complete now here we need not to flip so the C PR will simply become the current and then the account let's try to run it for the sample test cases the thing run finds for the sample test cases let's run for the hidden test cases as well so passes the good time complexity the time complexity for this solution is O of n where n is the length of the input string and the space complexity is constant here so the space complexity is O of one as we are using a constant amount of space you can see and uh you can also check my C++ Python and JavaScript code by going C++ Python and JavaScript code by going C++ Python and JavaScript code by going into the solutions panel and uh maybe you can get my solution this is my solution so you can go here watch this it consist of the explanation intuition approach complexity the Java code C++ approach complexity the Java code C++ approach complexity the Java code C++ code python code JavaScript code and yes aitt to Upward me so I hope you upward me thank you for watching the video please do like the video share it with your friends and subscribe to the channel if you're new to the channel thank you have a nice day
Minimum Changes To Make Alternating Binary String
distribute-repeating-integers
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not. Return _the **minimum** number of operations needed to make_ `s` _alternating_. **Example 1:** **Input:** s = "0100 " **Output:** 1 **Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating. **Example 2:** **Input:** s = "10 " **Output:** 0 **Explanation:** s is already alternating. **Example 3:** **Input:** s = "1111 " **Output:** 2 **Explanation:** You need two operations to reach "0101 " or "1010 ". **Constraints:** * `1 <= s.length <= 104` * `s[i]` is either `'0'` or `'1'`.
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
null
566
welcome to july's leeco challenge this problem is called reshape the matrix you can see i've missed a bunch of problems last week so i apologize for that i'll be trying to catch up throughout the month all right so in matlab there is a handy function called reshape which i'm well aware of which can reshape an m times n matrix into a new one with a different size r times c keeping the original data you are given an m times n matrix and two integers r and c representing the row and column numbers of the wanted reshaped matrix now the reshaped matrix should be filled with all the elements of the original matrix in the same row traversing order as they were so that's just roll to column 1 2 3 4 in that order now if the shape reshape operation is possible and legal output the new reshaped matrix otherwise output the original matrix so it's possible we're given rows and columns that don't make sense for instance two and four we're not going to be able to reshape this matrix into a two by four matrix because we don't have enough data all right so they give you a bunch of hints here but before we do that i think as soon as you see the problem um you can kind of see probably the easiest way would be to flatten our original matrix and this re traverse that and put into a new shaped array so let's not over complicate it let's just try to see if that's possible first thing we'll do is get the n and m which is the length of the matrix 0 and length of matrix here now the first thing i want to do is check to see if this is even possible so if n times m does not equal t that means this isn't even possible so just return the matrix immediately now if this is possible let's first initialize a temporary array here our output which is just going to be for blank in range of let's see this would be columns and we want these for blank and range of the rows so this will be our output but how do we populate this with our original matrix well um that's going to be hard so why don't we just flatten it by putting into a temporary array first that would be the easiest way so what we'll do is say four let's see our original matrix i in range of m and for j in range of n let's just add to our temporary array the matrix i and j right here so once we have that actually makes it pretty easy you can just say have a counter here and say 4 let's see i and range of our new matrix shape should be what rows for j and range of c and then we are going to add to our output i j but we need to take it from our temporary array here so this would be k and each time we do this we're going to increase our k by one finally we turn our output and that should be it let's see here if this works looks like it does so there we go that gets accepted this is a n times m solution we do use n times m space because of our output but this is two passes right and we do use some memory here there is a clever way that you could avoid doing this and they give you the formula right here what we can do is take our count and then divide it by the columns and that's going to allow us to do this in one pass what i mean is let's get rid of this and instead of traversing like this here what we can do is take our k we're going to let's see divided by the column and we're going to take our k and do a modular by the columns this will actually be end i'm sorry m times n matrix i j so this would be one pass it's still the same time complexity but let's see if this works oh okay so k is basically the total count of cells okay it looks like it's working so submit it and there we go so that's slightly faster but really both approaches should work this i feel like it's a you know one of those formulas that if you aren't aware of i think it'd be hard to come up with but if you do come up with it that's awesome good job so all right okay well thanks for watching my channel remember do not trust me i know nothing
Reshape the Matrix
reshape-the-matrix
In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data. You are given an `m x n` matrix `mat` and two integers `r` and `c` representing the number of rows and the number of columns of the wanted reshaped matrix. The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were. If the `reshape` operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. **Example 1:** **Input:** mat = \[\[1,2\],\[3,4\]\], r = 1, c = 4 **Output:** \[\[1,2,3,4\]\] **Example 2:** **Input:** mat = \[\[1,2\],\[3,4\]\], r = 2, c = 4 **Output:** \[\[1,2\],\[3,4\]\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 100` * `-1000 <= mat[i][j] <= 1000` * `1 <= r, c <= 300`
Do you know how 2d matrix is stored in 1d memory? Try to map 2-dimensions into one. M[i][j]=M[n*i+j] , where n is the number of cols. This is the one way of converting 2-d indices into one 1-d index. Now, how will you convert 1-d index into 2-d indices? Try to use division and modulus to convert 1-d index into 2-d indices. M[i] => M[i/n][i%n] Will it result in right mapping? Take some example and check this formula.
Array,Matrix,Simulation
Easy
2132
887
hey what's up guys this is chung here so today uh let's take a look at this called problem number 887 super act drop so this one is a very classic you know problem you know in terms of dp so basically you're given like a kx and then you're given like building floors with n floor from one to n right so i mean each act is identical right i mean basically the each egg all the eggs have the same hardness right and then if an act breaks right and then you cannot use it again so and our goal is to use this kind of kx to find out this there's a floor f right uh such that you know any ag dropped at either floor higher than f will break and any egg dropped at or below floor f will not break and basically on each move you can take a ag and drop at any floor and our goal is to find the this f and with the minimum number of jobs and this f is unknown it could be at uh at floor zero or it could be at floor end right so but we want to make sure the minimum number of moves that we need to make so that we can find that f right so which means that you know since the f is unknown so when we try to find this uh doing our algorithm we should always assume the worst case scenario right then that's going to be a certainty right so with this certainty it means that we always need to con assume the worst case scenario so we have some examples here but this thing are not very useful you know so to solve this problem you know so we need to i think first thing first we need to some somehow understanding understand how this thing works right so let's say uh i think it's a good idea to start with some base cases let's say we only have one ad right if we only have one egg and we have n floor right we have n floors how can we find the f this floor right this floor f within these n floors given like only one egg and assuming the worst case scenario right since we only have one egg so the only way we can find this f is to try to drop this egg from the first floor to the dense floor right so which means that you know if at the once basically we have to drop it from the lowest floor to the highest floor so that we can make sure we can find that floor right i mean this is one eye because you know let's say this f equals to 20 right assuming this n is 30 right it's 30 f is 20. so if we try to drop it from the floor one the first floor and then we try it from 21 to 3 until 20 right and then when we drop again at 21 right this act breaks right and then we know 20 will be our final answer right so that's so basically that's going to be the scenarios right the base case right assuming we only have one x left right so which means that you know the moves we need with one egg to find the uh at the floor in the n floor will be equals to n right assuming the worst case scenario right we're assuming the f is equal to 30 in this case right then we need 30 drops to find this n here so that's the very basic case right but how about if we have two x right so you what if we have two so i mean for two for these two x we have one that we can drop at any location right because you know let's say we have 2x basically let's say we pick case floor to drop the first act right if we pick the case floor to drop the k the first ag right so we have basically we have two options here right either the x bricks or didn't break okay so if the act breaks at the kth floor so what does it mean it means that the uh the f right the f is in a 1 to k minus 1 right if it's in one uh one to k minus one okay and then what's gonna left so if you guys remember so now we only have one x left because this the current the first act breaks broke right so then we only have one egg so with one egg with this one uh k minus one floor how many moves we need right we need the k minus one move in this case right okay so the second case is that you know what if the uh the act didn't break right so if that didn't break it means that you know the uh the x are in the uh i'm sorry not x the f is in what i've this india uh k plus one to two n right assuming we have an ends flowing in total right then this one also this one needs how many moves this one needs basically it needs uh n minus k minus one right assuming that we only have one uh one x left so which means that we will need to use that one act to check k plus one to n floor right so for that one we also have to drop this x from k plus one plus k plus two until n that's going to be a total uh moves right we need to check for the case of didn't break and since we're assuming we want to make sure we have we can find the f here so which means that we will basically do a maximum of the bricks i'll use the b and then not and not break amount those two thing here right because the bricks we have one moves we need to make and the b this didn't break we have an another one another move we need to make and since we need to assume the worst case scenario that's why we're gonna do uh the maximum uh of this of the brick and not break right and since we are choosing this case floor right assuming we are like let's say assuming we have an ins floor right we want to check basically we can choose this k to sk uh become to 1 to n right we can choose any floors so that we can have like either brick or not brick values and among all these kind of case uh scenarios we want to get the minimum of those two right of doing k equals to 1 to n that's basically gonna be our strategy to calculate the uh this minimum basically it's like a max of max a minimum of maximum values here right so and this is i'm only assuming uh trying to uh emulate the two x cases right so let's try to generalize the uh these things with like uh kx right so similarly at the 2x here right let's assume assuming we have dp uh dpr k and n right so this thing dpkn means that with k with kx and with kx to and we have n floors we want to check the number of floors right the number of floors we want to check what's going to be the minimum numbers of moves that uh that we are with that we can find this is this f with certainty right so like i said so this thing is going to be the minimum of the uh the dp of uh maximum okay maximum of dp let's assume we pick uh we pick the uh big floor we already have k n let's say we pick floor m we pick amps floor to drop the case act right so if the if this uh if this amp if this case broke at this amps floor then we have dp uh we have k minus one uh x left and then how many floors we need to track m minus one right because if it brokes then we know the f belong is within this n minus one uh floors right and then if the if this uh act didn't break right we're gonna have like what we can we need to check the k we have case at x left and then the floor number will be n minus m right and then we also need to do a plot plus one because this one means that you know the current drop right it's going to be 1. so for so this part is kind of easy to understand but the second part right actually so this one n minus 1 means that you know from m plus one to n basically this is going to be the total floors we want to check here since the uh since we're only considering the numbers of floors we want to check here so we don't care if it's a lower floor or a higher floors so in it will be the same right when it comes to these dp definitions because the definition of dp means that with this number of floors with this case number of x right so we should have the same result um yeah so i think that's going to be the uh the first the very first approach here okay and so let's try to code that things right so this dp here right i mean since we're getting the minimum so i'll be initialize that everything with some system max size and then the uh so we have a n plus one right and then for this thing in range uh k plus one okay so i think there are like some uh base cases we need to check we need to set so let's say there if with zero x when k is equal to zero right when k is equal to zero with zero x how many floors we can check of course is zero right so which means that in range uh and in range of uh n plus one i'm using this uh this one in here um so we're gonna have dp zero right uh n right equals to zero this one this thing means that with zero x there of course we can check zero floors right and then how about another base case that i think since uh that we have already covered is the we have one hack right so if we want have one act and we want to check each floor the moves we need to make is n like i said because we need to check from the lowest floor to the highest floor which is exactly the number of n okay so that's the first corner case and second corner case is that basically if the uh um if we have zero floors right i mean that's obviously uh k plus one right if we have zero floors of course that's going to be another zero right because we need zero moves k of zero right and then it is also zero then the rest will be then let's try to implement the main logic so we have range in k in range of 2 plus k plus 1 right because we have already a preset case for zero in one case right and then for each of the uh for each of the x right and then we also need to enumerate all the range all the ends right from one to m plus one okay basically given like a k a case at an nth floor we want to make we want to choose like a floor right between one two to n to try basically to drop this case at okay so that you know when we have like this k n is going to be the like i said minimum of the dp of kn right kn then the uh so first one is the one we need to do a plus one because that's the current move right to drop the case act and then we have two scenarios the first one is the act broke right so if it broke we have k minus one act left and then we need to go to m minus one uh floor to check because like i said we know the f will be in that range okay and another one is that you know if the act didn't break then we know we have first we have still have case act left and then the uh the floors that's left is going to be n minus m right that's going to be the other part of this force and in the end we can simply return the dp of k and then right so it means that you know that's going to be the final queries for us so run the code accept it yeah so i mean the in term in terms of logic this thing works but as you guys can see a tle right because uh given like this kind of uh no the constraints right so the time complexity for this one as you guys can see it's like it's what is k times n square right so with the with this kind of constraints this thing obviously it'll tle yeah so how can we improve that um so the way to improve that you know we have to basically look at this part so we so when we when you look at this one so we want to minimize the we want to minimize for each of the k and n right we want to minimize this max value the max between those two right so what does it mean it means that uh we want to make sure this these two values are as close as possible because you know let's say if we have if you have one nine right so the max of this two well of course we'll be we'll will be nine right i mean but if we have five and five then the max value of this one will become to five right so that's how we get the minimum right and so with this m here right so as you guys can see so the first one is in the amp so if the am is increasing right so if m is increasing the first part is also increasing right because the bigger amp the bigger the m is the bigger the value this one is because the amp is on the uh it's in the is in the positive side but for this one i mean the bigger the m is the smaller the value is because the m is the negative m right so since we have this kind of monotonical uh like increasing and decreasing we can use the binary search to help us to improve this uh this for loop into a log end time so how can we do it right so assuming let's we have the let's say we have this one right we have this one is like the uh dp right dp of k minus 1 m minus 1 right and we have another one which is the uh this one right this one is dp uh k and minor and minus m right so what we are trying to so basically the this one is it's a break it's a brick case right this one is a not brick case okay so what we're trying to find is that we're trying to find like ideally we want to try to find like uh if there's like in intersection between those two values right between those two lines otherwise we want to find like an m right we won't find the m doesn't give us the uh those two values as close as possible right so it could be somewhere here and it could be some somewhere here right that's basically that's going to be our approach here so and which means that we can try to find the m that you know and okay we can use a binary search you know if the break is smaller if the brick is smaller uh then the not break values right basically we're gonna uh increase the amp right which means that we're gonna move our left pointer equals to m middle m plot plus one else the right pointer will be m so that in the end we can simply use the uh the either left or right pointers to update the dp of k and n okay so i would i'll try to implement that one you know maybe i'll try to explain a little bit more here while i'm implementing it so instead of using the four uh for loop here right we can do a binary search so we have l equals to one and right equals to n right that's going to be our search base like i said the wow l is smaller than l and then we have middle the middle will be the l plus l r minus left right minus left divided by two and we have break and not break so the breaker would be the uh k minus one and then we have a middle minus one right and then not break will be the dp of k uh n minus middle right basically if the b is smaller then smaller than not the not break right and then we'll do an l equals to middle plus one oh sorry middle plus one yeah else we do a r equals to middle and then in the end we can simply do this dp of k the k n right becomes the middle minimum of the dp k and max dp k minus 1 l minus 1. since we have find the optimal uh indexes or the optimal m right uh either with uh equals either r l or r so that we can use that one to populate that in the end uh that's the break and the not break is a dp of k and then n minus l right so of course we also need to do a one plus this thing right this can be this yeah so basically this will give us the same result i mean if i run it uh but you know i just want to point this out here you know as you guys can see here you know basically we're trying to find out the first uh m where the uh where the brick value is not smaller than the uh then the not break values right but i think this is not a hundred percent accurate because you know since these two lines right so this brick and not break right so this is a brick right this is the not break since these two lines are not continuous so there's some like these discrete like values uh among those things your among the lines here because the i'm could the first item could be here second one could be here there could be no like intersections uh with this uh two lines here maybe the next one could be somewhere here right if that's the case but our logic here you know it finds the first uh m right the first item that's you know the brick is not smaller than the uh than the not break so we have could have m1 m2 and i'm m3 here so we're at m2 here you know the break is still smaller than the then the not break right but the next one right the next one could be this could be here in this case you know the brick will be greater than the then not brick and this is the one we're using here but i think to make this algorithm uh more accurate enough after getting this out here right i think it's say it's i think it's we also need to check use the l minus one to check to compare with this two basically i think we need to use two values to set this uh dp kn here because so the first one the first l is here but we might the l minus one might give us a better a smaller values just in just for example in this case right at here because the uh you know for this one the uh the max value is the uh is here right but for this one the max value is here right that's why you know maybe the previous one can give us a better result so that's i think it's to be more accurate we should use both the l values and l minus one variables to populate this dp k and n right assuming this l is greater than one of course right that's the boundary check um yeah so i think that's the binary search if i run this one you know the uh unfortunately even the binary search one with tle for python solutions as you guys can see now we have uh improved from 5000 if you guys still remember uh with the first solutions it timed out at 5000 but now we can handle seven thousand almost eight thousand but still timed out so the reason being is not reason being because for this kind of pro for this kind of approach the time complexity obviously is k times n times log n right but still with python it's still timed out and but you know i think at this point this one is good enough for most of the people and the remaining of this video is optional to you guys and cool so if we still want to improve this kind of solutions right i mean how can we further improve it i think the way there is a way now that we basically we need to redefine the dp functions here so currently we have dp uh k and n right so the dpk and n means that with k x and n floors when we want to check what's going to be the minimum uh minimum moves we need to make so uh if so the way it works is that we should define like this so this d with dp uh let's say dpi and j okay so dbi and j means that you know with i moves imoves and jx how many floors it can check okay so that's going to be the new definition for our d for the new dp so this thing means that okay so like i like what i just wrote here you know assuming we have ice eye moves and then we have a jx so how many floors we can cover right and whenever the floor is greater whenever the floor is the dp values is greater or equal than the n then the i will be our answer okay so basically we're trying to greedily uh include more floors uh given like the i the ice move and the j's jx and then the moment uh we can cover the entire floors right and then the value the current move will be our final answer so because in that for that reasons we have to loop through the uh the outer loop has to be the uh the moves basically with the moves has to be from one to n right that's the outer loop has to be this one so that we can uh greedily find the uh the answers right from one to n okay so this is kind of that the definitions so what's going to be the state transition functions for this is this definition so dpij let's say we drop this the js ack right so again right so the js to drop this the js act it has two up two scenarios the first one it broke the second one is didn't broke okay so and of course the first one is it's place one plus so now this one means that you know we have already checked the current floor right so remember it's how many floors we want to check so to drop this the json the first one is going to be a wheel since we have already checked the current floor that's the car that's where it's one coming from and then first if the if this by dropping the js act if it's broke and then the we need to go back like similarly we need to go back to what to the uh to the i minus one and then j minus one floors okay right so remember now the dp i dp distance this means that how many floors it can cover with this now since we have already uh used this uh x because it broke right now we have uh the previous step we'll have like j minus one x left and then the step will be i minus one right so that's gonna be the uh the brit the axe got broke case and then the second one is the what is the not broke the broke scenario it's going to be dp of uh i minus 1 and then j right so this one means that uh we have used one moves that's why we have i minus one moves left but we still have like j x left then the question is that how why we can summarize those two together here to get the total floors we can cover right i mean just think about the reason the definition of the cpi and j right since we're trying to define this dpi and j as the basically as many floors as we can cover right even though we have two scenarios right because you know uh if uh basically we have two possibilities here you know the first one is the current axe got broke right but the other side of this scenario is that if it didn't got broke then we can use this the same hack to reach a higher floor right to reach a higher flow means that we need to plus that floor on top of the current one because this one the one plus dpi minus one and j minus one is the floor uh below the current uh below our current floor right and then for the case of the egg didn't broke right and then we need to basically add more floors on top of the current floor because it means that we can check more floors in that scenario right so i mean basically the key idea here is that we you could we can we shouldn't assume uh we cannot always assume uh the ad the mean the x always broke because the again right f is not fixed right so which means that the f could be uh could be here it could be on this uh in this first part but f can also be on the second part right we never know that's why we have to uh concat because basically we have to summarize those kind of two scenarios together so that we can get the total floors we can cover with the vista with eyes moves and then j's jx number of jx yeah so let me try to code that things here so at the beginning so now the definition is has changed so the default will be zero right so we have k plus one x uh in total for this thing in range of n plus one right for i in range of one so k plus one right sorry not k plus n plus one so the outer base the outer space the other loop gonna be the moves right so that at the most we need n moves okay and then the inner loop will be the number of the x we have here right k plus one and then like i said we have dp of i j equals to what equals to dp of i minus of sorry 1 plus dp i minus 1 j minus 1 plus dp of i minus 1 j right so that's going to be the total flow of floors we can cover here all right and then if the dp i and k right it's greater than n and then we return i yeah so because we use the uppercase k here because we want to consider all the case x right for this ice moves and if this thing is greater than then we know this is our answer so if i run the code submit so now finally passed right because as you guys can see now the time complexity becomes to the n times k right which is mass much faster uh b k big k here yeah so actually so here we already covered some of the scenarios here you know basically the corner case will be let's say uh with zero floors right with zero floors and of course you know we could we can uncover zero floors but with uh with zero x uh we also gonna we can also only cover zero uh floors right so that's why uh we don't have to preset this kind of edge cases because we have already initiated everything with zero here yep so i mean i think that's pretty much the uh everything i want to cover here i know for this for the second part you know this one i know it's kind of uh hard to understand so even i spend a lot of time trying to convince my convince myself why we can i use this kind of formula to represent the cp i and j right yeah just try to think about that you know maybe i'll give you another like a very another like fun uh induction for these things let's say we have 2 2x okay 2x and then we have a and floors right so let's say we have two eggs and n floors what's going to be the minimum uh the minimum moves we need to make right so that we can find that f to find f within this n force so since we have two x right so it so the question is that which floor we want to drop the first hack right so how can we find that you know because you know as once we drop that uh once we drop uh choose that floor right and then we can only assume the worst case scenario okay you know but the way it works is that let's say the uh let's say we place which we chose k case floor the case floor uh to drop the first act right and if it didn't break oh sorry if it broke right uh we will have we need to use uh k uh minus zone we need to check the k minus one floor so right plus the current one which is going to be the k value right gonna be the case floor out of that but if it didn't break so what's going to be the next value the next floor we want to pick right uh assuming that we can assume that we have okay i think all right so assuming okay assuming this move is k the minimum number of moves is k right so how can we find this k value so basically the strategy will be what will be the so the first time we will try to drop uh drop the act on the case floor so that you know if this if at case floor the act broke right we still have a k minus one uh moves left and with k minus one moves is guaranteed that we can check k minus one floors that's why we chose this case floor as the first floor to as the first as the floor to drop the first act right and if this act didn't break right so if that didn't break so which will be the next place we want to drop so basically we have k case floor right so now the next floor we want to drop is k plus k my k minus 1 right so and why is that similarly like the previous one let's say at k plus k minus 1 floor right basically here i mean uh i can think of it like a k minus one because since because from here to here i'm increasing k minus one floor that's why the total flow is a k plus k minus 1 because if at this k plus k minus 1 floor it broke right and then we need to check k plus 1 2 to k plus k minus 2 floor so here we have this is a k minus 2. uh floors in total that we need to check and see and this one is exactly to our current remaining moves which is the k minus two so that you know if we pick the if we jump and k minus one floors even though this thing broke we still have enough moves that can cover the range from the k to this k minus one k plus k minus one floor right so again if this thing didn't break and then we'll jump to another one so basically we'll jump to visa k minus two uh floors with the same reason right and then as you guys can see so basically every time we jump uh from case floor we jump uh k minus one and then we jump k minus two until we jump uh to one okay so what's gonna be that re result right so it's gonna be a k plus k minus one plus k minus two plus and until 1 right so what's this what's the distance here it's a 1 plus 2 plus 3 plus k right and then this thing will be the k times k plus 1 divided by 2. so and we want to make sure this one is greater than n then right and that's how can we how we get uh can calculate this k here right and yep so i think with this thing i think it's not that hard to calculate the what is the value for k right actually you know so there's even like more generic version of this formula here you know now we have x is equal to two right so what if we have mx here right so what's going to be this formula so it turns out that the formula will be the m factorial in this case and this will be the formula right so we can use this formula to also find the uh the k values i'm not going to uh to go into details how we get these things but i think that's basically that's how this uh this formula works you know uh cool i think i have talked uh enough discussed enough about this problem so i hope you guys like these videos and i guess i'll just stop here and thank you for watching this video guys stay tuned see you guys soon bye
Super Egg Drop
minimum-cost-to-hire-k-workers
You are given `k` identical eggs and you have access to a building with `n` floors labeled from `1` to `n`. You know that there exists a floor `f` where `0 <= f <= n` such that any egg dropped at a floor **higher** than `f` will **break**, and any egg dropped **at or below** floor `f` will **not break**. Each move, you may take an unbroken egg and drop it from any floor `x` (where `1 <= x <= n`). If the egg breaks, you can no longer use it. However, if the egg does not break, you may **reuse** it in future moves. Return _the **minimum number of moves** that you need to determine **with certainty** what the value of_ `f` is. **Example 1:** **Input:** k = 1, n = 2 **Output:** 2 **Explanation:** Drop the egg from floor 1. If it breaks, we know that f = 0. Otherwise, drop the egg from floor 2. If it breaks, we know that f = 1. If it does not break, then we know f = 2. Hence, we need at minimum 2 moves to determine with certainty what the value of f is. **Example 2:** **Input:** k = 2, n = 6 **Output:** 3 **Example 3:** **Input:** k = 3, n = 14 **Output:** 4 **Constraints:** * `1 <= k <= 100` * `1 <= n <= 104`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
5
Hello friends, welcome to this video, question number five is the list code, the question of the longest platform is the question of all these media, it is the question of rings category, let's start with the longest and subscribe, then let's do the problem statement with the problem statement, I will give you one more and what should you do? You have to subscribe inside this train that it will be the longest and it will be so that you people know what happens and you should know that subscribe and subscribe because there are many people in it, I can quickly tell you the difference, subscribe, whatever you want, subscribe. The steps may be different but we are talking about all these strings which have to be found but it should be in Pentro, you will read it from the front also, you will read it from the back also, the baby name and if you use more than one in this trick. So you may have a long time that you are very big and inside that now the skin which is in all of it, if you have to subscribe to it, then this is our problem statement for example inside all of us and subscribe for example the chief which is yours. You can subscribe from this point because this Question Intuition Subscribe If you have not solved any other question of this type before but if you have solved the question of Longest Common Substring which was a difficult question then you must be getting intuition somewhere. Such that you can dry this question with the same approach, you can do this but it may be a little but in this question I want to discuss with you a very good algorithm which is optimized and its name is Expanded from the Center so this will be our optimized algorithm for this question which we will discuss after brute force and there is another algorithm which I have created which is charas algorithm which you can say is optimized but not interview rated if you have extra time So you can go and read this, so let's start with the brute force solution, you have a string and you want to remind the longest first intro mix, now the first intuition is to subscribe all this, as many for one side as for two. There are as many sizes as there are three sizes, there are as many pipe sizes as there are four sizes, so first we subscribe all of them, then we see which one is there first, then in this way, it is a simple solution and we can subscribe in the loop and add. It is very easy for everyone to do, so you can subscribe to know what is the complexity of this approach, you will not subscribe to the simple solution, you can do this, but now we are going to discuss the election which I have given you in the question. Told that we will discuss from the center in very good quality time and if you have these trick questions then you can like this in it and it is easily applied in the questions in calendars so let us try to understand this algorithm in this. What we will do is let's take an example, there is a big dedication string and inside this we have the first intro mixer, more than one is this string, you will see that in the calendars, it will be read from the front as well, it is the same, we will read it from the back, there is the same and one. And the first trick I took is the string and we have to point to the longest so expect from the center. The algorithm says that you have to look from the center. How to look from the center? For example, if I click any character randomly, for example, the center of G. If we look from this, we will look from the center, look to the left, look at the flashlight, the two characters are not matching, so we know that it is Suzy, she is any of the first intro mix, now the center of the screen is not there, she can be the first mix. The butt is not in the center. If I click on it, I will see that it is being expanded. Its left and right were correctly, so I came to know that the middle one is the center of the first intro mixing, but how much can it be expanded and let's see by friending. If there are more, then we have found the center, after that we will write a function and keep explaining till the work front is done, so basically our intuition is that you have to check from the center and explain as much as you can. Let's start with the first character, so on this we know that there will be no explanation. There is nothing on the left. C and on the right cannot be office dependent. If we come to the seat, then there is no explanation even from C. It is possible that the characters on the left and right are different and as they come to the match, we will come to know that this is what is expected, so we will save its length and finally if we get the first intro of More Than One, then we will get the most. If we want to return the maximum then we can calculate from the length and in the court and you will get a little bit of clear and in the same way if you come add the character and the village is able to pay and we know its length is that. We will check the first line, earlier it was found in the bigger one, so we can subscribe, so this is our very good from the center and very easy, you can do it, so now what we are going to do is a little subscribe number text ring. We are going to do two in this, if we explain then I have to do the center point but you may face a little problem in this, if you consider this one as a center then you will see that the left and right characters are not the same unless this entire string is our first. Intro Maker Now again if we consider the second one as the center then it is not from the electrolyte character then there is confusion here, we cannot consider a single character as the center, till now I had discussed that a single character was considered as the center but we have considered this one. If we do not handle the case, then our Expect from the Center algorithm which we are going to use in this will be we will pass two variables in it, then we will be the one who will speak and will match both of them, after that we will keep doing more, so come today we will I will be different and we will keep on explaining but now we come to expand on the old case so we will do it in this but what did Kasam do in the old one, in this one the center was the same but we will also consider I as this, we will consider this also first one. After checking like this, after expanding, we will make sandals of both of them, but in expanding, our I and J will be different, so we will match even if your center is different, if there is a center frame, then you If you first compare both of them and then explain them, then our code will become a little universal and now let's jump directly, all the confusion you have in the court will be cleared, once this and this time space complexity, now we will after the code. We will discuss, let's start noting that the code is going to be done in Java but the code of all the languages ​​is almost but the code of all the languages ​​is almost but the code of all the languages ​​is almost similar, you can understand it by looking at this code and can quote it in your language, so what we have to do in this algorithm. To check all the characters, I have to go to the center of each character and see how much can be explained, then I write one outside, I have to process all the characters, I can do something like this, plus I will do this, which is me, if it is like this. If any example center is ours and Plus One India which I told, then we will have to pass both of them and check both of them then we will have to do it again but if someone like this because we do not know what is our code then we will do it between the two for romantic. If something like this comes to you, then you will consider it as the center and what I said that on the other side, if our index is going to say J, then our JB will be at the same position, then we will pass I again. Basically, it is okay, so once. When I write, you can understand more, so find it in two lengths, village is one call away, name is given and it is very important to give the name, it is very important to give the right name because there may be some confusion in the coding interview, I will shorten it a bit and We are going to do a spread this from the center and here we will pass that time first and I will pass I plus one. Maybe we have written it wrong, so you have to use this album one more time. And this time we will calculate the length, one function call from each village will give the correct length, the second one will not give us the correct length, then in the second one we will pass it again because the center is our common, first both of them will check it among themselves because both of them have Indic I have explained and in the first case both the checks will be cleared separately then in this it can be something like this that I will go to one, 15 will come then a function is the correct answer about reducing the maximum of both. We have calculated that we will not give the maximum name, I am giving the wrong name, we will have to give the length because both are lengths, so we will calculate the maximum of these two lengths, we will write the length one, we will write it through online, till now we have come to know that first What is the length of the intro mixing but if you have a return type of spring then you will have to put a little mind into it, we can do it in this way, we will hit the start index and end index and we will take all the number of parent mixing that will come, we will just mark this index and The biggest one in the last will be next to the first one so we can cut from our how will we cut in the last you will return the dot substring and I am assuming that you have updated this stars end chart and You will pass the end and you will know that the substring function takes the parameter which is the right parameter, in which you have to pass one more than the index, then you will pass it like this. You can read about the submitting function but here we will focus on start and end. How to update, this is our biggest challenge, so we have to put a little bit of brain into it, first of all, we have the length, so we have to see that end minor start, that if our audio end - start, we if our audio end - start, we if our audio end - start, we have it is short, that loop is short, that means. We will have to update. You have got the big first intro mixing here, so you will update inside this block. If this length is small, then you are already doing end-stop. If you already have a small, then you are already doing end-stop. If you already have a small, then you are already doing end-stop. If you already have a big electronic substring, then you will not update. If the length is small, then end is start. If you update its length to be shorter, then we will update the start and end here. What will be the index of elegant and end? You will have to think a little here, and its calculation will basically come from this tuition, if you solve the question. Your intuition will develop, in which way to take contact, in which way to cut, for example, what will happen in the beginning, your partner is coming behind, okay and in the end, you are going forward, you are stretching, extending. So explain the length etc. Friends, we are going behind and you are also asking for length. If you are going behind then we will make it length-to and half the length-to and half the length-to and half the length if you are going forward then we will land by two. In this we If it is in I position, then we will do the length part plus half of it, we have gone half way and land by two - we will do half of it, if we have gone back, then it is land by two - we will do half of it, if we have gone back, then it is land by two - we will do half of it, if we have gone back, then it is calculated in this way, you can dip it in your chord by writing a print statement here that How the stars and ends are changing is fine, but there is a slight change in it, here we have to do the length minus one, only then your accurate answer will come, I will not discuss this in detail, you can check it by printing a print statement and locking it in this way. Now we are going to calculate the expense from the center. It is a very easy algorithm. We will take its code which is my Heli and at this time it is returning us in length point, we are length. So its return type will be * Ka, this is so we * Ka, this is so we * Ka, this is so we quickly pass the string, first you pass the string here, then you pass the index, one to I am giving and one to our name. Okay, so till when do you want to extend, first you expand, get up, don't know the bond. If you want to keep this in mind, then write a look while extending that your I have greater than CR, till then you can go back - greater than CR, till then you can go back - greater than CR, till then you can go back - if greater than zero, you can go back till it remains the same, do not go back and J is your There should be a string of islands on the left. Okay, if the length of the string is at 10 then there will be no more tax on it and we will add it to this. We have to do it by the way, for how long we have to mix, we have to see if your character is as long as this one. It is becoming one with the character, keep explaining, there is no problem here, keep explaining, I will shift it a little bit, okay, till then keep painting and expanding, so come - - keep doing Z plus, keep doing - - keep doing Z plus, keep doing - - keep doing Z plus, keep doing simple girl have. First of all, don't go to Tobo and I and J are one of ours, so keep explaining. I - If you keep having sex every day, then keep explaining. I - If you keep having sex every day, then keep explaining. I - If you keep having sex every day, then what to return. I have calculated the length of the belt, so first introduce the length of the fitting. How will you return? What will you do, basically you just have to return its boundary, do it - just have to return its boundary, do it - just have to return its boundary, do it - one is how much of our length is there, we are mixing it automatically, here you will get the length, you can do the index fund, you will update the start and end and here we will cut. But stay here, you will have to do minus one, only then the length of your actual substring will come. You can print it and see it. You will develop your intuition for this. If you solve the testing questions, you will automatically understand how this length is returned. And how did we do this start and end, if there is a little confusion in this then all this will be clear then the wife record is complete, let's discuss the time complexity of it, once quickly see whether it is being submitted or not, then submit. It is necessary to have some compilers which will mix us quickly and if it is submitted then it is accepted and then we will also discuss its complexity so you can see, if it is coming then quickly see what mistake has happened to me. I have to write bar code, what mistake have I made, so we have hit the tight end, we have calculated both the lengths, here we are doing it in this way - doing plus, doing this way - doing plus, doing this way - doing plus, doing okay IJ doing okay like - okay IJ doing okay like - okay IJ doing okay like - I plus If you are doing one then there is a small mistake in it that you will have to match this character also and after that as you will come out of your gender then we will not match so the first character which I had ensured then this small mistake. The rest of the pin code is required, let's submit it once more and then you will see that we have successfully submitted and what is the time space complexity of our function. First of all, let's look at this algorithm, expect from the center, its time. Complexity is there, it can be ours, stupid N because we were anchor actors in the entire Total TV, all the crushes are landing, we are subscribers of all the tractors, so there can be so much complexity and we are not offering anything in it and this function is ours. It has been used inside and you will see that which is the main function, in this also you have used that call, if you are processing all the characters once then the complexity of this function will go to the stupid end and inside you have another next function, so your The complexity which will be this will be Vivo Namaskar. In the final complexity I will say Kayan Tower which is our time complexity. Now Scarlett has used express, use some carriers which can be done and nothing is lost in it but if you do not want to do this leaf. Let's see how much space should we generate. If our work is not working then you will have to create it finally. If you take this then your space will be there. The entire string in Big [ __ ] and co-workers entire string in Big [ __ ] and co-workers entire string in Big [ __ ] and co-workers can be in the calendars. You will have to read the entire string from butter, we can ignore it, so this is our time and space complexity, so that's all in this video, we will meet again in the next video, thank you very much for watching this video.
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
344
okay so how's it going ladies and gentlemen so today we are going to solve one of the coolest problem which is reverse string 344 lead code okay so uh i have already made a like i have already posted a video on this problem like few uh like maybe a year ago okay now you asking like why you are putting it back again ah well because like i don't know i want to put it back again it's a easy problem it's a very easy problem so like what happened what was the thing okay so first of all ladies and gentlemen let's just understand like what the problem is saying okay and uh you can say like why i'm re-uploading you can say like why i'm re-uploading you can say like why i'm re-uploading this video because like in that one i have solved this problem like a in my computer but right now we're gonna understand using it pen and paper okay so pen and paper is like old method and all is good believe me okay so uh how what will be our flow to uh in this uh problem so first of all we want to understand what the problem statement is saying then we're gonna talk about its approach and that we're gonna call it so like i will not gonna call it with the code is very simple it's very simple trust me you just check the uh comments uh link in description like the link of this uh code in the description so the code is both available in java and c plus so java and c plus both the codes are available so it is it won't be an issue okay all right let's jump in so let's understand what the problem should be saying so we have given an input something like h e l hello and they have uh like we have to output in the reverse order okay so uh it's very simple like you put an idea okay so that's all the problems to me is it's like something like we give an h e l o and i have to originate something like o in l h and yeah obviously uh this one over here okay all right so i hope so this thing is clear okay so uh what first thing the very uh brute force thing come came in your mind is like uh can we solve this problem uh like using two pointers like for example like if i put my one my i sorry let me rewrite this test case over here so we have given h e l oh okay so guys remember one thing like okay so let's talk about first of all two pointers so a two point is way easier okay so my one of my eye pointer is over here and my one my j pointer is over here okay so what are we gonna do is i'm gonna uh i'm gonna put this value put my i value uh to my j pointer image value two over here something like this okay so for that one like so how it will gonna happen so i will say my uh i value is equal to my j value okay so whatever the j value will become my i value so initially it's also o will come over here or will come over here okay and my j value will become my ten so what is temp is i just created a temporary variable like where uh over where which i'm storing my uh s of i value s of i either index value okay which is h okay so as you're storing over here so it will become my edge over here similarly like this okay then what will happen my ipod will move my j pointer will move so my eye pointer will come over here and my j pointer will come over here okay and similarly what is going to happen my uh s of i my so i become the value of this one so this will be l my l will come over here and my j value will become my s of i value so that will be e okay so that's how okay ladies and gentlemen now similarly what we had after doing this we're gonna uh put it like we're gonna shift them so i will move forward and they will move kind of backwards so this decrementing and i is incrementing all the time so we are going i plus and j minus okay just remember this thing in your mind okay all right so now there they meet or made on the same point so what will happen my i will become my l and my j will become my even l as well so you don't have to share anything okay so now what will happen after this what will happen my i j pointer will come over here my j point will come over here and my eye pointer will come over here so once the once we encounter this thing once we face this thing we want to simply end our loop so that this is a very uh simple approach which is two pointer approach okay two pointers approach and guys code in the description so you don't have to we worry about the code so like this is two pointer and uh you can solve this problem using recursion as well okay that's we're gonna do the same thing indication you know in indication we gonna just worry about over this first swapping we just only our variable first second that's the remaining swapping will be done using our function called okay so we just gonna make our function for every time and stepping will gonna take place okay what's the another approach to solve this problem so uh you can think of stack house tank because stack usually for lifo order so leaf order means last in first out so uh for example like if i create my stack over here and i have my uh hello so hello is written something like over here h e l o so what will happen first of all my uh my h will come in my stack then my e will come in my stack then my l will come in my stack then my another l will come in my stack then my o will come investing once my stack is filled with my once i fill all the characters made mistake then what i will do i will create one another uh answer area for example and this is my answer i will pop them out and put it over here that's how their enjoyment we have to solve this problem so i also this thing is clear like this trust me the code is very easy i'm again saying java nc plus code java and c plus code both are available in the comment section pin linked okay so comment section pending so you don't have to be worried like now you're asking like why i'm not uh showing the code over here because like why you want to see this video away length here trust me the code is very easy you're gonna understand and thank you very much ladies and gentlemen for watching this video i will see you in the next one if you still have any doubt just do let me know i will see in the next one till then take care bye and i love you guys
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
221
hello guys welcome to another video of the series of coding trivia to solve the problem it's called maximal square given an mn2n binary matrix filled with zeros and ones you have to find the largest square containing only once and return its area okay let's try to take an example to understand this question better so we have to find the largest square so let's note the terms first of all it has to be a square okay that means the side length have to be same both the length and width have to be seen okay second thing is it should contain only once okay and you have to find the largest such square which has only once okay let's try to think how we can solve this problem so very brute force approach will be right see what is the minimum square that you can get of size 1 right and after that you can get of size 2 and then you can get of size 3 and so on right so the brute force approach will be list down a square of size 1 right so if you have found one square of size one which is having one then one will be your answer okay for size two you can check all the squares of size two right you can keep on drawing all squares of size two and check if you are able to find a square right of size 2 for example here you have found a square of size 2 which is having all ones so you have satisfied the property so you are satisfying for 2 also ok and then you can try to similarly find for 3 you can find 3 side square when you try to find three side squares in this case right when you list down all the three side squares and you try to see if any of the square contains all once in this case you will fail right so in this case your answer will be failing because you will not be able to find okay then you can try building fourth but there is no need to try building four side squares right oh sorry this will be four sides square there's no need to try building four side square if you cannot find any three side square at all right because if you cannot find a three size square how will you ever find a four side square okay so this sort of gives us a hint into optimal solution see for building three side square you need to have a two sized square consisting of all ones okay and for building two side square you need at least one size squares consisting of all ones if this is satisfied then you can go to the next case if this is satisfied then you can try to build three side squares containing all ones okay so it sort of uh gives us a hint that see if you have found one side square maybe from that you can find two side square how okay let's try to take an example to understand suppose you have okay one size squares right you need to find a two side square which has all ones okay suppose you didn't know the last uh letter was a one or a zero okay suppose you didn't know uh whether it will form a two side square or not you are still seeing it but okay let's say that these three are forming one side square that means all the three are ones right you have three one side square and if this also turns out to be a one that's it voila you have found a two side square okay but if any of this was zero right any of this was zero and even if this was one then in this case your answer will still be maximum you have one size square only because this is not a two side square consisting of only ones okay so this is the trick here see if you find all the three squares which are uh ones right and then your last number also turns out to be a one you have found a two side square which has all ones let's try to take uh example for let's say a bigger example okay let's say for n equal to 3 now you're trying to build again for n equal to 3 okay so in this case suppose here everything is 1 ok till now and suppose you somehow know that everything is one here in this case if you find a one you can change this answer right you can change this answer see if everything is one and this last number is also one in that case what in that case right you know that your maximum answer is now three size square how will you know this right see if we can store here instead of these values see let's try building from the very beginning how do we find a three side square first of all this everything should be one okay but we cannot keep making three sides square and keep checking if everything is one again and again let's do one thing suppose we know first number is one okay we'll let it be one next number is one we let it be one here it is one we let it be one okay now let's say here we know that okay instead of one we will change it to two okay so what do i mean see we have found three squares which are one okay that means we have three one size squares and if this number is also one in the matrix that means we have found a two side square for the first time because this is a two side square so we will let here be two okay now let's come to this square and this square again what do you see that there are two one side square on the top and there is one square which is a two side square like this and there are one size squares like this okay so here the maximum possible is a two side square because see this is a two side square this is this square is also satisfying the answer this is also satisfying that means here everything is one if this number is also one here maximum you can have a two side square okay now let's come to this cell in this cell again you see the top most is having one right topmost is a one size square and here it is a two side square right it's a two side square here it is a one side square so you are looking at all these three cells and you find out that okay what is the minimum of these three values minimum is one right minimum is the constraint so you have a one side square and one plus one is two that means is this at max can be a two side square why this at max can be a two side square because these are squares ending with one right i mean these are one side square only so it will be two here okay now let's take this example then it will be clear so now in this case you see that you have three two sides square this is also two side square this is also a two side square that means what that means these all cells are satisfying your property right that means you have two side squares okay if you have all two side squares surrounding you and if this number also turns out to be one that means you have fulfill the criteria and you have a three side square okay so now this number will become three so that is the logic in this question so from previously stored values you are trying to find out the next values now let's do a dry iron with this example and then it will be perfectly clear so this is the matrix now let me fill the dp matrix which is a so we are using previously stored values to find out the new answer that's why it's a dynamic programming problem let us see one two three four five okay so initially the maximum square that we have is one size square now this is a square that is ending with zero right so in this case you cannot form a square because this is having zero right this is having zero we for in the question we need squares to have only one but if this is zero that means the answer here is also zero there is no zero side square i mean the maximum size square which is ending at this cell is zero size because this is zero you cannot form a square using the cell okay using the cell you cannot form a square which will give us our answer so it is zero okay now let's see this value so again it is one because you have a one side square and for zero it will be zero similarly you can fill the first row and first column filling is very easy whenever you see a one filler one otherwise filler zero okay now let's go to this cell now in this cell c we have to see if see this can either this is very simple if it is a 0 you cannot have a square right with this cell that will satisfy your answer because what is the question itself says that you have to contain only once for your answer square right so if this is a zero it will not form an answer you can simply fill zero okay now let's go to the next cell now this is one here it gets interesting when it is one what do you do see this can be a part this cell can be part of a two side square one side square three square four square but how do you know so to know to get a hint of what this cell can constitute you have to look at these three values okay so when we look at these three values we know that c minimum of this it will be the constraint what is the constraint will be whichever is minimum of these values now you see it has zeros right that means this cell can never be a part of a bigger square like this it can never be a two-sided square it can never be a two-sided square it can never be a two-sided square it can never be a three side square because these are zeros so what do you do when you look at its neighboring cells right when you look at the neighboring db matrix you see the minimum now the minimum is zero okay so but this is one so what it will be this one can form a single square right so the maximum it can form answer it can form is a single one side square so it will be one okay answer will be one here because these are zero so it cannot form any uh any other square larger than one will be the maximum it can form which is itself it cannot be a part of a bigger answer of two sides square because these are zeros so it can clearly not be not form a two side square is the answer okay now let's go to the next cell again we see top is zero right so maximum it can form is one which is the square itself again let's come to this cell again it has a top cell zero so in this case also the maximum is one okay now let's come to this cell for this cell we have already filled the value for row and column it's very easy we have already filled the values let's come to this cell again top is zero right so the maximum answer will be one let's come to this cell now in this cell also you have diagonal zero see so it cannot be a part of a solution of a two side square because in this case the diagonal is 0 right so it cannot form a 2 side square what will be the answer will simply be 1 which is the cell itself ok let's go to the next value now next here it gets interesting okay so for this cell notice that you have three squares okay which are all one that means what now it can be a part of a solution okay let's see if there are any constraints or not there are no constraints right because why are there no constraints because see all its neighbors are satisfying the answer they are saying we are each one size squares so what will it be it will be a two side square it can form a two side square as the answer because these are all one plus one is one sorry one plus one is two so the answer will be two here okay now let's come to this send now this cell is also seeing it at its neighbors are also happy neighbors okay all of them are once all of its neighbors are one so it's also very happy it is saying that its neighbors are good neighbors and it can also form a maximum two side square how do you know maximum is two and not three for it to be at three what if every if all of this would have been two then we could have filled three here okay but what are these are one and two right that means there are constraints which is the minimum among one and two is one that means what that means maximum you are having one side square above that you have zeros right see here you have one square above this you have zero so it cannot form a three side square because here you have zero so maximum here is one okay so here you can only have one and here you can you have a two side square possible that's why we have written two here so this side is okay but that's a problem from this side right that there are zeros here that is why you fill the answer as one and one here okay so in this case this can at max be a two side square that's why you're taking minimum of these three values you are taking minimum of one and two which are its three neighbors okay so minimum is one and then one plus one is two okay that means it can at max form a two side square okay now let's go to the next value so next you have um the last row which is left to fill let's fill it quickly and then we'll move forward to coding it so again here you have zero so answer will be zero here again zero answer will be zero here you have one so in this case what will be the answer will be what is the minimum now you see here you have a zero so this is the constraint you cannot have a larger square because you have a zero right so the answer will simply be one now in this case it's zero so answer will anyway be zero okay now let me take another quick example before we move to the solution so that it's more clear okay now let us let me erase this okay so if instead of um okay zero i had one here and i had one here what will have been the solution would have changed okay let's see that so this is zero so anyway it will be zero okay but now let us come here okay now let us come here when we are seeing the cell for the first time right it's going to look at its neighbor minimum value is zero plus one is one so we can have a one side square here okay now let's come at this cell now this cell will again look at its neighbors minimum of its neighbors is again one so one plus one is two so it can form a two side square right you can see that the two side square is the solution okay now let us commit this last cell now when this last cell is looking at its three neighbors it is seeing all of them are forming two side squares right so this is also a two side square right that means it all these are ones okay this cell is seeing that all its three neighbors are forming two side squares so this can be a three set square two plus one is equal to 3 so it will finally form a 3 side square which will be our answer so this is how we solve this problem now let us see one more thing we have to return the area so in this case we will get maximum value as 3 but you have to return the area right so you have to return 3 into 3 which will be 9. so that is one thing which we'll note okay now let's quickly write the code for this so m is equal to matrix dot size which is the number of rows n is equal to number of columns which we have so that is matrix of zero dot size okay now for end i equal to zero i less than m i plus current j equal to 0 j less than n j plus we have to build our answer so let me declare answer variable which is initially 0 we will keep changing it and let me also build a dp matrix which we just discussed so it will also be of the same size and let me quickly write the solution and time complexity of the solution that we just discussed will be o of m into n which is we are just saturating all the elements once because we are just using two for loops okay and space complexity will also be same which you can optimize later so we'll just discuss this solution for now okay so now for the first row and first column it's very simple right if i is 0 or j 0 building the answer is very simple at max you can have a once one size highest cell right so one can at max be your answer for the first or first column right so it's very simple if matrix of i j is equal to one right in that case dp of i j will simply be equal to one okay first row first column it's very easy else now for all the other cells okay what do you have to do if it is 0 if matrix of ij is 0 answer is simply 0 by default it will be 0 okay otherwise what you can do you can give this condition right so if it is 1 in that case what will be your answer so dp of i j what do you what were we doing we were just taking minimum of its three neighbors right so minimum of dp of i minus 1 j dp of i j minus 1 and dp of i minus 1 j minus 2 now in c plus the minimum function cannot be defined like this you will have to loop it in another minimum function so let me just loop it like this because minimum function takes two parameters it always compares two values okay so i will have to give two minimum functions first you get the minimum of these two values then it will get the minimum of that with this value okay so if whatever is the minimum constraint right you can add that to one if answer of minimum of all this turns out to be zero and if it is a one cell it will be zero plus one will be the answer okay so this is it that is a simple solution now at last you can just change your answer is equal to max of answer okay come on dp of i g and finally what you can do is you can return answer into answer so that's it now let's run the code and see if it's working okay there is one syntax error let's run the code again and see if it's working okay it's working let me submit the solution that's it thank you for being patient and listen
Maximal Square
maximal-square
Given an `m x n` binary `matrix` filled with `0`'s and `1`'s, _find the largest square containing only_ `1`'s _and return its area_. **Example 1:** **Input:** matrix = \[\[ "1 ", "0 ", "1 ", "0 ", "0 "\],\[ "1 ", "0 ", "1 ", "1 ", "1 "\],\[ "1 ", "1 ", "1 ", "1 ", "1 "\],\[ "1 ", "0 ", "0 ", "1 ", "0 "\]\] **Output:** 4 **Example 2:** **Input:** matrix = \[\[ "0 ", "1 "\],\[ "1 ", "0 "\]\] **Output:** 1 **Example 3:** **Input:** matrix = \[\[ "0 "\]\] **Output:** 0 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 300` * `matrix[i][j]` is `'0'` or `'1'`.
null
Array,Dynamic Programming,Matrix
Medium
85,769,1312,2200
11
hello everyone so in today's question we are going to see container with most water that is a lead code question number 11. so here the program is there like bit between a largest height what is the maximum water we can store so here's the easiest way to do the same and you have the full fledged question like solution is available on the code for placement channel to do subscribe to code for placement and also you can check it is only beats is 93 you can pause the video and get the complete code from here as well and also with the explanation if you want separate video it is already live 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,839
hello welcome back today let's try to solve another lyrical problem 1839 longest substrate of all vowels in order so what did I mean by both remix Nae IOU and it should be Saturday in order like this way if it is not in order so we will not quote it we just need to return the longest so for example this one with a e i o u in order and the longest is 13 so it's after need to return the 13. that sucks the word dot less it is a 5 times 10 to the power of 5. yeah that is okay because I'm going to use ol to solve the problems or in time complexity I mean so for such a problem because it is a consecutive arrays and without needed to list Group by group so if it is a software AE 8 meter AEI meters condition we will list the group fluxes and then we're gonna check if admit conditions or not we just need to check if inside there are five distinct characters or not now for the next step we're going to check this character a and then go to the next a at the i o until we go from here we find the longest so we're gonna return this result now let me finish my template for such problem normally for the list groups template problem it always happened up to now I did more than like 10 liquid problems like this and basically they are soft easy and medium difficult problems yeah most of the time it is easy sometimes yeah it may be medium problems and for this one it's a medium problems template so for the result it will be started as a zero because if we didn't find it we still going to return 0 so for the result I'm gonna prepare a zero and for I the first index will be 32 from 0 and then it will be the it is the length of the word so zero and length of the word now I'm going to use the two while loop so while ilsl and my start pointer will have a record of I and then for the inner loop I will be less than a minus one and numps I to the equal uh not equal it would be length numbers less than and equal to number I plus one yeah you may wonder it is a surgery why you can compare a string with another three in Python actually you can compare like this yeah so this is why I write the code like this is even more simpler you don't need to convert it into odd with numbers yeah you just need to compare the string directly now let's just update the iporter by one so if it meets the condition the iporter will be subtited to the right but we have a record of the start that means we can use it for average hacking yeah now we have a record from start to I without need to type if inside there are five distinctive characters because this line is for checking the order for second the sequence now we first needed to attack if inside there are five distinct detectors how should we talk we just need to use if fat and inside we need to list the word from start to I Plus 1. because I plus Y is not included actually this is from start to index I so if the length of it is equal to 5 we're gonna update the result should be equal to the max of result with I minus this dot plus one and here we just need to put it inside our lens let me put it inside a lens yeah if it is five it means we have five distinct characters we need to update the result otherwise we're gonna not update it after that the ice pointer will be shifted by one and the type complexity is just o n and we should need a return the result because if we didn't do anything the result will be zero if we do anything we will update the result now let me submit a little tag if it can pass all the testing cases uh for the nouns yeah that is a normal if we are using the template maybe yeah we didn't attack the variables carefully we need to always check the variables before submitting let me copy oh where I did something wrong let me copy the word just copy this word and copy to this word now let me run it to tag if it is okay first as you can see it works now let me submit it to tag if it can pass all the testing cases even we use two while loop but we first updating the I one by one so that is why the time complexity is the subtle in even here we use the lens set list but that didn't increase the time complexity yeah at most the time is oh two times n but it is still for Big O it is still all in time complexity yeah as you can see it works and it's pretty fast thank you for watching if you think this is helpful please like And subscribe I will upload more lead called problems like that see you next time
Longest Substring Of All Vowels in Order
decode-xored-array
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**. Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu " **Output:** 13 **Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13. **Example 2:** **Input:** word = "aeeeiiiioooauuuaeiou " **Output:** 5 **Explanation:** The longest beautiful substring in word is "aeiou " of length 5. **Example 3:** **Input:** word = "a " **Output:** 0 **Explanation:** There is no beautiful substring, so return 0. **Constraints:** * `1 <= word.length <= 5 * 105` * `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
Array,Bit Manipulation
Easy
null
376
hello guys welcome back today we have this question called wiggle subsequence now first of all let's take a look at what the question means by the word wiggle now let's say we are given a sequence of numbers like 9 8 10 2 4 0 5 and 1. now the question calls such a sequence of numbers a wiggle sequence now this is because the first number is greater than the number to its right the second number is smaller than the number to its right the third number is again greater than the number to its right the fourth number is smaller the fifth is greater and so on so basically the signs alternate and you must have noticed the pattern that it forms a zigzag pattern and the first number need not always be greater than the second number we can have the sequence beginning with a smaller number as well even this is a valid gravel sequence now let's come to the question now the question gives us an array of numbers and asks us to find the length of the longest subsequence in that array which is the level so we need to find the length of the longest wiggle subsequence in the given array now this is pretty similar to the problem of finding the longest increasing subsequence in the given array and this is the this is to find the longest wiggle subsequent in this area so we know that we have a classic solution to this problem using the dynamic programming paradigm and we can use a similar approach to solve this problem as well and the run time for this would be order of n square and a similar complexity would be valid for this approach as well now the only difference between the lis problem and the iws problem is that the sequence is always increasing in the first case and here the sequence alternates between increasing and decreasing so we now we solve the longest increasing problem by keeping track of the length of the longest increasing subsequence at every index i and we calculate this using the previous using the values of the longest increasing subsequence at the previous indices so basically the length of the longest increasing consequence ending at the index i is the maximum of all the previous all the longest increasing subsequence at the previous indices plus 1 for all j less than i and a of j less than a of i because the sequence always needs to be increasing so a of i should be greater than a of j if the if a denotes the array now in this problem the only change that we need to take care is that the sequence should not consist of two steps which are both increasing so if we just modify this to max of decreasing of j plus one for all j less than i and a of j less than a of i so this would give us the length of the longest sub longest wiggle subsequence that is currently increasing at the ith index and similarly we can calculate the length of the longest legal subsequence which is currently decreasing by simply interchanging this plus 1 for all the previous indices and this time the sequence should be decreasing that is a of i should be smaller than the previous element now so you can see that this is pretty much similar to the length or to the problem of finding the lis so if i hope you understood this and if you didn't don't worry we will discuss a much more easier to visualize approach and with also a better time complexity than this so let's say we are given some array 2 3 4 6 1 zero let's say four five then nine six eight three seven four let this be some random array and we need to find the lws for this array now we need to develop we need to extract a zigzag pattern out of this array so let us just try to visualize this array in the form of a zigzag pattern itself so let's just plot the numbers in the given array like a graph or something so the first point is a 2 then the 3 would be somewhere here then we have 4 and we have 6. now the next point is 1 and 0. so the next we have a 4 and the 6 should be a little higher and we have a five here then we have nine and six eight and a three seven and four so this is our array plotted in the form of graph let's just connect it a better understanding of the problem so this is our graph in the form of an array and let's begin from the left hand side now we have uh four numbers which form a strictly increasing sub array now we can choose a maximum of two elements from the first four numbers because if we choose two numbers let's say two and four now two is less than four and this is a valid wiggle sequence we cannot choose more than two numbers because if we choose more than two numbers then the sequence would become strictly increasing but we want or want the sequence to alternate between increasing and decreasing so we can choose a maximum of two numbers from the first four numbers and we will choose two numbers so let's say because we want to maximize it so we will choose both two numbers so let's say the first number is p1 and the second number is p2 now the third number has to be from this decreasing part of the array like we can choose a third number from this decreasing part of the array because these numbers would be less than 6 if we choose 6 because c we need to maximize the length of this array so we would try to choose the largest number for an increasing part of the array and the smallest number for a decreasing part of the area now let's say we choose a p3 from these two points that is one or zero now if we choose one then the probability of finding a p4 from this slope would be less than the probability of finding a p4 if we had chosen 0 because there are more numbers greater than 0 then there are numbers greater than 1 so because we would want to have more choices we would the better choice would be zero so we would choose p3 to be zero now from this slope we have chosen a number that is p3 now again from this increasing part of the array we would like to choose the maximum number because if we choose the maximum number that is 9 there is more chances of getting a number in the decreasing part of the array that is smaller than 9 now see if we choose 4 then we cannot select a number from the decreasing part of the array because 6 itself is greater than 4 so but if we choose 9 then 6 would be a valid choice so our the best choice for p4 would be 9 so we cover this increasing part by choosing nine now the next decreasing part we can choose p5 equal to six so we have chosen five points till now the next point should be from this increasing sequence there is only one number so our number is going to be eight now in the next decreasing sequence we have another number that is going to p7 then we have p8 and then we have p9 so the length of the longest legal sequence would be 9 because we chose 9 numbers so basically what we need to find is we need to just count the number of peaks that are present in the given array and that would give us the answer so this can be achieved in one scan of the array and so this would be a linear solution and it is a better solution than the dynamic programming solution that we previously saw so the code for this solution would be available in the description below i hope you enjoyed this video and understood it and you can subscribe to our channel if you like this video and thank you for watching
Wiggle Subsequence
wiggle-subsequence
A **wiggle sequence** is a sequence where the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with one element and a sequence with two non-equal elements are trivially wiggle sequences. * For example, `[1, 7, 4, 9, 2, 5]` is a **wiggle sequence** because the differences `(6, -3, 5, -7, 3)` alternate between positive and negative. * In contrast, `[1, 4, 7, 2, 5]` and `[1, 7, 4, 5, 5]` are not wiggle sequences. The first is not because its first two differences are positive, and the second is not because its last difference is zero. A **subsequence** is obtained by deleting some elements (possibly zero) from the original sequence, leaving the remaining elements in their original order. Given an integer array `nums`, return _the length of the longest **wiggle subsequence** of_ `nums`. **Example 1:** **Input:** nums = \[1,7,4,9,2,5\] **Output:** 6 **Explanation:** The entire sequence is a wiggle sequence with differences (6, -3, 5, -7, 3). **Example 2:** **Input:** nums = \[1,17,5,10,13,15,10,5,16,8\] **Output:** 7 **Explanation:** There are several subsequences that achieve this length. One is \[1, 17, 10, 13, 10, 16, 8\] with differences (16, -7, 3, -3, 6, -8). **Example 3:** **Input:** nums = \[1,2,3,4,5,6,7,8,9\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` **Follow up:** Could you solve this in `O(n)` time?
null
Array,Dynamic Programming,Greedy
Medium
2271
35
That one ice welcome to record as per today's problem china shirt position this youtube channel please do subscribe vishal to complete your problems and problems is given solidarity and target value return indicated targets point is not returned and spirit be id in order to fill ajeem notification Vowel Problems Meanwhile Have Given One Shot Dead In One Target Element Free To Find The Target Elements Present And Not Left Is Not Done What Is The Current Position For The Element Newly Understand With Examples For Hearing On Terrace Give 1356 Add Dal Wheat Fiber Subscribe Button Intex 2012 to and example targets not present in the position for target of 280 in interview and out on prediction from correct position for to say Bigg Boss for the example sure 12307 will be the number at the fourth position 9000 for elementary will understand with a solution approach For this problem I would like to find its correct position for the number to draw tuitions to this one Left in Delhi near way and starting from first index will also be Anil's trading till they have found correct number and from North relax itself the target is laxative one example of examples will take you to fennel rather trading till they have found at number this gifted number will be clear RETURN THIS INDEX IS MADE WITH SOLUTION FOR THE SECOND WHERE IS NOT PRESENT FOR SOM WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOM WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOM WHERE FROM 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOM WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOM WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOME WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOME WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1.IS PETING THE NUMBER ARE SOLUTION IS NOT PRESENT FOR SOME WHERE FROM NUMBER TO THE CURRENT PRESIDENT AT 1. The Time Fix Position To Inch Update Number One Solution But What Is The Time Complexity Liquid Over 100 Time Complexity Of Ooo And Dadar Solution Good Also MS Word Know The Tower Eggs Already Ne Sort Order Know Member Skin Problem And Skin Approach Which Cannot Live In Applied Science Research to The Amazing Down Vansh MP3 Live And Six Digit Worker Dark Right Knowledge That All Apply For Your Research Pure Love For Interview Rather Test Servi And High For Interview Lipid Clear Ok Khan Will Find Out Amit Da Mein Acche Meet Will Come From very clear in between akbar and will check weather you are element airtel achhe no 8 minutes hu is equal to target net mushari find the number this year present in the giver send a return that media ab haq ke main mere 10 minutes And war number target number is not present in the case of which is not present in the given here in this case will report it to so number to meet office phone number Redmi left his alleged and target I show to you saying this reducer number This laddu is will a remote these numbers and will remove all the point to the mid day meal plus one and will start searching in this randomly ok so for media greater than the target it means a what are the numbers where searching for its going To all in this range that your in that case will move over a point to the meet - one OK flash light condition for the meet - one OK flash light condition for the meet - one OK flash light condition for dates which have two points on NH first will start from 0001 length of the - 151 number 8 minutes that - 151 number 8 minutes that - 151 number 8 minutes that your is All the u target latch a that your Lakshmi inch and target steel neck so that tower meat element your friend 's this want to move and come man and the next point 's this want to move and come man and the next point 's this want to move and come man and the next point up-to-the-minute plus one up-to-the-minute plus one up-to-the-minute plus one that after all in these second slices 100 The numbers were meant that this great day will be the target only in that case want right for inter and high school and inter ayush hi pointed to be easy edit meet - one who and different edit meet - one who and different edit meet - one who and different boards like to search is a message what a advantage will get here is the The time complexity will be reduced from of and to the login that Bigg Boss Wayron Lee is retracting and that of the year and every time you will remove that of elements and you will check the best all the week elements date when will reduce to the aa login complexity. Navras Write Down What For This Point Office Define And Low And High Point When Is Equal To Not Learn Loot Okay And Define Expectation Element Also Which Were Going To Calculate Tubelight Detail My Friend Will Proceed Chatur Aage The Language Fast Calculator Means Meet Will Be Picture Story Dar approach and plus 5 - Picture Story Dar approach and plus 5 - Picture Story Dar approach and plus 5 - Albert to that your knowledge healthy check weather element that at mid that this booty 's target 's target 's target that in this case loot return mixture not just phone number set mid that this plus new target let's you number so this day and targets And K Support Volunteers Will Like To Move Over Like Point To The Meet Plus One Has Nails A Movie And Right And Higher Point To The Meet - A Movie And Right And Higher Point To The Meet - A Movie And Right And Higher Point To The Meet - One Who Can Add And Will Have Correct Index Is The Lion Tax Return An Oil Pure Last Not Always Run only will not find exact match minutes of this will have the and index where they can insert other target elements of written test for lower limit submit alone that your dig submit to clean that in this video of you like it if you have a DIFFERENT APPROACH PLEASE EDIT INTO THE COMMENT IF YOU ARE LOOKING FOR ALL SOLUTION FOR DIFFERENT PROBLEM PLEASE EDIT INTO THE COMMENT THANK YOU GUYS
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
701
hello friends so today in this video we're gonna discuss an interesting problem from lead code which is a medium level problem name insert into a binary search tree so there can be a number of ways to insert in a binary search tree but first we have to understand what is a binary search tree and if in the simplest term it actually states that a binary search tree is like a binary tree in which every node can be of at maps two nodes and the left node value if it exists is smaller than the like the top node or the parent node and the right like right leaf value or like the right node value is larger so as you can see for every node the left one is smaller and the right one is large and so on now you have to insert a given value in this binary tree such that the resulting tree should be binary now there can be a couple of positions you can insert into binary to even make it a binary tree as you can see this if this is the binary tree and you want to insert five the simplest way can be uh just go to the end of the binary tree using this searching operation what i mean by the searching operation is like let's compare the value you want to insert with every node on ur okay so i'll tell you with the example but first you're going to see that the node 5 in this example can be inserted at this point and can be inserted at this point also but we can insert at this point which is the which is some sort of a leaf node which will make it easy so as you can see the simplest way can be because you know the property of binary tree in which the left or the right side node is having a value greater and the right on the left side node is having a very small and that condition is satisfied for every node value so now what you can do if you want to insert five you will compare five with four okay because that's the node from which you will start and you will see that the value which is five you want to insert industry is greater than four which means that you don't have to insert this 5 value on the left side obviously because you have to somehow insert this value on the right side so that when it boils down to some position it should be on the right side because every value which is greater than 4 should be on the right side so you will move down to this node now you cannot insert at this point because you cannot like if there is no node at this point on the right side you just insert right five at this point but because there is no node on like there is a node at on the right side of this four you will go to this node now you will compare the value 5 with this node now when you compare 5 with this node you have two options whether you can insert on the left or the right so you have to match 5 with this node now as you can see 5 is smaller than 7 so it is not beneficial to insert on the right side you have to insert on the left side i hope you get the point because see you have to assume you have to make sure that the value should be on the left side if it is smaller and right side if it's greater because it is a binding source tree and then you see that okay now i have to insert five at the left side now whether there is some node on the left side no so just i can just insert a new node on this new left side and that's the answer and as you can see that sounds and that's the simplest logic for this problem you can't do this on a like a recursive way because it is like a searching operation in a login because you can reach any leaf in the log n like login combination n is not the number of nodes it's actually the levels okay so number of levels because in each level or like in each step you go one level down and then you can reach the leaf node in log of n levels now that's the whole problem and as you can see for every uh like every two you just have to do the same thing so i will tell you with the code part now to even make it more clear so uh like you can write out the recursive function another recursive function also but i have written down in this i like the starter function also so what you can see here is i have a root node and a value okay i can even make it bigger so as you can see if root is null which means that the root like the given node the starting root road like the root on the starting root value is null only which means that there is no root value so then if the root value is null then the answer is just insert that value at the root value now you want to insert a new node now so you want to insert a new node like this so you want to make a new node of a tree node type insert a value because you have to insert a value at this point it is just creating a new node and you have to make your root equal to this new node and just return on the node all right actually the root whatever so okay that's the whole first like a base condition but now you have you if you ensure that the root is not null there is some root here you have to compare your root with the value itself if the value is greater than the root value as you can see then it means that i can insert this value on the right side if there is no node so i have to ensure that on the right side if there is no node means that the right side is equal to if the right side is equal to null just insert a new node on the right side but if the right side is not null what you'll do you will recursively call this function again on the right side i hope you get the point with the same value because you have to insert that value else if the value is smaller than the root value and as you can see every value is uh it is written that every value is original on like it is not repeating so that's why you don't have to carry about a worry about the equal to sign it's just greater than a smaller so as you can see if it is greater than the value is greater than the root value just go to the right side if this one smaller than the value then you have to go to the left side and then you have to do the same thing you just have to see that okay if this is smaller can i insert a new node on the left side if we can only insert if it is null the left side is null then you can insert it if it is not null what you can do you have to go to the left node and then recursively call this function again and in the end when you have inserted you have to just return on the root value because you are inserting a new node so the tree is not changed you are just inserted so in the end you just have to return all the like return on the original root value i hope you understand the logic and the code i will like post this code uh not actually in the description but i will make uh like in the description in the discussion forum i will paste this code and then you can see there okay i hope you understand the logic and the code if you still have your arts commission on as an experimental and keep coding and bye
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
289
hey everyone welcome to let boy coding today we're going to a soft 89 game of life and business a very common question in the interview this is the question that do not test our algorithm skills but it's test us on how to follow the instructions and how to handle age cases very carefully so unless without question the game of life is that table abort each cell is either left or die or dead and then based on these rules each cell will interact with its neighbors so we need to write a function to compute the next stage given the current state so the next stage is created by applying these rules simultaneously to ourselves in the current state so yeah there's nothing too you okay so before company to : and follow okay so before company to : and follow okay so before company to : and follow all these rules less least our steps first we need to copy the board to store the initial state because we cannot update the current state a while inter it over it then um for every cell into it over its neighbor and count the number of dead cell and number of life cell and then we can make the change based on these rules you so basically these are two steps but um we have two more questions to cover how to handle each case um for example if this is the board then we start from zero has three neighbors right it did not have eight neighbors but this cell zero has eight neighbors around him so we need to handle all the other edge cases in the boundary right this is how we handle it we can first get the number of rows and also then the number of column you let's say the current index is I and J so if I is larger than zero and I is smaller than the length of the current role and if the column is larger than zero and column is smaller than the length of column then it is a valid index otherwise we can just assume that they're um there is an additional pet cell around the current state so for example if this is a zero then it has five dead cells you yes you okay so this is how we handle the boundary and if it is out of index or we can just assume there's a dead cell around the state so yeah second question how do we enter it over the neighbor okay so if the Nexxus a zero let's list all the neighbors so this is 0 1 this is 0 negative 1 and negative one this is one and then this is negative one and this is one negative one all right and then this is negative 1 0 this is 1 0 so this is the neighbor index we can just create an array to store the neighbor you're next and then enter it over this array so you yes so this is our algorithm now let's code it you this is how we deep copy abort and we also have this neighbor away Oh need to get the number of rows you number of column then let's just follow the instruction for role in wrench rows four columns in wrench columns print port RC so this will give us every value for every cell let's just run it yes so zero one so on so forth so now you letter on two numbers life cell and that cell then we just need to endure it over the neighbors you neighbor R and then we just need to enter it over the neighbors you so the neighbor our and neighbor C is our new index of the neighbor now we need to check if um if the index is out of boundary or not you else we increment our dead cell if it is um within the index then you if the initial state is equal to zero then we increment our dead cell otherwise we increment our lifestyle then after the cycle of can update the board the number of a lifestyle and that cell so let's print led a life and dead yes so for example in this index 0 it has 1 life cell and 7 dead cells so here you any lifestyle with fewer than to life neighbors dice so you we need to check it is a lifestyle you so this is the first rule and then second rule any lifestyle with two or three neighbors leaves to the next generation you we just need to do nothing any lifecell with three neighbors dies you so yeah and then I need that cell with exactly three lifestyle become a life again and then we can just return the board so yes this is our algorithm you it's correct let's submit all old yes and for the time-space complexity yes and for the time-space complexity yes and for the time-space complexity analysis the time complexity is indeed and times m and the space complexity if we copy the unit of state then it would be also n times M okay thanks for watching bye
Game of Life
game-of-life
According to [Wikipedia's article](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): "The **Game of Life**, also known simply as **Life**, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. " The board is made up of an `m x n` grid of cells, where each cell has an initial state: **live** (represented by a `1`) or **dead** (represented by a `0`). Each cell interacts with its [eight neighbors](https://en.wikipedia.org/wiki/Moore_neighborhood) (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): 1. Any live cell with fewer than two live neighbors dies as if caused by under-population. 2. Any live cell with two or three live neighbors lives on to the next generation. 3. Any live cell with more than three live neighbors dies, as if by over-population. 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return _the next state_. **Example 1:** **Input:** board = \[\[0,1,0\],\[0,0,1\],\[1,1,1\],\[0,0,0\]\] **Output:** \[\[0,0,0\],\[1,0,1\],\[0,1,1\],\[0,1,0\]\] **Example 2:** **Input:** board = \[\[1,1\],\[1,0\]\] **Output:** \[\[1,1\],\[1,1\]\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 25` * `board[i][j]` is `0` or `1`. **Follow up:** * Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells. * In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?
null
Array,Matrix,Simulation
Medium
73
391
Yes, hello, this is Live Coding Labopal. Today, I will solve the problem called perfect rectangle, number 391 in Litcode. Today's problem is a hard problem. To explain the problem briefly, sub-squares are input, and sub-squares are input, and sub-squares are input, and when the squares are well combined, it is a large square that does not overlap. It's a question of asking if this is possible. If not, pulse, then true. So, since this is a problem related to starvation, it may be a little difficult, so let's approach it in the simplest way first and solve the problem. Of course, I've marked the constraints, but that's the simplest way. If you solve it, you will get a timeout. Of course, that is why it is a hard problem. This is how I expressed the form that was input as number 1 in the retcode. If you receive 1133 left coordinates and this coordinate, the square that can be created in that space is There are a total of 4. The starting point of x, the starting point of y, the ending point of If you paint the square, then the second square and the two squares, the entire area of ​​this square paint the square, then the second square and the two squares, the entire area of ​​this square paint the square, then the second square and the two squares, the entire area of ​​this square becomes the outer space. Then, if you go around the second gun and look at those spaces again, only the rectangles are colored like this. If you check that there is one square, you can return the tool. If some spaces contain the value 2 and some spaces contain the value 0, you can now pulse release and return those squares. Of course, I said 2. However, it could be 3 or 4, and the number will be increased by the number of overlaps. In that case, all you have to do is return the pulse. If you solve it that way, the code will probably be quite simple and you will be able to solve the problem very easily. The problem is entered like this: This is problem is entered like this: This is problem is entered like this: This is when the input comes in. When the input comes in like this, you have to color in the 10,111,100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 column. That's have to color in the 10,111,100,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 column. That's why a timeout occurs. First of all, most hard problems are first thought of in this very simple way, and when a timeout occurs or memory is not captured, the problem is approached in this way by attempting one more try to solve it. If you do it, I think it is a good problem that can help you develop your ability to think a little more and develop computational thinking. Unfortunately, problem number 2 has a good existing standardized algorithm called planciping, so if you apply it will be solved immediately. The problem will be solved. So, I will briefly explain this part. If you are curious and need a more detailed explanation, you can Google it and find some good blogs and other video lectures. It's the same, and I'll explain the biggest concept first. When all the coordinates come in, I entered them earlier and expressed them like this by doubling the So, without having to paint each space like this, I just paint this area that I have partitioned in red with one shot. Because it is not a big problem to go to this area at once, because there is no reason to split this area, if you look at it, If you compare it with this picture, it will be quite easy to understand. So, if you do this, you can compress the things that had to go around 4 times the gun port now because they are doubled in x and double in y, so you can compress them again. You will be able to do this. Ah, this is not North Korea. It is a typo. It is 4 spaces. The rest is correct. Anyway, it is not important. Please understand that part and find out how to make it like this by looking for this algorithm or on this next page or this next page. I will look at the code and explain it briefly. If you look at the code, I also know that this is not the original Python. As those of you who have listened to my lectures know, I originally study Python, solve retcodes, and film lectures on YouTube. So now I'm trying to solve the problem with Python, so the code may not be clean. It may not be clean, but please understand. First, I split the x and y coordinates like this, and when an input like this comes in, I get the necessary x and y coordinates. Save them all separately. Add up all y=y and save them. Add up all y=y and save them. Add up all y=y and save them. In other words, these coordinates are now two x coordinates and two y coordinates. For each input, add them all like this. Remove all duplicates. If you remove duplicates using the removal set and sort them all, the coordinates here eventually become 0, 1, 2, and 3. 0 1 2 3 Make it like this and now use the dictionary. The coordinates in the original are originally input by Rectro. The coordinates in the original were originally 1555 and 1155, but we change this to 0 and 2. This is 1 in the middle. This is 1 and this is 1. Since it becomes 2, I just changed the input itself by going around this type of opening and then changing this size to this size, After making this space 3-3 space 3-3 space 3-3 space x size and y size and initializing it to 0, it goes around each range and increases the corresponding column by one in the same way as I explained here earlier. So, all I implemented a code like this that goes around all the cells and later goes through all the cells on this board and returns a pulse if even one is not 1. I will give it to you. However, since this is a hard problem, there is not just one solution, so I solved one more solution. I added one more solution. This is a bit of a starvation problem, so I am not solving a specific problem with an algorithm. I have now solved it separately like this. As I was drawing, I thought of an extension, so I solved it. If you look closely at the square, when you check all the points, when this square comes in, these four points come in. The points come in this space one by one. And this space. When this square is input, another one comes in, so this space has two spaces, and this point is counted twice, and this point is also counted twice, and this point is counted once, and this input is the input. If you keep adding the counter each time you receive an input, this point is counted once here, so 4 counts are entered, and the remaining points, age point book, physical surgery points are entered only once each, and the rest You can see that the points are entered twice. I did not mark this point as well, but once here, and once here, so it is entered twice. So, we now You can think about it. The largest outer point occurs only once. Then, the remaining points are entered twice or four times. And each time this sub-square enters, the each time this sub-square enters, the each time this sub-square enters, the area of ​​that square is changed. If the area of ​​that square is changed. If the area of ​​that square is changed. If the area of ​​the square added and the outside is the same, area of ​​the square added and the outside is the same, area of ​​the square added and the outside is the same, then it is proven that they are on the outside. And the remaining squares do not overlap if the point is counted twice or four times in the coordinates. For example, this point and this square are here. Assuming that it did not come in but came here, it was number 2 earlier, and now it has number 2, but because it overlaps to this point, number 3 comes in. So this point also comes in number 3, and this point is 5. Numbers come in and they overlap in something like this. And even if we assume that it comes in like this, without this square or with this square as is, even if we assume that one more square comes in here it is three times, here it is five times, here it is twice. Once here, it takes the form of something like this, so if all of these conditions are satisfied, you can continue to draw it on the exercise book and check it. If you are satisfied, you can solve the problem a little faster by applying this part well and implementing it as code. This means that the runtime can solve it quickly. So, I have now implemented that part with code. First, in this entire rectangle, the left and leftmost x values, the rightmost x value, the top y value, and the bottom y value So, implement this outline In order to do this, I continued to update the four values ​​in this way using the max value and the continued to update the four values ​​in this way using the max value and the continued to update the four values ​​in this way using the max value and the private max value. Then, each time this sub-square came in, I continued to each time this sub-square came in, I continued to each time this sub-square came in, I continued to accumulate and add the area. Accumulated and added in this way, and then the same as I mentioned earlier. Every time a square enters, the count for all four points is increased. So, if the area of ​​the largest outer square created here and the of ​​the largest outer square created here and the of ​​the largest outer square created here and the sum of the sub-squares are the same, it is sum of the sub-squares are the same, it is sum of the sub-squares are the same, it is not true. This moves on to the next condition. If it is not the same, I created the largest square with Rectangle like this. Create the largest square and if the count of one, two, three, four of these points on the outside of this square is not 1, I incremented the counter here earlier. If this is not 1, then pulse. Otherwise, I removed 1. I later removed it here to make the code more concise. Except for this, except for the 1 on the outside, everything else has to be a multiple. So now, in order to implement the code like this, I have removed it one by one from here. If we subtract it is now 0. So, we go back through all the people who counted in the sub-square and back through all the people who counted in the sub-square and back through all the people who counted in the sub-square and check if it is a multiple of 2. Check if this count value is a multiple of this. If it is not a multiple of this, pulse. If this is a purchase, then true. This solves the problem. When I solved it, I got an answer. So today, I explained the solution to the problem in two ways: one by plane sweeping and the other by using starvation. explained the solution to the problem in two ways: one by plane sweeping and the other by using starvation. explained the solution to the problem in two ways: one by plane sweeping and the other by using starvation. And next time, I will use this to code both. Let 's try to implement it. If today's lecture was helpful, 's try to implement it. If today's lecture was helpful, 's try to implement it. If today's lecture was helpful, please subscribe, like, and set an alarm. Thank you.
Perfect Rectangle
perfect-rectangle
Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]` represents an axis-aligned rectangle. The bottom-left point of the rectangle is `(xi, yi)` and the top-right point of it is `(ai, bi)`. Return `true` _if all the rectangles together form an exact cover of a rectangular region_. **Example 1:** **Input:** rectangles = \[\[1,1,3,3\],\[3,1,4,2\],\[3,2,4,4\],\[1,3,2,4\],\[2,3,3,4\]\] **Output:** true **Explanation:** All 5 rectangles together form an exact cover of a rectangular region. **Example 2:** **Input:** rectangles = \[\[1,1,2,3\],\[1,3,2,4\],\[3,1,4,2\],\[3,2,4,4\]\] **Output:** false **Explanation:** Because there is a gap between the two rectangular regions. **Example 3:** **Input:** rectangles = \[\[1,1,3,3\],\[3,1,4,2\],\[1,3,2,4\],\[2,2,4,4\]\] **Output:** false **Explanation:** Because two of the rectangles overlap with each other. **Constraints:** * `1 <= rectangles.length <= 2 * 104` * `rectangles[i].length == 4` * `-105 <= xi, yi, ai, bi <= 105`
null
Array,Line Sweep
Hard
null
476
hi so let's talk about the number component so the complement of the integer is the integer you get when you flip all of 0 to 1 or all of one two zero right so this question is pretty straightforward so I'm going to just uh quickly summarize this so if you get a number of five right integer five right the component for the five is actually two in bit this is because uh the five the Phi integer is represents one zero one right and if you don't know what is one zero one represent it won't be about two to zero two one two so when you do the math this is going to be what four plus one is actually equal to five right so let's just turn out one zero one in bit and how do you know if how do you know the complement of the five is actually two uh again you want to flip but you want to flip one two zero to one two zero so this is represent one two this is five right so uh let's do a little bit math so if you add everything together this is going to be one right plus all right if we get 5 plus 2 is going to be seven so let's do uh one more step of math if you uh if you know all of the ones if not all those ones and if you know all of the Norms right I mean if you know the nums then you can get what the component right it's gonna be five seven minus five right is actually equal to two this is the number you want to find out all of a one is should be super easy because if you want to find out the order for ones you can definitely just Traverse the Norms you have and then just place every single uh position into one so what does this mean so I'm going to say n equal to zero right and then I know my nums equal to five so there are what three uh three digits right so I'm going to just switch my end left by one and using the All uh orbit notation and then plus one so I'm going to say only go to this right and then for every single time is switch left by one and now we just get one and until the end which is greater equal to the nums which is five then I will stop then once I have this is going to be all over one should be seven minus the current number num equal to what equal to two right zero one zero which is two so let me stop coding and it should be super easy so I'm going to say in once equal to zero and then well once less than num and I'm going to say 1 is equal to Once switch left by one using an orbit notation one and I want my when I get all of the ones after the while loop I'm gonna say once minus no so uh let me run it so submit and it should be easy so back to here and I'm gonna just uh make a breakpoint right over here and then using a debug mode install debugging and it should be okay all right so I'm gonna just keep going and then you'll just pause at any second and then you find out what happened five seven all of one equal to seven minus five which is two right so let me access all right so let's talk about the time in space complexity for the space constant right this is not you know uh this is pretty much nothing this is going to be a time is going to be based on the length of a bit uh yeah the length of the bit for the Norms so this is the time and the space constant and then this is the easy solution so uh if you have any question leave a comment below and then subscribe if you want it and I will see you next time 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
236
Hello guys welcome back to tech division in this video you will see the longest co ancestor of every problem which is remedy co number 230 6 and will see the solution for this entry problem so let's tree problem statement in this problem give a brief notes industry The Definition of the Best All the Difference Between The Guardian Edison Where Love Resides in Order to Understand subscribe this Video This You Will Always Tree To Avoid You Will Always Love Letter This Is The Definition Of The Giver Notification Subscribe What Is This Is The Root From Root Give Notice PM This Is Your Prayer From Rupee Withdrawal 2002 15 to 087 11th Know What is the Richest Man in the Best Wishes subscribe to subscribe and subscribe the Channel and subscribe the 2002 258 Ki in Four Yudh 350 2011suresh Seervi and the British Voiceover Like subscribe and 409 Dry Fruits subscribe and subscribe the Channel 90 A Question from Parties This uninstall busy ho woh 221 11082 this is to write a letter this is pe what is the root 2.20 2.20 2.20 daru 211 0216 servi id am id a new dates of candidates android saugandh nvr descendants of this world i can do It is the meaning of this is the solution math solution subscribe must problem already mentioned that you will always be present in the country and they will drop and key problem okay this part-- slice of 22 100 911 most important 298 2025 to must 2002 60 minutes What is the The 2000 subscribe The Video then subscribe to the gorgeous Not Know Where In Which Path SD P and Q Love You Too Simple Question OK Simple Preparation Method In Order To Reach You Have To Play With Both The Video then subscribe to the Page if you liked The Video Kundru Tnord ok and will start searching for the notes16 tarf 2f welcome to the self i will not include not equal And It's Something Subscribe To Channel Now To Receive New Updates Will Return To Main 9 This Will Return Nale Global Water From Both Sides Siddheshwar Will Also Written A Letter From Very 1089 Video Two Does Not Equal 960 The Video then subscribe to subscribe 9999999999 Subscribe 269 Bittu has no desire for not wish to receive the Nobel Values ​​from both sides Amendment Bill-2012 From Bill-2012 From Bill-2012 From Delhi to 99 Values ​​from both 99 Values ​​from both 99 Values ​​from both subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Channel and subscribe the Channel Loot Your Skin Tight Election Dish Two Is Equal Two and Shiv Unit Not Got Down Will Simply Return Value 200g Jara Two The President of the Two Subscribe 2010 The Present In The Road To You Are Not Able To Find The look but you did not from both of the Video then subscribe to the Page if you liked The Video then subscribe to the Page Hello Everyone Sister and There 's Only One Snowden This Is 's Only One Snowden This Is 's Only One Snowden This Is Paint You Have Enough Evidence Relationship Video then subscribe to the Page if you liked The Video then subscribe to the Difference Hai 200 And This Amla Video You Six Years During Different Streams And The Common Not The First Indian To Do It Is 98100 Time Complexity And Only One Channel Subscribe Must Subscribe Button Is Quote Under Trial Ok Notification Internal Dangers Will Make Electronic subscribe to the Page if you liked The Video then that remains turn on alveoli off set you must have done value what can happen if you have two places to visit in this can be and describe channel and subscribe this channel and If you have not subscribed the channel then subscribe The Channel and subscribe our Channel The Return of the Day Ki Jab Right Candy Here Candidates Can Also Be Easy and Channel Subs of the Video then subscribe to the Page if you liked The Video then subscribe to subscribe Thank you
Lowest Common Ancestor of a Binary Tree
lowest-common-ancestor-of-a-binary-tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor): "The lowest common ancestor is defined between two nodes `p` and `q` as the lowest node in `T` that has both `p` and `q` as descendants (where we allow **a node to be a descendant of itself**)." **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` will exist in the tree.
null
Tree,Depth-First Search,Binary Tree
Medium
235,1190,1354,1780,1790,1816,2217
526
welcome to january's leeco challenge today's problem is beautiful arrangement and buckle up this is going to be a long one but we'll get through it together suppose you have n integers labeled 1 through n a permutation of those n integers perm is considered a beautiful arrangement if for every i inside of our permutation the i is divisible by or perm i is divisible by i so i suppose that means the number in the index number is divisible by the index position or the index position is divisible by the number inside of the array okay so to understand this part i think is the tricky part there's really two parts to this question right number one we need to find every permutation between one what however many digits we have and that's doable but second thing is we also need to make sure that every number inside of this permutation is fulfilling one of these two conditions okay so let's start with the most straightforward approach and just do that in two parts we will find every single permutation here and once we do that we will check how many beautiful arrangements there are for each permutation so and then we can just count those up so to get all the permutations we there are ways to do it but let's just say we want to use inner tools to do that so we can do that um let's first start with creating our array and we'll call this temp and we'll say for i in range of n we're gonna do a i plus one and reason for that is because it's obviously zero index and you can see here the numbers are gonna be like one and two instead okay so now we have all our pro um you know a list of all the numbers and we're going to get every permutation to do that we will use iter tools find the permutation of and now we're going to have a list of tuples that have all the permutations right so finally all we need to do then is just say oh well first let's initialize a count of zero now for p there's going to be tuple in um permutation i should say perm we're going to check all right for the index number and the value in p uh and i should enumerate that right enumerate p we're going to check to see if these conditions hold and all them have to have that condition right so to do that i think what i'll do is say beautiful arrangement equals true here and if at any point we find that it's not the case then we're going to make it a false so to do that we'll say divisible we can just use a modular function right and we'll say okay either the value is divisible actually is modular of i plus one right is not equal to zero or the opposite where i plus one divided by the value is not equal to zero then we'll say beautiful arrangement equals false because that means it's actually not an or is it's an and so if both of these aren't true then we know that this is not a beautiful arrangement so we could just make that equal to false and we'll say once we finish this loop if not beautiful range or if beautiful arrangement still is true then we'll increase our count by plus square one and after that we can just return our count so this would be our knife approach and should work see if that worked oop okay their tools has no i think it's permutations right let's make sure that okay so it looks like that's working but unfortunately this is not going to be accepted and the reason for that is it's pretty expensive like getting all the permutations here um is going to be an end to the factorial power and on top of that we have to also check every single number inside of a permutation do this whole for loop thing so it just doesn't work in the end now if we didn't care about time this would be perfectly acceptable but we know that this isn't going to work so how about a recursive function and we can definitely do a recursive function we can kind of combine getting all the permutations as well as checking to see if a beautiful arrangement could be created so to do this i think the very first thing we want to do is create some sort of array to check where we've visited already so what i'll do here is create a list and just say zero for equaling false for i in range of n which is kind of a visited list all these zeros uh each one of these index numbers is going to indicate whether we've visited this integer yet or not now we're going to have our recursive function and what we'll pass in is the n as well as the number of items we've added to our list so far and we could kind of make sure that we're not repeating numbers by using this visit set here and do some backtracking okay so let's see first i think what i'll do is create a self variable of count equals zero and the very first thing we'll say is look if i the number that we've added is greater or equal to n that means we could just increase our counter because that means we've completed this permutation um to the end and we can just return now otherwise we are going to do some recursive stuff here and we'll say 4i um no not i should makes another one for j let's say and range of 1 through n plus 1 we are going to say to our visits make our visitor list and say okay j minus 1 here is now equal to one because we've just kind of imaginarily added it and we don't you really need to create a temporary array here we could just use our visited dictionary to make sure that um we're doing this in order so let's see because it said j equals one and i should also say um we gotta make sure that some conditions are met here right let me make sure this is right so if um visited j minus one equals zero so we haven't visited and we have to make sure that our beautiful arrangement condition is fulfilled as well so that would be j which is one uh divided by i'm sorry modular um here we defense i'm adding here i plus one i believe i plus one because we're checking the cones yeah so um we're checking our number here and we're taking the visited this one so number we've added so far right yeah so that's the number we're on right now and we just want to make sure that either this is equal to zero or uh j should say modular sorry all the way around it's i plus one modular j equals zero so make sure that this condition is met that means we can continue with our recursion and we'll say recursion now it's just going to be n and i plus 1 and we need to backtrack here because in case we need to meet the other permutations so j minus one now equals back to zero say that we haven't visited anymore okay so let's see once we finished that uh i believe we just need to call our recursive function say n and we can just pass in a 0 at first finally return the self.count so let's see if i missed anything here okay it looks like it's working let's see if this one gets accepted and this should be better than the other one and the reason for that oh and it does get accepted right because it's better because we don't go down unnecessary pass with the other algorithm we find every permutation regardless and then we check each one but this one kind of builds up from the bottom up and it'll stop the recursion if we find that oh hey this one's not going to work so we'll stop before we build it up but it's still not that efficient it's still uh factorial and you can see here it's like 17 like can we do better than that now there is a way that we could do better and that's by doing some sort of memorization right um and that's difficult though because we're going to have to start passing in um some sort of a race data structure to say be able to tell if we've visited this place or not and we could do that by passing in uh the path that we've traveled so far but unfortunately with using something like caching like say we want to use lru cash we're not allowed to pass in a list we can't just pass in the visited list here because that's actually unhashable so what if we passed in a string that represented the list and then reconvert that to a list then we could actually just pass in um convert that list back into a string and make sure that we could cache it here with our lru cache all right so that's going to be a little bit trickier but we can do it let's figure out how we can do that first thing we want to do is let's say pass in the visited set here and this is going to be a string right so to make sure that we are going to make that into a list let's see if we passed in like a string that looks like something like this like zero uh what we're going to do is take the sec take the string starting from here all the way to the second last position inside that string and we're going to recreate that into a list so to do that we'll take our visit string we are going to take just minus the first and last parts of the string and then we'll split it by comma now that's going to be a list but it's still going to be a string for these values so what we'll have to do is say all right for b and visited we're going to make that back into an integer and now this is going to be the same thing but luckily we can now pass this in as a string so let's see string visited some other things we could do here is rather than setting a self variable here we could instead return the count like this so we return 1 here and instead we'll start by initializing count as zero and we will say all right count plus equal whatever cursive here and we turn the count at the end like this if we do this then we don't need to return the self count we can just return whatever comes out of our recursive function so let's see if i missed anything here with this i believe should work it does let's see how that works out and there we go accepted and how much faster is that you can see it's quite a bit faster we went from like 2000 milliseconds all the way to like 200 so it's like 10x faster all right so time complexity wise i believe because of our memoization this becomes like a god i think it's n squared i'm not positive we do use extra memory with our cache but you can see it's still way better than other solutions all right so hopefully that helped this is not an easy problem in my opinion it took me a while to really get down to the lower levels of this but hopefully that helped and i appreciate you guys watching thanks for watching my channel and remember do not trust me i know nothing
Beautiful Arrangement
beautiful-arrangement
Suppose you have `n` integers labeled `1` through `n`. A permutation of those `n` integers `perm` (**1-indexed**) is considered a **beautiful arrangement** if for every `i` (`1 <= i <= n`), **either** of the following is true: * `perm[i]` is divisible by `i`. * `i` is divisible by `perm[i]`. Given an integer `n`, return _the **number** of the **beautiful arrangements** that you can construct_. **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** The first beautiful arrangement is \[1,2\]: - perm\[1\] = 1 is divisible by i = 1 - perm\[2\] = 2 is divisible by i = 2 The second beautiful arrangement is \[2,1\]: - perm\[1\] = 2 is divisible by i = 1 - i = 2 is divisible by perm\[2\] = 1 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 15`
null
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Medium
667
1,822
hello so let's talk about the sign of the part of array so you are giving the function so uh you want to just return the value if the part of the sum um actually negative or positive or is actually equal to zero so this question is pretty straightforward so oh what you actually need to do is by like when this is negative just multiply by negative one by negative multiply negative one and then this is still going to be the same negative one right and this is negative and this is going to be part of the positive right and but the problem is well if negative multiplied by negative one right and this is going to be positive one right so we just have to take care of the negative sign only right but uh this is better like if you just keep travel for the total sign of the array so let's see so if balance is actually one by default i'm traversing the num3 so if the if num is actually equal to 0 right then i can just return 0. and then if noun is less than 0 and then i'm going to say balance multiply an equal sign by negative one right and the outs and i guess i can say lc if num is greater than zero right but this is not uh this is not important because we already have equal sign and less than right so this is definitely greater so it's going to be negative multiply the positive one right so your return of balance so this is it right so continue all right so if you notice that multiplied by positive one it should be irrelevant uh it's not important be honest but uh let's see so you can still pass the test so pause multiplied by positive one doesn't affect the result this is because we only need to count the negative sign right so let's talk about the timing space for the time this is going to be all the fun right the for loop the space is constant so this is a solution and i will talk to you next time bye
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
1,863
hello welcome back to the last of lead code problem 1862 sum up on subsets saw totals okay um the store total of an array is defined as the bitwise saw of all its elements or zero if the array is empty okay and is to return the sum up on so totals for every success of the given array okay and a subset with the same element should be counted multiple times and an array a is a subset of an array B if a can be obtained from B by deleting some or possibly zero elements of B okay so for example we have this order is one and three so we have four success the AMT is upset they are a subset has one three and one free so we saw for each subset we will calculate the saw totals and then finally we will sum it up to receive the final answer okay so uh well for this problem uh whenever we see the word subset right we will always think about uh we will always think about recursion or especially backtracking right because backtracking is a very famous technique that people usually use to generate our own possible success of uh a given array so uh okay that is uh one solution but in this video I will not use backtracking or recursion to solve this problem I will introduce I would like to introduce you and another approach by using the bit manipulations okay using the bit manipulation okay so how can we use the bit manipulation okay uh well so our idea is we will map we will Mark each subsets to abysmash of the lens and well n is the length of the given nums and okay so for example let's see we have array is 1 3 and we have one five one and six okay and then for this array how many success do we have four right and for this array how many success do we have a is right okay so uh the totals of success of every array it always equals to two powers of end success where and is the length of the array okay oh let me move this here okay so for this uh array we will have two powers of two subsets so we have four success right and for this array we will have two powers of three it is a subset right and then uh okay so I will repeat again the idea okay so we will try to map each success of a bit mass of the land ends or for example here we have uh we have four possible success right it is empty it is one three and one three okay so we will try to map each subsets to abysmas of the lens and so for example the lens of this array is uh two so okay so we will generate a business uh it has the length is two uh so for example and where um whether the bit ones uh it means the beastmas it presents is present in India right and uh we will use the bismars uh the bit of zero to say is absent from the subset so for example this subset is empty right so we will represent this by zero and then for this subset we have one we will represent as one is the first element so we will represent it as one zero two okay S2 is the second element and the first element is zero is absent from this subset so we will uh generate it has a zero one and for this subsets our own elements uh appear so that is one right so uh let's uh try again for this array right so we have is possible success so they are empty right empty it is zero so as the length of this array is free so we will generate Abyss uh of the length three okay and then uh the second subset is five right it is one hour the tough subset is one it is oh one oh and then six oh one five and one oh five six one oh one and one six zero one and five one six one okay so uh yes so that's all the idea okay and okay so I think uh we can dive into the implementation okay so uh let's say we do have an S case that is the array is empty right so we will check if nums dot lens is zero we will return zero okay and we will declare okay I think we can declare the answer here zero and return answer so finally we also return answer and um okay so we will have a for Loop uh okay so I think less me declare another variable for the nums dot lens okay so we will look through on the numbers of success so for uh and bitmash is starting from zero so this Mass less than Mark dot pow 2 and right smart.power which is uh two powers of n smart.power which is uh two powers of n smart.power which is uh two powers of n Plus okay so uh okay so we will try to generate own possible subsets but we will have uh another for Loop so for uh in positions is starting from zero so position less than and position plus okay so we will get the bit at the current position uh well okay so to get the bit ads a certain position okay so we can use this formula we will get uh the bit aggressive to position and then ends with one okay why because when we receive the bits to positions at we will try to shift the current bit to the end of the bit the bitmash and then we end with one to get the bit at the end of the bitmus right okay so we will check if um okay so we will apply this formula if this Mass shift left position and good one is equal to one right so we will uh equal to one and then okay equal to one and then what we do we will uh solve them right uh where we will show them so we will declare a variable for the saw total so total is equal to zero and then so total so equals to uh nums as position right and then we will add the salt total to the answer right so I think that's it for the implementation let's try to run okay so we have bet or parent types okay it should be to enter no and I think is and one okay so looks good try to submit okay except
Sum of All Subset XOR Totals
sum-of-all-subset-xor-totals
The **XOR total** of an array is defined as the bitwise `XOR` of **all its elements**, or `0` if the array is **empty**. * For example, the **XOR total** of the array `[2,5,6]` is `2 XOR 5 XOR 6 = 1`. Given an array `nums`, return _the **sum** of all **XOR totals** for every **subset** of_ `nums`. **Note:** Subsets with the **same** elements should be counted **multiple** times. An array `a` is a **subset** of an array `b` if `a` can be obtained from `b` by deleting some (possibly zero) elements of `b`. **Example 1:** **Input:** nums = \[1,3\] **Output:** 6 **Explanation:** The 4 subsets of \[1,3\] are: - The empty subset has an XOR total of 0. - \[1\] has an XOR total of 1. - \[3\] has an XOR total of 3. - \[1,3\] has an XOR total of 1 XOR 3 = 2. 0 + 1 + 3 + 2 = 6 **Example 2:** **Input:** nums = \[5,1,6\] **Output:** 28 **Explanation:** The 8 subsets of \[5,1,6\] are: - The empty subset has an XOR total of 0. - \[5\] has an XOR total of 5. - \[1\] has an XOR total of 1. - \[6\] has an XOR total of 6. - \[5,1\] has an XOR total of 5 XOR 1 = 4. - \[5,6\] has an XOR total of 5 XOR 6 = 3. - \[1,6\] has an XOR total of 1 XOR 6 = 7. - \[5,1,6\] has an XOR total of 5 XOR 1 XOR 6 = 2. 0 + 5 + 1 + 6 + 4 + 3 + 7 + 2 = 28 **Example 3:** **Input:** nums = \[3,4,5,6,7,8\] **Output:** 480 **Explanation:** The sum of all XOR totals for every subset is 480. **Constraints:** * `1 <= nums.length <= 12` * `1 <= nums[i] <= 20`
null
null
Easy
null
203
hey everyone welcome back and let's solve another elite code problem today let's look at lead code 203 remove linked list elements and don't forget to hit the like button it supports the channel a lot so let's say we have a linked list 1 2 six three four five six and we want to remove all occurrences of the value six from this list well we can just check okay one not removing that two not removing that six gotta get rid of it three's good four is good five is good but this last six has also gotta go and then we update some pointers and the new output is over here so how can we actually solve this problem with an algorithm well like many linked list questions we can have multiple pointers and using these pointers we can iterate through that through the list remove the elements we want to remove update the pointers and then return the new head that's going to be over here right but what if the value that we want to delete happens to be one that's the first value over here right so in that case what we would do is you know get rid of this node we don't really have to update any pointers and then this is our new list so we have to uh return a head and this is a new head now right like this is not the same head that we had originally in the input so a neat little technique we can use for this is have a dummy node so this is dummy and the value doesn't really matter i'm just going to put an x here because we don't really care what the value is so we're creating an extra node that's a dummy node so this is basically just for when we write our code we don't have to deal with too many edge cases so now let's just see what the actual algorithm looks like so we're gonna have two pointers i'm gonna have a previous pointer i'm going to initialize it over here with the dummy node i'm also going to have a current pointer i'm going to initialize it to the actual head of the linked list and we check our current value and see that it's equal to the value that we want to remove from the linked list so what do we update the pointer because that's what's going to allow us to actually remove this node so now our dummy node is going to point over here so now how do we actually update these pointers well current can be moved over here right because this is the next position but what about previous are we going to update previous i mean the next logical position would be over here but we just removed that node so in this case since we removed a node previous does not need to be updated we can leave it exactly where it is so now in the algorithm we see that we're at value two that's not equal to one so we're going to move forward we're going to shift our pointers now we're going to check 6. in this case since we did not remove 2 there is a logical there is a position for our previous pointer to now move to right so since we did not need to remove a node we are going to shift our previous pointer and now you might be able to see what we're going to keep doing with this algorithm we're just going to we're going to notice that 6 is not equal to one so we're gonna repeat the same process shift our pointers and last but not least three is not equal to one so we shift our pointers one more time current is going to be over here but this is null so we've basically gone through the entire list we removed the one element that we needed to there was only one element that we needed to remove so now what is our new list well this is what our new list looks like right so we initially started with four elements we removed this one and now we only have three elements remaining but we need to return the head of this list this is the head how do we get the value because we shifted our pointers we kept shifting them until they got to the end of the list that's one of the reasons why we created this dummy node notice how the dummy node points exactly where we want it to point it points at the new head of the linked list so what we're going to do in our algorith in our algorithm is return dummy dot next and since the only extra memory we're using is pointers the memory complexity of this is o of 1 and the time complexity is big o of n because we do have to iterate through the entire linked list so now let's get to the code just like in the drawing we have a dummy node it's going to be a list node we don't really care about the value that it has but we do want the next pointer to point at head it's basically inserted right before head and we are going to maintain two pointers previous and cur previous is going to initially be to the left of current which is going to be dummy and current is going to be set to the head value that we're given as a parameter to the function and so we're just going to keep iterating through this list while current is not null and i'm going to get the next pointer which is just current.next i'm going to put it in a current.next i'm going to put it in a current.next i'm going to put it in a variable so we make sure that we have it stored and i'm just going to check if current dot uh not val current.val is equal to the not val current.val is equal to the not val current.val is equal to the target value that we're trying to eliminate which is also a parameter if it's equal to val then we know we can delete current and we can do that by updating our pointers so previous dot next instead of this pointing at current we can point it at the next node in the linked list and if we're not removing that value we can then say previous is going gonna be shifted to the right so the reason we're not updating previous over here is because there's no need to right because we had to delete current so there's no position for previous to be shifted to and regardless whether we delete a node or don't delete a node we do want to update our current pointer so current is always going to be shifted to the next pointer and so the last thing we need to do is return the new head which is always going to be at dummy.next dummy.next dummy.next because remember dummy is a node that we're never going to delete and so whether dummy.next is null whether dummy.next is null whether dummy.next is null or not it's always going to point at the first node in the linked list and when you name variables like this and you have name con flicks like this you got to remember to not have any typos and so it works i hope this was helpful if it was please like and subscribe and thank you so much for watching
Remove Linked List Elements
remove-linked-list-elements
Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. **Example 1:** **Input:** head = \[1,2,6,3,4,5,6\], val = 6 **Output:** \[1,2,3,4,5\] **Example 2:** **Input:** head = \[\], val = 1 **Output:** \[\] **Example 3:** **Input:** head = \[7,7,7,7\], val = 7 **Output:** \[\] **Constraints:** * The number of nodes in the list is in the range `[0, 104]`. * `1 <= Node.val <= 50` * `0 <= val <= 50`
null
Linked List,Recursion
Easy
27,237,2216
96
hello welcome recently partly we are going to solve this little problem named GUI by nice asking so given on given numbers so number three so that how can I mean how my number three who can make closed chamber one this way so check this example so you know that 25 Knightley writes one is the other chef whose child loan and one parent nodes and whatever tried if they certain the very good website contain a link on the right side therefore the magnet minority work and so you see that input tray then you can make five kind of finally you define a tree so select one as a note and you can create two kind of an idea like one A two and one was kind of like so if you make known then you can make only one you depend if we same similar for free also thing you can mix together by Newton so it's kind of like going to lose than any program we had without this and so I will do I leave one pp area and if size only one so you can create only one and T we are using DP because so to select click the right one right on the left side is zero so you can create only one binary button that I said look too so we don't people so if we know that easy to learn how many from this you can create then we can use those result competition for this is in where you returning program come on or look so we are going to use iPods - I like a repeal is equal to n ni iPods - I like a repeal is equal to n ni iPods - I like a repeal is equal to n ni plus that is into for loop time from the scalp you order of n square J then we compute the value so ext3 all together hello for 0 and 1 I first what we calculated earlier plus with the I plus J minus one yeah that's pretty much what is old and I will return after about a theory DPN should be all minus 1 now i'm just put once again but it's not good enough it's potentially inertia conservation circuit you can see it's 100% you can see it's 100% you can see it's 100% yeah thanks ecology we next video these are taking us at the 2-liter put the are taking us at the 2-liter put the are taking us at the 2-liter put the media itself thanks
Unique Binary Search Trees
unique-binary-search-trees
Given an integer `n`, return _the number of structurally unique **BST'**s (binary search trees) which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. **Example 1:** **Input:** n = 3 **Output:** 5 **Example 2:** **Input:** n = 1 **Output:** 1 **Constraints:** * `1 <= n <= 19`
null
Math,Dynamic Programming,Tree,Binary Search Tree,Binary Tree
Medium
95
257
hey welcome guys so let's solve this 257 binary tree pass this problem is uh really uh this code is really important to make to solve other problems like a 900 a in the other problem so basically uh this problem basically will uh give you the code now you can start from roots and go to all the paths also all or at least so given a rules of binary written or root leaf this is a important in any order so one two five so you want to five one three okay so uh simple problem if there's no roots right you just written none otherwise you initially okay so now you start from the empty you start from empty string right and you go start from you that value at the current note so for example uh you start from here you start from let me just run to just run the code one two three five let me just go through okay so now uh when you start from roots right you get the you get this okay and it's not low not no left and no right so this is the condition that you reach a leaf if you reach the leaf then you just return this so this uh that will make the results into a string okay and so but if there's still no left there's your left child and then you go through that but you add this arrow right so in this case there's still two right so i added this so now i become one and this and uh so i left i added the value so because this okay and at least well keep going right because there's just still no right and i add another one and the final i arrive here and therefore once i arrive these five there's no rest right so i can just open so basically the simple idea that if i see if there's left no left and no right then i just get answer if there is no left then i go left if there is a right i go right that's it and then you just return the path and uh you just go around this path so this is somehow like the dfs and you change okay so this is a very uh important technique for you to uh for you to solve other problems because there are many problems asked about the property of all rule to leave okay so that's it just very straightforward okay so uh see you guys next videos
Binary Tree Paths
binary-tree-paths
Given the `root` of a binary tree, return _all root-to-leaf paths in **any order**_. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[1,2,3,null,5\] **Output:** \[ "1->2->5 ", "1->3 "\] **Example 2:** **Input:** root = \[1\] **Output:** \[ "1 "\] **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `-100 <= Node.val <= 100`
null
String,Backtracking,Tree,Depth-First Search,Binary Tree
Easy
113,1030,2217
93
so good evening so I'm back with another video uh this time I'm going to be making a video called restore IP addresses in wheat code so on the offset this question looks somewhat difficult but I can show you how to do it in somewhat of an easy manner all right so this is mainly a backtracking question if you think about it so the one way to figure out it's a backtracking question is just look at the constraint it's one trick wedding so that's not a lot all right so let's look at the question a valid IP address consists of exactly four integers separated by single dots each integer between 0 to 255 inclusive so you guys might have obviously seen IP addresses right it's that weird number that comes up when you try to hack someone's internet or something like that so I mean I'm just making that a flashback so in general IP addresses are how you identify networks or other people's networks so something unique about IP addresses is the way they look so they always four numbers separated by dots like this usually they are like this something like this so this is a class A address and so usually it you I'm not too familiar with this like I have studied networks before but yeah it's these are IP addresses so ads irrelevant to this question either way the only thing you'll need to know about IP addresses in general are that they are consisting of four integers like this uh the now these integers are always between 0 to 255 and also one thing you have to know is that the first address can never be a zero all right it should only be after that all right so that's what we're going to do so now what we are given is we're given a string and we have to place these dots given a string s containing only digits written on all possible valid IP addresses that can be formed by inserting dots into s all right you're not allowed to reorder or remove any disk it's perfect so we're given an integer like this a string like this and we are supposed to find out combinations by making IP addresses and they should be complete so for example one possible way to do it would be to add a DOT here then you cannot do this because 525 does not come in this range 0 to 255 inclusive so one way to do it in this case would be to put a dot here so this is 255.255.11.35 inclusive perfect so 255.255.11.35 inclusive perfect so 255.255.11.35 inclusive perfect so another way to do this would be to make this here so 135 is a valid IP address 11 is 255 is so as you can see for this one you have two valid IP addresses so there will be no other combination where you can make it valid so for example if you thought of putting the dot here this would be 113 which is not a valid IP address similarly you couldn't do one here because this won't be a valid IP address similarly you cannot remove this and put it somewhere else because then 511 won't be an ielted IP address so that's how we have to solve this question so let's begin solving this question so like any other backtracking question so usually when I think about questions like this where you have to validate across a huge number of the possible combinations permutations Etc I would always suggest going for a backtracking approach so let's define a function called backtracking that's how we always started and what do we need in this backtracking function so first things first we need to keep track of the lengths that we are adding into this question so we'll call that variable length all right then we'll also need to keep track to a great extent you will also need to keep track of the word or the uh the IP that is forming so I would like to keep it in the form of an array because I think that would be really useful so if you have an array we can put each individual element and then combine it at the ending to give you this perfect with the dot result all right and also one more thing that we need in this question is the dots if you can see so an IP address you need it consists only of four parts so we need to have four dots so the initial one wouldn't really be a dot but after you do this we need to decrement it so let's keep dots as one more of the variables that we need for the backtracking function and now we're ready to go so right now I'm just defining this function like this let's call the backtracking function with the parameter so initially the length will be 0 you will have four dots that you can place an IP so yeah this question you can see three dots technically but the first element is also a DOT you also have a DOT before the first one if you think about it logically you don't have to display the dot but you have a DOT for the first one so anytime you encounter a DOT we reduce it right so if we have four dots here we put this reduce it to three then we put this reducer to two we put this reducer to one then we put this radius it to zero and then we can start so evalu putting that entire string into the answer all right so now yeah so what is this IP this is an empty array initially all right and we also need to keep an answer array where we'll keep track of all the answers and we'll return this answer array after we call this backtracking function all right so let's start with this backtracking function so first things first let's look at the edge cases so the first edge cases is that if the length if the number of dots that we have is equal to zero so now you have exhausted all the possible dots and the length is not equal to S the length of s the length of the string so you have exhausted all the dots and you do not have any more you have not reached the end of the string so that means you're not able to use this entire string that they have given so in this case you have to return so there's one more case where if you've reached the zero dots and in this case you do have reached the end of the string so for that we have length is equal to line S so now that in this case we will save this answer we will save the IP address that we have gotten so how are we going to save the IP address we will append it to the answer and the way we do it in this case is so we will have an array of all possible combination somewhat like this so you'll have two five 255 dot then you'll have 11 and you'll have a one three five so how do you get this output that you require from this well it's very easy in Python all you have to do is open apostrophes dot so this is the variable that you want to join it with dot join and then you just pass in the array that you need which is this one which will contain this in the ending suppose you wanted to print this with commas and not dots all you'll have to do is put a comma here if you didn't if you just wanted to join it without anything all you'll have to do is this and lastly anything any variable that you have you can join it with that here so all right so you have joined this here and then you can return all right so now let's actually do it okay so now as you can see we are we at Max the number of uh the number of elements that we can take here are only three right so because anything more than three at that point it's no longer a valid IP address because it's it should be between zero to two five so how can we do that so let's do it this way all right for Num in range one comma four so what does this do so we will take the current value whatever it is we'll try at taking one element we'll try taking two elements we'll try taking three elements that's why so this range is inclusive and within that range we will put we'll try to backtrack with each of those values all right so now let's check so one first thing that we have to do is if is valid all right so is valid we are not defined yet so let's assume that Z is valid function which will Define which will take in a string as a parameter and it will return true or false whether the string is a valid string or not all right so if is valid now what do we have to take as the word where it's very simple we need to take the string we need to start from the length whatever we are at right now up to length plus the number here all right or I'll just call it I think it'll be easier if I call it I here so length up to length plus I so what would this do okay I'll explain it in more detail all right so suppose you start with two five let's start with the string to this entire string here what will it do all right so first it will check from 0 to plus one right so 0 to 1 inclusive so it will take two it will call backtracking on two and then it'll increase the length so from in the next thing onwards we'll check from the rest of it so if this does not end up being valid we will check with two five then we'll check with two five after that we'll exhaust this range and it will stop using it anymore I'll show it to you in the debugger as well so if is valid this if this is valid what do we need to first of all append it to the IP all right IP dot append s of length Okay one thing why don't I save this enough value all right number or let me just call it IP part is equal to this all right so if I if is valid IP part if this IP part is valid if whichever path that we get it if it's valid we will append it to the array all right after we append it to the array we will call backtracking on it all right so we'll call that so what do we need to pass now into this backtracking function now since you have added this to the array we'll have to do length plus one since we are moving to the next element remember we have added a DOT so we'll have to reduce the DOT reduce the dot so we have only three dots remaining for the rest of the thing all right so after that what do we need to also pass the new IP so we have added this element to the IP so now if this ends up not working what do we need to remove that last element from the IP so yeah this part is perfect now we're done with this part now all you have to do is you have to create this valid function that will check if it's a valid IP address or not all right so one thing is that if your string looks like this 0 7 is 0 7 a valid number it's not uh 7 is a valid number you there is no in actual numeric system there is no such number called zero seven so we will have to take care of that term case as well all right so if the length of the word is greater than 1 and word of zero is equal to a zero we will return false this is just a test for the cases where the word starts with zero suppose it's 0 9 or something like this which does not work but just 0 is a valid numerical that's why I'm checking first if the length of the word is greater than one all right apart from this let's check if the word is valid right so first of all it needs to be an empty string okay if either of these cases or if not word all right so if you pass an empty string by any chance then also it should return false so if all these cases it will return false so now after this check we can check if 0 less than equal to integer word if the word less than equal to 255 if it comes within this range we will return true and we'll just return false in case it does not come match any of these criterias okay so now your first is valid word you have defined the backtracking function you have passed this and now it will populate the answer array that we defined here and it will return the answer so let's run this and there's some issue let me just check what the issue is um second we're calling it correctly and start okay if just let me check here word and um okay so I figured out what the issue was earlier so the issue is that after just a second yeah so the issue is that when you're calling the backtracking function the second time uh one of the main things that you have to take into consideration is when you're passing the length so once you take one element for example then you have to do length plus one but if you take two elements then you have to do length plus two and if you take three elements then you have to do length plus three so this is not length plus one this is length plus I yeah yep now it works so test data to make sure so let's run this problem and yes it's accepted and it beats 75 to the solution so let me show you guys the debugger too just to make sure uh apologies for that earlier actually I had coded this some time back I had a small doubt within it yeah so let me show it to you guys in the debug up so I'll just show you one a little bit into it how it goes and then I'll show you guys the rest all right so let's do it you begin backtracking from zero four all right so now the dots this conditions don't matter so yeah now we'll start from one so it will first take zero one so it will take the string two so let's just keep track of the string that we have to take so it will take two so this is the string and we are taking the part is two all right so now we will first append it to the array so now we have just two in the array now let's call backtracking for the rest of the elements all right so now for the rest of the elements and we've reduced the number of dots okay so none of these conditions matter so now we do it again with one since it's coming back to the function we'll check if the next element which will be a 5 after that is it true so then we'll append it backtrack and then we'll have to do it again so now we'll reduce the dots again round dots are two we'll do it again so let's find the next five We'll add it and we'll decrease dots again all right so now we have taken two five so now we it one last time which will take the fourth five and we'll call backtracking again so now as you can see in this case we have taken the first four elements and now the dots have reduced to zero we do not have any more dots to be placed and we have not read first of all we have not reached the end of the string in this case so since we have not done that what we have to do is we have to return we'll break from this Loop okay once you break what happens why is this pop important now we'll remove this two the last two that we took now what is it going to do we completed I in range one now we have to do two so when we do 2 it will take two elements so two five it'll take two five in this case so it'll take 2 5 it will add 2 5 to the element now so like that I'll tell you how it goes so first it will take two five two individually then it'll take two five of two five yeah like in this case two five all right after that in the next case it will take two five it'll take these three so now it's already exhausted three so now what will happen is and we have not reached the end in either cases so it will pop both of these it will pop five and two five so you will be left to two and five after that it will take in combination of two so it'll take five two and then five then it will take five to five then five and yeah it'll keep going like that if you get my gist so yeah that's how we do this question it's a backtracking question it looks complicated from the offset but it really isn't so yep thank you so much for watching and I'll be uploading more videos
Restore IP Addresses
restore-ip-addresses
A **valid IP address** consists of exactly four integers separated by single dots. Each integer is between `0` and `255` (**inclusive**) and cannot have leading zeros. * For example, `"0.1.2.201 "` and `"192.168.1.1 "` are **valid** IP addresses, but `"0.011.255.245 "`, `"192.168.1.312 "` and `"[email protected] "` are **invalid** IP addresses. Given a string `s` containing only digits, return _all possible valid IP addresses that can be formed by inserting dots into_ `s`. You are **not** allowed to reorder or remove any digits in `s`. You may return the valid IP addresses in **any** order. **Example 1:** **Input:** s = "25525511135 " **Output:** \[ "255.255.11.135 ", "255.255.111.35 "\] **Example 2:** **Input:** s = "0000 " **Output:** \[ "0.0.0.0 "\] **Example 3:** **Input:** s = "101023 " **Output:** \[ "1.0.10.23 ", "1.0.102.3 ", "10.1.0.23 ", "10.10.2.3 ", "101.0.2.3 "\] **Constraints:** * `1 <= s.length <= 20` * `s` consists of digits only.
null
String,Backtracking
Medium
752
271
hey everyone welcome back and let's write some more neat code today so today let's solve the problem in code and decode strings so you can tell the interface is a little bit different this time and that's because we are going to be solving this problem on lint code because this is a premium leak code problem and we can solve it for free on the website lint code and also this is a problem from the blind 75 list a list of 75 common leak code questions that we've been tracking on this spreadsheet the link to this will be in the description if you want to take a look and we're pretty much done with the main problems i'm going to be solving another one today a premium one in code and decode strings this is a pretty decent problem to understand so let's get into it so it's a bit of a design algorithm because we're going to have two different functions that we want to implement so we're given a list of strings and we want to write two functions we want to encode this list of strings into a single string and you can kind of see that down here we were given an input list of strings lint code love you and we want it to be a single string such as this one in the bottom right and then the d code is just going to be the opposite of in code we're going to be given a single string and we want to be able to convert this string in into back into that original list of strings that we were given and it's up to us on how we want to design this algorithm but the tricky part is going to be that where the basic assumption is that in our input we could have any possible character in the inputs not just limited to lowercase a to z so the difficult thing is going to be how do we create some kind of delimiter between each word how do we know when one word ends and another word begins that's kind of what we're going to be focusing on so let's get into that solution so suppose we were given two strings like this neat and code and we want to convert it into another string basically into a single string right so a naive way would be something like this right just say okay neat code now the problem is okay we did that the encode was fine but now we want to decode this back into the two original strings that we had but there's no way for us to determine right because we can't remember where one word ends and another word begins right so we need to have some kind of uh character or something to separate words what if we used a pound sign or something right something like this or any character maybe a question mark or something right but this is like our special character that's what's going to separate words for us so in this case it works out right we'll go character by character in the input once we get to a pound sign okay we'll say that this word ends so we'll say okay we have the first word neat and this is not included in any of the words so we skip it and then we get to the remaining portion code and there aren't any more pound signs so that works out in this case right but basically our assumption when we're using this pound sign is that the pound is never going to actually show up in any words what happens if we have a word suppose in our word code in the middle of the word we have a pound sign right there's no reason why we can't have something like this so in that case when we take this and encode it we're gonna get something like this as the encoded string right and then when we split it we're gonna have three different words neat co and d e but in the original you can see we only had two words but when we get our output we're gonna end up splitting this into three words which is not what we wanted to do right we want to transform it back into what was originally given to us so having just a single special character delimiter is not going to work because that delimiter could actually show up in some of the words wouldn't it be nice if in the encoded string we somehow already knew how many characters would go in the first word how many characters would go in the second word etc so then we could just say okay let's take the first four characters encode it back into the first word then take the next five characters and code it into the second word so how could we you know do something like that well one way would basically be by maintaining some kind of array right when we're given this uh inputs a list of strings and we want to encode it to a single string we can for every single word basically have an integer right the first word is four characters the next word is five characters etc but then where are we gonna store this list because you know this is a valid solution if we're storing this list somewhere but basically in the description they don't want us to store any kind of state variable this encode and decode needs to be stateless so when we have this list 4 5 we cannot store it in a separate data structure is it possible for us to store it in the string itself how about when we're encoding this we want to know okay starting at the beginning here how many of these characters are going to be in the first word well why not just put that number at the beginning right 4 at the beginning of this encoded string that works because then we can look at the beginning transform it into an integer but one thing is what if the word itself had some integers in it well now we need another delimiter right we're gonna have our integer always at the beginning there's always going to be an integer at the beginning the string is always going to start with an integer that integer is going to represent what the length of the following word is going to be but we're going to have a delimiter in between the integer and between the word itself so basically we're going to read each character until we reach the delimiter and once we reach the delimiter we're going to take all the characters that we just read which are going to be transformed into an integer so this 4 is going to be mapped to four and then we're going to count the next four characters after the delimiter which in this case is going to be pound and that works because we're only going to read one delimiter we're always gonna we're gonna expect a single pound sign no matter what right so even if the first character here was a pound it still works because we're gonna read an integer four read a single pound sign and then say okay take the next four characters even if they include pound even if they included some integer like eight or you know six or something right if they include integer pound it doesn't matter because this tells us how many characters are going to be in the first word and then once we read those four characters what are we going to expect to be next well we're going to expect some word but we want to know how long that word is going to be so we're going to do exactly what we just did over here having an integer followed by a pound sign and we're going to put that same thing over here so in this case we're going to have a 5 and a pound sign because the next word is going to be five characters long so this is kind of how we're storing the integers inside of the encoded string so that we know how to decode it we know how long each of the strings is going to be so i hope this makes sense now i'm going to show you how to actually code it up by the way the overall time complexity of encode and decode is going to be of n where n is going to be the total number of characters given to us in the list of words so with that being said we are ready to get into the code okay so now let's get into the code you can see the interface is a little bit different yes we are doing this on lint code rather than leak code because it's free on there so let's start with the encode function it's a little bit easier so remember we're given a list of strings and we want to encode it into a single string how are we going to do that well we're going to go string by string in the input and to the result we want to append this encoded string s how are we encoding it again well remember we're going to take the length of the string and you know this the length of the string is going to be an integer but we want to transform that into a string so let's do that in python pretty easily just like this plus we want to add the delimiter to the pound sign so we have the length of the string followed by the delimiter pound sign followed by the string itself s so then you know this is kind of the format that we agreed upon this is how we're going to be encoding it because it's going to be easy for us to decode this as well so we're going to do this for every single string in the input add it to the result and then we can go ahead and return that result so encode was pretty straightforward d decode is going to be a little bit more tricky but we know the rules that we can follow so this time we're given a single string a single encoded string which is going to be you know encoded using the function that we just wrote so how are we going to decode it into a list of strings in this case our result is going to be a list of strings and i'm also going to have a pointer i which is going to tell us what position that we're at in the input string so far so i'm going to just iterate character by character so while i is still in bounds we are going to read character by character basically decoding each string so when we start off the first position that we're going to be at is going to be an integer right so what we want to do is we want to find the delimiter we want to find the end of the integer so we're going to have a second pointer j initially it's going to be at i and while the characters the character at pointer j is not equal to the pound meaning that we're still at an integer character we're going to keep incrementing j by 1. and we're guaranteed to find a pound character right because we that's kind of how we encoded it up above so we're going to keep incrementing until we get to that pound character and then once we get to the pound character we know that our integer the length of the following string is going to be from our string starting at index i going all the way up until index j but not including index j right so that's this portion is going to be the integer right now it's a string so we want to uh transform it into or convert it into an integer we can do that in python pretty easily just like this so now this length variable tells us how many following characters we have to read after j in order to get every character of the string so in other words if we start string at index j plus 1 because remember j is at the delimiter character so j plus one is going to be the first character in the string itself and we want to go all the way until the end of that string how do we get that well right now we have the length of that string so we can say j plus 1 plus length this will give us the entire string and what do we want to do with the string well we want to append it to the result so let's go ahead and do just that so basically each iteration of this loop is gonna read one entire word and then we're gonna go again loop again and read more words until we reach the end of the string but one thing we forgot is how are we gonna update our pointer i well we just read a single word so now we want to start at the next word how do we get that well our pointer i is just going to be set to j plus 1 plus length because this is actually not this is going to be basically the beginning of the next string or it could be the end of the entire string right but either way this is how we are going to be updating our j each iteration of the loop once we're done with that our result will be containing all the decoded strings so we can go ahead and return that result and as you can see i just ran the code and it looks like it works and it is pretty efficient so i hope that this was helpful let me hide that 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
Encode and Decode Strings
encode-and-decode-strings
Design an algorithm to encode **a list of strings** to **a string**. The encoded string is then sent over the network and is decoded back to the original list of strings. Machine 1 (sender) has the function: string encode(vector strs) { // ... your code return encoded\_string; } Machine 2 (receiver) has the function: vector decode(string s) { //... your code return strs; } So Machine 1 does: string encoded\_string = encode(strs); and Machine 2 does: vector strs2 = decode(encoded\_string); `strs2` in Machine 2 should be the same as `strs` in Machine 1. Implement the `encode` and `decode` methods. You are not allowed to solve the problem using any serialize methods (such as `eval`). **Example 1:** **Input:** dummy\_input = \[ "Hello ", "World "\] **Output:** \[ "Hello ", "World "\] **Explanation:** Machine 1: Codec encoder = new Codec(); String msg = encoder.encode(strs); Machine 1 ---msg---> Machine 2 Machine 2: Codec decoder = new Codec(); String\[\] strs = decoder.decode(msg); **Example 2:** **Input:** dummy\_input = \[ " "\] **Output:** \[ " "\] **Constraints:** * `1 <= strs.length <= 200` * `0 <= strs[i].length <= 200` * `strs[i]` contains any possible characters out of `256` valid ASCII characters. **Follow up:** Could you write a generalized algorithm to work on any possible set of characters?
null
Array,String,Design
Medium
38,297,443,696
1,696
Hey everyone today I want to explain the solution&nbsp; to problem 1696 on LeetCode called Jump Game 6.&nbsp; In this problem, we're given a number line&nbsp; with n steps. We are also given a number,&nbsp;&nbsp; say k, which represents the most steps&nbsp; we can take forwards in each turn.&nbsp; On the number line are certain numerical&nbsp; values. Every time we land on a number,&nbsp;&nbsp; that is the number of points we get. If&nbsp; the value is negative, we lose points.&nbsp; The question is, given this number line and&nbsp; k, what is the highest score we can obtain&nbsp;&nbsp; by the time we reach the last number? At first the answer may seem obvious,&nbsp;&nbsp; but coming up with an approach that&nbsp; works for all cases is trickier.&nbsp; To start, we can express this number&nbsp; line as a one dimensional grid. This&nbsp;&nbsp; grid will have a height equal to one,&nbsp; and the length is given by the problem.&nbsp; With this, let's try to come up with some&nbsp; procedures of getting the highest score.&nbsp; First, we should land on every possible&nbsp; positive value. Positive numbers are always&nbsp;&nbsp; going to increase our score. And it's always&nbsp; possible to land on all the positive numbers.&nbsp; On take note of is that backtracking is&nbsp; not allowed. This means that if we pass&nbsp;&nbsp; a positive number without landing on&nbsp; it, then it is impossible to go back.&nbsp; With this in mind, if there&nbsp; are multiple positive numbers,&nbsp;&nbsp; then we should always land on the closest one. So far the strategy is to choose the positive&nbsp;&nbsp; number as our next step and when multiple&nbsp; positives are present we choose the closest one.&nbsp; So what happens if there are no positive&nbsp; numbers that we can reach on the next turn?&nbsp; Let's say we have the following number line. k&nbsp; = 2 and all our options are negative. For now,&nbsp;&nbsp; let's pretend our code only stores&nbsp; numbers that we can land and we do not&nbsp;&nbsp; keep track of future values until later. Here, we have to between -2 and -10,&nbsp;&nbsp; and we choose -2 because it causes us to lose&nbsp; fewer points. However, the next number is&nbsp;&nbsp; actually -100. And now we also have to land on&nbsp; -10 to avoid losing 100 points. But in the end,&nbsp;&nbsp; we actually lost more points than necessary. So what if we land on -10? Well, the same thing&nbsp;&nbsp; can go wrong. The next square can be positive&nbsp; 100 and we could have just landed on -2 and&nbsp;&nbsp; only two points instead. This tells us that&nbsp; if we started from the beginning of the grid,&nbsp;&nbsp; we cannot have a simple solution.&nbsp; So what if we start at the ending?&nbsp; Along with this change, we will also add a grid&nbsp; where at position x, we store the optimal score&nbsp;&nbsp; we can obtain if we started from that position. In this example, we're going to start at&nbsp;&nbsp; position 9 with a value of 7. In our&nbsp; second grid, we can call an array,&nbsp;&nbsp; the last value should be 7. Since this is the&nbsp; highest score we can get starting at position 9.&nbsp; Now let's move one step backwards. We're now at&nbsp; position 8 and we lose 3 points. But -3 is not&nbsp;&nbsp; the highest score obtainable from position 8.&nbsp; It's actually 6 (4*). The game only ends when&nbsp;&nbsp; we reach the highest square 9. So this means that&nbsp; if we take one step forward we can actually gain a&nbsp;&nbsp; net total of 7 points. The means that the highest&nbsp; score obtainable starting from the square #8 is 4.&nbsp; Again, we take another step backwards&nbsp; to position 7. Our current value is -1.&nbsp; This case is a little different because k = 2,&nbsp; so we can actually choose between 4 and 7. In our&nbsp;&nbsp; problem we will always choose the maximum value.&nbsp; If we choose 4 we'll gain additional 4 points by&nbsp;&nbsp; the end of the game, and choosing 7 means we will&nbsp; gain an additional 7 points by the end of the&nbsp;&nbsp; game. As a result, our maximum value here is 6. Let's take one more step. At position 6,&nbsp;&nbsp; our value is positive 4. We can reach up to&nbsp; 2 squares ahead. So 7 is now out of reach.&nbsp;&nbsp; So we must choose between 6 and 4. Since 6 is&nbsp; greater that's what we go with. So the maximum&nbsp;&nbsp; score get can at square 6 is 10 points. See this where is going? If we continue&nbsp;&nbsp; until we reach square, we essentially&nbsp; have our answer, which is the most&nbsp;&nbsp; points scored if we start from square #1. A solution like this known as dynamic programming.&nbsp; By using the procedure we can&nbsp; get that the maximum score is 17. You can pause&nbsp;the video to&nbsp; confirm that this is the answer.&nbsp; To program this solution we can create empty array that stores the optimal values. But for&nbsp; each square, how do you find the highest value&nbsp;&nbsp; within our reach? For instance, take our current&nbsp; example and say we're at position 3. Since k = 2,&nbsp;&nbsp; we have to find the greatest element that&nbsp; is up to 2 squares ahead. k is small here,&nbsp;&nbsp; so we can check every value, but as k&nbsp; increases, we have to loop through each&nbsp;&nbsp; value and this gets increasingly more expensive. For the first approach we can try using a sorted&nbsp;&nbsp; array which keeps all the values in ascending&nbsp; order. Every time a new value is added,&nbsp;&nbsp; we can use the binary search algorithm&nbsp; which takes up to log_2(L) computations,&nbsp;&nbsp; where L is the number of elements, or length, of&nbsp; the array. With this method, getting the maximum&nbsp;&nbsp; value only takes 1 computation, and that would&nbsp; be finding the last element of the array. So far,&nbsp;&nbsp; the program runs in n * log_2(L) computations. And&nbsp; since the most elements in the array is equal to&nbsp;&nbsp; k, the worst case scenario would be n * log_2(k).&nbsp; This is reasonable, but the problem lies not in&nbsp;&nbsp; adding elements, but removing elements. You see, every time we take another step&nbsp;&nbsp; backwards, there's a good chance that a value&nbsp; becomes out of reach. It's difficult to know&nbsp;&nbsp; exactly where this exists in our sorted array, and&nbsp; we usually just loop through all of these values&nbsp;&nbsp; to find it. And doing this would take an extra&nbsp; n computations. We can use a faster method, but&nbsp;&nbsp; this will make the code a lot more complicated,&nbsp; and there's also faster ways to do the same job.&nbsp; In this approach, we store the values in a type&nbsp; of map. A map is where a key is linked with a&nbsp;&nbsp; value. We can use the a type of map sorts the&nbsp; keys in ascending order. And since keys cannot&nbsp;&nbsp; be repeated, we use the value to store the&nbsp; amount of keys present. Here, we have 7 as&nbsp;&nbsp; our value in the array. We stored this value in&nbsp; array as the key, and store 1 as the value in&nbsp;&nbsp; the map because there's only 7 present. When we take a step down in the grid,&nbsp;&nbsp; we use the highest key in the map and add it&nbsp; to the array. So now, we have 4 and that is&nbsp;&nbsp; also added to the map. Eventually, if we repeat&nbsp; this process, there will be a number that we&nbsp;&nbsp; can no longer reach. In this case, it's 7. And instead of searching all the values to&nbsp;&nbsp; remove it, we can just search it by the key. And&nbsp; this only takes up to 1 computation. So this code&nbsp;&nbsp; runs in at most n * log_2(k) computations.&nbsp; And is relatively a lot easier to implement,&nbsp;&nbsp; but still not the fastest solution. In our final approach, we store values&nbsp;&nbsp; in a deque. You can think of a deque&nbsp; as a double sided line where values be&nbsp;&nbsp; either removed or added from both ends. For this&nbsp; approach, instead of storing the maximum values,&nbsp;&nbsp; we store the position of the maximum value. To understand the solution that uses a deque,&nbsp; we have to use an example first. Also keep&nbsp; in mind that k has increased from 2 to 3.&nbsp; Here, we start a position 9. And we add that to&nbsp; the deque. We have to track of the positions,&nbsp;&nbsp; not the values. Next up is -3 at square #8. First&nbsp; we get the position at the head of the deque, 9,&nbsp;&nbsp; to get the highest value that we can reach, 7.&nbsp; Then we add 7 to -3 and put it in the second&nbsp;&nbsp; array. Then we also add this to the deque.&nbsp; Now we can do same thing to the next square.&nbsp;&nbsp; We use 9 to get 7 and add it to -1 to get 6.&nbsp; And we put position 7 at the end of the deque.&nbsp; Now let's make an observation here. Position 8&nbsp; has the value 4, and position 7 has the value 6.&nbsp;&nbsp; This means that we would never choose position&nbsp; 8 whenever position 7 is one of the options.&nbsp;&nbsp; The only reason we would choose position 8&nbsp; is if position 7 is out of reach. However,&nbsp;&nbsp; position 8 will always be out of reach before&nbsp; position 7 does. This means that position 8 is&nbsp;&nbsp; obsolete when position 7 is always here.&nbsp; So we can just remove it from the deque.&nbsp; Let's keep going with this example. We're&nbsp; now at position 6 and the highest is still&nbsp;&nbsp; position 9. We can use that and get 7, add it&nbsp; to 4, and we have 11. Now we add position 6 to&nbsp;&nbsp; the end of the deque. We compare position 6 to position 7 and find that position 6 is higher,&nbsp;&nbsp; so we can remove position 7 from the deque.&nbsp; The same things goes with position 9. We&nbsp;&nbsp; find that position 6 is greater, and&nbsp; we remove it from the deque as well.&nbsp; Let's continue animating the&nbsp; last few steps of this solution.&nbsp; Ok, pause. We notice here that we're at position&nbsp; 1, but now position 5 is out of reach. So we&nbsp;&nbsp; simply just remove it from the deque. Now we can&nbsp; use position 2 to find the optimal score we can&nbsp;&nbsp; obtain from position 1, and that is 20. And that's it! 20 is our solution.&nbsp; If you want, you can pause the video to confirm&nbsp; this. Keep in mind that k increased from 2 to 3.&nbsp; This marks the end of the implementation&nbsp; section. I'll show my java code but I&nbsp;&nbsp; advise you to try programming this on your&nbsp; own to get a better grasp of the concept.&nbsp; This pretty much sums of the solution&nbsp; covering problem 1696 on LeetCode. I hope&nbsp;&nbsp; this video proven helpful in solving&nbsp; this problem. Thanks for watching.
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
1,046
Hi guys welcome back to my channel cpp code and today we will do question 1046 of lead code, it is a good question, I have solved it before, see what is given in this question, the name of this question is last stone wait or r. Given an array of integer number of stones, what is the weight of each stone? We are given an array of stones and in them we are given different weights. We are playing a game with the stones on each turn. We choose the Heaviest Two Stones and Smash Them Together We are playing a game in which we pick up the two heaviest stones and throw them and smash them. Suppose the heaviest two stones have weight x and w and x is less than equal to w. The Result of the Smush: If of the Smush: If We have to push that stone at the end of the game, there is at most one stone left, there will be either one stone left or zero, so now let us see its code, how will we do it, we can apply an approach in this, priority. We create Priority Why do we have to create it? We create Maxi. We have created Priority Cube. In this, we will first push all the elements and put a loop from E to A. In this lesson, we do this by replacing the stos with A. Let's keep it will be easy for us to use, we can do this also, by doing this, we have put the loop till the size, now what will we do in this, we will push all the elements in P, we will push all the elements, how by putting A and we have pushed. Now we have pushed, what to do now, we have to put a loop, while which is our priority, why is its size greater than one? As long as one is bigger than one, we will keep running the loop, till then we will keep running the loop and what will we do? We will extract two elements, the two largest elements. How to extract them? Now in this text we will store the top of PK. In the top of PK, now see, it is in the priority key such that if we had made only max, then the biggest element would have been the top. But it is the largest element and we have taken out the largest element. We need the two largest elements, otherwise we will remove both of them. Now first we take out the first one and we have stored that element and popped it. Now that element has been removed. Now, whatever max is left in the heap, the element that is left in it will be the biggest but it will be the second largest element, so we take that out too, put it in it again at the top of the page and do it again. Popped, now we have two elements Their absolute value means even if What we have to do is push the dot, what we will push is we will push it and again a heap will be created and after this we have pushed it, after this what we have to do is again we will put a loop and like this It will continue, okay yes, so now we will check if the size of the puck is that If it is equal to two then we will return the top of the puck We will return the top of the puck Else Its size will be zero or one. Either it will be zero, it cannot be bigger than that, because if it were bigger than that, and it would run in the loop, it will come out of the loop only because its size has reduced, either it will be one or it will be zero, else its size else, we have returned it to zero now. Let's run this code and see if there is any problem then let's see it will work. Oh no, look, we had to create a function Yes, it works and it will also be submitted. Look, it has been submitted. Now look in the code, we have done this. What is the priority? What is created first? All the elements are pushed in it. After that we put a loop until the heap which is our priority is not empty or its size does not remain the same. Then What we have done till now is to remove two elements, the top two largest element, calculated their absolute value, if it is not equal to zero then we have pushed. If it is equal to zero then we do not need to do anything. Now at the end we will see the size. If its equal to two is equal to one means there is only one element then that means the same thing will be left then we will return it to the top else we will return zero that was it our submission is also done this was all for this video see you in the next video Thank you with another good question.
Last Stone Weight
max-consecutive-ones-iii
You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone. We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: * If `x == y`, both stones are destroyed, and * If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is **at most one** stone left. Return _the weight of the last remaining stone_. If there are no stones left, return `0`. **Example 1:** **Input:** stones = \[2,7,4,1,8,1\] **Output:** 1 **Explanation:** We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then, we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then, we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then, we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone. **Example 2:** **Input:** stones = \[1\] **Output:** 1 **Constraints:** * `1 <= stones.length <= 30` * `1 <= stones[i] <= 1000`
One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on.
Array,Binary Search,Sliding Window,Prefix Sum
Medium
340,424,485,487,2134
684
hey everybody this is larry this is the 25th of june uh for the june daily leco challenge hit the like button hit the subscribe button join me on discord and smash whatever uh today's problem is redundant connection so i usually start these live so if it's a little bit slow fast forward whatever you need to do okay what is it in this problem a tree okay you're given a graph that started out as a tree with one additional edge the added edge has two different vertices so okay we move we turn it actually with the multiple answers we turned it into that occurred last night input okay so basically i suppose let's put this down a little bit so basically now we have a graph it's undirected um and it is a tree right and what is the thing with a tree so the thing with a tree is that there's only one unique path from any um any two nodes um so and the other thing is that there are no cycles right so if there's a psycho that means that it is no good yeah that's pretty much it i'm trying to think about which way to do it uh if there are multiple answers we tend to enter that it could last so this tie breaking thing is a little bit critical because then now we have to process them backwards i think the ideal thing to do is just you know given these edges one at a time add them let's see actually the answer that it could last is a little bit annoying um maybe not i think that part i'm going to have trouble with but yeah but you can just go from the beginning to the end and then add these edges into the graph and then if adding these two uh or if adding an edge between these two nodes creates a cycle then uh by definition that is the one that you can remove and there are some like things that are maybe hand wave you over um and which is that it's the first one that and there should only be one answer and that's the first one because once you generate a cycle that means that by definition all the other ones uh within the same cycle um you know they you can remove any of them and the last one the one that occurs last in the input is the one that um no that's the one that's the tiebreaker so you should be able to process them from left to right uh is what i'm trying to say here um okay so how would you do that well it turns out that there is a data structure that you can use and that's basically the idea is that you just process them left to right and then you just draw these edges um you can literally visualize it by doing it on paper as well and then just doing it from left to right and then the other question is how can you do it in a quick enough way and that becomes a data structure question though in this case n is a thousand so even if you're a little bit lazy or sloppy um you can do an n square algorithm and that'll be okay so you don't actually need something that crazy but i am gonna do it with junior and fine uh and you know give yourself some props if you already guessed that's where this is going and let's get started then i think that's actually pretty straightforward once you have the union find implement it then you can just it becomes straightforward so i actually recently did a video with us or did a problem i think maybe last week or the week before with union fine so get another chance to practice it as well so let's go so what i do um i don't know i wouldn't say that i memorize it but i remember a couple of concepts and then i just kind of implemented the same way every time you should find a way to do it for yourself as well because that's the best way to kind of um to do it um okay so what is end that may be a little bit tricky but keeping in mind that as we said the number of edges is also the number of nodes because there's only one extra edge so it's a little bit wonky without explanation but try to think about it if you have trouble at that point but yeah so now we have two things with union fund there's the union and the fine uh i always yeah let's do the fine first and then if parents i guess parents not parents right for x is equal to uh if it's not equal to x then parents of x is equal to your final pound of x otherwise return parent of x uh and um again just as the other video i'm not gonna go over union find that much because like i said back then too is that if you take like algo or something in college union fine could usually be one a day or two in semester um so it's like you know a couple of hours uh maybe some of it's academic but you know so i'm not gonna be able to explain it that much here and also i think they're probably good videos anyway i have explained it in the past in my stream but maybe one day i'll do it if you're interested in me explaining union find my way let me know in the comments and maybe i'll you know maybe i'll come across it uh but in any case this is how i usually write it uh i did do path compression but i don't do um by rank um yeah i don't what was it called something by rank so yeah in case you're curious and that's pretty much it like i said there's only like 10 lines of code and that includes spacing so i don't usually think about it the only two concepts i think about is this path compression where like okay if this is not the uh the head node of this union fine tree then we fi we set it to you know we recursively set it to the parent so that it keeps on compressing that's why it's compression um and then union is just here find the head node of a find head number b set the head node of a to head over b sometimes you could and if you have like if you wanted to do uh tie breaking by rank or size or whatever that this is where you would break it but because of path compression i don't find it usually that matters um some people might disagree with me but for the most part it's hard to construct um i mean you have to be very specific about constructing a test case in which this doesn't work so probabilistically okay and in theory depending how you do it you could just randomize the input or something like that if you worry about um getting charged or something but yeah so now that we have the union find that becomes straightforward so now you have for you we in edges uh if u find of u is equal to u find v that means that they belong to the same component so then we just return uv right we'll return it as a list yep okay otherwise we union you and we and that's pretty much it i guess we don't have to return anything here because it'll never be reached but i just want to double check that this is one okay so this is actually from zero to one a one to n sign not from zero to one oh sorry anyway is one index not zero index so i'm gonna you depend on how you wanna write it i usually just modify it like this here and that should be good and of course that would come out in testing anyway but i always double check usually it's not a big deal as long as you double check oh no i mess up somewhere oh i have to add back one whoopsie daisies for the answer i was like oh that doesn't seem to make sense but okay so that looks good let's give a summit uh one thing that i should have tested which i did not was actually with if um if n is equal to one or something i forgot to just double check either in testing or just double check to constrain but this one seems okay so yeah so we got a little bit fortunate there because sometimes problems like to kind of focus you and whatever but yeah so what is the complexity of this um well technically that's not the way that i did it but if the if you do the optimal union fine there is a quote-unquote constant fine there is a quote-unquote constant fine there is a quote-unquote constant or the very slow growing function that reverse inverse acumen function uh which will you know explaining that part is i feel like beyond the scope of this video because even i feel like even if you get explained in class people don't even use it um but there is a user proof of the lock staff and which is the repeated logic room or whatever um so maybe you could play around with that as well but even dan that's like i don't know i think inverse i come in function of the size of the atoms in the universe is like sex and the log star of n is like 10 or something i don't know something really small i forget what it is but effectively constant really if you look at either of those numbers um so yeah so for the sake of purpose i'm gonna say you know uh this is constant uh you may you know you may play around with that idea um yeah you would play around with different ideas and i think you know if you're on an interview sometimes these complexes they just want to know that you know what you're talking about and whether the semantics is this is constant or not you know like if you know this stuff it doesn't matter right they're not this is not a you're not testing against a robot who'll be like nope you press the one button so uh and that's your oa i guess but anyway so yeah so let's just pretend for now that these are all one operations roughly speaking and therefore for a number of edges we do all of one for each one of those edges we do all one operation so total is going to be of end time which is linear time and keeping in mind that linear in this case is the number of edges because that's the size of the input and also in it number of edges is just the number of vertices plus one so we usually if you want to talk about v plus e we as you're gonna use effectively at least in the big o sense uh and in this case it actually is exactly because they guarantee that it's exactly the scenario but yeah um that's all i have oh in terms of space this is also linear that part i think is easy to explain i don't think anyone uh needs to hear from larry here uh and you can also maybe add a little bit additional factor about the path compression but again even then that's going to be at worst linear if you never compress until some weird thing but it should be okay uh but yeah that's all i have for this one i think uh happy friday happy weekend coming up uh stay good stay cool i'll see you later and to good mental health bye
Redundant Connection
redundant-connection
In this problem, a tree is an **undirected graph** that is connected and has no cycles. You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph. Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input. **Example 1:** **Input:** edges = \[\[1,2\],\[1,3\],\[2,3\]\] **Output:** \[2,3\] **Example 2:** **Input:** edges = \[\[1,2\],\[2,3\],\[3,4\],\[1,4\],\[1,5\]\] **Output:** \[1,4\] **Constraints:** * `n == edges.length` * `3 <= n <= 1000` * `edges[i].length == 2` * `1 <= ai < bi <= edges.length` * `ai != bi` * There are no repeated edges. * The given graph is connected.
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
685,721,2246
139
Hello everyone welcome, we are going to do video number 53 of my channel and you will know that you can watch DP Concepts playlist if you want to study DP from scratch but I have mentioned one thing that it is not necessary that you will watch that playlist. Only then you can understand today's question, there is nothing like that, I always go from Brat Force i.e. from scrap to optimal, from Brat Force i.e. from scrap to optimal, from Brat Force i.e. from scrap to optimal, so do not worry about that, let me explain in such a way that you will understand, even if you are new or a beginner, you will understand, it is okay. More videos will come in the playlist of questions, man, give me some time, okay, and today's question is 139 medium marks in liquid, but it is very similar, man, we will write the code in a simple way, our code will be done, okay and my DP. In the concept playlist, I will also tell the question momo plus bottom of all the questions, that is why here I am telling the DP concept question only by memorization, look at all the approaches, it is very popular, many videos are already in YouTube and I am sir, all the videos will be good. IF YOU WANT TO TREE ME VIDEO YOU CAN DEFINITELY COME AHEAD WITH THIS VIDEO OK LET'S START A LOT OF PEOPLE ASKED THIS QUESTION IS POPULAR IT IS A VERY OLD QUESTION AND IT HAS BEEN ASKED IN MORE COMPANIES YOU WILL FIND IT IN THE DESCRIPINION OK So like always, our first family method will be meditation in recreation and before that, please find out that brother, this is the topic of recreation, is it bikini? First of all, if you find out, then let's see the question. I have to say that I have given you string S. One is fine, but see the example here and a dictionary is given. Dictionary is fine in that too, just return sequence of one and more from the string. The word dictionary means to say that this is true to me. If you divide such a string into different parts. Tod pe par example, a little in L A I and a little in T and a little in C O D I. It has been broken into three parts but all three words are there and should also be there here. The word which is there in the dictionary, you have to break it S. If we look at it, then it is there, otherwise it is not possible to break it, then it has gone wrong. Okay, so there is some other way, let's see, there is a way, if even a way can be found to break it, then you will get the answer true. There is a way to do this, you will also find it in apple, a little in pen, then there is another apple in the last, okay, so let's see if the word is in the dictionary, apple is there is pen, it is also apple, so look at this apple twice. What happened here also, it can have multiplayer time, okay and we have found a way to break it, the true date, all the broken words of all the words are present in its dictionary, so what will be the answer to this too, it will be true. Okay, it's great. Friend, my best friend diagram is okay in such a question, my best friend is ours, so I want you to learn from an example that brother, if you give a dog to any child, then this question 's brother, you have to break 's brother, you have to break 's brother, you have to break all the things in which you have broken. If this and this is present in a dictionary then the child also knows how to do it. See, I will tell you how he will do it. The first thing he will say is brother, the word you are breaking should be present in the dictionary. The dictionary which is given in the question is remembered in the question. Let's take the mother in the dictionary, had given the code and had given the mike, okay, so I told the child that brother, if you break it then he showed the whole brother, first let's break a little bit of one length in it. Toda to L, I got a little bit of a line here, so I said, brother, L is not there in your dictionary, then he said ok, no problem, we will not break to one length, let's see if we break to two lengths, then okay, he said, brother, right now I am zero. But I am standing from here, I have seen that it has been broken by two lengths. Okay, so okay brother, I have broken it, Ali child, what is ETC for me? Then I said, brother, the first part that you have broken is not there in the dictionary. Where should addictions be? So this is also not there so he said come on if this also goes wrong then I am three so what do I do ok so in this we ca n't even break it to three lengths so he said no problem I will try to break it to length i.e. this It's okay, try to break it to length i.e. this It's okay, try to break it to length i.e. this It's okay, so let me draw it here, do a little bit of length in it, okay, now do a little bit of line, let's see the rest of the child, what is C and D AMI, okay, so you are showing the lead, it is in my dictionary. So I am happy, no, it's ok, but now I will try, there is a code mic, can it be broken or not, ok, first we will check if there is one in the court, where is it in our dictionary, if not, then break it and check. Okay, father, we will have to check on this also, okay, I will reduce it. First of all, let me clean the street diagram a little, it has become a little dirty because look, the one with one length is not less, but the one with two lengths is also less. No, the one with three lengths is also less, so I remove it. It's fine for now and let me make a little clean diagram. So look, I have made it a little neat, I have also shown the length in the trade gram, I have shown all of them, I have not removed them completely. Look. A bit of one length would be this, a bit of 2 length would be this, a bit of three length would be this and a bit of four length would be that, so look at how the one of one length was not there in the dictionary, so it cannot be broken down in it. All the broken words should be in the dictionary. This also cannot be broken. Okay, so now it is here that we know that okay, this is the lead, it can be broken, this is correct because the lead is present in the dictionary. Okay, but. Still I am not guaranteed that the rest of the words are ok, this is the entire present of Kodmi or not, if not, then let's see, it will be broken further. If so, then its broken text should be here. Okay, so again that child. Yes, he was happy that brother, I got a lie here but I said, brother, look at this also, is it a present or not, there should be all the words in writing, then he will say, okay, I will put the thing here also, first I will break it. I will give it okay, learn a little bit of length here, it is okay, pay attention, it is a toda of one length, child, what is it, then I said, you are not like a brother, why are you breaking six, if you want to break like this, then you have got the lead, you are very happy. You, you broke it in 'C' and what a child, broke it in 'C' and what a child, broke it in 'C' and what a child, O'Di IMI's brother, this is it is not C, it is not this is wrong, it is wrong, come on, no problem, I have seen a break of two lengths, it is okay, a break of two lengths. When I looked at it, I came to know that what will become of two lenses, what will become of C, what will become of O, no give, this is also not in our dictionary. Okay, so in the same way you will say what will he say, three length, let's not talk about it, let's break the line, so I will remain here. I am giving it of length because there is no space there. Then the child said, let's try to break the line, then give me a little O. Okay, now pay attention to one thing, here the child became happy and said, brother. The code is there, okay, the code is there, where is happy, no, okay, it is present, then he will say, okay, the child is there, now let's check the remaining string, right, let's check this too, so I said, Earlier in the beginning we would have checked whether Me is already present or not, I am already present, what will you break, Me is already present, now it's just that when I saw the channel like Me is already present, then I clicked here. I told True that brother, Mike is present, right? I will write here and will make Mike the President. I will tell you, brother, there is no need to search for Mike is already there, so True is found here, it is okay, here we can find a room for Mike. So what did I do? Okay, it is in the dictionary, I found it true, later we returned it here too, brother, you can break the let code mike, how come let in N code and mike is ok till here. Now one very important thing is clear, look carefully here, remember what the child had said in the beginning that I am index is zero here, start from here mother, I am late, okay, got a little of nothing, got a little of two lengths, got nothing of three lengths. After adding a little bit of length to nothing, this is the lead, it is okay, after that, after doing length, you are looking at C O D MI, then what will be the index of C. Think for yourself, it is a little bit of zero length. It will be done i.e. C O D MI K, i.e. C O D MI K, i.e. C O D MI K, look at its index, it must be starting from K, see, now I will clear these 03 indexes, first index, second index, third index C, which is the fourth index, see this from here. What does it mean when I start, as soon as I find a word here which is in the dictionary, then the code for the next time is Mike, from which index will I start? Last time I was on RDX, here I am on ID. Ok how many lengths did you break? After explaining the ID of 4 lengths, till now one thing has become clear, this was the most important thing, after this there is a very important thing which is asked in the comments, many people do not understand that recognition. Look, what they are writing about the loop inside the branch is that they have difficulty in understanding it. Look, first of all, let me tell you one thing that brother, we make branches, what is this branch, this is the meaning of branch but there is a loop, okay this is The meaning of branch is loop. Even if there are two branches, you do not need to write the form, but it is best to write many branches. So look here, on which branch is the branch running? The branch I have made is running on the length. A little bit of one length is this. A little bit of three lengths is this. So now the thing is, whatever I will write in the loop, I will write something like this. What did the child say earlier? Let's break the length of one. Okay, and you think yourself, how much will the length be broken? If you can break one length, you will get L, two lengths, three lengths, five lengths, six lengths, eight, 10, 11, lengths, you can break up to L ≤ N lengths, what will happen with L plus. Okay, so that's why I want to say that the branches are there but they are for the loop, okay, it is clear till now and let me clear one more thing that how all the strings come out in C Plus, now see right here. You are extracting it here, how would I have extracted this L, I must have extracted the substring, okay and what is the second parameter? Look in C plus, pay attention, Java is different, I will show you the court today from Java also, okay show the court. I will share it with you in the comments and in C+Plus and Java, the parameter of sub string is different in C+Plus and Java, the parameter of sub string is different in C+Plus and Java, the parameter of sub string is different and it depends on which index you started from. Look at the beginning and the child said that I started with IDEX. Okay, we started from ID, after that how much length is to be taken or this parameter is length, this is the difference in Java, here also we have to know the index, up to which index is required C Plus Not like this. If I have to tell the length of C plus, then I started with IDEX. I remember how much length do I need. Here is the length of L. We were running a loop on L. First there will be one, then there will be you, then there will be three, then there will be four, right? It is possible that in the future you will have to try five and also six and so on, there will be a time when the ID which is Here again you started from C, then in the same way ID will also be auto bound going forward, so we will have to check that also, understand these are small things but style, I am telling you the substance before writing the code, learn how to write C plus. And you will know about Java that there is a substring in it. It is something like this. We have to write the starting index here, that is, what is our starting list, but okay, then I will show you the code of both and will also comment in the comment. I will show you by doing live C plus. Okay, so just imagine how simple the above story is going to be. You know that you will write the solution, you will write it. Okay, and what the child had said is that always start from the beginning, start from zero cold. So he said, brother, I will start the string from zero, my life is like this, okay, I accepted his point, he wrote the solution, he wrote the history, is this zero in the beginning and he sent the string and S. I understood the thing here. Here I write the bids, okay as usual, if you want to enter the base then see what is changing, like this is changing, isn't the ID changing, so where will the ID of the year go in this? Start searching for Mike. If you started searching for the mic then you found the mic, you had found the mic earlier, so you did n't even have to break the mic in the beginning, so look, I didn't even make a slight turn right here and if Aa, this is not in Mike's dictionary, so I will have to break it and see. Which length will you break first in four? Will you break it at one length? What is the maximum length at which you can break it? L &lt;= n++ Okay, it is clear till now I have to extract all the scenes. Sabse me nikal hoon lay pe time is equal tu s my string hai me s dot sub spring see how many lengths of length do I have to break this time, I have to break the length of time, I am fine and what I have broken is present or not. It should be present in the dictionary, what were you sending, now see what is remaining, remember from which index it was starting, look, if you got the lead, code S, then you do not have to send, okay, true, what does it mean, this is also true. Because this is a present, I will start my dictionary. Okay, and if this complete look is over and you are not able to return true to the story, then by the way, you will be on the verge of breaking. Take another small example, do some other dragon. This is how simple it became in a simple recursive code. Actually, there was a whole bread force. We have seen the length of each one. Look, the length of one is the length of you. What will we do? This is a recursive function, isn't it? So we will memorize this and this will be our Recon Plus Memory. You will also see it from there. You will get a big tree diagram. Problems will come due to repetition. Okay, so now let's see what is the time complexity. Let's check the time before coding. We have made a very poor proposal, I mean, break each line and see, mother, what is the length of my string? Do one, two, three, maybe we will break it from here or else. If we break from here, how many possible options do we have and there are N options to break from here? Now see, I may not break a little from here, meaning, we may or may not break here. You can break it here, you can break it, you can not break it, you can break it, for every slot and position you have the option either you break it or you don't break it. If you get the answer then it will be very good. It's a good thing, start the return at the same time, if you don't get the answer then look ahead to break the flood from here, I am saying the same thing that there are two possibilities for each position, then your power will be N and its time complexity will be fine. We have tried all the possibilities, it has become clear till now, let's quickly code it, okay with the story, when the court will write, then they will also understand okay, brother, I did not leave it here, okay, what does this mean? Do you know what happened that we were breaking here, then we broke it again and did regen yesterday, RDX, see further flooding, then a little further flooding, and all the truths are coming, that is why we were flooding further, right, when like you mother, you take late. Now the code is there, why were you flooding ahead, why did you push the IDEX ahead, then when it got true, that's why the ID came here again, right, then the code got a further draw, that's why you came on the mic, so look sir, it is getting mixed. That's why there are floods ahead, so finally the idea came here, what does it mean that all the parts were found, that is why I came here, so what do we have to do, we have to return through, okay, but why did we come because I got these parts. I had thought that this is in the dictionary, then you have got the braid, you have not got the sedition, that is why you have come to see the code, you have also got the court, only then, if you have to see the mike, you have also got the mike, then the ID is here, the idea is out. It is off bounds, right? I returned it after being out of band. Till now, everything is clear. Now write the court without looking. Okay, now let's go to the lead code and solve it. So let's quickly go through our Let's convert the story into code. As much as I told you is fine. Now look, pay attention. First of all, N = After this, remember one thing, I told you that when you break any word, you have to look at yourself first. Is that word in distance or not? Now look at the word dick, vector of string has been given here, brother, repeatedly put a loop in the vector of string and check whether it is present or not. In the verdict, it will seem overfine every time. I will have to do my date again, but in the date, why don't I create an ordered set of strings, okay, I will store in it all the words, as many words as there are in the word, so that I can check directly in this section to see if any string is present. Is it right in off one? Is it right or not? It is clear till now let's move ahead, I simply said, return, solve, we will do the index, starting from zero. Yes, children, I had asked, S is my string pass. done very good bids solve ok string and s ok if IDEX becomes my greater den or equal tu n &gt; then it will never happen return proof this &gt; then it will never happen return proof this &gt; then it will never happen return proof this also I told you why are you returning true right now no more What I had said before that, check beforehand whether it is necessary to break it or not. If this word is already present in my st, note it is equal to st.ind, then it is not necessary to break it, I have st.ind, then it is not necessary to break it, I have st.ind, then it is not necessary to break it, I have got it, please return it to me. From here and if present is okay if present sorry if not present then tod ke dekh hai na eat length is equal tu one todenge length kitna length tak tod hain length = n tak ka l length tak tod hain length = n tak ka l length tak tod hain length = n tak ka l plus I will try to do , how many days' how many days' how many days' length, a little length, after that the remaining string will be from here, okay and sent it like this and if you go from there too, then we will proof the return, if it doesn't come then return in the last. This is our simple calculation, it is done without memorization, okay, let's submit it and see that the most fabric time limit will be the same, we did not define N here, eat N should have been there in global and defined it without N. I have submitted and tried it's okay and in the end I will show you the similar code of Java also, it is okay to wait, it will give the maximum time limit seat, we will have to memorize it, so to do the voice, I am late to see how consistent it is. Length of 300 t 301 maa lo ok I have taken a bigger one for security ok and before doing everything I will check here that if t of id axis is not equal to -1 then t of id axis is not equal to -1 then t of id axis is not equal to -1 then return t of id x and one Hey, because look, only one variable is changing, only IDFC is changing, rest is from Here, initialize it, I set T - 1 size function, so I do it so that I have it, now let's submit it will not give, see this Java code, I have pasted it here, find it in my Github Rapon. This is the Java code of it is also fine, I have given the link in the description. Look, here I am doing this thing, I have made a DP, it is fine here, done RDX, checked the memorization here and see the split from here. Doing it now see here the method of splitting is different here starting and index and here indic index okay thots it is from everything else here okay submit this see this will also pass okay this is also from Java Let's solve it, see it in detail, it has also been done in Java, any doubt, Reasoning, D, General Session, Attract you, Bill, B and C, Weight, Next Video, Thank you.
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
461
hello everyone welcome to quartus camp we are at 18th day of november lit code challenge and the problem we are going to cover in this video is hamming distance so the input given here is a two integer value x and y and we have to represent those two integers in form of binary and we have to return the number of positions at which the corresponding bits are different so x and y return hamming distance between them so let's understand this with an example so consider two numbers 7 and 5 and we have to represent them in binary first so representing 7 as 0 triple 1 and 5 as 0 1 so we have to return the number of positions where the bits are different so let's start comparing the bits if you see at first position 0 and 0 are equal next 1 and 1 are equal so here one and zero are different so we have one position added to our output and next value is one and one so except this position all other positions are having same value so one is going to be our output so how are we going to approach this programmatically so there are pretty easier ways in uh java and c plus there are predefined methods that calculate the number of bits and for example in java you can use bit count to count the number of bits in the integers and etc but the purpose of this program is to do that logically instead of using predefined functions so how we going to do that so we need to know a bit of bit manipulation functions to solve this so first thing is we have to have the number of positions where the bits are different so we have lot of operations in bitwise so which operation will actually give you one when the positions are different and 0 when the positions are same so which is nothing but xr so xor will actually give you 1 in the output when both the numbers are equal sorry when both the numbers are different that is 0 xor 1 is equal to 1 x or 0 is equal to 1 otherwise if the numbers are same then they are going to give 0 so this is the function we are going to use here to find wherever the positions are having different numbers so let's do x y which is nothing but 7 x r 5 so which is going to give you 0 1 0 so we have got a final product where which represent one wherever the numbers are different so now we came to a point at the program that we have to count number of ones in the given binary representation of the number and we are done so how many number of ones are there will be our output so here one is going to where output so how are we going to count that so again we have a lot of options to calculate the number of ones in the given binary number uh by compare converting that to a string and comparing the bits or uh again using the bit count method and etc but here again we're going to use the bit manipulation operations to find the number of ones in the given binary representation so how are we going to do that so how are we going to calculate the number of ones in the given binary representation so we're going to get the help of and operation to do that so purpose of end is if we do end one with any bit if the bit is one it is going to give one that is one and one is going to be one otherwise if the bit is zero or whatever it is going to be give you zero so this is going to give you one only if there is a one so we are going to perform one operation which each of the bit and whenever there is a one we are going to increment the counter of our result so let's have result is equal to zero and start doing end operation with each bit so the last bit is zero so zero and one is going to be zero so result still stays the same so the next integer is one so one and one is gonna give you one so we are going to update our result to one and then comes a zero so it is going to give you zero so the result is going to be stay the same and again zero is no change in the result and finally result is going to be one so it is pretty simple by doing an under operation to find whether it is a one or zero and adding or incrementing the counter of a result count of a result based on the ones we encounter the x or y so again how do we do specifically to each bit and operation so which is pretty simple again we have used a lot of times right shift operator to shift one bit at a time so what will this do actually is if suppose the number is one zero one time if you do left shift of one it will shift the last bit over and move all the bits towards the end which is nothing but it is going to push this 1 0 1 towards the end again if you do then it is going to push this one and 0 1 0 and again when you do it is going to push this 0 and number is going to be 0 1 and again if you do it is going to become all 0s so its purpose is to shift the last bit and push all other bits towards right so we are going to imply the same to this number so every time it is going to have the last bit and we perform an end operation and then shift it over so now we are going to perform zero one zero right shift one so what this will do this will shift one operator next to it before that will perform an end with one so the result is going to be zero so after we shift it the number is going to become 0 1 so now it's time to perform and operation 1 so now 1 and 1 will give you 1 we are going to add that to a result and then do again a right shift to this number so once you do this is going to become all 0 and yes once it becomes all 0 we know we can't further shift it is going to be all 0 all the time so that's it we are going to return our result so we are going to perform this right shift operation until the number becomes zero so hope you are understanding this concept this is very pretty simple if you already know about xor and right shift and etc otherwise it is always good to learn this simple logic so that we can approach many bitwise operations in a very simpler way so let's go to the code now so as i said first we have to perform an xor operation for the given numbers so once we perform this we are going to iterate this bit until it becomes zero we are going to perform a and operation with 1 and if it is a 1 then we are going to add to a result so let us declare result as well which is what we are going to return finally so now every time we perform an end operation with xor we are going to add its result anyway one it is going to give you one or 0 so if you add 0 that doesn't matter so finally every time we perform the addition and update the value to our result we are going to do a right shift to our example yes this is it let's give it a try let's submit yes the solution has been accepted and it runs in zero milliseconds so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Hamming Distance
hamming-distance
The [Hamming distance](https://en.wikipedia.org/wiki/Hamming_distance) between two integers is the number of positions at which the corresponding bits are different. Given two integers `x` and `y`, return _the **Hamming distance** between them_. **Example 1:** **Input:** x = 1, y = 4 **Output:** 2 **Explanation:** 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. **Example 2:** **Input:** x = 3, y = 1 **Output:** 1 **Constraints:** * `0 <= x, y <= 231 - 1`
null
Bit Manipulation
Easy
191,477
1,460
hey what's up guys uh this is chung here so today uh it's called 1764 form array by concatenating sub arrays of another array so you're given like a 2d integer array groups of length n and you're also given like an integer array of nums here so you need to choose like un disjoint sub arrays from the array nums such that you know the uh the i sub array is equal to the group's eye and you need to return true if you can do it otherwise false so basically what does it mean it means that you know you're giving you're given like a longer basically a pretty long like numbs here and another like bunch of uh like array of groups of array so you need to find some subset right from this num so that you know you can basically find a match for those kind of for each of the group within a sequence right so for example this one right we have this kind of numbers and we can find so for one minus one this is the match we can find and then we have another one here and remember so basically those two matches cannot be overlapping to each other that's why we call it disjoint right that's why this one is true and for the second one here uh we have t minus one right because t minus one is right here but you know the one two three four is not because it's a the sequence the b basically the other matters right so when whenever basically we have to find the first one first and then we can find try to find match the second one so and after matching the first one we already reached the end of this numbers here that's why we'll just return false okay and here are like some more examples here and the constraints is like 10 to the power of 3. okay and then that's the range of the numbers here so i mean for this problem you know i think brutal force way not a brutal force way i mean in the evil protest simply we just try to match this kind of groups one by one right and whenever we find a match right whenever we find a match we will basically move to the recursive function a dfs call right and then we'll try to match the next one until we have reached the end we either have matched all the groups that's when we will return true or we have reached the end of nums which means we need to return false all right basically that's the basic idea here and so for this problem that's the basic idea but to do this uh stream match or the array match here you know we can simply do a brutal force uh like array equals to array or there's another like more efficient way it's called kmp right so basically today i'll be doing the naive solutions and then i will also implement the kmp basically the kmp will change the o of m times n time complexity to o of m plus n all right so let's try to implement the first one so for me i'm using this kind of dfs approach basically you know uh we have n equals to length of the groups right so that's a there's a total groups we need to match and then for the m equals the length of the target the nums okay and then we have the dfs right so we have the dfs so we have a group index okay and then i have a num index so that's the two things i'll be maintaining in this function here and then in the end i simply return df as zero and zero cool so and the base case right if the group at group index equals to the n it means that we have matched all the groups so we just need to return true here right else not else so if the index if the num index is equal to m which means that we have reached the end of the uh the end of this array but we haven't matched all the groups that's when we need to return false okay otherwise right so we have a current group equals to groups dot group index right and then for card numbers you know and i'm since you know a brutal force ways that we just need to iterate all the numbers right from all the index from this num index until the end until m here right but then to be able to form the current numbers we have is we have to basically uh do a uh array slicing that will be another layer of the time uh end of end time complexity so for me i'm just using a dq here so that i can only append to the end and the pop from the left so that i can basically update the uh the current nums in the o one time so which means that you know first i'm going to start from the num index right and now stop at m okay so the current num start at the beginning i'll just append this one to the nums.i which will be the current the nums.i which will be the current the nums.i which will be the current numbers right and if the length of the current numbers is greater than the length of the current group right and then we know okay we need to pop right because uh in order to make to find a match the length has to be the same if the current one is greater than then the current group we simply do a pop-left and then we just we simply do a pop-left and then we just we simply do a pop-left and then we just do this if the current group equals to current numbers right uh i think for this one since we're defined as a dq we have to convert it back to the list so if they're the same right and then we can just uh simply return this one we can return the dfs basically we have find a match and we just need to uh throw this uh the question to the next layer which is the index group index class one and the i induct i plus one so this is this one is easier to understand i plasma means that uh we have to start from i plus one because the uh the group has to be destroyed which means that uh the remaining part is only from uh from i plus one to m okay and here actually so we do a return we didn't do uh we didn't do something like this okay uh let me finish this one so and if not none of the matches will simply return false right but keep in mind here so we do this one we didn't do something like this i mean the uh if this one is this one then we return true something like this so what does this one if we change it to this way it means that let's say if we have multiple match for the same uh group here we'll basically we'll try all the possible matches and then we'll return anyone who will give us a true here otherwise if this one is a false basically we'll keep uh try a different uh maybe the next match so the reason we didn't do this one is because this is here is kind of like a greedy idea here you know so the earlier we can stop the current match i mean the bigger chance we can find like uh the match for all the groups right because let's say we have a discus this is a number right let's say we have the current groups is three so let's say we find like uh we find it like a match from here to here and then let's say if this one didn't give us like uh didn't give us like a true return let's say there's another a match uh from here to here okay so if this one didn't get give us a true right so this one will definitely not will not definitely not give us an a true either because the earlier we stopped the current one i mean the more numbers the more like numbers we have for the remaining groups right so basically that's why you know as long as we can find the first uh match we can simply return that value directly because we know that this will get guaranteed that can definitely tell us if we can return the true or false okay so i think yeah that i think that's it so if i run the code here okay submit yep so it passed right and so for the time complexity right i mean as you guys can see so here we have a range right so we have a range of you can call it like an n right because the constraints for example and then they are the same so we have a n here and then for the comparison here right we have a basically we have n squared here because for the compare the list we have to compare them one by one that's why we have n square and how many times we're gonna basically do this dfs right so ideally i mean the worst case scenario it should be like an cube right i mean the n square times another n but the reality is that you know every time when we have matched uh a group here you know the search range for the next uh for the next dfs will be smaller basically it will not be uh exactly and it will be smaller than the n right so that's why the uh i think that the time complexity for this one is going to be uh between n cubed n squared to n cube so i don't quite uh i'm quite sure i'm not quite sure about how what is the exact time complexity but it should be in this the range of this two here yeah so basically that's the basic idea and so let's talk about kmp right so for hope for those who don't know what kmp is basically it's an algorithm to find us like a pattern within a string you know so to find let's say we have a string right let's say we have a string with this one right and then we have a pattern the substring if we want to know if there's a match for this pattern in this string right so the brutal first way is that basically we loop through all the indexes right and then we do a comparison which means that you know let's say this is m this is the length of n so the time complexity obviously is going to be m times n right but for the k and p algorithm you know we can basically improve this one from m times n to m plus n okay so how does kmp works you know i'll basically i'll briefly talk about kmp here and for the entire uh complete explanations uh i have like another videos another video to explain this kmp algorithm i'll post it into uh the description of this video here so basically you know the way the kmp work is that you know we're gonna build like a helper array for these patterns basically it's going to be a longest to the hardware array called the longest prefix as suffix okay yeah so which means that you know if we have if we can build this longest prefix as suffix you know so whenever we try to find uh basically we try to uh find the match for this one so basically it works the way it works that you know we're gonna have like i here for that for a source and then we have a j index for the patterns you know every time as long as they are they're the same you know basically this i both i and j will keep moving forward okay and uh whenever there's a mismatch let's say you if the i is here and the j is here and if there's a mismatch for i and j right basically we'll move j back to like a previously state so that you know the uh the i and j can keep moving forward basically and we can still uh comparing only this i and j index uh for each of the move so and how can we and let's say if the i and j are different how can we know which place this j should move back that's when we need to use this longest prefix as suffix basically with this values here we know with this helper array here and then we'll know like you will know basically where we should move this j back to this a certain location yeah so i'm not going to talk about that here but i'll post that video here later so let's try to implement these things here um we have dfs okay so to do that you know like i said we need to build the uh the longest pre longest prefix suffix uh helper functions so for the group because the group is the pattern we're trying to match here okay so the way it works that you know we have a group here and then lps right the longest prefix suffix so at the beginning the length for each of the element is zero and then we fro n and then we have a j equal to zero okay so i'll basically i'll just keep typing here for i in range of one plus n while j is greater than zero and the group of i is not equal to group of j if that's if they're not the same right they'll basically uh update j with lps j minus one and then if the group i equal to the group j basically lps i equals to j plus one and then j will increase by one and then in the end we return the lps okay so that's how we build this helper like function here and the uh and let's see what else so here you know uh we have current group and we can just change this one to the lps right so lps is going to be the helper functions we just created ps of the current group right so that's that and then to match the uh these things we're gonna have like the j equal to zero so here we don't need to do this kind of match so uh i can just do this basically while j is greater than zero and nums i is not equal to the current group of j right so if they're not the same then like i said the j will be fall back will be falling back to the previously uh value right and then if the nums i is equal to the current group right then j we simply uh increase the j because the i has already is already increasing right because we have four up here so whenever they are the same we move both and i j and j forward okay and so the condition to know if we have final matches that will happen the j equal to the length of the current group okay so basically this g means that how many characters we have matched so far for the for this pattern which is the cardinal group here and whenever j has reached the end of it we know okay we have find a match for the entire group and that's when we need to call the dfs right current group index plus one and then i plus 1. yeah basically that's the change we need to make here and if i run the code here okay return code round code range oh range okay accept it yeah so it works uh this one is even slower than the other one yeah they're basically has the pretty exact uh almost the same speed but i mean regardless right regardless as you guys can see here so now for each of the uh the dfs here so to build this lps here we have a photo here right so that's the uh n here right so we have in here and then for this one for the for loop here as you guys can see here now we only need to do like this kind of uh this range here there is no nested for loop here and so this while loop here you know even though we have while loop here this one has a very limited uh time complexity because uh because the nature we built this lps so this one we can consider as so1 here and then as you guys can see we don't have like a array comparison all we have is kind of a struct like a in lighter single letter comparison this is also one right so that's why the uh i mean the total time comply civilizations dfs is going to be a n plus n right because we have a actually n plot plus m let's say we have m here right and then for the total time compressive for this solution i mean maybe like a times another n here because we have a basically another layer of the dfs right yep basically that's how this problem works and how we can use the kmp to speed up to improve the time complexity for this one and yeah i think i'll just stop here and thank you for watching this video guys stay tuned see you guys soon bye
Make Two Arrays Equal by Reversing Subarrays
number-of-substrings-containing-all-three-characters
You are given two integer arrays of equal length `target` and `arr`. In one step, you can select any **non-empty subarray** of `arr` and reverse it. You are allowed to make any number of steps. Return `true` _if you can make_ `arr` _equal to_ `target` _or_ `false` _otherwise_. **Example 1:** **Input:** target = \[1,2,3,4\], arr = \[2,4,1,3\] **Output:** true **Explanation:** You can follow the next steps to convert arr to target: 1- Reverse subarray \[2,4,1\], arr becomes \[1,4,2,3\] 2- Reverse subarray \[4,2\], arr becomes \[1,2,4,3\] 3- Reverse subarray \[4,3\], arr becomes \[1,2,3,4\] There are multiple ways to convert arr to target, this is not the only way to do so. **Example 2:** **Input:** target = \[7\], arr = \[7\] **Output:** true **Explanation:** arr is equal to target without any reverses. **Example 3:** **Input:** target = \[3,7,9\], arr = \[3,7,11\] **Output:** false **Explanation:** arr does not have value 9 and it can never be converted to target. **Constraints:** * `target.length == arr.length` * `1 <= target.length <= 1000` * `1 <= target[i] <= 1000` * `1 <= arr[i] <= 1000`
For each position we simply need to find the first occurrence of a/b/c on or after this position. So we can pre-compute three link-list of indices of each a, b, and c.
Hash Table,String,Sliding Window
Medium
2187
1,648
hey there everyone welcome back to lead coding in this video we will be solving the question number three of lead code weekly contest 124 name of the problem is selling diminishing valued colored balls the problem statement is you have an inventory of different colored balls and there's a customer that wants orders balls of any color so orders is the number of the balls that the customer want the customer weirdly values the colored balls each colored balls value is the number of balls of that color you currently have in your inventory for example if you have six yellow balls and the customer would pay you six for the first yellow ball after the transaction there will be five yellow balls which are left with us so for the next yellow ball that he wants to purchase he will be paying us 5. the value of the ball decreases as you sell more to the customer you are given an integer array inventory which represents where inventory i represents the number of the balls of the ayat color that you initially own you are also given an integer orders which represents the total number of the balls that the customer want you can sell the balls in any order return the maximum total value you can attain after selling orders colored balls as the answer could be large you have to take the moderato now in this question we are clear that we wants to maximize the profit and in order to maximize the profit we will be selling him the ball which had the maximum frequency so let us say if the color yellow had the maximum frequency it is let's say 87 so first ball that we are going to sell to the customer will be from yellow color and the profit that we are going to get is 87 and now the yellow colored ball will reduce to 86 so let's try to simulate this so let us say we have the greatest element inside our vector which represents the maximum frequency of any colored ball so if it is 87 let us denote it in yellow color so it is of yellow color and it is 87. so we are going to pick this up the profit that we are going to get is 87 and now the frequency of these balls will reduce to 86. again we will be searching the greatest insider vector or inside our array and let us say again we get 86 as the greatest now again 86 will be added to the profit and the frequency of the yellow colored ball will now reduce to 85. now let's say we have balls which are 86 in numbers so the next greatest number that we are going to get in the array is 86 so this is a blue colored ball so 86 will be added to the profit again and the frequency of yellow colored ball will now reduce to 85 so till the time we have orders remaining we will be picking up the greatest element from the vector that we have we will add that value to our profit the way that we are doing here and then we will reduce that value by one and we will reduce the orders by one so this is the first algorithm that we have discussed actually in this video we'll be discussing up many approaches the final approach is going to be the most optimized so watch the video till the end so if we see that we are searching the maximum element till the time we have orders remaining so let us say if we have x number of orders and we have n elements in total so x into n will be the total time complexity that we are going to use of course it is going to give us tle that is why we are not going to use this approach now as we want to find the maximum element each time why to search it inside the array instead of doing that we can create a heap so heap is a data structure which returns as the maximum element each time so the top most element in the heap is going to the maximum or the minimum depends on the what kind of heat we are using so if you don't know about the heap i have a video on heap as well i will provide the link in the description you can study about here from there and come back to the problem now let's move forward so the heap is going to return us the top most element that is the greatest element and it is going to return us in big o of one complexity so let us say the greatest element that we obtained from the heap is a number y so this number will be added to the profit so y will be added to the profit orders are going to get reduced by 1 so x minus and this value will be reduced to 1. so in order to reduce y by 1 first of all we will have to pop out y from the heap so that is going to take log n time and then insert y minus 1 to the heap again so again it is going to take log n time eventually it is log n to log n or we can say it log n so instead of doing a big o of n search that we were doing in the previous solution we are simply doing log n insertion and login deletion so the overall complexity becomes x where x is the number of orders that we want and multiplied by log n for each order so this is much better than the previous approach that we discussed now let us see a slight optimization in the second approach that is using the heaps so what we are doing here we are simply picking up the greatest element so let us denote the greatest element by g so g is the greatest element and then we will add g to the answer reduce g by 1 insert it back and reduce the orders by 1. till the time we are having orders remaining we will be picking up the greatest element and do the same operation so now instead of picking up the greatest element we will be picking up the greatest and the second greatest element all right so let us say the greatest element is 15 and the second greatest element is 10 so now the difference between these two element is 5 so this will be topmost element this will be the second topmost element after we removed the topmost element this is going to come at the top so we can get both of these elements in log n time so now after getting these elements we know that g or the greatest element is going to remain the greatest so 15 is it is going to be greatest the next time it is inserted after doing the operation it will be 14 still it will be the greatest then 13 12 11 and 10. so till the time it is reduced to 10 it is going to remain the greatest all right so why to insert it each time and then pop it out each time and then insert back again so instead of doing all this we can simply see the difference between these two elements the differences of five elements so we can simply reduce the order by five instead of reducing it one by one we can directly reduce it by five so orders we can denote orders by x so x will be equal to x minus 5 and what all elements we are going to get 1 2 3 4 5 6. so actually it is 6 element we can get 10 as well so x minus 6. now we will be adding the summation of all these elements in our answer to do that we can use a mathematical formula that is the summation of n natural numbers that is n into n plus 1 divided by 2. so we can use the same here we have 15 as the element the rightmost element is 15 and let us say the leftmost element is 9 and this is l plus 1. so actually i'm denoting it left or right in the reverse direction but yeah let's assume that this is the right most and this is the left so now what we can do is we can write it as r into r plus 1 divided by 2 minus l into l plus 1 divided by 2. so this will be the summation here so this is a bit optimized but in the worst case it is the same solution i will tell you why so now let us assume that the greatest element g is 10 and the second greatest element is 10 again in this case we will be able to use only one element that is 10 so we will add 10 to the answer and then the second greatest will become greatest and the greatest will become second greatest so it will reduce to nine so that's why it will become second greatest and it will become greatest in the next iteration now 10 will be reduced to 8 so we will add 10 plus a to the answer and now it will be 8 so it will be second greatest again and it will be greatest which is 9. now 9 can be reduced to 7 so it will be 9 plus 8 and now this will be second greatest as it will become 7 and it will be the greatest so when the difference between these two element is only 1 so it is almost same as the second solution that we discussed but now let us discuss the final approach and which is going to be most optimized let us say we sort all the values inside the vector which is the frequency of all the balls so let us sort them and let me denote them pictorially so let us say this is the number of one ball with a certain color then this is another balls with some other color then these are the number of other color balls these are number of brown color balls and let us take white so these are the white colored balls and let me take this galaxy color and these are the number of galaxy colored balls all right now cos first we'll be starting with the galaxy color because it is uh is having the most frequency let us give some number to all of these this is nine this is let's say seven six three uh then two and one all right so now the difference between these two the greatest and the second greatest is 2 so we can use 9 and we can use 8 over here and now the frequency of these two elements is going to be 7 so it is going to be same so this will be added to the profit the orders will be reduced by 2 minus equal to 2 and now let's move on to this element now we will see the difference between this and the previous element the difference is of 1 but we can also see that there are two bars with the same height and that is seven okay first let us denote it as seven because the height just got reduced to seven now there are two bars with the same height that is seven so we can get one ball from here and both will give us profit seven each so we will be getting seven plus seven as the profit orders will be reduced by 2 and height of these bars now will reduce and it will become 6. so these heights are now going to be 6. now we have three bars with the height as six next we will be going to this bar and we'll compare it with the previous bar and here the difference is three so we can use six we can use five and we can use four but we can use these values in three bars so this value let us say this summation of this is uh 15. so 15 profit we are getting from one bar but the same profit we can get from this part and the same profit we can get from this bar as well so 15 multiplied by 3 will be the total profit and in this case the number of balls or the number of orders that will be reduced is six because uh it will be nine because from each part we are using three values six five and four and we have three such bars so it will be nine order minus equal to nine and now the height will get reduced to three so height of all these three bars will be reduced to three okay so it will be three each then we will go to this bar we will see the difference is one so we can only use the ball three but the ball three could be used in this and this so it will be 3 multiplied by 4 as the profit and 4 number of balls could be used so orders will be reduced by 4 and the profit that we are going to get is 12. and now the height of these bars will be reduced to 2. so this is how we are going to do this and now let us see one thing let us say this height is 3 we're just changing it a bit let us say this height is three this side is one and now the difference between this and this is two so we can use the ball width which will give us the profit three and then we can use the bulk which will give us the profit two and that we can do in all these five bars so we can in total we can use ten number of balls uh two from each of these so ten number of balls could be used and the profit that we are going to get is five multiplied by 5 where 5 is the profit from 1 bar and 5 is the total number of bars so that will be the profit but let us say that the orders which we are remained with is only 6 okay if the orders are only six we can't sell 10 balls and we cannot have a profit of 25 that we were having in the earlier case so what we should do is we should simply use the balls which will give us profit three from here and three from here so we will be able to use five balls which are going to give us three as the profit okay so it will be three into five now we still want to use one more ball and that will give us the profit two that we can use from anywhere but let's say we are using it from the bar with the color pink so the profit will be three into five plus two will be the profit of one ball similarly if it was seven then also we would have used five balls which will give us the profit three and then two balls which will give us the profit two all right so we will be handling these cases when we are coding this so just keep in mind when we are coding that we have to handle this case as well now let us go to the coding part and let us try to code this approach the other three approaches that we have discussed you can code them and i think the last approach the third one will be accepted but in the worst case it should not be accepted now let us go and code this one so first of all we are going to sort the given array inventory i am going to represent it as v so using the sort function v dot begin v dot end it will be sorted in ascending order but we want it in the descending order so we will be traversing from the last position so for in i is equal to v dot size uh let us denote it by n so i is equal to n minus 1 i greater than equal to 0. and i minus n is equal to v dot size and let us say we want to calculate the result and for that i'm going to use long so that i can avoid integer overflow because we have to take the modulo and we will assume that the answer would be very large so we are going to use a long now what we are doing is we will see the uh difference and the difference is going to be we were discussing the difference between the current bar and the previous bar so we are actually talking about this difference between this bar and this bar so this difference will be equal to v of i minus if i is greater than 0 then v of i minus 1 otherwise 0. so this will be the difference now we will take another variable which will be the number of orders that we want in this particular iteration let us denote it by x so x will be equal to minimum of orders which are remaining so let us denote it by o is the orders which are remaining comma the number of balls that we can take so that will be equal to the balls here multiplied by number of bars with the same height so the number of bars with the same height that we can simply get by doing n minus i where i is the current bar so n minus i will give us these number of bars and the difference that we just calculated will give us the number of balls that we can take from one bar so now this will be equal to n minus i multiplied by difference now we calculated the l and r we want l and r for the calculation of the profit so for that we are taking r as v of i this our r calculate l as r minus the x divided by n minus i so in order to calculate l what we are doing is we are reducing r we are reducing from r x divided by n minus i so in the case when x is equal to n minus i multiplied by a difference this x is going to be the difference and which is obvious but in the case when x is not equal to this and it is equal to the number of orders remaining then in that case we will have to do what we just discussed over here that we have to take a certain number of balls with the maximum height and a certain number of balls with the height which is just less than that so this is what we are going to use here so in the case when we have sufficient orders remaining and the x is equal to n minus i multiplied by difference we don't have to worry about anything and we just have to do our return plus equal to r into r plus 1 divided by 2 minus l into l plus 1 divided by 2. so basically if this is 3 and this is 1 we know that this is our r and our l is equal to r minus the difference is 2 so 3 minus 2 is 1 so it is equal to 1 so l is equal to 1 so r is equal to 3 and l is equal to 1 applying the formula here 3 into 4 divided by 2 which is equal to 6 minus 1 into 2 divided by 2 which is equal to 1 minus 1 which is 5 and we can see that we have the elements 3 and 2 available and the summation of 3 plus 2 is equal to 5 so that is what we are using here this is the formula for that finding l and r and just subtracting it now what we have to do is we have to do return plus equal to l multiplied by the x where x is the number of balls that we have used modulo n minus i the number of bars that we have of the same height so this will only apply in the case when there is a modulo or when there are only a certain number of orders remaining because in the case when we have x as n minus i into difference this modulo is going to give 0 and this will not be counted so only this thing will be counted but in some cases as we discussed here that if the number of orders which are remaining is 7 and we have ten balls that we can use we will be using the five balls from these five bars with the greatest height and then we will be using two balls with the height just less than that so coming back here finally we have to reduce the number of orders that is o minus equal to the number of bars that we have used and that is equal to x and finally we can return our answer also we have to take the modulo so let us define the model of hash define so this is the number from which we have to take the modulo we will be taking the modulo after this so return modulo equal to mod and after this return modulo equal to mod let us try to run this and see if there are any compilation errors hash define mode so we have a huge answer and we should not have that answer module because we are not initializing our return with zero it is giving us 12 we should have 14. let us see where the error is and we will find that in the line number 15 here this is the summation but then there are certain number of bars and the number of bars are n minus i also here we have here we had 1 instead of i so we have to make it i now let us try to run this and it is giving us correct answer let us try to submit hopefully it is going to be accepted so this video turned out to be a bit long but then we discussed not many approaches here so this is how the process goes into an actual coding interview you come up with a solution and then you will get some hints from the interviewer and then according to the hint you will be able to work out so we have an integer overflow here signed integer overflow uh that is because we have to take them as let us take them as long we are going to take everything as long now even this difference as long let us take this as long let us try to submit this finally so finally it got accepted so this is how you build solutions in an actual coding interview the interview is going to help you to optimize the solution and you have to keep optimizing it till the time he's satisfied so if you like the video please subscribe to the channel please share it with your friends and if you haven't hit the bell icon please do that because we frequently upload videos and you will get the notification as soon as we upload the video the videos to other solutions from the same contest is going to be uploaded soon we have already uploaded the solution to the problem number two and we will soon upload the solution to problem number four and one as well so this is it for the video thank you
Sell Diminishing-Valued Colored Balls
minimum-insertions-to-balance-a-parentheses-string
You have an `inventory` of different colored balls, and there is a customer that wants `orders` balls of **any** color. The customer weirdly values the colored balls. Each colored ball's value is the number of balls **of that color** you currently have in your `inventory`. For example, if you own `6` yellow balls, the customer would pay `6` for the first yellow ball. After the transaction, there are only `5` yellow balls left, so the next yellow ball is then valued at `5` (i.e., the value of the balls decreases as you sell more to the customer). You are given an integer array, `inventory`, where `inventory[i]` represents the number of balls of the `ith` color that you initially own. You are also given an integer `orders`, which represents the total number of balls that the customer wants. You can sell the balls **in any order**. Return _the **maximum** total value that you can attain after selling_ `orders` _colored balls_. As the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** inventory = \[2,5\], orders = 4 **Output:** 14 **Explanation:** Sell the 1st color 1 time (2) and the 2nd color 3 times (5 + 4 + 3). The maximum total value is 2 + 5 + 4 + 3 = 14. **Example 2:** **Input:** inventory = \[3,5\], orders = 6 **Output:** 19 **Explanation:** Sell the 1st color 2 times (3 + 2) and the 2nd color 4 times (5 + 4 + 3 + 2). The maximum total value is 3 + 2 + 5 + 4 + 3 + 2 = 19. **Constraints:** * `1 <= inventory.length <= 105` * `1 <= inventory[i] <= 109` * `1 <= orders <= min(sum(inventory[i]), 109)`
Use a stack to keep opening brackets. If you face single closing ')' add 1 to the answer and consider it as '))'. If you have '))' with empty stack, add 1 to the answer, If after finishing you have x opening remaining in the stack, add 2x to the answer.
String,Stack,Greedy
Medium
2095
729
alright guys welcome to our channel code with sunny and in this video i will be talking about the lead code problem again and again for the daily habit and index is seven to nine and the problem is of medium type problem of the late code okay so i thought something interesting that before moving to discuss this problem i just want to show you something interesting and it is this one thank you for your love and support that is currently we have reached the thousands of subscribers and currently it is like incrementing by a huge amount and thank you for your love and support since you have liked our content and subscribed it and share it among your friends again i'm asking you that if you love our content if you have any doubts regarding any of our videos or any of our things just mentioned in the comments section of the video we will try to update ourselves and we try to help you guys in all possible ways and also i will just ask you that if you love our content and all that stuff then i you should must have to recommend to your friends so that it can help them out also and you can share it and help us by subscribing our channels and that's all okay so talking about this problem implement a my calendar class to store your events a new event can be added if adding the event will not cause a double booking okay so what is the event i think start to end like it is actually a range of dates i think yes so we will have to implement the method book this one formally this represents a booking on the half open interval you can see the start time has a inclusive bracket while the end time doesn't have some inclusive bracket okay so rather than focusing on this one let's move for the double booking happens when the two events have some non-empty intersection that is there is non-empty intersection that is there is non-empty intersection that is there is some time that is common to both the events okay for each call to the method my calendar book return true if the event can be added to the calendar successfully that is if you try to add my current event to the calendar and if there exists some another event which is going to make an overlap with my current event i cannot add my current event right okay otherwise return false do not add the event to the calendar okay so here are some series of examples i will discuss over that i don't think this example is sufficient i will take some my own example i will try to explain in the best possible way and there's a note also if this is at most thousand and this is this one okay so we'll try to make it uh something like really cooler code okay like it is actually much interesting you can see the constraints like start and it can vary up to zero to ten point and it may cause a trouble to us and what is that trouble suppose it is like up to 10 power 5 then you can maintain an array i think and it can be done easily but here is something like interesting 10 pound and you cannot maintain this i array of size 10 power 9. that is a boolean it may help us but here it is not going to help us and it is causing some trouble okay we'll manage that okay so let's move further to understand this problem in the with help of examples and learn the concept i will try to implement that also okay so let me give it a like over here because we are going to learn some new concepts so let's move further okay so this is stuff that i have made over here okay so it is basically asking that suppose we have some intervals like call let's say five to seven and it's open and there is some close it means that we have some okay so let me make a line over here like using this one okay so it is a line and what i am going to do here it is five and somewhere six around and somewhere seven okay it means that uh this is included but this is not included okay so this is one of the intervals suppose this has been given to us you are just going to take into account suppose another interval comes over here and it comes like 729 can this interval be taken with this interval or not you must have to check it out and what is the method of doing that just try to make a line also okay let's try to do that so note that this point is not included due to this because there is an open bracket okay so let's try to do that if i will try to increment this line up to this 9 and then somewhere 8 and this is included can this is included in our answer on note that 7 is not included by this interval so i should have i can include this one okay so now this is included yes i can take fives comma seven and i can take seven comma nine okay so let's try to pick another interval and what is that another interval so let's suppose i am going to take like 4 to 6 can i take this interval let's try to understand that let's try to extend this one up to this one i'm going to say yes there it is 4 i can take 4 so i will try to take 5 now note that 5 is already taken so i cannot take 5 so i should have to return my answer as false when this interval is given to us and this will return true and this will return row note that there is a sequence of operation being done like first this will be done then second this will be done then this will be done so if i will follow a sequence of operations like this will be done first then this will be done this will return true this will return to but this will return false okay so this should be cared off like how you can implement this entire scenario let us try to understand that again like suppose we have some interval okay this is not a straight line i guess so i will take some straight line to have a better feel over this question so okay so this is some straight line then i will take some color other another color what i'm going to do is suppose this is 5 and this is six and this is seven and this is eight and suppose we have been given some interval five to nine okay and this is included i'm not taking nine over here okay now the advantage when that is the start and end you can see s and e is going to vary up to 10 power 9 right and it is like greater than or equal to 1 zero okay now suppose it is not ten power nine it is like ten power five let's suppose for a while then what you are going to do is suppose you are going to maintain an array boolean array of ten plus five size i guess and when you have encountered this interval five to nine and five to something you all mark this positions as what room right that is these positions have already been included into your calendar okay and whenever you encounter another interval and when you try to mark these positions back into this range of the array then you will find that at a certain position if you find that the value at that position is already true it means that event that position has been already included into your calendar and then this raises a contradiction you're not going to add this even to this calendar then what you are going to do you are going to return false denoting that this event this current even cannot be added to your answer and otherwise if you can add this position that is if you are able to mark all the positions which are already false and we are going to make it true now under these positions let's say s1 to e1 you can easily claim that yes this event can be added to your answer okay this is the very brute force approach and a brute force approach you can also say like when it is 10 power 5 but i am i want to deal with 10 power nine how we can do that okay so let's move further so what i'm going to do is so suppose so let's take a line and it is like again five six seven and then eight okay now what i'm going to do is you can insert the elements into your uh like let's maintain some set or you can also say you can insert the start positions and end positions into some vector or some area what i'm going to do let's try to understand that okay you can see what i'm going to do is if my position let's say i'm i've been given some 5 comma 9 okay and i will insert the value corresponding to 5 with 1 and i will also insert the value corresponding to this 9 s minus 1 note that 9 is not included in our current interval it is it has an opening bracket and doing this what is the advantage of doing this right you must be wondering that okay so what i've done is let me recall it like i whenever i will encounter some start position or some end position i will push the value push the pair to start comma 1 that is the value corresponding to start is 1 and the value corresponding to the end position is -1 position is -1 position is -1 to my uh let's say let we are maintaining a multi-set and what is that multiset multi-set and what is that multiset multi-set and what is that multiset doing it is actually basically a set with multiple same values you can also take us like set but i am here taking multisite it's my choice okay so i will take a multiset and what is this multiset doing over here multiset will store the pairs that is this one and this one for every entry that we have been given in this question okay so corresponding to the start position i will push up this one value and corresponding to this end position i will push up the minus one value okay so my multiset will store the values in ascending order with the help of first element of the pair then through the second element of the pair okay so my values will come up to 5 comma 1 will be at the top of the multiset then again 9 comma minus 1 will be again at the top of the multiset now suppose another pair comes up like what is that another pair like uh let's say another pair comes up is 9 comma 11 9 has the closing and 11 has the opening again what i am going to do is i am going to push up the element 9 and what is the value corresponding to this start position is 1 and what is the value corresponding to this end position is minus 1 ok then i will push up this 9 and 11 so 9 will hold the value of 1 and 11 will hold the value as -1 okay so the you can easily observe -1 okay so the you can easily observe -1 okay so the you can easily observe that this is the correct order that is present in this set right and you might you must be wondering that why i am pushing this one with star that is i am appending this value one with start why not minus one with the start and end with one and the reason is very simple you can observe here this example like this example because here i am maintaining the multiset it will store the start comma and that is start comma the key and if i will store the val start as minus one okay and end as one okay i will write as minus one and then this one you can see this will come up first and this will not come up at the second it will come up as nine comma one and it will come up as nine comma minus one but uh if you follow the sequence of operation it means that five comma one event has been started and it is being end first that is nine comma minus one should come up the first because this event is going to be ended uh before the another event is going to be started that's why multiset will store the values in like on the basis of first element that is ascending order of the first element of the pair then it will sort on the basis of ascending order of the second element of the pair okay right so it will first certain the first element the of the page like that is nine and nine you can see the elements are seen then it will sort on the basis of second element of the pair that is minus one will come first okay that's why i have just sorted on the basis of start corresponding have the key as one end corresponding has the key as minus one okay so this will hold the correct value like nine comma minus one will come like before this nine comma one it means that five comma one event has started and it has ended before the starting of another event like this line command is going to be started okay now uh there are some sequence of events okay so let me take another page and explain you a little bit faster like 5 comma 1 and then it will have this 9 comma minus 1 note that it is like a pair in this multiset then again 9 comma 1 then 11 comma minus 1 and suppose you have another pair like let's say uh okay so i'm just writing it out as so 4 comma then 5 okay if this element is going to be inserted in the multistate what will happen 4 will have the corresponding value as 1 and then 5 will have corresponding value of minus 1 and then 9 will have corresponding value of 4 okay so i'm writing out as fast 5 as 1 and then 9 s minus 1 and then 9 as 1 then 11 is minus 1. okay you can see that when this element is going to be started that is 4 event 4 started and ended at 5 the sum is coming out to be like when the sum is coming on to b1 then again sum is coming out to be 0 like i'm going to write it as 1 then sum 0 then again sum is coming out to be 1 and summing sum is coming on to b 0 and again the sum is coming out to be 1 and some is coming on together note that i'm talking about the prefix sum of the elements presented present in the multiset in ascending order right and how this will help us in finding out the answer okay so whenever some element some segment is going to overlap with some another segment the prefix sum becomes greater than one and when the prefix sum greater than becomes greater than one i can claim that yes there is a segment overlapping with that okay so if you're not understanding this right now don't need to worry about let's say i'm going to append another element and what is that another element let's say i'm going to insert another interval starting with three and ending at five okay ending at five then what will happen this element will be inserted in this multiset so it will insert it at the top so 3 will have the value of okay so let me erase this first okay so 3 will have the value as one and five will have the value of s minus one okay so what will happen if you insert this in multiset three will three corresponding to one income first then you can see four corresponding to one will come first because this has the value of five then four corresponding to one corresponding value is one come first then five corresponding value as minus one then five corresponding value of minus one and so on uh but if you maintain a prefix sum it means that there is a one event one started but it has not been ended and another event has also been started if you take the prefix sum will come out to be greater than one and it signifies that where it signifies that the set there is some segment that is being overlapping okay so you have to return first otherwise if this everything goes right then you have to return through and insert that element into this multiset okay so i think this have the complexity not good and you can see it has the run time as 420 ms and the time complexity goes like of n square what i am going to do maintaining a multiset and inserting this one start and end and this is the running prefix sum and take start i treating in this multiset and if it is positive increment your running otherwise decrement your running and if running whenever becomes greater than one i need to erase that entry from this multiset and return false otherwise return true okay this is one of the methods but i don't think that is a cooler method okay this is what but this method is like making your concept very much clear so i have just to try to understand this another method which have been implemented by modify optimizing that code and what is that another method let us try to understand that okay so another method is like pretty much simple what i am going to do is like pushing up the pairs directly start comma end into this set and how this is going to help us okay so we have some certain element of the pairs like s1 e1 s2 e2 and s3 e3 and s4 e4 let's say these elements are already presented in this multiset or not the multiset now it is lecture i'm maintaining the set and it is already present in the set and all are the valid no one like no two pairs is going to overlap with each other okay now if this is present in the set it means that s1 is already going to be like less than s2 and s2 is already going to be like less than s3 and all are this like sorted in ascending order right so now what i'm going to do is like suppose we have found that another element pair like s so let's say sx and ex okay now if i will have the sx and ex as the pair then what i am going to do is find the lower bound in this set and avoid this lower bound is going to help us the lower bound is going to help us like in just checking it out if this uh this element can be inserted into its correct position in this multiset or not okay so what i'm going to do is like suppose uh this s1 e1 comes over here then h2 e2 comes over here and now suppose this sx and ex is the that is this pair is correct position is over here let's suppose and then comes s3 e3 and so on like suppose this has this sxex the correct position of this sxcx is over here now let's check it out if this is the correct position of this sx ex or not okay and suppose lower bound is pointing at this iterator like you know the concept of lower one like suppose we have the elements like three five and if you find out the lower bound of this five then it will point out to this position okay so i'm trying to just find out whether this position is the correct position in this set or not okay so this will be correct position only and only when the next element of the pair if present will hold the criteria of this non-overlapping condition non-overlapping condition non-overlapping condition and what is that non overlapping condition you can see the ex okay so i'm just pointing it out with another thing you can see the ex and s3 must hold some relation right and this e2 if there is some backward element the backward pair present then e2 and s6 must also hold some relation and what is that relation okay because this is the e2 of the ending uh ending time of the previous event if we have some series of sequence of events then you must have to write some condition what is that condition that is sx okay uh okay so you must write down this one if e2 is going to be like greater than sx or this so like if e2 is greater than sx or ex is greater than s3 right if any of these two values is coming out to be true like this is the this is a boolean result let's say bool one and this is the bool two this is the boolean result and this is also the boolean result if e2 is greater than sx it means that these two values are overlapping because this uh like s2 e2 is another event which has not ended but this event has already started and similarly sxex and s3 e3 it means that sxex is not yet finished and s3 has started then i can say this ss ex cannot be inserted into my current sequence of events otherwise we can insert that so we need to check these two conditions by taking the lower bound okay so let's move further to understand this with help of coding part okay you can see i've already submitted some code like i've maintained the set pair s and this is actually maintaining the pairs check if the current time interval can be inserted or not find the lower bound to find out the correct position and if my next element exists and this end is greater than itr dot first that is the current ex you can see is greater than itr dot first that is the next element starting value starting time itr dot first then i can say return false current element cannot be inserted also i need to check with the previous ones also if the previous one exists and this previous value that we know that i am decrementing this iterator by one previous value second that is previous ending value you can see e2 is greater than my current start value then i can also return false because this element cannot be inserted otherwise insert it and return true so this is all about the sequence of questions like okay so you can see it has a runtime of 124 and 389.9 mb and it's like good one and 389.9 mb and it's like good one and 389.9 mb and it's like good one so if you have any doubts do not forget to mention in the comment section of the video and i will ask the viewers to like this video share this video and do subscribe to youtube channel for latest updates thank you for watching this video
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
92
hey everybody this is Larry I hit the like button hit the subscribe button let me know how you're doing this farm I'm gonna stop alive right about now Oh 92 we must link this to we were said link this from position m2n do it in one pass one is less than or you could M which is less than you go to N or which is less then you go to the length of the list with M and n oh so not entire necklace just a position m to end so it is to this is a precision though for some reason they the numbers are the same so it's kind of unfortunate okay so basically I would just it's kind of tricky it's one of those things I just have to think about there's a lot of weird edge cases and the way that I would attack this poem is just recursion well yeah well I'll it's time to be cushion or a stack that's what I was going to say and they're both the same it's just whether you want to do them implicitly or explicitly I think I'm gonna do a verse that so that it this time just so that ah yeah we could kind of visualize it together that's let's put together let's go yeah so now that's half a node is to go to order this quarter notice you go to hit and then wow well current know that value is not M so we want to get to the beginning of when do we want to do this we do current no next yeah and this part is the point where you can in theory do recursively but I'm using it in explicit stack so now while current node is not equal to n let's just put it into the stack so stacked on a pen current node may have they died to have two orders order incorrectly backwards roughly the same know that okay so if this starts to be queer this starts at a current known is equal to M and then it ends at kernel is equal to n but it does not append it so we actually kind of want to do wow look which we do it manually by just I've been pacing disquiet and now we can actually do this for here so now we have to stack that content or denotes that we have to be worse so then now what do we want to do well we want to go reverse right so that's just to die I think I'm missing one thing here is that after we reverse to just sub link list we have to set the pointers from the beginning again so that's all we could we might have to play around just a little bit and we did a couple of ways to do it cleanly I'm gonna just write it more procedurally so that it's a little bit maybe easier to read but that will play around that but let's reverse to like this first we will just stop this and now let's just go from for node and the stack reverse of the stack basically from the top of the stack and we popped them one by one this is just a way syntax evening of writing it kind of but now know that maybe I should just reverse the stack okay fine and it's a slightly easier to understand all right so yeah so let's actually keep track of two previous known yeah let's do that together here we just know this is equal to none I now previous note is you go to current node and then okay so now that decor note and then now we want next notice you go to none for this yeah next no it is you could occur in no time next so then we could they say this I just know it's that uh next to the stuff that we wanted worse in this case will be one and five so then we could kind of keep track of them later oh yeah that's we were still this yeah let's do it with the stock I'm going to try to do it with two well length of stack is graded or you go to so that you can look at the top two let's do stack of negative one which is the last item on the stack point that to stack of negative two okay and then now we start top right is a pathway this is this pop up pathway okay pop dust we remove the last item so that's pretty much what we have to do now we have to go and point the one to the last element so previous know is decode to previous note down X is equal to the current to the last item now yeah the last item so it should be the only thing that's on the stack of one item laugh and then the neck we want something to point to the next node which is two to the five and it's actually the first all right no that's why maybe I mix this up a little bit actually cuz the last item to be popped now every three pointing to two so yeah so this is right but now we once the two point two five which is the first item that comes here so then the previous known okay so then now previous note a dot so previous oh it's old next dot next is your next note I think that's it's a little bit weird let's give it a go oops I don't know what we're supposed to be turn you didn't tell me okay maybe just for different ahead now and we have to do some checking with if you reverse to first note and stuff like that but I just want to get something right okay let's just we turn head and then touch it and he's gotta see where it goes for us okay well that didn't go well oh the head gnome or them what is the previous no that's just double check there's a lot of edge cases with ds1 so that's why it's always good always tricky and I'm wearing a ring of how scary this is so one points to two so previous notes next should be still was oh no oh yeah this is what I keep on confusing it but we want the first item popped so let's just do first know there's to go to none and yeah first note is equal to current no this is not this is a mess of sorts right now the first though should be the four none right nope oh no whoops no this should be right why still Oh develops this should be here a little confused okay there we go but this is not done because there's stuff like one two three four five you want to reverse the entire list let's be worse a subset of doing Titleist with something beginning and then again but from TN let's try that I'm pretty sure this is not why cuz we didn't handle any of those cases somewhere you would get a error initial thing yeah okay and I now have to check if previous note it's non damaged it's our head then pretend head is you go to next note else I guess through this and what I have to do no song right now but everyone is on a server for me you refresh the page Oh No but in my test cases not to type it in again okay and as I suspected we definitely of something wrong which is not handling the foods know correctly so that's breakdown of cases you have to previous notice none that means the first and the previous notice none that means that M is the first case so now we went head to be the last note so that's coming next note but however no we want that to be the first note so that's why and then that's good enough now found sigh corner like this ok well that's that my output does not my help in it my output foot and second and personal I mean like I guess that could be right but or that could be an interpretation but uh by which they just print out what I tried to give it won't let me print it out because there's a psycho in the necklace which is fear the same just goes on forever okay head is you the first note and we've so we want a head it's next downs so we want the previous Hicks that next is to go to the next node I think that's it I don't know if we can have time for this play one of those to test one element cases okay wait as long and that's fine I'm off by one that's okay what something that we can handle because we do not handle if had done next time next head is a way that thing so maybe yeah okay but now let's test the one element cases I think that's what I would worry about I've pretty easy and also just yeah that's well until one is fine expected it's okay well then we could apply some ever handling for any single M case because why now just code assumes that they're not the same so that's just to be honest let's just shortcut this M is equal to and we turn ahead and that's okay let's just try it I think there might be still this is where you still get wall oh I don't like to entire oh these are indexes that undervalued that annoying okay I mean I think I went but they ordered the one input did not okay that's easy to fix still but it's just that well just that I think I'm just about to thing but yeah let me think about it for a second let's just do count I think this is why but it could be off by one - let's try it so one is the first one - actually do this in a Queenan way - actually do this in a Queenan way - actually do this in a Queenan way which is let me basically we wonderful power 0 index ok let's try again oh I should have tested that test case for us there's a Luigi go but yeah but that's all it is it's just a lot of edge cases so I think there a couple of caveats here one is that you implement your length list one thing that I would recommend these things is to use the cell know a cell know why you so that kind of wraps around in a way but so that you don't have to worry about all these things where so your head will actually be a new head but of course this is a very special problem where they you have to do things in one pass and you have to do it well I guess technically you don't have to do it in place but with linked lists a lot of the times that's what they want you to do because that's the difficulty in an interview because otherwise you could just put on a list and create an entire linked list right so that gives the point a little bit but it's a we saw there is a lot of weird things about this Paul and you just have to like I think in terms of understanding it's very straightforward but there's just a lot of edge cases and you have to figure out what is the best way to handle those edge cases but I use an explicit stack I feel free to use a recursion an implicit stack and that's the way I would think about this problem yeah and like this comes up a lot on interview so good luck and good practice and have fun and all that stuff oh yeah that's why I have for this forum and cool thank you
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
1,498
hello everyone welcome back to Lee coding on this channel we try to solve the problems which are frequently asked in programming interviews we try to build the solutions in a stepwise manner and then talk about the space and the time complexity which is asked in the interviews now the problem which we are going to look today is the number of sub sequences that satisfy our given some condition let us go through the problem statement in the sphere are given an integer a announced and another integer target we have to return the number of non-empty sub sequences of numbers such non-empty sub sequences of numbers such non-empty sub sequences of numbers such that the sum of some of the minimum and the maximum element on it is less than or equal to a given target now for example if we have the given array s 3 5 6 &amp; 7 and the target is 9 the possible 6 &amp; 7 and the target is 9 the possible 6 &amp; 7 and the target is 9 the possible sub sequences are 3 because in this case the minimum and the maximum is 3 itself and the summation of minimum men and maximum is equals to 6 which is smaller than 9 so this is a possibility then we have 3 &amp; 5 as a possibility because in have 3 &amp; 5 as a possibility because in have 3 &amp; 5 as a possibility because in this case the summation is 8 then 3 5 &amp; this case the summation is 8 then 3 5 &amp; this case the summation is 8 then 3 5 &amp; 6 is another possibility &amp; 3 &amp; 6 is another possibility &amp; 3 &amp; 6 is another possibility &amp; 3 &amp; 6 is another one in break both of them the summation is 9 which is equals to the target and which is allowed now we cannot take 6 &amp; 7 because then the cannot take 6 &amp; 7 because then the cannot take 6 &amp; 7 because then the summation would be 13 I guess and that would exceed the target similarly we cannot take 5 &amp; 6 so if we look at the cannot take 5 &amp; 6 so if we look at the cannot take 5 &amp; 6 so if we look at the solution to this the first obvious thing would be to generate all the possible sub sequences which are non empty and then check the smallest and the greatest element in those sub sequences and then figure out whether we can consider this one or not but the t generate all the sub sequences the time it is going to take his exponential so let me quickly explain you what do you mean by sub sequences let us have 1 2 &amp; 3 so these sequences let us have 1 2 &amp; 3 so these sequences let us have 1 2 &amp; 3 so these are the 3 elements which are present in the announced array now if we consider we have to generate nanami subsequences so there should be an element which is fixed let us consider one as the fixed element so if I is the fixed element then we have two and three they could be present there or they could not be present there then if we have two as the fixed element then one could be present and could not be present and similarly three and another possibility is to have three as fixed element and one and two as optional now if you are generating for this one we will have one two and an option for three and we have one and two is north there then an option for three here we will have one two and three is not present here also we have two choices one two is not present and three is there one two is not present and three is not there as well similarly we will have choices for this and this so on each step we will have choices there will be two choices for each element so for two there were two choices for three there were two choices so in total there were four choices for this one so we got one two and three four so these are the four sub sequences which are non empty they have a shear element or a fixed element which is fun same is the scenario when we have two as the fixed element and three as the fixed element so these are the sub sequences now we cannot generate all of them because that would take to raise to the power n time if we have n optional elements so what instead we can do is we can go with another approach which is similar to a problem called twosome which is a very famous problem so first I will discuss what that problem says and then I will try to explain the same problem using death approach now let us say the given array is 1 three five nine eleven twenty now let us say the summation which I want is fourteen so the problem to some is asking us to tell whether there are two elements which are present inside the array the result of the summation of those two elements should be equals to the target which is 14 so I have to tell whether those two element a percent or not the given array is sorted and I will start on the first and from the last so it is a two-pointer approach I will see it is a two-pointer approach I will see it is a two-pointer approach I will see the summation of these two elements first the summation of these two element is 21 as I know that 21 is larger than 14 that means I had to reduce something so obviously I am going to reduce the larger element and it will now come to 11 now the summation will be 11 plus 1 which is equals to 13 which is smaller than what we need so we will move forward and increase the smaller element now the summation will be equals to 11 plus 3 which is equals to 14 now this is what we actually need and then we will return true in this case we are going to stop if we are not able to find such a solution and in case he'll it be in 15 I don't think yeah 15 this would result in the collision of start and end and as soon as start and end are colliding I will return false in that case so this is the approach and how we can implement the same approach in this case as well now here we are taking the example 2 3 4 6 7 I think this is the example 4 3 4 6 7 2 3 4 6 7 and now I will apply the same approach as we were using in the twosome problem here is this starting in the ending index the target which is given to us is 12 twelve is the target now the summation of two and seven is 9 which is less than it has less than the target so this can in fact be a possible subsequence and for this I will keep 2 as fixed so I will be left with 1 2 3 4 and 5 optional elements which is 2 raised to the power 5 this is equals to 32 so this is my first answer this is my one of the answer then I will keep adding all the possibilities into our answer and then finally return now as we can see that it was 9 as the submission now we can try to increment this third pointer now it will come to 3 the summation is 7 plus 3 which is equals to 10 and which is smaller than 12 this is also permissible so the range from here to here is also permissible I will keep 3s fixed and 1 2 3 &amp; 4 for optional elements 2 raised to 3 &amp; 4 for optional elements 2 raised to 3 &amp; 4 for optional elements 2 raised to the power 4 which is equals to 16 and this is my second part of the answer then again I will increment this and I will be having 2 raised to the power over 3 this time which is equals to 8 now I will increment it again because again the summation was 10 which is more than 12 now I will get this summation as 11 this is also smaller than 12 so in this case it will be 7 plus 4 which is equals to 11 and optional elements are 2 raised to the power 2 is 4 so this is my fourth part of the answer then I will increment is again in this case the first element will be 6 and the last element will be 7 the summation will be 13 which will exceed the given target and this will not be considered now in this case I will not add anything to the answer and here I will decrement the last pointer so now both the pointers are at and the starting and the ending elements are six the number of optional element is 0 so 2 raised to the power 0 which is equals to 1 this is the fifth answer let me combine all of them it will give us 40 50 56 plus 5 which is equals to 61 the answer was 61 yes it is correct 61 is the answer in this case this is the strategy that I am going to apply and let me try to explain it with the code I will be talking about the time complexity in just a moment now so initially our starting point will be 0 our end will be dark a dot size minus 1 sorry now start size minus 1 while it starts smaller than equals to end if the summation of if nums of start plus if this is smaller than equals to target then answer plus equals 2 power 2 and minus start so end minus start is basically 1 less than the number of elements which are present in the current subsequence because one element is fixed there so this is what we have to add to our answer and in this case we have to do s plus because we are smaller than or equals to the target else in all the other cases we have to do n minus finally we have to return our answer and yes it is going to handle some cases but not all of the cases that we are going to see in our file in douses equals to 0 for let me run this for another test cases see it is giving us correct answer for all of the mentioned test cases but it will not give us correct answer because the answer could be very huge and we have to take the model based well so this thing over here this power this will exceed the integer limits and it will give us something it will guess wrong value which is not what we actually want so we should take the modulo while we are taking the power here while we are considering the powers for that I will have to implement this power function by myself and that I will implement using this helper function using recursion so this is X raised to the power y at the same time I have to I will have to take modulo so mortal is something that I am going to hash define mod as 10 raised to power 9 plus 7 this is my modulo to calculate X raised to the power 9 I will do this using binary exponentiation so in case y is equals to 0 so something raised to the power 0 is 1 if x is equals to 0 or I turn 0 if y the power modulo 2 is equals to 0 that means it is even in that case what we can do is we can calculate an answer which is equals to help of X raised to the power Y by 2 and then we can do answer x equals to answer in case it is odd we can do int answers equals to help of X comma y -1 now y -1 equals to help of X comma y -1 now y -1 equals to help of X comma y -1 now y -1 would be even but we will have to multiply the answer by Phi and then we can return the answer so we can declare answer outside both of them answers equals to 1 so this is the strategy but I will have to include this modulo a spell and for that to handle the corner cases I am going to take long instead of into here long answers equals to 1 it should give me long as well here I will return answer mod answer modulo equals to mod here also okay it is handling those cases let me see I will try to improve this if I find that the answer is wrong so instead of this you can do help yes answer modulo equals to mod or C error the error is use of undeclared okay the spelling of returns false the answer is wrong because we are not calculating the powers okay there's something else which we need to handle if y equals to 1 then we have to return X x equals 2y y divided by 2 answer x equals 2 answer it's more than equals to target I think all of this is correct but this power function is not functioning properly so the problem is with this one when it is odd I am subtracting the power by 1 and then sending it and in that case I have to multiply this with X now it should give us the correct answers let me try to run this and then I will improve if there are wait a second expect release it was wrote in fine for all of those cases for okay ie okay so the num serie which is given to us is not already sorted we have to sort it salt num start begin comma num start end if we see the answer for the last case is 56 it is correct okay so it got accepted that time complexity if we consider n as the number of elements in nums the time complexity is Big O of n log n for this sort function Big O of n for this one but that doesn't matter much now because we already have something as large as n log n so this is the final complexity of this the space complexity is constant this function will okay so this is a binary exponentiation function so it is logarithm exponent this is a logarithm function Y could be as large as the size of the array which is N and in this case this will give us our answer in log of n so both of these sort function as well as this while loop will result in n log n because n for this while loop and inside the while loop while we are calculating this answer we are going to use helper function which is a login so n multiplied by log n for this one as well if you like the solution please don't forget to leave a thumbs up you can also provide me suggestions in the comment section so you can tell me whether I should make tutorial videos or interview experiences thank you
Number of Subsequences That Satisfy the Given Sum Condition
find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
You are given an array of integers `nums` and an integer `target`. Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[3,5,6,7\], target = 9 **Output:** 4 **Explanation:** There are 4 subsequences that satisfy the condition. \[3\] -> Min value + max value <= target (3 + 3 <= 9) \[3,5\] -> (3 + 5 <= 9) \[3,5,6\] -> (3 + 6 <= 9) \[3,6\] -> (3 + 6 <= 9) **Example 2:** **Input:** nums = \[3,3,6,8\], target = 10 **Output:** 6 **Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). \[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\] **Example 3:** **Input:** nums = \[2,3,3,4,6,7\], target = 12 **Output:** 61 **Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]). Number of valid subsequences (63 - 2 = 61). **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 106` * `1 <= target <= 106`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,833
Hello friends, today's question is of medium level question of maximum ice cream bar delete code. In this question we will be given an arrangement named cost, its length will be end and cost and the arrow will represent me, price it for the day. Which will represent the price and we will initially have some coins given to us, we will also have that in the parameters, there will be coins in the given, so we have to get the maximum number of ice cream inside the coins given by them, so if we Let us look at this example. In this example we have Koi Bata Rakhi which is 13241 which is 7. So if we look at this example then in this van is taken first, it is okay plus three, you do plus, we also see that van is okay, first taken, three taken. You took it, okay, at this time its sum becomes six and if we add four to it, then the cost at that time will be 10. We do not have that much money, so we cannot take four, we have to take 7. Okay, this is an example in which we have to buy according to the cost, should we buy ice cream, so if we look at this question a little more carefully, then like, if we get this row sorted, first like van, okay. You are three and four, now we have 7 in this, okay this is 7, we need it, we took the first ice cream, so how many do we have, these children, six, we then took one more ice cream, how many coins are there, 5, we took back two ice creams, so how many coins? Sorry coins will be 3 and we have taken 3 ice creams, how many coins have become zero, now at this time we have nothing left to take anything, so the four we have selected can be our answer, okay and if we If you wrap it up a bit and understand then what did we get done in the first place, got it sorted, what did we do in the second, which coin was ours, we got the coin mined along with the cost, okay and the number of accounts means the number of times we did this process. We will return the account of tax which we have taken from him. Now let's look at the solution in the court. So first what do I have to do. I want to get shorted in it. So the arrangement has been sorted here. Okay, now after this my There will be a variable which will be my post, now inside it we will check the cost which is already mine, which cost is more than mine, give this grater, it is from the coin, okay, what will I do in that case, I will return the ice cream from here only. If the ice cream is not there, what will I do here? Add the ice cream and copy it. First I will return the ice cream by spelling it wrong coin mines cost i did it. Okay now I will return the ice cream here and let's run it. Let's see, there is no syntax in the code, sorry, which one will come here and which one will come here too, okay, all three ran successfully, now I submit it, this is my code successfully submitted, if we now add time complexity and If we talk about space complexity, then my time is taking like my time. If I look at the time complexity, the time it is taking for sorting here will be this much, its time complexity will be and my total time complexity will be, only we have the time complexity of sorting for the sorting of my court. We will reduce it and if we talk about space, okay gage, this was our code. I hope you have understood both the code and the approach. If you liked our video, then like the video. Don't subscribe the channel yet. If you do then immediately go and subscribe the channel, see you again with another video, till then bye.
Maximum Ice Cream Bars
find-the-highest-altitude
It is a sweltering summer day, and a boy wants to buy some ice cream bars. At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible. **Note:** The boy can buy the ice cream bars in any order. Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._ You must solve the problem by counting sort. **Example 1:** **Input:** costs = \[1,3,2,4,1\], coins = 7 **Output:** 4 **Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7. **Example 2:** **Input:** costs = \[10,6,8,7,7,8\], coins = 5 **Output:** 0 **Explanation:** The boy cannot afford any of the ice cream bars. **Example 3:** **Input:** costs = \[1,6,3,1,2,5\], coins = 20 **Output:** 6 **Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18. **Constraints:** * `costs.length == n` * `1 <= n <= 105` * `1 <= costs[i] <= 105` * `1 <= coins <= 108`
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
Array,Prefix Sum
Easy
null
1,029
English Video I Will Discuss Another Liquid Question Key You Which Was Two Cities In This Question A Company Planning You Interview You And People Life D Aage Of They Are Cost Of Or Cost Of IB Cost Of I D Cost Of Flying And D Cost of flying is D and percentage B is cost of five. See what it means, we have a company which has to take interview, two more people in which we have been given an error, what is the name of the cost in which the cost of I is? We are telling two things, A is the cost of I and B is the cost of I. What is the meaning of cost of flying the day after tomorrow? A means how much will it cost to fly the day after tomorrow. This is the cost of I and how much I means the cost of flying the day after tomorrow. I came the day after tomorrow you fly to city base b cost of five then what do we have to return Minimum cost you fly every percentage exactly and people arrive in it This is an important line What is there in this We have to make such minimum cost return due to which execution and people Only we have been able to arrive, okay, we understand through the example what we want to say, okay, so we have no first of which body they have of life, we have given cost of I, date is cost of I, it is a cost of I and B cost of I, in which what are we telling about our post, which record flower, high percentage, you are city A, and cost of because required, you fly the day after tomorrow, I, you are city B, we did not understand, after that, what is written to us that the return to us is minimum. We have to get the return done so that whatever other people are there, they can read it, meaning in every city, there are more people, they are Jains in one city, and whatever paper is there, they are Jains in the setting among us, we have to get the returns done like this, okay, this much we have understood. We have this example of what they need you in this question, so what cities do we have in this, we are given the cost, A B is given to us like this, so we can see which T road is the day after tomorrow and which two are after that. Chances are 10 and 20 means this one on A and next one for B and similarly on D Fourth question 30 and 200 means similarly for A and B Second personally this is 400 and 54 A and B city and similarly on third day after that at 3820 Going to know which A and B to T, so we can see here, we have 2 more people, so 2 more people, how many people are there, then it means 2 more people equal, you are four, so n't one means. How much does each paper have, that is, you give us two cities to go to one, we have to go to two cities, okay and for the people, okay, we understood, after this, what will we do, so the minimum cost has been worked out, otherwise where will we go the day after tomorrow? In situation A and where will we go the day after tomorrow, B, then what can we do in this is what we have been given here, so we can be this, then minimum of means whatever has been given to us, right from A and B. Bill is taking the minimum, so whatever minimum we get, we will write it in our post. Okay, so what is the minimum among these? Earlier it was 10, so we wrote 10, first we wrote which initial was zero, then we are going to insure which further. Further, first there was cost so we wrote 10, after that first minimum which is 30, so we wrote 30, then if it is 50, we wrote it as 50. After that, if it is 20, we wrote it as 20, our total. How much is it? One one zero. Okay, what did we do? We took the minimum cost of the saree so we can sleep. So you can see that this is the cost we took and the answer is also how much is it? 110 Okay height. Yes, there is power, it is divided in test and in M ​​and N, it is divided in test and in M ​​and N, it is divided in test and in M ​​and N, it is divided in A and B, but look, but its not a draw, this is April 1, it is not right, look, what is the reason for this, so change the place, so what I go 5400 What will I get? What have I got? 20 200. I have kept the above one only, I have just interchanged these two, so then I got this one, but you can see, if you do the minimum thing, here A, here also A. Here also A and here B is like this, I got it, so what will be there in this, three people are going to A, one minute, but what should be the partition in this, meaning more people should come to A and more people should come. If we want B then this condition is not happening, what is happening here is that we have here pe 2 and in means we can say 1/3 1/3 means 2/3 here pe A in can say 1/3 1/3 means 2/3 here pe A in can say 1/3 1/3 means 2/3 here pe A in where and here pe by three. Where are we going? Sorry, four is there, three by four will come, so this is our three because three are going to A, so we can do it, so three by four is going to A here and 1/4 of ours is three by four is going to A here and 1/4 of ours is three by four is going to A here and 1/4 of ours is going to B. But this condition is not there, where did we recognize that equal means one by you should be, that is, our approach is not right, so they have, you do things something else, so what bill does in this, how come we have this. If there were any, then there is also A in this. You guys know that A and B are written like this. Okay, this much we have understood A. Now what will we do, let's make a deciding factor of red A minus B and see if We do in this A - B see if We do in this A - B see if We do in this A - B so what I bill get 350 A - B of this one so what I bill get 350 A - B of this one so what I bill get 350 A - B of this one white bill get this - 170 meaning this is how much is the white bill get this - 170 meaning this is how much is the white bill get this - 170 meaning this is how much is the first one is positive and the second one is negative then we can calculate what does it mean if positive virus. Is this greater then if it is coming out you are negative and a this is understood we have okay so what will I do first I took out the positive negative difference our -10 here at -179 - 35 and minus sorry plus -10 here at -179 - 35 and minus sorry plus -10 here at -179 - 35 and minus sorry plus 10 came this a What should I do with these orders, I have to arrange them, what will come to me first, the most negative one, then after that minus 10√3/8 sending order, I 10√3/8 sending order, I 10√3/8 sending order, I left these in the sending order, so then what did I do, simply these were their pairs, right? Means Minus 170 this is the deciding factor which one is this our 30 - 200 debt is this which one is this our 30 - 200 debt is this which one is this our 30 - 200 debt is this one so I have this one so I wrote this first then Minus 10 which one is this one's 10 20 so I wrote this down 10 whose one was this one so we wrote it similarly this one difference coming out tu b 350 where is 450 from so I wrote this what I did first of all I have found d difference of which d numbers and getting and after date I have a reset in and ascending order after date what you bill get is simply you can see that we have got the numbers right from all of them what will I take from here 30 from here I will take 10 from here and what is the minimum I will take from here 20 And if I took 50 minimum then what came to me are these two and these went to A and these two came to me as B so what is bill get in this simple answer I wrote what is the minimum and from here till 30 I wrote 39 I wrote our from here How much is it, okay, then look, 50 has come from here, I have come 20 from here, I wrote 50 and 20, so how much have I given as the answer, 110 means like approach is going, you will be helpful, you are okay, I understood, so I told you the difference. Off how A - B and A look is smaller it the difference. Off how A - B and A look is smaller it the difference. Off how A - B and A look is smaller it means look negative A has been if it means A is smaller and B is bigger I have done this and its arranged means like I have value A after that from these to these pending order okay This much we understood that I found the difference, we arranged it in the form of values ​​and I we arranged it in the form of values ​​and I we arranged it in the form of values ​​and I wrote down which of the smaller ones, which half would be for the A person and which half would be for the B person, okay, that's what I did. So I approach bill B 10 ho every first of which what I have done sorting according to difference of A - B date in difference of A - B date in difference of A - B date in ascending order then I have done first and first order which is for city A and next and first order which is for city B. And in this too, if you do B minus A, then what happens to us is the first one, then which I is the first and value, then it is for tomorrow, for city B and give next and value. For whom will it be for 8 but now I have given these mines B so which is our first one this is my next value on CP Okay this much we have understood so what we did here I told you all what we have to do see Sorting is done by short according to D basis of D difference getting. Okay, so I have written here that A - B. See how it is written here that A - B. See how it is written here that A - B. See how it is written. I have explained to you that this is ours, this is how ours was, after that I look here. What is written but A of zero minus A of one and minus B of zero minus B of one what is it D meaning of this light you can get from each key comparing element fuel is compared in that a1-a2 means fuel is compared in that a1-a2 means fuel is compared in that a1-a2 means this one and this here Look what they say, 10 - 20, first I have mined these two, 10 - 20, first I have mined these two, 10 - 20, first I have mined these two, then 30 minus 200, I have done subtraction, so what I am getting is simply 160. Okay, that's what I told you, this is to mine these two. Here I have mined it, then I have compared second and third, so what I have done is 30 - I have mined them and taken out the what I have done is 30 - I have mined them and taken out the what I have done is 30 - I have mined them and taken out the subtraction of all of these two and seen similar but this one and this one so what will I get, the difference of all will be found here. Pay this look, got the difference but I bill do it simply arrange it has a positive value. Look here what is 400 and 50, 450 means which one was ours. Look, you can see from here that 450, so what does it mean? That is, this element will come first, then this element will come, then this one will come according to this meaning the difference, see how much is there, see it was 340, so I wrote this one first, then this one, after that this one with difference, the value is A. So I wrote this one and the similar last element went to A, so this is what I did first, what to do with it, sorted it according to the difference getting no, okay, this much we understood, after that what I have done is write the initial cost here, write the price here. Think then after that what did I do I initially I took from the total price now what have I done for the first half the value of my price what have I done plus equal tu cost of i and zero of zero Meaning here what is that they have you take d first place is d minimum I am getting look at the meaning of this I am telling you this was ours what we have to do in this is that we have zero meaning this one value and what is the meaning of one this value second one. Whatever our value is, we will have to take it. Okay, I have taken two volumes, what I have done in the first half is to divide it in half and in the first arc, I will take its zeros i.e. the in the first arc, I will take its zeros i.e. the in the first arc, I will take its zeros i.e. the first value and look at what I have done in the second half, the one behind it. Look at the back values, I will take this one, okay, what I have done is that first we have to take only one value and what is the value of B because it is written in it, what do we have to do in 'Tu' and ' what do we have to do in 'Tu' and ' what do we have to do in 'Tu' and ' Peepal', to whom do we have to give only one and And Peepal', to whom do we have to give only one and And Peepal', to whom do we have to give only one and And what is this one for B? This one is for A and this one is for B, so what I have done is that I have divided both of them in half. Okay, now that we have understood, this is what I have said here about the first half. Look, you can see that from zero to Ks 90 and the rest from Ks to Ks till more are written and it is not me, what can I do in one price, the cost of I means I have made it. Look, the one with zero means the first one, like this is this, isn't this the value of 10? And look at this, I one means the one behind it, I one means we have to take the value behind it, we will keep adding values ​​to it in our total price, take the value behind it, we will keep adding values ​​to it in our total price, this means it is our initial price, meaning it is zero, we will keep doing things in it, then its value will come and then further. Whichever price will come, will it go to that means the previous price and the next five bills will be added up and the total price will be our further return. Look, I did not do anything in this, simply first Dr. Hey and see this is it means compact. Okay compare d think date for this we do that in Java it is compare fear so I have nothing here I have sorted what I have Dan simply for the first half I have taken the value of A means I of zero and then here For pay second half I have taken the value of B and simply after returning from D loop I have just written D price
Two City Scheduling
vertical-order-traversal-of-a-binary-tree
A company is planning to interview `2n` people. Given the array `costs` where `costs[i] = [aCosti, bCosti]`, the cost of flying the `ith` person to city `a` is `aCosti`, and the cost of flying the `ith` person to city `b` is `bCosti`. Return _the minimum cost to fly every person to a city_ such that exactly `n` people arrive in each city. **Example 1:** **Input:** costs = \[\[10,20\],\[30,200\],\[400,50\],\[30,20\]\] **Output:** 110 **Explanation:** The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city. **Example 2:** **Input:** costs = \[\[259,770\],\[448,54\],\[926,667\],\[184,139\],\[840,118\],\[577,469\]\] **Output:** 1859 **Example 3:** **Input:** costs = \[\[515,563\],\[451,713\],\[537,709\],\[343,819\],\[855,779\],\[457,60\],\[650,359\],\[631,42\]\] **Output:** 3086 **Constraints:** * `2 * n == costs.length` * `2 <= costs.length <= 100` * `costs.length` is even. * `1 <= aCosti, bCosti <= 1000`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Hard
null
735
hey what's up guys think white here I detect encoding stuff on twitch and YouTube check the description for all my information you can support me on my patreon that I really appreciate that I do like a bunch of stuff on there and then you know message me on discord if you're trying to reach out it's a good spot but we're gonna be doing asteroid collisions today got a lot of likes I like this problem it is definitely a little bit annoying to code but I like the concept school so we're given an array of asteroids of integers representing asteroids in a row so we're given an array of integers representing asteroids you could tell because it's called asteroids for each asteroid the absolute value represents its size the sign represents its Direction positive meaning right negative meaning left each asteroid moves at the same speed okay that's actually a lot of information so the absolute value is the size if you don't know what absolute value is that's just the value without the sign so negative 5 is absolute value is 5 so that's the size so 5 and negative 5 are the same size because we're doing absolute value what else the sign represents Direction so positive is right so this negative 5 this fives going to the right negative is left so negative 5 is going to the left each asteroid moves at the same speed and then they all go the same speed so this is the same speed as this size doesn't matter for speed find out the states of the asteroids after the collisions if two asteroids meet the smaller one will explode if both asteroids are the same size both will explode two asteroids moving in the same direction will never meet okay so what they're saying is these are gonna run into each other and we want to return what happens after they do if a bigger one meets a smaller one then the smaller one explodes and they will meet if they're going opposite directions for example if one's going to the left not exactly not always if they're going opposite directions but if one's going to the right and ones going to the left and the one going to the right is on the left side of the one going to the left is on the right side you know what I mean if it were the other way around like if it was you know in this case 10 negative 5 this is good you know this one's going to the left this one's going to the right they're gonna meet but if we were looking at negative 5 10 this one's going to the left this one's going to the right they're not gonna meet though cuz they're diverging off they're going you know they're going in different directions but they're going on their own paths in different ways they're never gonna cross paths because they're already past each other you know what I'm saying so they'll meet in this case let me know if you need clarification on that but I think it's pretty easy it's you know what I'm saying so the smaller one gets blown up if they're the same size they both get blown up and that's pretty much it that's all we got to know so oh and it's a I guess it's important if they're going in the same direction they'll never meet so like five and ten will never meet ten and two would never meet even though you know two gets blown up these will never meet and these will you know these will never meet and these will never meet so there you go let's go through all the examples really quick negative five is going to head into ten so negative five gets blown up you have five ten left negative eight and eight are going to hit each other one's going left one's going right boom and same size so they both blow up two and negative five run into each other the negative five blows up the two then the negative five keeps going and the ten blows that up just so you guys know you could see that when the negative five hits the ten and the ten blows this thing up the negative five the ten doesn't lose any value it doesn't lose five so the size isn't decreasing it just blows it up so and then for these you might think Oh negative one and one they are gonna hit each other but no they're like I said they're past each other these two are going to the left but they're already on the left side so they're not going to hit the ones going to right if they're on the right side if it was the other way around like I said I'll do this one more time and you guys really should understand this I don't think it's too difficult if you reverse this so you put the one in the two before the two it the negative two and the one then they hit each other because the negative 2 is heading to the left while the two is heading to the right and they're on opposite side so boom you know what I mean so that would be an empty array alright so let's get into it so the strategy for this problem is we are going to use a stack and there's only one thing that makes you think of this it's not that intuitive it's just kind of first of all it's a great data structure to use for this because you're blowing things up you're removing elements constantly you're checking against you're gonna be like looping through checking against things it's pretty perfect it's kind it is a little bit intuitive but the main thing that makes me think of it is if you have a stack when you're putting thing when you push things that are positive asteroids that are positive you can just push on fine and it'll be good to go anything you're pushing on to the stack if there's a negative value on the stack so if we see negative 4 and then we see a positive 5 we put this on no problem they're going different directions they're never going to hit each other if it's a positive value already on like a 5 and we see a 5 we just put that on as well so no matter what's on the stack if we see a positive we're just putting it onto the stack so that's why stack is really great for this problem and then all we have to do is handle when we see a negative value and in that case we'll check the top of the stack we'll compare what the asteroid we're looking at and decide what to do so maybe blow them up pull them both up or you know blow one of them up push one on or whatever so let's get into it I think that was a pretty good explanation we're just gonna set up our stack now we're gonna say stack is equal the new stack we're gonna loop through all of our asteroids so we're gonna go I less than asteroids plane I plus and what we're gonna do for our condition is if the stack is empty we'll put any value on it first or if the asteroids of I is a positive value we will like I said any positive value can go on to the stack no problemo it doesn't matter if it's a negative value you put a positive value on doesn't matter it goes right on if it won't explode nothing explodes if it's a positive value and then you see a positive value put it on nothing explodes but the first element if the stack is empty then we can actually put a negative value on and it won't matter because if we put a negative value on first then we put the positive value on it just shows like it doesn't matter that's why we just allow the you know when the stacks empty just throw the negative value on it doesn't even matter cuz we'll just see positive you know if you keep seeing you know negative ones it'll be fine and then you see a positive one it'll be fine so it's like perfect now here's the tricky part the annoying ugly code part is you're gonna need a while true block which I'm not big fan of but it works really well here and this is the case where okay now we've we have something on our stack right we have a negative five or we have you know a negative three and negative four and now we're gonna see and then we have a five and four and then we see you know maybe a negative four now right we see a negative value we see an asteroid coming to the left and we got some to the right or whatever it doesn't have to be to the right it could be like this and we see it but this is the case else right in this case we're gonna check the top of the stack because when we see a left value there can be some problems here right when we see a negative we're gonna see some explosions maybe so we want to check the top of the stack we're gonna do stack top P great method it doesn't pop off the stack it just checks what's at the top and now we have a few conditions here okay let's say if the step if the top of the stack is a negative like in this case negative four and then we see another negative four so they're these are going to the left we see a left there's gonna be no explosion there they're all just going the same direction it's fine so if the top is a negative already well whatever we'll just push the asteroid on the current asteroid and it'll be good to go it doesn't even matter we're done here break out of the wild true loop go on to the next asteroid okay but that's not the only condition now if we see a negative and let's say we have a four on the stack right like this we have a four on the stack okay else if the peak is equal to and we're seeing a negative asteroid now the negative version of the asteroids of I so the negative of a negative is a positive so if the top is positive and then we see it's basically just checking if the values are the same well then in this case we've got to blow them up right the same values and they're going different directions we got to blow them up because this one would be positive in this case this one would be negative or this one we positive this is negative that's why we have the negation sign we got a pop and we just break because we're not adding the asteroid on because we blow both of them up right both of these blow up and another case is okay if the peak is greater than the asteroid we're looking at in value that means the peak is bigger a bigger value so if we saw if we had a 5 on the stack and then we see a negative 4 well we could just break because we're not blowing on e we're not taking anything off the stack we're not we're just getting rid of this one's blowing up so we just break it'll go on to the next asteroid in the array and last but not least the peak is less than so if we have a negative 3 and then we see a negative 4 but let me make this a better value let's do a third let's do 4 3 2 1 and then we have a negative 4 right this is a good example and why we need the while true loop because what we'll do is okay first of all this is the case where peak is less so 1 is less than this is a bigger there we going they're gonna collide 1 and negative 4 but for the negative 4 is greater in size so we got to pop the value off the stack we got to remove this value but not only that now we have to that's why we have this while true loop because it's going to go up to the top and it's gonna do this whole process all over again so it's gonna say okay what's the peak now - oh crap - is okay what's the peak now - oh crap - is okay what's the peak now - oh crap - is still smaller than negative 4 in size so you keep poppin until you hit one of these conditions or the stack is empty so if you have you know in this case we see ok peak is equal so we just blow them both up and then we're done but in the case where it was like let's say it was just there's a lot of cases in this that's why it's a little bit messy guys sorry let's say the case was three to one and then we see negative four it would be like blow this up go through the while loop again blow this up okay now it's empty though so in this case we have we pop we saw that three right we pop it off boom okay but now it's empty so what are we gonna do we're not going to be able to get another peak so we have to add a condition if stack is empty that means we blew everything up so now we want this asteroid to go onto the stack so we do stack top push asteroids of I because it was bigger than everything so the stack pushes this negative four on and we break after this now whatever is on the stack at the end of all of this junk and it is pretty messy like I said yes it's you know that's why I didn't like this problem that much but it I do like it's good concept wise we're gonna make our output array this is what we output right so there we go it's an int array it's going to be the stacked out size and whatever is at the end of the stack we want to go at the end of the array so what we're gonna have to do is we're gonna have to set the pointer to stacked out size minus one start at the end go down to zero I'm sure you guys are familiar with this I greater than or equal to zero I - - a little space there equal to zero I - - a little space there equal to zero I - - a little space there and then what we'll do is output array of I is equal to stacked up pop whatever's at the top of the stack goes at the end and then we return our output array I think I explained this pretty well it's a really long one especially with all this you know code stacked out size new int stacked out sighs sorry you gotta make sure you don't think we should have it here Oh God stack if stacks empty or asteroids of AI is greater than zero if it's positive I hope you know I don't want to redo this it's so hard to not make mistakes on this and also if you some feel like I submit and I get different percentages over so but this is a fast solution and you know see look now it's way faster but great solution here using a stack is a perfect scenario for a problem like this I do think it is complicated especially with a while true to write clean code but you know I think it makes sense it's just a little bit long so let me know if you guys have any questions about this conceptually really like this problem just wish maybe let me know if you can find a cleaner solution but there you go that's my solution let me know we guess think just scanning through using a stack and that's it so I will see you guys in the next one I my channels growing so I appreciate every on the watches these and let me know if you have problem suggestions too questions problem suggestions clean their code whatever you guys want to contribute you know do it I appreciate you guys love you guys see you in the next video
Asteroid Collision
asteroid-collision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. **Example 1:** **Input:** asteroids = \[5,10,-5\] **Output:** \[5,10\] **Explanation:** The 10 and -5 collide resulting in 10. The 5 and 10 never collide. **Example 2:** **Input:** asteroids = \[8,-8\] **Output:** \[\] **Explanation:** The 8 and -8 collide exploding each other. **Example 3:** **Input:** asteroids = \[10,2,-5\] **Output:** \[10\] **Explanation:** The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. **Constraints:** * `2 <= asteroids.length <= 104` * `-1000 <= asteroids[i] <= 1000` * `asteroids[i] != 0`
Say a row of asteroids is stable. What happens when a new asteroid is added on the right?
Array,Stack
Medium
605,2245,2317
1,962
hello everyone welcome to my channel so today we are going to delete good daily challenge remove stones to minimize the total so let us postage this question then about the constraint and then finally about the coding part about the same and then at the end time complexity in the space complexity possible now here uh let us first read the question then we go ahead so here you are given a zero index integer array files so basically pile error is being given to us in which at right position the number of stones which is there in that I file that is present means basically the array is something like one two is one two three so here this represents that there is only one stone in the pile here it represents the two stones are in the pile and here it represents three stones are in the pile so that's the thing add an integer key you should apply the following operation exactly three times and what that operation is about choose any pile I okay we are required to choose any of the pile which is being given to us and remove floor of pile I by 2. so basically we will be choosing any of them and then we will be removing 3 minus 3 by 2 so basically we are required to remove from that three by two that is what we will be required to rupees whatever there is this three is there right so we now we will be having with this three by two only so that is the thing and then if it is here so we will be removing 2 by 2 minus 2 that is now there would be one only so that is the thing which we are recording it is given at slower and seal which are there so according to that only means presently we are just writing like this but whenever we will be doing floor or seal for three by two then surely they've uh slower we all know what the answer would be so like that only that particular number would be present in that particular pie so then notice that you can apply operation on same time more than once so basically this three which is given to us first we applied the three by two now we are having this 3 by 2 then again we can apply this base 3 by 2 minus 3 by 2 upon 2. so this time we can again apply on the same so this is the thing which is required to put our ultimate goal is that we are required to return the minimum possible total number of stones remaining after applying the key operations so basically the total number of stones which are being there remaining right after applying K operations so that is the thing which we are required to return means total number of stores which are being left after applying this key operation because see at a particular pile we can apply any number of operation right but that any number of operations still have a limit that is K so that's the thing and ultimate goal is to require minimum possible total number of stone which are being remaining after applying that key operation so that's the thing and floor of X is the greatest integer that is smaller than or equal to X that is rounds X down please it is the greatest integer means 3.2 it is the greatest integer means 3.2 it is the greatest integer means 3.2 it if it is there right so greatest integer that is smaller than or equal to X basically 3.2 smaller than or equal to X basically 3.2 smaller than or equal to X basically 3.2 which is there so we do floor of X actually I myself forgot that what exactly Flora a particular number was in actual like CL is always the upper limit which is there and flow should be the lower limit so in that sense uh flow Returns the largest integer that is smaller than or equal to can I get some example also floor of X like 2.5 lower will be 2 floor of X like 2.5 lower will be 2 floor of X like 2.5 lower will be 2 minus 2.1 that will be minus 3 okay minus 2.1 that will be minus 3 okay minus 2.1 that will be minus 3 okay and then 2.9 okay even if the number is 2.9 so 2.9 okay even if the number is 2.9 so 2.9 okay even if the number is 2.9 so here when we round it off so it should be 3 but that 3 would be first seal and 2.92 would be for a flow so that is the 2.92 would be for a flow so that is the 2.92 would be for a flow so that is the thing here so now let us go ahead for our actual question so basically the operations which we are required to do here now let us first check for the example which is there so here input piles of a pile which has been given to an okay number of operation we can perform so at the end what the maximum possible would be left that we are required to but uh just think about one thing that if there is a small term means if the pile which is having less number of students right or even if there is a pile which is having large numbers from and we are ready to see right so what would be more beneficial is removing from the max number of piles or smaller number of piles just think in this context a let us sort this 9 5 4 right every time we are required to do one operation on any one of that pile right so let us do this nine that is the maximum which is there 9 minus nine by two so this would be uh again nine by two only right and what is the Flora for the same so 9 by 2 would be something like uh four point uh what would be left right half opened means to uh one is less than 10 then point then ten and it would be something around there 4.4 around there 4.4 around there 4.4 then when we do floor for the same that will be four right so now our new piles would be something like 4 5 and then four and then again if we sort them so it would be like five four and four right so now the largest one would be five I'll show you other way around also means starting from smaller to greater and greater smaller first we are talking with the greater to smaller so for this Pi see if we do by five minus 2 right so it would be 5 by 2 only okay and then that this two tools uh over and point one that would be nine right then again 2.4 then it would be 2 right then again 2.4 then it would be 2 right then again 2.4 then it would be 2 again right so now our new would become 4 and 2. and they have told us that only two operations can be done so this is one operation right and this is second operation so our final apply the operational pile to zero one two the resulting pile would be 545 resulting file are yeah five but how it becomes five percent if we do because 9 byte only we are required to do right so four five four to open it if we go a operational file to that assigned that only we applied resulting pilot pipe over and pipe right how it becomes 5 is like 9 minus nine by two means whatever I is there from that we are required to remove nine by two so if we remove this it becomes double and then from the value we subtract single one it would be same only right into the four point then would be there in that from that list one okay but still you are required with the floor not with the ceiling so how it comes out to size yeah we required floor okay then uh we do the next steps that it would be apply operation and type 0 that is on file that is rating would be 3. in actual we have seen the definition right please floor of x if we do the same as per KFC only so these are examples if it is 2.5 right so it would be 2. if it is 2.5 right so it would be 2. if it is 2.5 right so it would be 2. not the three I don't know why they are taking it as five and three it is seriously strange total number of stone that would be 3 4 5 is 12. negative okay and then for next example foreign according to them what they are doing is like this means not taking the exact lower and then after that for this next example this port 367 which is there so first if we take the seven then do seven by two that would be 7 by 2 again and then it would be like uh two threes are and five right so now it will become four to add what they are seriously uh okay they just chose the sixth in actual that's the pinch but how we will be doing it we will be directly choosing for the largest which would be there so that we can easily go ahead with minimizing these stones because see whenever we are taking the largest one right so see if we have the if we would have taken something like this means this would be 2 right yes if we take any smaller one or even the even ones which are there see if we take this so it would be 0.5 see if we take this so it would be 0.5 see if we take this so it would be 0.5 right so it will become 1. but if we take this 7 minus 7 by 2 which is you can see 3.5 7 minus 7 by 2 which is you can see 3.5 7 minus 7 by 2 which is you can see 3.5 now it becomes 4. as per their I don't know why they have not chosen here as clover but they have seen means they have taken in the question that we are required to do the flow so as per all of this we will be first using for the largest number which is being there and then after uh because when we eradicate means then where we eliminate half of that number that after that what we are required to do is uh we will be having a smaller number out of them right so like this only it will be easier for us to make all the numbers more smaller and that's why we are choosing for the first number which is the larger one and then we are going ahead with the smaller ones and then constraints which are given to a stranger strip of 5 so that's why in order of n login or order of in solution would work fine not order of n Square and 10 raised to power 4 is a maximum limit of value which could be there in the pile uh this basically content of that pie that could be up to 10 rich per 4 and K could also go to 10 is per 5. so basically we are required to go away with n log n solution else it will give us detailing so now let us go this question see the way we were moving ahead with this question was that we were choosing the largest out of it and if every time we are required to maintain the largest number so we can't sort it again and again right so that's why we will be taking help of a data structure where it sorts internally by itself at every step so that's why here we will be choosing try to queue where we will be taking the largest number uh means math priority QB will be using so the at the top there would be the maximum number this would be the first thing which we will be doing and second step would be that is starting only we will be having the whatever uh what we say whatever sum is there that we will be doing is starting only and we will be eliminating from that particular sum half of the largest number every time so that's the thing which we will be doing until this K is being exhausted completely so like this we will be able to come up with the are minimum possible piles uh aggregate which could be there so now let us code this particular question but before coding I have already told that what is intuition behind the scene so you could try with code in the scene by your own as well if you are stuck anywhere then you can see the code so now means you can pause the video and to code by yourself so now let us go into the coding part for the same as pre-coded the same as pre-coded the same as pre-coded the same so I don't take much time in explanation and so on stuff so here the thing is that uh we have taken the priority queue there's a maxi because C plus provided by default the Maxi that so that's what we have taken here and then we are putting a dot b into a Dot N that simply represent putting all the elements into a priority queue then result we are accumulating the sum means total sum which is it actually the actual representation of this part is running the for Loop for this piles array and then adding them up if we want to do actual implementation of this accumulate function s and C plus inbuilt function is there where this is the starting sum and this is the starting portion of array and the ending portion of array so this is all now here comes the impact that until a k gets exhausted till then we will be taking the top of the priority tube then popping it out and then pushing into our priority queue again with the uh half of that particular maximum value means first eliminating the half from that particular element and then pushing that back to the priority because we are again required is if that particular element could be still the greatest element right so it would be at the top and then accordingly we will be again performing the same operation on the scene so that's what we are doing here and then result minus equals to A by 2. so because we have eliminated already from the priority queue was just for a processing purpose but in actual result is being stored in this particular part and this is what we are going to return means basically what we are doing just in this priority queue every time this is 5 4 9 which was there now it will become nine five four right and then after performing our operation now it will become 5 4 right but when we have performed this operation so in our result here in the result earlier it was 9 then it was a 14 and then 18 right earlier result was 18 but then we are uh after that we are required to means when it becomes this Pi then at that moment only we would have subtracted this particular right so that our final answer becomes um something which would be the required one so that's why we are just eliminating that a by 2 from our result so that's the thing which we are doing here so this was all about the same but now you can see part about the time complexity and the space complexity so the time complexity is because of this priority queue accumulate function is simply a for Loop that is order of n this while loop that is K times right and this uh order of one operation in the priority queue but this top and pop basically in this only sorting would be there again and again right and this sorting will take place K in 2. uh number of elements which are there that is log in so basically this while loop will result in order of K times because this Loop will run in the log of n basically log of n that's why because n elements are being there so that is what the things would be like in this and this is the same now comes the part for this accumulate function so for this accupulate function the time complexity is order of n right and the priority queue and starting when we are pushing into the same then again it is trying to maintain the ordered uh means what we say that means the order it is to maintain right so that is in log of in operation so uh if we take for all the time complexities which are there so as per that the time complexity means total time complexity which is there is came to log in Plus order of n plus log n so to be precise the time complexity for the same is order of K into login and now comes the part for this space complexity so basically the space complexity here is because of the priority tool which we are using that is the only extra space which are which we are using so that's why the space complexity becomes order of n so yeah this was all for this particular question if you have any doubt you can comment that down and see I have not used here floor because while we were doing all that we just recognized that they are not using access load by default but I case and C plus only it will take the floor value only rather than taking a sale value uh sorry I just spoke but need to read about the same as well because without using the floor it was working so that's how I have chosen beans I have not explicitly use the floor here but now let us read about the same as well that I guess by this we moved it actually I just forgot enough fill the thing was that by default C plus will either means uh when we do this particular thing is a by 2 means whenever we divide so by default there was a case that either it will do seal or do clothes so in that scenario only I was thinking that what exactly the thing is but need to read about the same as well and you can take this also as one of the tasks and let me know in the comments as well yeah helping out the community is the best thing so yeah this was all for this video if you like the explanation please do like and subscribe to my channel and any suggestion then surely I need the answer in comment that what exactly P plus um C plus 2 by itself while dividing we started to this field or does it do the floor for that particular and I am saying just about C plus because according to language the way priority queue here is Maxi but in Java it is mean key so in that context only I just wanted to know although I was doing but now I forgot I am required to search again but no issues I'll read the comment and cross verify yeah this was on thank you
Remove Stones to Minimize the Total
single-threaded-cpu
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times: * Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it. **Notice** that you can apply the operation on the **same** pile more than once. Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_. `floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down). **Example 1:** **Input:** piles = \[5,4,9\], k = 2 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[5,4,5\]. - Apply the operation on pile 0. The resulting piles are \[3,4,5\]. The total number of stones in \[3,4,5\] is 12. **Example 2:** **Input:** piles = \[4,3,6,7\], k = 3 **Output:** 12 **Explanation:** Steps of a possible scenario are: - Apply the operation on pile 2. The resulting piles are \[4,3,3,7\]. - Apply the operation on pile 3. The resulting piles are \[4,3,3,4\]. - Apply the operation on pile 0. The resulting piles are \[2,3,3,4\]. The total number of stones in \[2,3,3,4\] is 12. **Constraints:** * `1 <= piles.length <= 105` * `1 <= piles[i] <= 104` * `1 <= k <= 105`
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
Array,Sorting,Heap (Priority Queue)
Medium
2176
64
so first let's take a look at minimum path sum so we're given a m times n grid filled with non negative values so positive all positive values including zero find a path from top left to bottom right which minimize the sum of all numbers along its path so you can only move either down or right at any point in time so we're starting from the top left and we're trying to go to the bottom right so we want to find the minimum sum of all numbers along its path and we can only go down or right we cannot go down right so if i over here i cannot go here right i can only go here and then here or here and then here right so i cannot go just directly here right so you can see here we have given a 2d array and uh in this case the output is seven because the minimum path sum to reach the bottom right is gonna be this path right here right so it's gonna be one three one which give us a sum of seven right seven so in this case if we were to choose other path that will give us a larger path sum so we want to find the minimum right so in this case um we're going to just return the minimum half sum and you can see here we also have another example where we have just one two three four five six right if i were to draw this so one two three four five and six if i want to go here the minimum right if i were to start from here then i have two decision either i can go this way or i can go this way right so if i go this way um i going to have one plus two which is total of three if i go here i have uh three plus three which is going to be six right so six if i go down here that's going to be a total sum of twelve and if i choose a different path in this case one plus four is five and then if i go here one plus five in this case is going to be ten and five uh plus six in this case is going to be 16 right so in this case you can see if i go to another path i have a larger sum but if i go here right if i go like one plus two plus five that's uh that's eight plus six that's 14. so that's also not going to work so you can see here we cannot go up we cannot go left we can only go down and right so in this case this will give us a result of 12 right which is our minimum path sum so to solve this problem we know that for each and every single step we have two decisions either we can go this way or we can go this way so if that's the case then what we can do is for each decision we can make two decisions right because we have to traverse all those paths to see if it's good right because we can't just do it in a greedy way where we take okay this is the smallest element then we go this way but then we realize that those two values are all bigger than those two values right so this will not give us the accurate results so what we had to do is we had to go traverse all to path because we have two options we had to go through those two options and figure and when they backtrack coming back to the current stack level we will determine who had the smallest path sum and then we're going to return the smallest path sum from those two options that we chose right that we traverse plus the current elements value right let me show you an example so in this case we're starting from here and we're going here right so we have one plus three which is going to be four right and then we're going to keep going down we until we find right for each uh element we have two decision right we can go here right and once we reach to the bottom right we know this is the element then what we can do is we can just return back right when we backtrack we can just return back the current element's value right which is going to be one and once we get here we're basically just going to return the smallest element in this case because here we're going out of bound so we can do is we can just return a maximum value so that if this is the maximum value right when it returns back if this is outbound we can just return the maximum value compared to one is smaller than maximum value then we're just going to take the minimum value which is one which reached down to the bottom right one plus one which is going to be two so at this position the minimum path sum to reach the bottom right is gonna be two right so one and two right and then same thing here so the minimum path sum here is two and then we know that if we were to choose here right this will give us a max because we're going out of bound so or we can go below right which give us a um a minimum half sum of two so two is smaller than max so here the minimum half sum to the bottom right is going to be 2 plus the current element's value which is going to be 3 right and then same thing here i can choose here i can go here and if i go here uh five right plus in this case one is six plus one is seven so this will give us a minimum half sum of seven or we can choose this way but this will give us eight right so in this case seven compare three seven is bigger than three so we're going to choose we're gonna have the minimum half sum which is gonna be three so we're gonna backtrack we're gonna take the minimum pass on between those two options which is three plus three which is the current elements value is going to be six so the current minimum path sum for this position right here which the bottom right is going to be six okay so we're gonna return six and backtrack to this root stack level and then once we have one we're going to compare either we should go down or we should go right so we know that if we go here it's gonna be something bigger like one plus four which is five plus two which is going to be um uh seven plus one which is going to be eight so it is either eight right or it's um going to be six so six is smaller so we're gonna take 6 plus 1 which is going to be 7. so in this case the minimum right so the minimum path sum to get to the bottom right is going to be 7 for this position right so now we know how to do this recursively right for the top down approach basically the goal is we going to make those two decisions right and that's going to give us a big time complexity of big o of 2 to the power of n which is going to be exponential or i should say 2 to the power of m times n right because this is the size of the 2d array or all the elements that we have into the array so in this case we're going we're getting a exponential time complexity so we can do is we can use memorization to bring time complexity down to big o of m times n by using the same approach that we just talked about right we're going to have each sub problem for each sub problem we're going to uh have two decisions and once if we visit that elements before we can cache it in our 2d array and then if we visit that element before we can just return that precomputed value if we didn't visit it we can compute it and save it onto a 2d array so this will give us a time complexity and space complexity of big o of m times n so let's take a look at that in our code so here you can see we have our code and basically we're have a we're taking a 2d array to the integer array and then we're making those variables in a global variable then we're going to have a cache 2d array that has a size that has a m number of row and n number of columns then we're going to call this helper method which starts at zero and zero right we are starting for the first element in the 2d array so let's say this is our grid right so we're starting from here so we're going to basically check to see if the current position is out of bound right if because we can only go uh right and left so we check to see if the current row is out of bound or if the current column is out of bound right so if it is then we can just return the maximum value okay because once we backtrack to the position to the root uh recursion stack we're going to compare c if the value uh if whoever has the smallest value right if both of them are large values like integer.max value large values like integer.max value large values like integer.max value then this is not going to work right because we need to have a bottom right in our grid so at the end we're just going to return the smallest value right so if we found the bottom right in this case if we would find about bottom right then we can just return the current elements value in our grid so if we found our bottom right we can just return it and then we also check to see if we pre-computed this value before if we pre-computed this value before if we pre-computed this value before if we pre-computed this value before we can pre-computed this value before we can pre-computed this value before we can just return that precomputed value and this is basically our core concepts right basically we have to uh traverse both path do a dfs for both path if we go to the right then the nets then we have to traverse the right path right if we traver and then we also have to get the minimum path sum if we go down uh go down path right if we traverse downwards um and then in this case at the end we're going to get a minimum value either the right minimum sum path sum or the down minimum sum path and plus the current elements value uh will give us the minimum path sum for the current position and at the end we're just going to return that to our parent recurs uh recursion stack and at the end we're just going to continuously do that until we uh found our minimum path sum and that we're just going to return that in our main function right so in this case at the end this will give us a time complexity of m times n and so does the space complexity so how can we optimize this so one way we can optimize this is we can use a two a bottom up approach right basically this will still give us a time complexity of m times n but that's gonna be a good start to talk about how we can be able to optimize this so this to start we have m and we also have n and we have a 2d cache array and then we're for the first element we're basically going to save the first element in the grid right so if i have a our grid like this the first element uh is going to be the same as the cache first element right and then what we're going to do is we're going to define the first row and basically the idea for the bottom approach is that let's say we have um like one three one um basically let's say if we have one three one five one four two one right basically the idea is that uh the minimum path sum right because we know that there is going to be a bottom right element in the 2d array so we just want to know the minimum half sum from here to here right or the minimum path sum or the path that gets it from here to here is going to be the sum of those two elements right so that will give us the previous elements or the previous half sum which is 1 plus the current elements value which will give us a 2. so if i have a 2d array right so in this case i have 1 and the next element is going to be 2 because 1 plus 1 right the sum of this is going to be 2. and then in this case same thing for this element as well it's gonna be three plus the previous element right which is gonna be four right so four so that's gonna give us the minimum path sum from here to here right and then what we're going to do is for here the minimum path to from here to get to here is going to be the total sum of those entire values but we already computed the minimum path sum from here to here so we can use that to compute this element's value so it's going to be 4 plus 1 which is going to be 5. and then so does this element right here the minimum is going to be either 2 or 4 right it seems like this has a shorter path so two plus the current elements value which is seven and then so does this element right here so the minimum path from the here all the way to here is gonna be five right five plus one which is six so in this case the smallest element between those two is going to be five plus one which is the current elements value which is going to be six and uh and then at the end we're going to have uh two plus four right which is going to give us six so the smallest element between those two which is going to be six plus the current elements value which is going to be eight and for this element right here the smallest between those two is going to be 6 plus the current elements values which is going to be 7. so at the end the answer is resides at the last element in the 2d array so this will give us the minimum half sum right by comparing the top and the left right we're going the reverse way to solve the problem we're starting from the top um and working our way down in our grid to figure out the minimum path sum to get to this position right so this is how we do it here right we basically compute the first row because we know that for the first row it's kind of like the current uh minimum power sum is based on the previous columns value so that's what we did here plus the current elements value in our grid and then this will give us the minimum half sum for the current position in our cache and then we're going to build the remaining rows right we're going to basically build the cache remaining rows and then we're starting from the second row right we're starting from the second row because we compute the first row and what we're going to do is that we're going to use the data that we computed in the first row to build our second row okay so in this case for the first element is going to be the current elements value plus the previous rows first columns value to compute the first element right so we need the first element to be able to compute the remaining elements so then what we're going to do is we're going to compare we're going to get our top element right top computer value as well as the left compute value once we get those two we're going to find the minimum value between those two plus the current elements value and this will be the minimum path for the current elements value right for minimum path sum from the top left to the current position in the 2d array once we save that in our cache we're going to continue to do that until we get to a point where we get uh where we have cash at m minus one right we get to the very end last element and then we're just going to return the minimum path sum for the last element right so just like what we did here that's our answer right that's our minimum half sum to get to the bottom right okay so this will give us a time complexity as well as the base complexity of big o of m times n but what we can do to optimize this is because we know that to compute the current row we need the previous rows result so if that's the case then we need to uh save or pre-compute or uh save or pre-compute or uh save or pre-compute or uh we need two 2d array where we need a two array one array basically um saves the previous rows data or saves the previous row cache data and then the current row basically uses the previous rows data to compute the current rows data and at the end we're just going to have a uh which is going to improve the time complexity down to big o of n or the space complexity down to big o of n because we just need two arrays to traverse down the entire 2d array right because all we need is the previous rows data to compute the current rows data and at the end we just need to erase the current row array and the previous row array and at the end we're going to get our value and the value that we need is going to be the last element in the array
Minimum Path Sum
minimum-path-sum
Given a `m x n` `grid` filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. **Note:** You can only move either down or right at any point in time. **Example 1:** **Input:** grid = \[\[1,3,1\],\[1,5,1\],\[4,2,1\]\] **Output:** 7 **Explanation:** Because the path 1 -> 3 -> 1 -> 1 -> 1 minimizes the sum. **Example 2:** **Input:** grid = \[\[1,2,3\],\[4,5,6\]\] **Output:** 12 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 200` * `0 <= grid[i][j] <= 100`
null
Array,Dynamic Programming,Matrix
Medium
62,174,741,2067,2192
1,001
1001 grid illumination on an n-by-n 1001 grid illumination on an n-by-n 1001 grid illumination on an n-by-n quit of cells each cell XY z-- with x quit of cells each cell XY z-- with x quit of cells each cell XY z-- with x between 0 and n + y between 0 and n as a between 0 and n + y between 0 and n as a between 0 and n + y between 0 and n as a lamp initially some number of lamps are on lamb sub i tells us the location the I am 10 is on each lamp has that is on elements every squareness XY and both diagonals similar to a cranium chest but I've Curie course of eyes are going X Y the answer to query is 1 if the sours on our 0 after each query we turn off any lamps down and sell X Y or 8 or Jason a directionally returning away advances teaching why you answer by should you go to the answer of 2 ie query queries supply ok let's look at some examples I might get it conceptually but that's kind of look oh yeah is that how that works I don't know anything about the incomplete oh so n is equal to 5 you have this lamps ad so before we were problems and still and for good represent cell it's lit like this how does things get it again XY and both diagnose okay like a queen okay what is n 20 oh and is 10 to the 9th Wow so you can disseminate it which would be so much easier for okay and then the crib at once of one we turns 1 because the cell is Nick and I've disk we remember at so soon turns off after this query oh so then this cell grandson before performing the second query only the second time I saw so now the query tensor because that sounds no longer than how sad what do you turn off again we terminal am start at cell okay or nearby okay let's let me think about this for a second I don't have an immediate obvious answer my chair okay one second we're gonna have them back so yeah so I have to keep track of oh and it's not lamps and was add-ons to oh and it's not lamps and was add-ons to oh and it's not lamps and was add-ons to just a boundary and lamps is the twenty thousand that's okay so we just have to keep track of them and then one is so obviously the naive okay but it so the naive algorithm is just having a much McCoy yeah just like a valium is just do an N squared type album which it's gonna be way too slow that's like what four hundred yeah that's gonna be too slow to one so okay so what does this mean again so what do you think about and we see lamps is that we keep I think what we want is a sort of binary search tree type thing where you know you do it on an extra two under why maybe even a diagonal and then you can kind of figure it out but because then you could do every request in log in and then that is straight floor and then also the query with which record we moved lamps and then reverse self-balancing binary then reverse self-balancing binary then reverse self-balancing binary search trees and like that's trivial right so but what I'm thinking right now to be honest is just I'm trying to figure a way to be lazy and in terms of implementation so I'm not gonna write a binary search tree so what is a way to do stuff that it's a search tree like thing it's there are in Python and because I know that in C++ very I should because I know that in C++ very I should because I know that in C++ very I should do in C++ well - set do in C++ well - set do in C++ well - set that's it half they set up binary search or lower bound or whatever it's call physical doorbell you know I think there's the bisect but bisect this five-second we're gonna set what you and five-second we're gonna set what you and five-second we're gonna set what you and your Cartesian trees I guess not hmm maybe I should don't C++ I guess not hmm maybe I should don't C++ I guess not hmm maybe I should don't C++ because they have to think yeah I just have to do it once I think I'm just I try to be very no copy and paste when I do these things but yeah I guess it's in C++ so I may be out there in C++ okay yeah maybe one day I'll look into it I would add it to my to-do list yeah I would add it to my to-do list yeah I would add it to my to-do list yeah just so now I'm gonna focus on kind of pre-processing the names of that so that pre-processing the names of that so that pre-processing the names of that so that yeah so that we get which record so we could do lookups in of well again but basically we have four directions to cache which is the vertical horizontal and then the two diagonals that gets the lit I think that's right and you could kind of think about just and you just have to think about how to label your diagonal so that's consistent which I usually so we thought no it's not hard to draw the thing to see if it's late but yeah because I'm you know I just say you have four sets and then int it's called um Hassan vertical oops Monsanto diagonal one diagonal two and then four and then it's all be consistent doesn't matter which one sex and which one's the why but I were a girl that instead of zero croissant anytime and say them one and the diagonal one don't have this worry like I can endure become trees apparently going them this is roughly right well and now for enquiries to many language mixing we call that fine curry Sub Zero and this is true results now we turns one so okay so let's just have a boolean found as you go to 0 I know it's supposed to be four is fine but that's just too funny to go so just because that's what we're pushing back into results what so that's the credit okay so this is the case from UC but the one that's not the right syntax and I know same thing for the other ones this is very more worthier than in Pikeville and maybe not I don't know if this is right though today I go no one I always forget it whether you could be off course let's say God I survived one at one and it goes at two and then that's the only one to sue but then what about the other diagonal will be they sum to sum the same thing right because at 1 it goes to 2 0 and so - okay and then what's it called all that push bag found but then inferior you're done if the palm didn't require it seems that way a little bit yes sue do via now we have to watch I'm a car of one civil yeah I mean we should do one is what to expected wrong and service I said he's got that know it's quick why are you doing I have a typo or something this is one of those songs proud to do this because Cruz is a raptor it's okay I try go quick I mean if I get out I was out get out there was no auto-hide some out get out there was no auto-hide some out get out there was no auto-hide some stuff that's why I'm a little sometimes on them I've been getting better at using them but nada really why is this a pool did I yeah oh I just have a double program that's why okay that's silly okay so this Christmas expected wrong answer so now what we want to do is turn off lamps right so for that we have to so do we remove all eight of them that's not bad I mean we just put them in a hash table and then we move on to diagnose when we remove and then I think the tricky thing is now well now we just hope is maybe really that is something never define an overhead is that now that room so I can't think and it was very loud okay so actually what I mean it's the same but what I have to do is convert just set into well like a hash table which is a map I mean it's not a map actually a map is ordered in C++ so it's actually a tree map and we C++ so it's actually a tree map and we C++ so it's actually a tree map and we definitely want anyway but uh but I it's kind of like dad so that we could keep track of something like that so then when we move we can keep track because the case that I was worried about it's like gravy I've saved two lamps on the same vertical do when you remove one your one and we move to the other one by accident there so yeah and also we need to check I guess this is still the same function know for now let's see if that still not die if I spell our infinitely am just missed something there we go I think one thing before I do that though I want to check Tara checking the diagonals correct just cuz these things you never knew actually I guess one checks dad right okay so maybe that's fine and wasn't one so check three let's also check to two just for six I should still get me two trues to true cool yeah so actually I just expected everything couldn't miss me didn't move money oh yeah but now that we did that now we can start moving stuff and we actually want to put the coordinates so we have to do eight each that's like hundred sixteen thousand I always missed really these that's fine so you know because you only have to look at the a direction you just put them in the hash table and we move them when we're ready yeah so let's do that do we have lamps in the same place yes that's an edge case I guess it doesn't matter if we have them in the same place except for that this may end up weird because then we have to remove it in the same place knowing but okay fine I can handle that case so now we have a pair of intense four coordinates and not that into an int for let's say lamb coordinates yeah let's do that and then where we lamp let's lamb coolest I guess maybe just to make pair I'm subsume I'm someone and then just a comment that okay so now for every query we do all this for key stuff and now that just say if found yeah so we only I mean this I don't know if this is a necessary optimization per se but it's a slight optimization in any case so maybe if I was on if I was doing like a time-sensitive competition I might not time-sensitive competition I might not time-sensitive competition I might not add this unless I'm forced to for whatever is it but the only reason why it's just the only check of this family is because if it's in one of the directions every one of your eight adjacent locations and that means or if it's not in one of if you're in a place that's not lit that means by induction I guess there's none in the nade adjacent squares next year so a slight optimization but me it's always helpful so if I should say if not Frank continue so then we do keep the nesting in there good level and he's if you get your parentheses correctly and now we do that and see a directional dxdy trick but you can just two folders really mmm no weird where I did it but okay and then now we could do something like for i call it k just because it's story is how i turn it's not just for consistent six and then now let's just say i still try to declare everything in the beginning other than autumns cuz i don't know you just me i still try to file the c style of yeah declaring everything in the beginning but uh okay so let's just say your new ex is you go to the d xf k plus are your current ex with just a curry of civil and then similarly do this and now we just check to see if it's within bounds let's say if this is the case that you quote - if this is the case that you quote - if this is the case that you quote - yeah no oh no this is Python syntax got too used to that part so someone like this if just as within bells check to see if a coin it's you know it's not Pena whatever it name cornets if we could find I'm like pair of it's I say we find I know reason yeah if we found it then let's just do let's just say current count is they go to the lamb coordinates of okay that and we want to remove it so let's just but now we want to remove it from vertical horizontal and diagonal as well yeah so now will it go that fine of ya and X in this case should definitely be in there really so if not then we have more issues or you should need to check for this let's do that if I don't know we need t race well we do because then we have to change somebody's a little bit can be rather not for slight performance issues they say if it's zero then we remove an X and then we do the same for the Santa there is definitely an opportunity for code reuse but well oops dia diagonal so close to gun hopefully a lot of typing actually the way that's the way I did it so now we erased them so that hopefully the second time evaluation call they should not change the input that we have because we modified slightly now we want to change it back to yeah and that does change start back to was it 1-0 hmm that's unfortunate there was something that would work let's just print out something to buggy maybe just time I'm okay maybe you know I vote in a real way you should have waited to kick in a consistently symmetric way why does it take so long to judge okay so I do we move to the lamp but I don't know by the title but I guess I don't be base for whatever reason and the one that we want to the horizontal unless I miss my mistake sir yeah let's take a look real quick at the count I mean that lot of typing and just the thing with these typing is that there are a lot of potential for silly mistakes but they'll get down let me double check real quick that I used to write case because I definitely won self unfortunately well one zero so one so is this one ladies that's why I leave my intention there like what a question is then hmm that's alright well that's kind we'll get up real quick well that is a lot of typing maybe I should use the teapot ring but I feel like they're the leak code today is a little bit on the slow side so it'll be a little bit annoying to kind of do it one by one that's just by walking step by step also be helpful we do anybody spell things correctly mmm okay I mean this seems for why we expect one two in the diagonal and one in the other diagonal which actually doesn't really show up I am just silly actually because I don't reset found that's kind of actually a silly book I guess that is the one thing that comes from see that I wouldn't have happened in other languages just because if you declare a finger there never been good okay let's try again on the other one then where I was a let's try one again and then two for funsies and both of these should be true still and then maybe we can remove another one like three and three till we move okay I think right now I'm just little think about performance if n is equal to 20,000 we do mostly linear is equal to 20,000 we do mostly linear is equal to 20,000 we do mostly linear stuff I mean okay log any of your count is said stuff but it should be okay knock on wood cool all right that's somebody real quick maybe I have some boundary mostly oh noes okay I'll put 1 but 1 0 either zu so for this one turns up one of them this turns out the other one so why is this doing don't-don't-don't mystery that was a city mystic actually yeah okay let's point this out real quick so I think I expect to see a bunch of now this is under Fame that's why I don't check to remove on the I check to I remove with its next to it but not on it that's silly no understand I mean the directions tell you I am just I mean I'm being sorry okay fine I don't know I think I just saw eight and then I missed her first half of that sentence yeah there we go okay reading still the hardest part sometimes not all the time a lot of time just the other stuff a reading is still a critical part oh no I have another reading thing isn't just to input did like the test case input maybe I miss somebody study and he's in terms of complexity ones pretty okay I just have to not mix the Mystics okay so this one turns off this step and this is literate and output so why am I having issues or like the sample take sample case okay the first one turns out lambda Brazil does a bunch of stuff all right and then we move some I assume I touched this what did I fix again hmm my trickster spit oh yeah there we move we're just sitting on it but I shouldn't affect that anyway oh because then this is 9 so I'm just a fun part about using ok well so then just forget 100 erections oh well yeah I guess if I was a lazy I would have tested more but please be kind okay so just silly mistakes okay silly mistakes I can do I mean I think some of it I'm just a little bit tired and lazy which is in honestly I mean I just changed her away from 8:00 to 9:00 and I changed her away from 8:00 to 9:00 and I changed her away from 8:00 to 9:00 and I didn't change to for loop which you know which some of it is that I am a little bit used to Python where you know just you would range over the ways instead of a hard-coded number so definitely and a hard-coded number so definitely and a hard-coded number so definitely and that same book cost me twice which is something I need to think about because definitely even if it wasn't stayed out like I it is an edge case tiny to consider and then just like look up just to make sure like it's not a reasonable assumption without looking it up that said and I did it twice or that if I was in a competition I've been ten minutes worth of silliness but yeah but overall not a way tough problems but only if you have I mean I think this is a simple problem if you have a lot of the second learnings that been done and maybe I'm phrasing down everybody and take them away max Taylor yeah I mean if I think also if I yeah and we did a couple ways like this could be just to fold ups right like I usually I do it this way if they're like weird conditions but yeah anyway yeah so over this is an easy problem coin code easy if you already have the foundation for it there are a lot of things now as a prereq for this stuff I think I talked to a friend of mine recently about not this problem cuz you haven't seen this but a similar kind of quid EEPROM where it's just quit properties that you kind of get used to but because you've seen a lot of quit problems and definitely I don't know how I feel about that for interviews for someone like this because like I'm I wouldn't necessarily recommend people to you know practice a lot of great forms because from that grid problems so how long did I end up taking well I took half an hour this one I just talk a lot I guess I talked I'm good but oh and I did try to use different languages and so forth but wow that's longer than I've expected concerned but when did switch to C++ and concerned but when did switch to C++ and concerned but when did switch to C++ and I was talking through it a little bit and also I didn't think I had too much but yeah but I think the thing that I mean the work on Horizonte I think this is relatively straightforward to think about but in an but in that same way where like someone could be like okay yeah you just do a hash table or a lookup table a tree map thing under x-coordinates because that's the work or x-coordinates because that's the work or x-coordinates because that's the work or you have a lot of experience with kind of dealing with the guy these things would come natural to your way so that's and that's this type of stuff that you get only from practice and thinking for pom really deeply but the in terms of interviewing like I don't know if this has worked at effort to kind of these things and because after that like all these are relatively straight for and this is just a regular like two for loops so what did I do and then you're raising them and keeping track that way and everything is in O of log n so this is n lock and oh well n log n for building two for the pre-processing and if we each query is pre-processing and if we each query is pre-processing and if we each query is lock and yeah so it's n log n plus and not sorry Q log N or something like that so Q and plus Q times log n so yeah that's kind of the situation here so for interviewers I would definitely not worry about it that much for in a sense that like I think they're way more things you could spend your time better than learning about great poems then probably will give unless have a real-life equivalent unless you'd like real-life equivalent unless you'd like real-life equivalent unless you'd like to play chess or something which is fine but then you may be all you know how to I have these things if you explore chess problems but for competitive programming I think this is relatively standard way of doing to kind of hash both where the corner horizontal but also to diagnose don't it was a little bit of time for me so I had to remember a little bit as well yeah cool that's all I have to say about this problem also yes and person Q log and yeah cool
Grid Illumination
n-repeated-element-in-size-2n-array
There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially **turned off**. You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is **turned on**. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it **illuminates its cell** and **all other cells** in the same **row, column, or diagonal**. You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, **turn off** the lamp at `grid[rowj][colj]` and its **8 adjacent lamps** if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`. Return _an array of integers_ `ans`_,_ _where_ `ans[j]` _should be_ `1` _if the cell in the_ `jth` _query was illuminated, or_ `0` _if the lamp was not._ **Example 1:** **Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,0\]\] **Output:** \[1,0\] **Explanation:** We have the initial grid with all lamps turned off. In the above picture we see the grid after turning on the lamp at grid\[0\]\[0\] then turning on the lamp at grid\[4\]\[4\]. The 0th query asks if the lamp at grid\[1\]\[1\] is illuminated or not (the blue square). It is illuminated, so set ans\[0\] = 1. Then, we turn off all lamps in the red square. The 1st query asks if the lamp at grid\[1\]\[0\] is illuminated or not (the blue square). It is not illuminated, so set ans\[1\] = 0. Then, we turn off all lamps in the red rectangle. **Example 2:** **Input:** n = 5, lamps = \[\[0,0\],\[4,4\]\], queries = \[\[1,1\],\[1,1\]\] **Output:** \[1,1\] **Example 3:** **Input:** n = 5, lamps = \[\[0,0\],\[0,4\]\], queries = \[\[0,4\],\[0,1\],\[1,4\]\] **Output:** \[1,1,0\] **Constraints:** * `1 <= n <= 109` * `0 <= lamps.length <= 20000` * `0 <= queries.length <= 20000` * `lamps[i].length == 2` * `0 <= rowi, coli < n` * `queries[j].length == 2` * `0 <= rowj, colj < n`
null
Array,Hash Table
Easy
null
242
hello everyone and today let's go through one classic liquid problem and also a kind of introductory problem to help people get into computer science and data structure and algorithms um so it's legal problem 242 valid anagram let's take a read at the problem first given two strings s and t written true if T is an anagram of s and false otherwise so let's take a look at the definition of what is anagram is a word or phrase found by rearranging the letters over different word or phrase typically using all of the original letters exactly once so for example number one and this s is anagram T is n-a-g-a-r-m it's not a valid word but it n-a-g-a-r-m it's not a valid word but it n-a-g-a-r-m it's not a valid word but it doesn't matter we just want to check whether this is a anagram or not it is because for every single eight one two three A's one two three is here one n here one G one r one m so it matches perfectly so this is meeting the perfect definition of anagram an example and example number two is rat and car apparently this one has t while this one has C although they have R and A the same so this one is not a valid anagram um constraints for this is s and t within the length of 5 times 10 to the power of 4 which doesn't matter too much and S and T consists of lowercase English letters only well this simplifies the problem but there is a follow-up we'll talk about both of these follow-up we'll talk about both of these follow-up we'll talk about both of these okay so first there are multiple ways to solve this classic problem first way is that we can sort both strings so this string is formed by concatenating characters so if we sort all of the characters based on the ASCII uh order then we have both strings in sorted order we can just compare whether these two strings are equal if they are equal then we know it's an it's a anagram otherwise it's not that's one way but this way the time complexity is going to be o of n Times log n because we need to sort it this n stands for number of characters in both given strings all right we can just quickly implement this first solution first then talk about it okay so first we can convert all of as chars convert all of these two an array and then we can solve them sort them result as charged teachers and then what we can do is that we can just return as charged equals three teachers as simple as this let's Let me give it a try to hit run it's accepted hit submit to see all right it's accepted so the gist of this solution is pretty stressful as I just talked about we'll just converts two strings into character arrays and then sort all of the characters in both given strings so that we then we form two new strings right with the sorted with all of the characters in them in certain order so that we can directly compare whether there's two newly formatted string are equal or not if they're not equal they cannot be a valid endogram then with the code inside let's talk about the time complexity of this algorithm so suppose n is the number of characters in s and t so first s and t must have equal length otherwise we cannot be valid and the grand pair okay so then in this case time compactity is going to be n Times log n because we apply a sorting algorithm here right for both of them in order so it's not multiplication it's just going to be o n Times log n can we do better than this absolutely we can so follow up we can iterate on this solution to have a more ideal solution which is since the problem consists only of lowercase English letters which means 26 letters total whatever duplicates or however performation you want these two strings to be total number of unique characters is only 26. all right with that said let's shift the gears and change this up to use what we can do is that we can have one integer array which keeps track of the frequency of each character in s and t for whatever character that we encounter in s or just increment the frequency for this character by one and we do this for t as well but we'll just decrement the frequency for that character by one so in the end what we can do is we'll just check all of the frequency for each of the 26 characters in this integer array should be zero that means every single character coming from both s and t should balance out if any counter frequency is not zero that means it's not a valid anagram whether it's positive or negative it's not a valid anagram right I hope that makes sense if that does we can quickly put this idea into code as well so we'll have a integer array total size is 26. we assume s and t should be of equal size or we can have a simple check here if as length not equal to T length or directly return box or we can be more if s well we don't need to track if it's now it's a simple problem but to be more defensive we should definitely check that otherwise SNT minus 12 9.0 exception if otherwise SNT minus 12 9.0 exception if otherwise SNT minus 12 9.0 exception if it's nullable four then we go through every single character since they are of equal signs we can use either s or t to check its length then we put as counter at I minus a plus so this is to give us so the reason this is a another typical classic strategy is that we can if it's lowercase English letters we can just do this character itself minus a lowercase a that will give us that will shift all of the asking numbers to be between 0 and 25 inclusive so that we can use all of these index to directly map right so in this case counts zero is the frequency for a counts one is the frequency for B right so we'll keep doing this for string s every single character will just do plus and then for every character in t would just do minus if it's a valid anagram pair for SNT every single character frequency should balance out so it should be all zero so in the end we'll just check if counts if I not equal to zero we'll just return false otherwise we found a valid underground which is written true let's see hit run accept it submit running all right also accept it and now let's talk about time complexity of this algorithm so for this one it's just going to be o of n so you see we improved the time complexity from o of log n to o n why because we only have one for Loop and we go through n just a still is the number of characters in both s and t we go through every single character only at once and in this case we use some extra space which is only o of one because it's only 26 characters it's a constant so it's o1 extra space that's it for this and the second solution to solve this problem given the test cases for lead code for this one consists only of lowercase English letters all right then let's take a look at the follow-up what if the inputs at the follow-up what if the inputs at the follow-up what if the inputs contain Unicode characters how to adapt Your solution to such a case for Unique case and for Unicode characters 26 is definitely not enough it can have like Chinese characters Japanese characters whatever characters which can mount up more than one million characters so and we don't know they might not be consecutive in asking a table so in that case what we can do is we can come up with a hash table what we can use the mean let me just reset this one in this case how do we adapt our solution to for input that contains Unicode characters we can use a hash map the key of the hash map is just the character and the value of the hashmap is just the frequency in both strings in s still we increment the frequency for n capital that's in t we still decrement the frequency and in the end we'll just go through the hash map once to see if every single value of the entry in the hash map is zero or not if any one of them is not zero that means it's not a valid endogram pair we return false otherwise return true in the end I hope that makes sense let's quickly put that idea into code as well character integer map hash map now or just to go through the same thing um since they are of equal length we can use either s or t to get its length and then we'll put a map as Char at I map get or default as charad I default should be zero if we have never encountered this character before and then we'll increment it by one because this character is coming from s then we do the same for the character coming from t but for any character that's coming from Teen Wolf decrement is frequency by one all right this is the case and then in the end we'll just go through uh well it's a character map key set if map get C not equal to zero in this case what we can do is we'll just return first because each character on the counter pair in both s and string they were not able to balance out each other so we return false in that case otherwise where we just return true now let me hit run accept it submit run answer let's see what's going on here as oh all right so I shouldn't miss that check the check should be if as the length not equal to T dot length or directly return false I'll grab that new code does have this test case otherwise it's not a is this test case is this and then there is this should be returning okay accept it let's see all right this one is also accepted but I'd like to test it like a Unicode for example let's say uh pricing all right just some Unicode all right this is a valid anagram period they are not uh English characters anymore so let me hit run oh it's not a valid value of type string all right uh when you find a bug of lead code or a feature that they don't support Unicode really all right but this is a valid test case if we expand the problem to be supporting Unicode characters um feel free to check it out in your own code instead of on leave code but this is the solution to support unique Unicode characteristic time let's say n is the number of cars in s and t um then time is going to be o of n still because we only have one for Loop we go through both s and t for every single character and false space um well space complexity is basically the number of unique uh uni code charged this is the space I assume it should be like similar to a constant number like say let's at least a million it might not be over 2 million just my ballpark gas I don't know but it should be a very it's a definite number um so it's and it's not going to grow linearly as in so that's the solution um I hope this video makes sense we iterate uh from the simplest Solution by sorting and not super ideal it's not super optimal in terms of time complexity and then we go to the second solution which is to use an integer array to keep track of the frequency of each capital in both s and t and then lastly we expand our solution to support Unicode characters if the if you think this video helps you understand valid anagram this problem and all of the different test cases please do me a favor and hit the like button that's going to help a lot with the YouTube algorithm and I really appreciate it and also feel free to comment down below let me know if you had any thoughts comments I really appreciate that with that said I'll see you guys in the next one thank you
Valid Anagram
valid-anagram
Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "anagram", t = "nagaram" **Output:** true **Example 2:** **Input:** s = "rat", t = "car" **Output:** false **Constraints:** * `1 <= s.length, t.length <= 5 * 104` * `s` and `t` consist of lowercase English letters. **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
null
Hash Table,String,Sorting
Easy
49,266,438
1,466
hi guys good morning in this video we're gonna see a problem reorder routes to make all paths leading to the city zero problem is exactly what it says that we are given n cities numbered from 0 to n minus one pretty cool and minus 1 Rhodes such that there is only one way to travel between two different cities and this network is form of a tree cool no worries last year the Ministry of Transportation decided to orient the road in One Direction because there are two narrow so basically we have a tree which is directed tree cool roads are represented by the connections where connection is just an edge between a i to b i it's a sentence between AI to bi uh this year there is a big event in the main city capital city zero and many people want to travel to the city zero so your task is to reorient some nodes such that each City can visit zero so as we know that our cities were directed so we had this tree which was directed let's say it is the city zero now we have to make such that every city can actually visit this city zero by this path so every city should be able to visit City zero that is our main task return the minimum number of edges that needs to be changed so let's start with the problem itself reorienting some nodes such that each City will be city except 0 because 0 is adds itself zero so we don't have to visit zero each city which means one two three up to n minus one needs to visit zero let's see itself that each City needs to visit City zero so for every city X I just try to reach and go zero but we know that our graph is directed so it is not necessary that from every city I can reach to City zero so for that let's make that graph undirected which means that if the edge is like this only so what I will do I will also add an edge like this which means that it will be bi-directional right so what it will be bi-directional right so what it will be bi-directional right so what I did was I can just make the graph bi-directional because I just want graph bi-directional because I just want graph bi-directional because I just want to visit from City X which is access one two three four clear minus one to City zero it is what the question is saying what I have to do I'm just following the question itself nothing extra right now cool then but for every city X which means that for every node in the graph let's say one three two four five you want you will try to go and visit zero which means that for one you will do a BFS or EFS and go zero for three you will do a BFS or DFS you will visit zero for two you will also do the same first photo you'll also do the same for five you also do the same which means for n minus 1 nodes you have to travel n which will result in complexity of n Square this is not pretty much for n nodes you are traveling to City zero that will be of n Square let's think complexity is more for sure we know that because that op we can not afford to be n Square in this let's see um what we can do let's try to optimize it so basically what we are doing is for every city X I am going to city zero it's the reason that okay I was actually having n minus 1 cities and to go it is taking in time so rather than this n minus 1 is it possible I can just have one city why not see as you can see that we are going like this right from 1 to like one to three n minus one to zero how about we reverse it we go from 0 to every city does from 0 which is one city I just go to every city which is just n minus 1. as simple as that this is how we can optimize it from n Square to O of n and it's a standard trick which can be used in future if you are just seeing that okay from multiple nodes I need to visit a particular node let's say X or let's say 0. and it is like having a high time complexity so how you can optimize it just remember it's a standard trick and it will be used specially in the weighted problems whenever you are having multiple cities or graphs or nodes and you want to reach your particular node let's say this is 0 then if it is having high time complexity then what you can do to optimize it to start from the node 0 itself and try to go to Every node it will help you a lot cool it is what we're gonna do that we will try to go from zero to every city and nothing but a standard beams or dfsb can do now uh now it says the same problem okay I have this node 0 I have to go to every city which is one two three four and so on but as you know the graph was unidirectional which means that it is not necessary that the edge will be from zero to one only it can be from 1 to 0 itself it can be any way possible Right so if we want to Traverse we have to make it the bi-directional so let's try make it the bi-directional so let's try make it the bi-directional so let's try let's make this graph so basically the one in the blue is less it's literally like natural nodes which were already there the one in the pink are the ones which I added right so I just made this graph bi-directional which means I can graph bi-directional which means I can graph bi-directional which means I can go from one to two now and one to three now but uh if I have to go and like you said okay I just have to make it bi-directional but how to make it bi-directional but how to make it bi-directional but how to make it bi-directional cool no worries see one bi-directional cool no worries see one bi-directional cool no worries see one option is that okay you just know the natural nodes you can just store in a map what are the added nodes like further nodes one and two the natural is from one to two and the added one is from two to one I can just use a map or see you can see it is taking extra space because map will take extra speed of n to store those or nodes or you can optimize it and just do something like having a sign see it's just either this way or this way right so whenever we have two options what we do either as 0 1 or a plus minus so we just have to say okay for an edge we have two main options either this or this so either I can just assign a zero and a one I can assign a positive and a negative so we usually like do something like this when we have two options and we have to assign some values to it so I will do the same thing I'll assign a positive and a negative to what like positive is actually like the natural Edge is the positive Edge and what I added will be in the form of a negative how let's see one to two it is in the pink one which is added one so I did a minus two rather than 2 it is a minus two it shows me from one to two there is no Edge I added that edge from two to one there is a natural Edge which is the blue one from three to one it's the added one which is the pink one so I did a minus one from one to three it's a natural one which a blue one so either added three simple three it is how I can make my adjacency list which will represent me oh which node has an added Edge and which node has a natural Edge cool so by this I can just help by this I can just get to know okay which is the natural Edge and which is the added Edge if I am standing at the node one and I want to go to any node let's say node so if this node is negative which means that my one to node was not there I just added that sign which is one two node so already it means that my one my node to one was there and not one to node if my node is negative if my node is positive which means that okay one to node was there and it was not there cool so with this I can just get to know okay if one to node is there or not if one two node is there then my node is less than zero then my one to node Edge is not there I just added that edge if node is positive then one two node H was there cool no we have got okay we start from 0 we'll just have the tree as bi-directional we can go to Every Edge bi-directional we can go to Every Edge bi-directional we can go to Every Edge and we also know okay which Edge is actually the added ones nothing remains as of now you can just do a simple BFS or a DFS and by this you can just get to know okay what's the edge which is being added while I was doing a BFS which means I just start from zero I'll just go to one I'll see if I am going to one because see I just I can easily go to one because the edge is what bi-directional so I can easily go to one bi-directional so I can easily go to one bi-directional so I can easily go to one but when I reached one I'll check okay was the edge naturally present or it was the edge which I took which means if my one is negative so The Edge like this would not have been present but the edge like this would have been present right if my one is negative so the opposite Edge would have been present and ultimately what my me name was to remove from 1 to 0 which means one to zero will be moved so if my one is negative I can actually move from one to zero although I am moving from 0 to 1 4 to optimizing my algorithm But ultimately my aim was to move from one to zero right thus I can easily say if my one if we it means if I'm reaching to a node two uh let's say the variable name is t02 then I can say okay my if my this node 2 is negative which means here the node number is one so I can just say okay my node is negative I have that backward Edge which means okay I don't have to change my Edge but if it is positive then if it is positive which means my null to 1 is positive then the edge would have been something like from 0 to 1 But ultimately my main aim was to reach from one to zero thus I will just add an extra Edge or I can just say I have a variable called as change in which I will add a plus one because it's not required I have to change this and bring it something like this so it's pretty simple let's see the problem uh algorithm pretty quickly I'll just drag them also for you guys because sometimes it becomes hard okay how this DFS is working but DFS is the easiest thing you can do it's short and simple um let's see firstly we make a graph while making the graph although it was unidirectional although it was Union Direction which means from node U to node V I had an edge but I purposely added an edge from node we back to node U but I just made sure that okay from let's say if known you to node V I had an edge but from V to U also I'm adding back but I will just make sure when I'm adding back to like let's say node V I'll just make that negative so that ultimately I can just remember oh if it was negative so the background Edge was present which means I'm good now I'll just do a standard uh DFS which will actually give me the number of changes required at every start of the DFS I'll just have a variable called as change which will give me the number of changes required in that subtree uh I'll mark that node as visited because I don't want to visit the node again and again then I will go on to every child of that root node like from is my just root node and two is my child node I'll just see if that child is not visited then I will visit it but you can see I just checked for the natural child like I spot visited I can't have in my visit like the negative ones so to check okay with that note is visit or not I just have the absolute value which means it will just check okay one is present or not first present or not it will not check minus 4 minus two it goes it minus 4 minus 2 was to actually let me know if the ash was backward or forward it was not for me to know if it was present or not visited is for present and not for backward or forward cool then I will just have a change variable which will actually bring me the number of changes in the sub tree Plus if it is the condition I showed you above if I am from 0 to 1 if this one is positive which means my actual Edge was something like this from 0 to 1 only but ultimately I wanted something like from 1 to 0 because I have to go from 1 to 0 right my main aim was one to zero so I need to add an edge if my this node one is more than zero machine is positive but if it is negative which means if this number is negative minus one so the edge something like this have been present right and I actually wanted this because I wanted to go from one to zero thus I added a 1 because of this that okay if I'm reaching to a node and if it is negative then I have to add an H backwards and ultimately I can just return a change let's write them pretty quickly it's pretty easy uh if we have the graph something made like this I just made an adjustment list something like this because minus uh 4 is representing the backward Edge the white one is the edges which I have added and the orange ones are the ones which were in the problem itself cool we start from the uh zero DFS we just do from zero then our Childs are 1 and minus four right five minus 4 because white Edge I have added it was not naturally present cool then I have this one I have this minus four I just go into one if it is positive which means backward H is not present it means it was a natural Edge so I have to add a backward Edge which means I have to add in a change so the change is required here while it is minus 4 which means that the edge would have been present something like this from 4 to 0 as you can see the natural Edge Falls from four to zero so it will just same if it is minus 4 which means that okay from zero to minus 4 The Edge like this I have added it was not the natural Edge and the natural Edge was from four to zero if it is because I just actually want it from four to zero itself so I just added if it is same okay if it is minus 4 which means I had that naturalization which I wanted from four to zero so I just had no change required then it will again go from this one it will again go do a DFS then from four it will again do a DFS ultimately it will just go to three it will check if it is more than zero which means oh the edge orange Edge is the natural Edge which means I just wanted an edge backwards I have to do a change is required I'll go from four to five oh it's also positive which means orange one is natural Edge so I have to again add a backward Edge because I want it to go from five to four and back to zero A change is required the changes will become three earlier it was one again it will land on three it will land on five is just a leaf node it can't go anywhere so nothing required three uh it just landed to a minus two or you should actually say two where the actual node is minus two minus 2 will represent okay the edge is the white one which is I have added which means the natural one would have been reverse one only right see as you can see natural one was reverse one uh I am super fine if it is -2 so if it uh I am super fine if it is -2 so if it uh I am super fine if it is -2 so if it is less than 0 then no change is required my changes still remain three and ultimately it will just go on to two it's a leaf node again the change will not affect because it's a leaf node complexity is nothing but as you are going on every node once a time so it is just o of n to visit every node space is also open because firstly for storing our graph which is adjacency list then also for the visited array which is Boolean array you will say okay then you said about the map and stuff see assist you are using an extra n right so it will not increase the complexity in O terms but actually in the actual complexity terms it will increase in plus n something like that so it's good to actually optimize it as much as possible so yeah by this we can actually get to know okay how we actually have to do a DFS in this we can also do a BFS but DFS is always better and easier when both can be done so I hope that you guys liked it if yes then do the like button and secretly next video until then goodbye take care
Reorder Routes to Make All Paths Lead to the City Zero
jump-game-v
There are `n` cities numbered from `0` to `n - 1` and `n - 1` roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow. Roads are represented by `connections` where `connections[i] = [ai, bi]` represents a road from city `ai` to city `bi`. This year, there will be a big event in the capital (city `0`), and many people want to travel to this city. Your task consists of reorienting some roads such that each city can visit the city `0`. Return the **minimum** number of edges changed. It's **guaranteed** that each city can reach city `0` after reorder. **Example 1:** **Input:** n = 6, connections = \[\[0,1\],\[1,3\],\[2,3\],\[4,0\],\[4,5\]\] **Output:** 3 **Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital). **Example 2:** **Input:** n = 5, connections = \[\[1,0\],\[1,2\],\[3,2\],\[3,4\]\] **Output:** 2 **Explanation:** Change the direction of edges show in red such that each node can reach the node 0 (capital). **Example 3:** **Input:** n = 3, connections = \[\[1,0\],\[2,0\]\] **Output:** 0 **Constraints:** * `2 <= n <= 5 * 104` * `connections.length == n - 1` * `connections[i].length == 2` * `0 <= ai, bi <= n - 1` * `ai != bi`
Use dynamic programming. dp[i] is max jumps you can do starting from index i. Answer is max(dp[i]). dp[i] = 1 + max (dp[j]) where j is all indices you can reach from i.
Array,Dynamic Programming,Sorting
Hard
2001
849
welcome to october's leeco challenge today's problem is maximize distance to closest person in the asia kovid it's a pretty pertinent question you're given an array representing row seats where seats i equaling one represents a person sitting in the ice seat seats i equaling zero represents that seat is empty now there is at least one empty seat and at least one at one person sitting and alex wants to sit in the seat such that the distance between him and the closest person or persons to him is maximized return that maximum distance so if we had this example here we can see there are people seated at one four and six i'm sorry zero four and six uh sitting at seat two is going to give us the maximum distance of two between this person here and this person here right so that would be the answer so how we go about solving this well the very first kind of thought might be to go with some sort of dp solution and we'll go through that totally works let's see how we would do that for this example say that we had this list say we create like a dp array of all zeros at first and this dp array is going to store the maximum distance between some person and a populated seat seated a seated seat so maybe we start with like a distance of zero here and if we see that our seat is seated we can reset our distance to zero and if it's not then we'll increase our distance by one and we will populate this dp array to say okay the maximum distance from the person to our left is one now the next is also zero so we increase our distance to and we'll update that and so on and so forth once we see that it is seated we will reset our distance and we'll continue this algorithm which will give us a dp array looking like this so what this kind of tells us is what's the maximum distance from the leftmost person right but that's not enough obviously if we turn the maximum of this dpa we get three but the answer is two so we actually have to go the other way as well and really we can just follow the same algorithm here what we'll do is start with distance of zero if it's populated we'll reset it zero and if it's not we will increase it to one and what we can do is just take the minimum of what we calculate and the previous dp array so here we'll say one what's the minimum between these two it's one so we'll keep one here two it's the same so it doesn't matter here we calculate three well the minimum before was one so we'll have to update that to one so now this dp array contains the maximum distance on both sides and we can just return the max here there is one caveat though what if it was looking something like this well if this was to occur uh the dpo would end up looking something like first it would calculate from the left most side it would look like one two three four so it looks good now but when we go backwards we take the minimum between these two so we'd say one minimum two and we say three well it's minimum this is two uh and what's the minimum here in four and one it's one so it looks like this and that's not right because basically we have to this kind of assumes that there's a person sitting here uh but there's not so how can we account for that well we'd have to have some sort of boolean or some sort of way to indicate to us that uh we need to reset this distance otherwise don't update it so we'll have to account for that in our algorithm all right so how could we do that let's start by saying uh initialize our n to the length of c's next we'll create our dp array of all zeros times the length of sheets now we need to first initialize our distance but we're going to start with negative one here and what this will allow us to do is indicate to us whether we've seen a seated seat before yet and if we haven't we don't quite want to do the same thing so for i in range of n we'll say look if not seats dot i okay and distance does not equal negative one then we will update it we'll say okay this sense make it equal to plus one and we'll update our dp array to equal the distance here and notice at this point we don't need to take the minimum between the two because we're just doing it the first time otherwise else if um else we will update our distance to equal zero and this indicates to us yeah a seat was populated and now we've found one okay otherwise we don't do anything else so we've done our first pass now let's go our second pass we'll do the same thing but we'll move backwards and we will pretty much do the same thing except we will take the minimum between this distance and our dp array once that's finished we can just return the max of our dp so let's give it a shot here uh this should return to us two and it does let's submit that and i believe there's one thing i didn't account for yeah so one of the things that happens is uh if we haven't touched this dp array and we keep it at zero then actually ends up just storing that zero as the minimum so that's a problem uh well one way easy it's kind of easy way to take care of that is just say look if dpi if it equals zero just take whatever we calculate here to equal distance otherwise take the minimum because that way it accounts for this kind of weird edge case okay so let's go and submit this and that takes care of it there we go accepted so this is an of n solution but we also use of n space so can we do better than this yeah and there are a couple approaches uh there was one using two pointers and there was another one using a group by but i'm not going to do that instead i'm going to try to use some sort of greedy method here and what i'll do is first again initialize n and we're going to have something called max gap equaling well first zero this will be well yeah the max gap that we can find as well as some sort of start and we'll initialize that first with negative one so for i in range of n the very first thing we want to check is if the seat is populated then we want to i guess increase our pointer to equal or i'm sorry not increase it we want to make it equal to i so if we've seen some if we've already seen one before um well i should say if we haven't seen a probability before so if start is equal to negative one that means the max gap at this point is just whatever the length is right so if we haven't seen anything before then we're just going to store our max gap to equal i otherwise we have seen something so if that's the case we'll have to take the max between the max gap that we've calculated so far and what we'll do is say hey take our i and subtract it by the start that we've stored from our last populated one and one thing that we actually need to account for here is because we have to account for like both sides we're actually going to have to divide this by two take our i my start and we'll divide it by two and that's going to guarantee to us that uh if the other side was um you know account for that left side of the person that's seated but one thing to note if our seats look something like i don't know um let's say it was popularly populated but it was all zeros afterwards well this wouldn't work because this again kind of assumes that there's somebody sitting eventually at the right side so to take care of that we'll just say okay once we've taken this we'll just take the max of the max gap as well as the n minus 1 minus the start which is the very last see the person that we've seen so there you go after that we can just return our max gap and this should also work there we go accept it so this is better it's o n and it would use constant space all right so that's it i'm just going to end it here thanks for watching my channel and remember do not trust me i know nothing
Maximize Distance to Closest Person
maximize-distance-to-closest-person
You are given an array representing a row of `seats` where `seats[i] = 1` represents a person sitting in the `ith` seat, and `seats[i] = 0` represents that the `ith` seat is empty **(0-indexed)**. There is at least one empty seat, and at least one person sitting. Alex wants to sit in the seat such that the distance between him and the closest person to him is maximized. Return _that maximum distance to the closest person_. **Example 1:** **Input:** seats = \[1,0,0,0,1,0,1\] **Output:** 2 **Explanation:** If Alex sits in the second open seat (i.e. seats\[2\]), then the closest person has distance 2. If Alex sits in any other open seat, the closest person has distance 1. Thus, the maximum distance to the closest person is 2. **Example 2:** **Input:** seats = \[1,0,0,0\] **Output:** 3 **Explanation:** If Alex sits in the last seat (i.e. seats\[3\]), the closest person is 3 seats away. This is the maximum distance possible, so the answer is 3. **Example 3:** **Input:** seats = \[0,1\] **Output:** 1 **Constraints:** * `2 <= seats.length <= 2 * 104` * `seats[i]` is `0` or `1`. * At least one seat is **empty**. * At least one seat is **occupied**.
null
null
Medium
null
1,418
Hello hello friend this question from decor previous contest don't like problem number 1418 district table pappu doctor's national interest directly click on subscribe button order that customer number and kashmir and restaurant in order to were sardar this fit and food water telephone numbers Gautam And List On The Table Number For B.Sc B.Com In Wave Loot Diner Dash Lord In B.Sc B.Com In Wave Loot Diner Dash Lord In B.Sc B.Com In Wave Loot Diner Dash Lord In The Road To This Channel Subscribe To 200 Blueprint District 100 Watermill Hotspot Of Medical Test Subscribe Difficult As Its President In This Old Is Gold Channel Subscribe to like and subscribe must subscribe and subscribe item to website phal is fear points table medium jhal postpaid tariff table date of birth send this paste sheds pet and will start from bigg boss me entry vid oo hua to post Which chapter cost a stand in the way I request you for scheduled to table solvent send you trick record this to avoid a is MP 10th that time orders do okay you and dishonor old restaurant at first with oo a quest for 10th That I don't 210 pocket subscribe that person number two were the intention a product of that I want to see the question Bihar is closed according to tennis athletics and research skin superintendent a family doing MP love scene objective of that and decision so Apna spring hua hai 210 post entry and dish table research 9th forces festival and champions trophy introduce 36 the risk factor of this dish formed is sharp and this post to oo 20130 a temple and attempt to state open 10th hua hai MP4 audio file ok and parents Any do se pak software David Kushwaha and edit that in the answer a text post to of name is computer name person talk to oo hai brother mast me ruke to post plugin maker tractor string to teachers to t&amp;c me happiness peace award Invisible Number Airtel Number Is The Map Of Entry Subscribe That I Don't 400 A Northern Twist And Tractor Off Hai To Aap A View To Enter The Destruction Of The Most Difficult To Decide On That They Are Equal To One Pimp In A WhatsApp Message That One Word Kosh It's All The Special First Post Entry Of This Temple Run Luta Do It Is The President Of Hai And I Don't Post On 119 A That It's Okay And Anti A 200 Ko Kidnapped Ka Pushpa Friend Hoon That You Of Micro Post On Plane Mode ki reddy hai ko direct tweet boxing and entries not present safe test positive ok and after spreading sp quality of which took place in a that Uttarakhandi Chhau 's work and quality has given extensive written on to 's work and quality has given extensive written on to 's work and quality has given extensive written on to WhatsApp food is one of the brand hai hua ko There is vitamin point in there is a meeting on behalf ticket to contest and logic 5th most loud significant and start the element sid lottery pun free nepali ko whatsapp is open
Display Table of Food Orders in a Restaurant
display-table-of-food-orders-in-a-restaurant
Given the array `orders`, which represents the orders that customers have done in a restaurant. More specifically `orders[i]=[customerNamei,tableNumberi,foodItemi]` where `customerNamei` is the name of the customer, `tableNumberi` is the table customer sit at, and `foodItemi` is the item customer orders. _Return the restaurant's "**display table**"_. The "**display table**" is a table whose row entries denote how many of each food item each table ordered. The first column is the table number and the remaining columns correspond to each food item in alphabetical order. The first row should be a header whose first column is "Table", followed by the names of the food items. Note that the customer names are not part of the table. Additionally, the rows should be sorted in numerically increasing order. **Example 1:** **Input:** orders = \[\[ "David ", "3 ", "Ceviche "\],\[ "Corina ", "10 ", "Beef Burrito "\],\[ "David ", "3 ", "Fried Chicken "\],\[ "Carla ", "5 ", "Water "\],\[ "Carla ", "5 ", "Ceviche "\],\[ "Rous ", "3 ", "Ceviche "\]\] **Output:** \[\[ "Table ", "Beef Burrito ", "Ceviche ", "Fried Chicken ", "Water "\],\[ "3 ", "0 ", "2 ", "1 ", "0 "\],\[ "5 ", "0 ", "1 ", "0 ", "1 "\],\[ "10 ", "1 ", "0 ", "0 ", "0 "\]\] **Explanation:** The displaying table looks like: **Table,Beef Burrito,Ceviche,Fried Chicken,Water** 3 ,0 ,2 ,1 ,0 5 ,0 ,1 ,0 ,1 10 ,1 ,0 ,0 ,0 For the table 3: David orders "Ceviche " and "Fried Chicken ", and Rous orders "Ceviche ". For the table 5: Carla orders "Water " and "Ceviche ". For the table 10: Corina orders "Beef Burrito ". **Example 2:** **Input:** orders = \[\[ "James ", "12 ", "Fried Chicken "\],\[ "Ratesh ", "12 ", "Fried Chicken "\],\[ "Amadeus ", "12 ", "Fried Chicken "\],\[ "Adam ", "1 ", "Canadian Waffles "\],\[ "Brianna ", "1 ", "Canadian Waffles "\]\] **Output:** \[\[ "Table ", "Canadian Waffles ", "Fried Chicken "\],\[ "1 ", "2 ", "0 "\],\[ "12 ", "0 ", "3 "\]\] **Explanation:** For the table 1: Adam and Brianna order "Canadian Waffles ". For the table 12: James, Ratesh and Amadeus order "Fried Chicken ". **Example 3:** **Input:** orders = \[\[ "Laura ", "2 ", "Bean Burrito "\],\[ "Jhon ", "2 ", "Beef Burrito "\],\[ "Melissa ", "2 ", "Soda "\]\] **Output:** \[\[ "Table ", "Bean Burrito ", "Beef Burrito ", "Soda "\],\[ "2 ", "1 ", "1 ", "1 "\]\] **Constraints:** * `1 <= orders.length <= 5 * 10^4` * `orders[i].length == 3` * `1 <= customerNamei.length, foodItemi.length <= 20` * `customerNamei` and `foodItemi` consist of lowercase and uppercase English letters and the space character. * `tableNumberi` is a valid integer between `1` and `500`.
null
null
Medium
null
139
hello welcome to ricobed today let's explore this circle program 139 so we are giving a lovely streamers and the dictionary vertically containing restaurant and reverse the multi-determining path can be the multi-determining path can be the multi-determining path can be divided into space separator sequences one or more digital worlds okay for example so we have this s is this the word echo contains two words lead and code so we know that s can be divided by two words lead and code since they both contain a vertically will return true for another example we have an apple pen apple so we divide the s into three separate words apple this the authority in the particularly sounds good so you can do a pen in there so it's good and then the last one is apple and that voice in the world let's take this for example we have in the production rates of return force we can also choose the cuts which block our unit and then end and it never is so that's not a very divided so we'll turn it off here okay so what do we do is we want to say uh to check small so we want to divide that as different small words so i will check small words first for example so we have v code so to see if l is the unit so l is not we'll say l e i'll use another one so e it's so that's about it then we'll explore further furthermore and to see if they can be divided to prediction so for example we have weight so we can see that modifying the liquid lab is very divided into a three small sub problems so okay so defined state functions malaysians and now what we need to do is we just need to find speed so how do standard is true you want to explore so just want to explore the state that's true smaller is you want to check if the code is true so what we want to do is we go back to financing where you know as aj is true and then as i do there is a little prediction to find that slide is true as i2j is called same do a hashtag because that way we can find that's faster so we define a state visualizer is tp okay so because we want to find it backwards to see guys last one that will be good because that's pretty good the time complexity for this album says backwards so that takes all the square time with this whole problem and also you should be noted with this it's better to invite to the right gpu and then check this later because the uh checking dpi even checking if dpi is true it's cheaper than this so since the end is the conditional operation it's faster so and also since which is very important but if uh s i j and your website so directly it takes all one but we should notice that we still need to calculate the hash function for this minus one so if we explore backwards like this then it could be a little bit faster so let's take a look yep it is faster so okay that will be today's video if you like my video please subscribe it and recommend it to your friends as soon as possible thank you very much
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
1,591
hey what is up guys today we're going to be doing problem number 1591 strange printer number two so there's a strange printer with the following two special requirements on each turn the printer will print a solid rectangular pattern of a single color on the grill this will color up this will cover up the existing colors in the rectangle once the printer has used a color for the above operation the same color can't be used again you are given an m by n matrix target grid where target row col is a color in the position row call of the grid return true if it is possible to print a matrix target grid otherwise return false okay so we have this target grid right over here and so we're going to start printing a rectangle so the first print right now we printed from one to one over here and then again we put the rectangle two on top of it and that's how we got from here to here we have other target grid right here with color five and as you can see we're going from one to one and then we print this rectangle three over here then four and then five that's how we get here and then we have this last rectangle right over here let's just draw this house and give us an example one two one and as you can see it's false because there's no way we can print a rectangle and print another rectangle on top of it to get to this final answer okay so how are we going to approach this problem well we have this empty grid and we're trying to go to the target rate and like i always say when we have these kinds of problems we're going from one situation to the end to the next then we can also uh reverse that process this is that way we can think of it and we can also think of it as uh going from the target to the end so let's think of it like that we're going to go from this target to the end and so okay i know now i maybe instead of going this way to this way i can go this way to this way and how am i gonna go from here to here well i know i keep adding colors so in this case i need to keep removing colors so i have these colored squares over here and now i need to see okay which color can i remove over here first well i can remove uh four this rectangle over here and i can also remove the rectangle five so let's just remove one of them and instead i'll just decide to remove the rectangle four first i remove that one then i check again which ones can uh oh five first which one can i move next four which one can i remove next three what's your credit move next one and then i get to a final answer and so that's how we're going to approach this problem we're going to work backwards and see which rectangles can remove until we get until we end up with an empty uh grid and so over here as you can see let's try to remove a rectangle which rectangle can remove well can i remove the rectangle one no because there's things overlapping it can i move the rectangle two no there's something overlapping it so can i move any rectangles no and is the grid empty yet no so then that's how we'll know this will return false so now we know i need to keep removing rectangles until i get an empty grid and if i can't do that i will turn false at any point i can't move any rectangles i'll return false now the next question is um how do i know a rectangle is able to remove able to be removed okay the way i know a rectangle is able to be removed is if i don't have any overlapping colors on top of this rectangle so i see over here four to four this rectangle doesn't have any overlapping colors but the rectangular from one this one at the end of right at this step over here has overlap overlapping rectangle sorry about the background noise um you see we have this rectangle three and five and four they're overlapping this greater rectangle 1. so that is problematic so the way i'll know is if i see an overall lapping rectangle on that color so if there's no overlapping a color then i know i can't remove it so now that's that but now how are we going to know the dimensions of our current rectangle because how do i know one the boundaries are at this point over here i can tell just by looking at i know the boundaries of the this rectangle of color one but in code how am i going to know that well the first thing we're going to do is figure that out and how are we going to figure that out well what is actually a rectangle it has a leftmost point uppermost point a rightmost and a bottommost point so i'll find the leftmost point the bottom top and right most points and then i'll figure out the corners on my rectangle that way so i'll look over here and i'll see what's my leftmost one that occurs it's all the way in index zero right and column zero and row column zero what's my right most one that occurs it's in column zero right over here what's my upmost um topmost uh one that i see it's in row zero what's my bottom most one that i see in row one and same thing for three we'll see the top is in row uh one index one the column is uh left most is one rightmost is one uh sorry leftmost is three two right most three uh bottom most index where we see um three is row two right row of index two so that's how we'll approach that so i'll find my top most left whatever and so then once i find the corners of my rectangle right then i can go through all the entire grid and see if at any point um if at any point there's an overlapping color so for example i'll go from um three to i'll go through this rectangle right which is from a two to three and also from here to one to three and i'll go through this entire rectangle by using a double for loop and i'll check if any of these colors aren't three then i know there's an overlapping rectangle and i'll add that in so for example i'll start with three that should be over here this three and i see it's a three that's good this is a four that's not good so i'll say four is an overlapping rectangle and now i know and that way i'll know uh and then the third step which i'll explain that four is an overlapping rectangle so now that i get all my overlapping rectangles well let's do one more example for this grid right here so look i find my topmost leftmost right most corners and i'll see uh over here and the next zero is my left and next one is my right uh top is one zero bottom is two so i'll get my corners and i'll know my corners these points right here these four right so now then when i'm checking if anything's overlapping it i'll go through this entire grid right over here this sub grid in this case it's an entire grid but in this case we saw it was a sub grid and i'll see if there's any overlapping colors that are not one so i'll go through it this is the one that's good this is a two that's not good so this is overlapping i had two of them are overlapping and i'll go keep going two again and so i know two is overlapping then i'll try to remove two and then oh we'll keep going that way so that's the next step we're gonna keep trying to remove the colors so now i know two is overlapping so then i'll try to remove the two and then i'll try to move the one so i'll see this now and i see two is overlapping so let's try to remove the two i'll try to remove the two but then for this two right if we do the same thing for two you see this two's rectangle is also this i'll see one is overlapping two one is in the middle of two's um rectangle and two is in the middle of one's rectangle so we have some kind of cycle going on here when i try to remove and all the overlapping rectangles for a rectangle number one i encounter two in the way so then i'll say okay let me try to remove two but then when i try to move two i see i'm trying to remove one again and therefore that's impossible because then i'll try to move one i'll try to move two then one that's going to keep going back and forth in this case it's possible for example over here let's try to move one i'll try to remove one and i see three is overlapping four is overlapping five is overlapping so let's try to move one of them i'll try to remove the three so then i try to move the three and i see four is overlapping three so then i'll try to move the four i can remove the four and since i can move the four then i can move the three and now that i move the three can i remove one yet no i still have five so now try to move the five can i remove the five fully yes nothing's overlapping five so i move the five and then finally everything's removed from one and then i can remove one and then all the colors have been removed same thing if we started at three let's try to move three i see four is overlapping and then let's try to move four i can properly remove four side move four then three is free to remove i remove three then i go to the next color let's say it was five i try to move five is good to go i remove five then i go to one the next color and then i see can i remove it yes all these are going three is gone the four is gone the five is gone i can probably remove the one so that's how we're going to approach the problem and i'll show you the code and i'll just show you right now it's right here so like we mentioned the first step is to um find the boundaries and how are we going to do that well i'm going to create this hash map and so this the inter the key is going to be the color and the this list is going to be a list of size four and it's going to create it's going to have my boundaries so i'm going to go through the entire target grade as you can see we have our two dimensional uh two double four loop and i grab the color and then i grab the extremes how am i going to grab the extremes well i'm going to see if i have a list already for the color this color get her default and if i don't i'm going to create this new list and it's going to have the topmost left most bottom most and rightmost and then i'm going to reset the extreme so for this color i'm going to check is my uh current um is my current topmost value um greater than or less than uh the current the value for this color that i current have so which is i right and so i see is i smaller or uh what i currently have extremes i get 0 which is the top most value is that smaller so if i is smaller meaning it has a smaller index meaning it's higher up then i'll set i to this new value again right to zero again and we're gonna do the same thing for one same thing for two and the same thing for three then i'll add it back into my colors right so that's what we're basically doing right here where finding the boundary the top most leftmost rightmost and bottom most boundary sort of hair and the next step we're doing is going we're going to find all the overlapping rectangles as we talked about so i'm going to go through all my colors i'm going to grab the boundaries and i'm going to go through that subgrid so this double the for loop right over here is going to go through my sub grid as you can see i'm getting zero and so zero is my uh topmost value and i'm going to go to my bottom most value which is two right over here right i'm going from the top to the bottom and then i'm gonna go from uh left to right which is this inner for loop right over here so i'm going to top to bottom left to right i'm going through the entire subway and i'm checking if it's not the color that it's supposed to be right if it's not the color that it's supposed to be for this rectangle so this was this is what this is checking then i'm going to add it to my overlapping uh set right so then this is what this is doing didn't get it or default and i'm adding this um color to my overlapping set and i just put it back in right over there that's what that is doing and this is basically the third step which is the gist of the problem at the end of it i'm going to go through all my colors as we talked about i'm going to try to remove every single color if i can't remove a color i'll return false and so what this what is this can remove this is basically a depth first search um as you can see we have um canon over here it takes in a color it takes in all the overlapping rectangles and it takes in the visit status and so what is it the business status the business that is basically keeping track of whether we visited something yet meaning it's been fully removed or we're visiting it meaning we're trying to remove it or we just basically haven't seen it yet meaning it's just we haven't seen it yet so the first thing we're going to do is i'm going to check if i visited already that means true i'm going to return to it meaning i can remove this rectangle this color already if i'm visiting if i if it's visiting already meaning i haven't fully removed it yet and i'm in the process of removing it that means i encountered a cycle that means i hit back to where i was originally and i'm going to return false right this was in this example where when we tried to move one then we counted two then we had to remove one and so on and so forth it's going to keep on going infinitely so i have to return false if i see something that i'm currently trying to remove else um this is just another condition meaning uh if there's no overlapping rectangles for this color i can also return true so i'll just return true meaning if it's not this color is not an overlapping camera meaning it wasn't there ever then i'm going to set this color visiting meaning i'm currently trying to remove it i'm going to go through all the overlapping colors by over all the overlapping rectangles in this current rectangle for this current color and i'm going to check if i can remove them right it's going to recursively call this function again if i can remove this overlapping color sorry if i can't remove this overlapping color then i have to return false else if i uh i can remove it completely then i'll remove it from my overlapping color set right because i don't want to keep going through it again you kind of don't need this i'm pretty sure you don't need this but it's going to increase the time for it and so if i can move all them completely then i'll set this color to visited meaning it's been completely removed and then our turn true so also here again if we couldn't remove it return false and end of this when we go through everything i'll just return true and so that's basically the problem walk through for a number of 1591. if you guys enjoyed this please leave a like subscribe and comment if you have any questions i hope you guys enjoyed i'll see you guys for the next problem
Strange Printer II
strange-printer-ii
There is a strange printer with the following two special requirements: * On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. * Once the printer has used a color for the above operation, **the same color cannot be used again**. You are given a `m x n` matrix `targetGrid`, where `targetGrid[row][col]` is the color in the position `(row, col)` of the grid. Return `true` _if it is possible to print the matrix_ `targetGrid`_,_ _otherwise, return_ `false`. **Example 1:** **Input:** targetGrid = \[\[1,1,1,1\],\[1,2,2,1\],\[1,2,2,1\],\[1,1,1,1\]\] **Output:** true **Example 2:** **Input:** targetGrid = \[\[1,1,1,1\],\[1,1,3,3\],\[1,1,3,4\],\[5,5,1,4\]\] **Output:** true **Example 3:** **Input:** targetGrid = \[\[1,2,1\],\[2,1,2\],\[1,2,1\]\] **Output:** false **Explanation:** It is impossible to form targetGrid because it is not allowed to print the same color in different turns. **Constraints:** * `m == targetGrid.length` * `n == targetGrid[i].length` * `1 <= m, n <= 60` * `1 <= targetGrid[row][col] <= 60`
null
null
Hard
null
24
hello guys I hope you are all doing well in this video I will show you how to solve the problem lead chord 24 swap node and purse so let's get started so the problem is that they give us a linked list and as we know a linked list is a data structure that have nodes and each node have a value and reference to the next node and they ask us to swap nodes and pairs means every two adjacent nodes need to be swapped without modifying the values in the list node for example if we have this input linked list the result should be like that so this problem is a good problem to learn to manipulate and understand how the linked lists work so the best way to solve this problem is by using the iterative approach so let's say we have this input linked list the first thing I'm going to do is to make an empty array and store all the value of the node on it then we calculate the length of the array the goal from knowing how many nodes we have inside the linked list gonna help us to know how many time the swap node gonna be performed inside the linked list after that I'm gonna initialize a dummy node that's going to have the value 0 and reference it to the linked list and this dummy not gonna help us to reduce the need for special case code and the swapping code part then we're gonna initialize three variables the first one is the previous which is value gonna be the dummy note the second one is the current and we get a set his value to the head no the third one is the temp and he is initialized at the next node after the current or after the head then we're gonna use the length of the list that we created before and divide it by two and that's going to help us to determine the number of time the for Loop or the swap is going to be executed so the first thing we're going to do is to take the next pointer of the current node and updated it to the node after the temp node then we're gonna update the next sponsor of the temp node to the current node after that we update the next pointer of the previous note to the temp node so after we swap the first two adjacent and the linked list in order to perform another swap for the remaining notes we need to update the previous variable to be referenced to the current node and also we need to move the current node to the node after the current node so after that the same process is going to be repeated by moving the theme node to the next node of the current node and then the next pointer of the current node to the node after the temp node the next pointer of the next node is updated to the current node and then we update the next pointer to the previous node to the temp node so here the loop gonna stop iteration because this input Link at least the node are only 4 so we perform only two swapping that's it guys so let's jump at coding the solution first we initialize a variable called pointer and set his value to be the head of the linked list then we create an empty array and we Loop over the linked list and each time we push the value of the node to the array then we calculate the length of the array I should demo initialize a dummy node with a value 0 and the next pointer to the Head node then we initialize another variable called previous to The Domain node and another variable called current to the Head node then we set a for Loop that we're gonna Loop over the linked list and first so we take the length of the list and then we divide it by two so that's gonna determine how many times the loop gonna run after that we set a variable called temp to the node after the current node then we'll update the next pointer of the current node to the node after the temp node and we update the next puncher of the temp node to be pointing to the current node and then we move in the next puncher of the previous note to the temp node after then we move the previous variable to the current node and we move the current node to be the next node after the current node finally we return the next pointer of the dummy node which is now the head of the modified linked list with nodes and per swap so the time complexity of this solution is all firmware n is the number of node and the link at less and because we are looping over the linked list once and the space complexity is also often because we are using an array of size and to store the values of all the nodes so to reduce space complexity we can determine the length of the linked list without creating an extra space so initialize a function called calculate length this function take the head of the linked list as a parameter and then we initialize a length variable and set his value to be zero after that we Loop over the linked list and each time we increment the length by 1 until we reach the end of the linked list and we'll turn the length after that we keep the same code for swapping the nodes so the time complexity of the solution is often and the space complexities of one sense we are not using any extra space memory means we are not using an array data structure to store the nodes or calculate the length of the nodes inside the linked list that's it guys thank you for watching see you in the next video
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[2,1,4,3\] **Example 2:** **Input:** head = \[\] **Output:** \[\] **Example 3:** **Input:** head = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. * `0 <= Node.val <= 100`
null
Linked List,Recursion
Medium
25,528
212
hey everyone welcome back and let's write some more neat code today so today let's solve word search two and once again like usual this is a problem from the blind 75 link code list a list that we've been tracking on this spreadsheet and the link will be in the description to this and we are very close actually to being done with all the major problems on this list that i wanted to do and probably at some point i will finish up some of these easy ones like contains duplicates i think that's a pretty trivial problem don't know how many people are waiting for a solution on that one but i probably will do it eventually just for the sake of completeness so this is word search 2 and word search 1 actually we already solved on this channel and that is leak code 79 so i do recommend understanding that problem before you try to do this one because this is definitely an extension of that one so we are given an m by n board exactly the same as we were in word search one and we are given a list of words this time previously we were just given a single word but in this case we're given a list of words and we want to know from that list of words which of those words exist in this board and whichever ones do exist we want to return those words so previously we only wanted to know if one word existed in here or not so we returned true or false but in this case we want to know how many or exactly which of these words do exist so if we just reuse our solution from the first word search what we're gonna do is we're gonna go to every single position in this grid and we're gonna start a depth first search recursively on here so it's just backtracking right we're gonna be checking brute force what's every word we could come up with right so starting at o could we come up with a word in our list of words right so we just go in every all four directions basically right so if we go here we'll get oe if we go this way we'll get oa right etcetera we could you know possibly make a word like this o a n or we could make a word like this o a t h and this happens to be a word in our list of words so we would return we would say okay o a t h this is a word so this is going to be added to our solution set so it's going to go in the output so a very brute force approach would be so for every single word we're gonna run a depth first search starting at every single position and check okay could we make the word oath starting from here etc until we get you know all the way to the bottom of the grid and we have run a depth first search on every single position now that's not going to be super efficient right and then we're going to have to do the exact same thing for the next word p right because maybe this word could exist so we'd have to brute force check every single position etc and one way to analyze the time complexity of that would be something like worst case four and four because that's the number of directions you know from a any position we could go in four directions now we can't revisit the same position twice of course so basically the length of our depth for search is going to be the dimensions of the board let's call that m by n right so that's how much one dfs would be and we're going to be doing a dfs starting at every single position so it's going to be something like m by n to the power or and by n multiplied by 4 to the power of m n and we're going to be doing this for every single word so basically let's say w is the number of words so this is going to be super inefficient now there is a way basically where we can make this more efficient where we can get rid of this constant w basically the solution is going to be we're only going to have to run dfs starting from each position a single time because as we're checking you know what are all the words we can create starting at this position right starting at this character a what are all the words that we could create now the main idea that we're going to be doing instead of just checking a single word at a time like running dfs on here just to check if this word exists let's check simultaneously let's check all the words in our set which of them can be created starting at this position so that's the idea we're going to be using and we're going to be using a data structure which is going to be very useful for it because what we're going to notice is we can check all words starting at here based on the prefix right so clearly here we only want words starting with the letter a right so the prefix is going to be a and what kind of data structure can help us organize these words based on their prefix guess what either you have heard of this data structure before or you haven't if you haven't heard of this data structure then you probably don't have a chance of solving this problem in the optimal way so i would learn what this data structure is first but if you do already know it the solution is actually not too bad to implement so this the data structure we're going to be using is a try aka a prefix tree which is going to help us organize these words based on their prefixes so let's say we had a pretty small grid and we had a pretty small list of words the words are app ape and ace so we want to know which of these words can be found inside of this grid now let's use the idea of prefixes that i mentioned so let's say we're going to start our dfs here right so this is the first position we're going to be at and we can't revisit this position twice makes sense so far we have a single character right we have found the character a right so we can basically we want to know all the words that we could create starting at this position dfs from here and of course then we're going to repeat that by doing a dfs from here and here but we're so far we're only starting here and of our entire list of words we want to know which one of them have a prefix of a because if you know if we had a word such as bat then we'd say okay bat does not start with an a so basically we don't even have to consider that right we don't have to run a dfs on here searching for the word bat it doesn't even exist in this position right the letter b does not start here so what we're gonna have to do is basically go through every single word this word starts with an a so potentially so far all of the words could be found starting at this position right so we haven't eliminated any of these just yet so now let's say we go down first right of course if we go up that's out of bounds so you know we're just going to return there because we're going to see okay the it ended with the word a does not exist in our list of words so of course we're not gonna do that of course if we went left that also would not work but we can go down so let's start going down first so we add a p to our word so far we have ap so then again we're going to just go through every single word check okay does this start with ap yes does this start with ap no so we don't want to consider this word anymore right but as you can see this is going to get kind of complicated right we're having to go through the list of words every single time that's not really helping us out in terms of efficiency a more intuitive way would be if we could check the prefixes of these words more easily and of course we know a data structure prefix tree is exactly what that is for so basically what a prefix tree is going to be it's going to be you know every single character is going to be a node so one node is going to be a and we're just going to take these words and add them to our prefix tree so we want all words starting with the character a to go here right so let's add childs of these so what characters come after a of course we have a p and then we have a c so all words that start with a p are going to go down here and all words that start with a c are gonna go down here and how many different words do we have that start with ap we have uh app and we have ape and all words that start with ac is just one word ace so do you see how this is this tree is organizing these words based on the prefixes so now we started at a right we want all words that start at a so this is where we're going to be at so far and we see that of course there are three words that start with a and by the way let's say ap this is not a word even though it is a path in our tribe because basically let's just say we call these three leaf nodes happen to be the end of words it's possible that we could have a word ap but in this case we don't up here right we don't have ap so this node is not going to be marked as the end of a word so only these three are marked as end of words but so now when we go down in this direction we go to a p all we're going to do from this position is check does this have a child p if it does we're going to say okay let's go there so now this is going to be all words that potentially start with ap so this prefix now if we did not have a p right then we would say okay we went down here ap we don't have any words that start with ap so in that case we would just return that's our base case right if we didn't have any words with a prefix of ap which we could check pretty easily with this prefix tree we wouldn't want to continue going down this direction so you can see that we're making things a lot more efficient for us using this try so now from p we can't go down that's out of bounds we can't go left we can't go up because we already visited that position so we can go right which is going to add the character e so from here from this p we want to check do we have a child e well this is not the e this is though right okay so far we did find a path in our prefix tree now let's check is this the end of a word since it's marked purple that's what i'm just indicating so yes this is the end of a word therefore we found a single word down this path that we were maintaining called a p e that yes you can see it's found in our list of words so therefore we found one word that we can make from this grid that you know can be found basically so we're going to add ape to our results now from here we would want to continue now we can't go right we can't go down we can't go left because we already visited there so we would go up so we'd say okay add a c right so from here a p e and then we add a c does this word exist well this does not have a child of c so of course we can't do that and that makes sense because this word apec does not exist in our input list of words so therefore at this point we would return because we don't even have any words that start with this prefix so far we did find one word ape now when we started here the first direction we went was down but it's possible we could also go right so let's do that so now we have ac so we started here we check does this have a child c yes it does it's over here right so now we can't go right we can't go up we can't go back left so now we go down a c e do we have a e child under this c yes we do and this is the end of a word right it exists in our list of input words so now we found another word ace and then we would continue from our grid in the only position we can go to which is the p right so we'd add a p we'd say okay does this e have a child p it does not so therefore we can't continue so that's going to be our base case but it's okay because we at least found one word so we can go ahead and add that to our list of words ape and ace so now is going to be the easy part so we started our dfs from this position now let's start the dfs from c so we look in our prefix tree we do have a prefix starting at a do we have a prefix starting at c we don't so immediately we can say okay we know for sure none of our words start with the character c we didn't just have to we didn't have to run through the list of words to do that we just did that in an o of one operation we just checked do any is our root node does our root node have a child c it does not so therefore none of the words start with a c so we don't even have to continue the dfs from this position and you can tell that's the same is going to happen for the character e none of the words start with e we don't have an e root node in our prefix tree similarly p we don't have any root node p in other words start with p so we're not going to find any additional words in this grid we only found two words ape and ace we found ape and ace we did not find app so we're going to return these two words as a list so once you kind of understand that this problem can be solved by the prefix tree and you know how to implement a prefix tree and you know how to implement backtracking dfs which you can learn from word or word search one this problem is not too difficult so now let's write the code so the first thing i want to do is actually implement a try node class or a try class basically and so in the constructor of this if you have written a try before you'll know that there are mainly two things that we worry about for a try node and that is its list of children so that's going to be one member variable for this class a list of children now you could use a list in this case all characters i think are going to be from lower case a to z but a more generic way to handle it is just using a hash map so the key is going to be the character and the value in this hash map is going to be the child node the child tri node and also for each node you want to be able to mark if it is the end of a word or not so one member variable for is word it's going to be a boolean initially we can set it to false now to our try we are going to want to add words to it so let's define one function add word and this is really going to be the only function so we'll be passed in a string a word and we just want to add that word to our try so let's get our current pointer to be at the root node which is just the self node and then we're gonna go character by character in this word and just start adding them now it's possible that the character might not exist in our tri node if it does not exist so if c not in current dot children if this character does not exist then we're going to obviously have to insert it so current.children at character c we so current.children at character c we so current.children at character c we want to create a try node for this particular character if it already exists then we're going to skip this if statement and simply we're just going to move our current pointer to that position so current.children position so current.children position so current.children at character c so that's the try node that we want and at the end all we have to do is return the current pointer or actually not return the current pointer at the end we have to mark that this is now going to be the end of the word so the last character that we ended at current is word we want to set that to true when we insert a word now the reason we're not going to define a search function like searching a word in this trinode is because we're going to be doing that simultaneously as we do our depth first search on the board so now let's start getting into the dfs we're actually the first thing we're going to want to do is create a root tri-node tri-node tri-node so let's create a trinode with the class that we just defined and for every word that we're given in the input so for w in the list of words we just want to go ahead and take each word and add it to our try so root dot add word w and now we can start going ahead and doing the depth first search so first i like to do is get the dimensions of the board so rows and columns we can get the length of the board we know for sure that the board is going to be non-empty and be non-empty and be non-empty and the list of words is going to be non-empty as well they do tell us that non-empty as well they do tell us that non-empty as well they do tell us that in the problem description now i'm going to create two sets result and visit so result is going to be the set of words it's possible we could visit the same word twice inside of our board so we don't want to have to return duplicates and the visit set is pretty self-explanatory when we run a pretty self-explanatory when we run a pretty self-explanatory when we run a dfs on the board we don't want to get stuck in like an infinite loop or mainly we don't want to repeat the same character twice we're not allowed to do that so once we have those defined we are going to define a dfs recursive function we're going to be going through every position so we want to pass in the coordinates row column as the coordinates we want to pass in the current node that we're at in our try you know depending on what characters we've already visited before and we also want to pass in what is the word so far so for example you know we visited two characters ac we want that to be stored in this word variable and of course if the node that we're visiting happens to be the end of a word what we're going to do is just take that word and add it to our result which is out here we don't have to pass it into every recursive call so for this dfs let's go ahead and define the base cases so of course if we go out of bounds row is less than 0 or column is less than zero or row is too big meaning it's the number of rows or a column is too big meaning it's the number of columns or maybe this position row column is already been visited so if it's already in visit then we're going to return or maybe the character that we're at for example board at position row column maybe this character is not even in our try maybe it's in bounds right but it's not even in our try at the current position that we're at in our try node right meaning this character is not in node.children is not in node.children is not in node.children right if it's not in the children of the current node that we're visiting that means this character doesn't exist in our tribe therefore it's not one of the words that we were given in our input list of words so if any of these are true then we're going to return that's our base case if that's not true first thing we want to do is make sure we mark this position as visited and after we're done the last thing we do before we return is we're going to have to mark this as unvisited basically since this is backtracking uh we can't visit the same one twice but once we're no longer done visiting it after we return then we can go ahead and you know remove this position from being visited so since we got to a new character we want to update some variables so we want to update node so node is going to be set to node.children node.children node.children of the current character that we just visited which is board at position rc so we're updating the node because we know that node does exist and we're updating the word right so we're taking the current word adding to it the new character that we just reached board at rc and before we do the recursive case again before we look at the neighboring positions we do want to check is this the end of a word so we can check that based on our node so if node is word is true then of course we can take our result and add to it the word that we just built right the string itself not the node we're not going to add the node to result we're going to have the string word so this is just basically you know checking if it actually is a word in our list of words and we're you know doing some uh bookkeeping here and once that is done we can go ahead and actually do our recursive case you could write it with a loop but i like to be lazy and i think it's pretty okay to just copy and paste dfs four times so we're gonna pass in the coordinates and we're gonna pass in the node and we're going to pass in the word that so far we have built so let's just copy and paste this four times going in each of the four directions up down left right so all that we have defined our dfs function about 15 lines of code so remember what we actually want to do with that dfs is go through every single position every single starting position in the grid so i'm going to do a quick 2d loop a quick nested loop on the entire grid and call dfs from each starting position in the grid now for node what are we going to pass in we're going to pass in our root node that we defined up above and for the word initially it's going to be empty right so that's what we're going to pass in for the word once that is all said and done we want to return our result but don't forget our result is a set to eliminate duplicates we can cast it into a list pretty easily in python so that's what i'm going to do as you can see this is the entire code so this is the entire code and all of its glory so this you can see that this solution does work once or twice it actually did give me time limit expire i think there is a slight optimization that you can make to this problem i don't think it actually improves the overall time complexity but once you find a word in the try basically what you can do is actually remove that if it's a leaf node you can remove that from the try because you don't want to have to you don't have to search for the same word twice that's a slight optimization that you can make but i think this solution is mainly good enough and it's too big to even fit on the screen that's how you know this is a hard problem no matter what you do it's going to be a lot of code that you have to write but 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
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must 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 in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
1,200
hello guys my name is Ursula and welcome back to my channel and today we will be learning about how do we solve a new lead code question that is minimum absolute difference with the help of JavaScript so let's start this tutorial and just before starting with this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel given an array of testing in teachers ARR find all pairs of element with the minimum absolute difference of any two elements written a list of peer in ascending order with respect to Pairs and each pair a b follows a b r from error a is less than B minus a equals to the minimum absolute difference of any two elements in ARR okay so this is the thing the this these three things we have to keep in mind while we are solving the question first of all we will be focusing on this thing that is B minus 1 should be the minimum absolute difference of any element in an array so then we can move from for this step to this step that each a should be less than b okay and a and b are from ARR so let's start solving this question guys and so first of all I will just sort this array ARR dot sort uh ARR is equals to AR dot sort and a b return a minus p so while I have sorted this array I will get this whole array in an ascending order which will give me one two three four okay now I'm gonna just create a range from here to here for 4 to 1 that will be my minimum difference for now but however from a loop I will be just checking for possible a minimum absolute difference so minimum min diff so it will be my ARR AR dot length minus 1 minus ARR 0 that will give me a range of minimum difference and I will be just seeing that for let I is equals to 0 uh if is less than error Dot length minus 1 I plus main difference is equals to main difference or in math dot min math dot Main and main difference again main difference mean difference and I will check for ARR I plus 1 minus ARR I so this will give me a minimum value of any value in an array when your minimum absolute difference in the array and that should work for all the values in an array now when I have got the minimum difference I will just have to con compare that minimum difference in the array so that I can append the values in my nums that nums is equals to an empty array let this now I will just create another loop for let is equals to 0. I is less than error.length I plus I is less than error.length I plus I is less than error.length I plus if ARR ie minus ARR I minus 1 is equals to T sorry min div then nums dot push ARR so we have to return them in this form a b so a is our error I minus 1 and ARR Ive I will be RB now let's run return that nums and check for the answer so it's running fine for all the cases history and an answer has been accepted successfully let me explain it to you again that what we have applied a logic here and uh so first of all I just have a sort this array and I have just targeted a minimum difference that will be in the range from uh four to one I either uh so sorry it will be in a range from four to one and in the range of that if that is not correct so I will just go I have created a loop it will check for each and every very possible value from this and that will be my minimum difference so either it will be this or it will be this okay so once we have got the minimum difference then we can just push the values which are equal to minimum absolute difference so how we gonna check that we have created an empty uh Mt list here and then we have created a loop in which we have started from 0 to AR dot length and we have increased y one by one and then I have just said that ER I any ith value for example let's say 4 that 4 will be my this value here I then error I minus 1 will be 3 and if it's equal to man if I minus 4 minus 1 will give us 4 minus 3 will give us one so if it's equal to minimum difference then just push those values in an ARR so first of all we have to return 3 here in the list form and then we have to return 4 here so that's all we have done here I hope you have understood this question and you have no doubt left if you still have any doubt ask in the comment section I will try to sort it out thank you guys for watching the video and see you next time
Minimum Absolute Difference
remove-interval
Given an array of **distinct** integers `arr`, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair `[a, b]` follows * `a, b` are from `arr` * `a < b` * `b - a` equals to the minimum absolute difference of any two elements in `arr` **Example 1:** **Input:** arr = \[4,2,1,3\] **Output:** \[\[1,2\],\[2,3\],\[3,4\]\] **Explanation:** The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. **Example 2:** **Input:** arr = \[1,3,6,10,15\] **Output:** \[\[1,3\]\] **Example 3:** **Input:** arr = \[3,8,-10,23,19,-4,-14,27\] **Output:** \[\[-14,-10\],\[19,23\],\[23,27\]\] **Constraints:** * `2 <= arr.length <= 105` * `-106 <= arr[i] <= 106`
Solve the problem for every interval alone. Divide the problem into cases according to the position of the two intervals.
Array
Medium
null
287
in this problem we have to find a duplicate number from a list of given numbers so we are given a list of numbers and there are a few conditions that all the numbers will lie from 1 to n both inclusive and there are exactly n plus one numbers so this you can find from the size of the vector that is given to you or size of the array so numbers are in this range and one of the numbers not more than one of the numbers can appear multiple times like 2 and rest others may be 4 5 this n is let's say 20 so it will be in the range 1 to 19 1 to 20 then we will have 21 elements so you have to find which number is duplicated not multiple elements will be duplicated so uh the condition is that you don't have to use any extra space other than one that is constant space you can use but not of the other order of number of elements so this is a space constant and time constant is that it should be less than o n square and we are not allowed to modify the array so we will see a few algorithms uh starting from basic and then we will gradually advance so one very simple approach that comes to your mind is that do an in-place sort so it will convert do an in-place sort so it will convert do an in-place sort so it will convert to 1 2 3 4. so this will take order n login if you use any n login algorithm and then you scan this array from left to right and keep track of the previous value here previous value was nothing so it is one different from previous then we come to two it's different from previous which was one then we come here we see that previous was two this is also two so we return 2 so time will be order n log n space will be o 1 we will not use any extra space but we have modified the array and we have no way of going back to this we don't know which element was at which position so this would work but this changes there next we will see is that we know that it has one two three four five elements are there so this is n plus 1 which we saw here size of there is n plus 1 so numbers will lie from 1 to 4 only and you can see that you cannot see any 0 here you will also not see any number 5 or more it's between 1 to 4. so what we will do we will see what is the size of array this is 5 so we know that this is more than the maximum value that will be here so what we will do uh we will see that whatever is the value it will denote a valid index of this array as well so what is the index of this array it has 5 elements and numbers are from 1 to 4 so the indices of this array are 0 1 2 3 4 which will always be less than 5. so the numbers themselves denote a valid index so what we will do so we have this original array and let us also put the values although we will modify it one three four two so we see that when we encounter one we go to the index one and we add this value 5 whatever was the size of array so we go to 1 because this is first value is 1 and make it this plus 5 so it becomes 8. so this is now 8 next index is 3 so how do we get what is the value here this is now 8 so we have 1 8 4 2. now this is not a valid index but we know that we are always adding a value which is larger than the maximum value so we see that next value is 8 we are iterating this array so we will take 8 modulo whatever value we had added we will always add this value 5 so 8 modulo 5 is 3 and you will notice that 3 was the original value so this way we can retrieve back the older value so now we go to index 3 and add again 5 to it so this will become 7 so let me write 7 here next we come to this value we take modulo with 5 it remains 5 so we go to index four which is this index this is the fourth index so we add five here so this will again become seven next we come here take modulo with 5 then we get back the older value which was in the original array which is 2 so go to index 2 and add 5 there so this 5 will be added to it and it will become 9 so this is now 9 then we come here we see again we have 7 we take modulo with 5 and we get 2 which was the older value so we go back to index 2 and add 5 there so this 9 becomes 14 now we have reached the end of the array so now we will do one scan of this array again and we will convert them back to their original value and we will also keep track of which value is maximum so we naturally see that 14 is the maximum in this array that means whatever was the index whatever is this index which is 2 that number occurred maximum number of times because we are adding a value which is larger than all the original values so if we add this value to any number it will lie in the range it will be less than 2 times 5. since the value is from 1 to 4 so if we add 5 to it will become in the range 6 to 9 for the numbers which occur once for the number which occurs twice or more ah it will lie in the range of 11 2 again add 5 here which is 14 11 to 14 or if it's occur even more than two times then again add 5 to it so it will become 16 to 19. so you can see that the numbers which occur once will lie in this range 6 to 9 but number which occurs twice or more will be more than 11 so this way we can find which number has occurred maximum number of times and then all of them we have added a constant value a constant number of times so either we have added 5 once or we have added some multiple of 5. so when we take modulo 5 we will get back the original value so we will do a scan of this array keep track of maximum initial initialize to first value so maximum was let's take say 0 initially so we come here maximum becomes 1 and we also keep track of max index so it's 1 and index is 0 then we come here it's more than maximum so next maximum is 8 and index becomes 1 then we come here it's more than 8 so max becomes 14 and index becomes 2 then we see 7 which is not more than this next we go to 7 again not more than this and now we have reached the end so we know that at index 2 we have the maximum value that means 2 has occurred maximum number of times and while traversing this we also keep modifying this array values so 1 modulo 5 is 1 8 modulo 5 is 3 14 modulo 5 is 4 7 model of 5 is 2 7 modulo 5 is 2 so this is same as the original array so we get back the original array and we have not used any extra space and we have done in order n time so let's write the program for this so we will current maximum so these are the max and max index values ah this is the max that will be added to every value n and we are taking n since uh when we reach some value it may have already been modified for example we had modified this eight so when we were at this position so we come here so this is invalid index so we will take modulo so that we get a valid index and we keep adding n so for duplicates it will be added at least two times now we have uh added this max to all the values depending on how many times they have occurred we went to that index and added this max value now we will scan this array and find at which index max is occurring and we will also be reverting it back to original array value so this will revert it back to original value and finally what we need to do we need to return the max idx so let's submit and the solution is accepted next we will do it in java and finally we will do it in python so all the solutions are in this range if it's two millisecond so most of the solutions are concentrated in this range only so this solution is also accepted
Find the Duplicate Number
find-the-duplicate-number
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive. There is only **one repeated number** in `nums`, return _this repeated number_. You must solve the problem **without** modifying the array `nums` and uses only constant extra space. **Example 1:** **Input:** nums = \[1,3,4,2,2\] **Output:** 2 **Example 2:** **Input:** nums = \[3,1,3,4,2\] **Output:** 3 **Constraints:** * `1 <= n <= 105` * `nums.length == n + 1` * `1 <= nums[i] <= n` * All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times. **Follow up:** * How can we prove that at least one duplicate number must exist in `nums`? * Can you solve the problem in linear runtime complexity?
null
Array,Two Pointers,Binary Search,Bit Manipulation
Medium
41,136,142,268,645
1,168
hey what's up guys this is sean here so this time uh lead called number 1168 optimize water distribution in the village okay so this one this time we have earned houses in the village and we want to supply water for all the houses by building wells and laying pipes okay so basically we have own houses and we want to supply waters to all of them and for each house right we can we have two options we can either build a well inside it directly with the cost of this well okay note that you know the minus one due to zero indexing because you know this house is labeled from one to n right not from zero to a minus one or the second option is that we can pipe it piping water from another well to it okay and the cost to lay pipes between the houses are given by the rail pipes right so where we have a house one house two and the cost between those two okay and yeah and then we just need to return the minimum total cost to supply water to our houses right so that's why you know for example we have this uh we have three houses right and we have this wells so wells means that you know to build a well for house one is a the cost is one right and then two and three and the pipes means that you know between one and two we have a to build a pipe the cost is one and between two and three we have a cost to build a pipe also has one that's why we have three here right so the strategy is that you know we build a well uh we build a well in the first house and then we use two pipes to connect them okay so then we have some uh constraints right so obviously this one it's like a it's a graph problem right and this one where since we're getting the minimum total cost right so this one is exactly with what is the minimum spinning tree right so i think most of you should know this minimum spin injury which means that we have a bunch of edges right with a bunch of edges in the forest basically right it doesn't really matter how many edges we have but we have a bunch of edges and each of the ad has its own weight right and we want to connect basically we want to connect odd nodes with minimum cost together right and that's exactly what this problem is asking us to do right and so the way we're doing this to connecting all the nodes is by using the crosscar algorithm right which means that we know we'll be using a union find after sorting the address by its weight right so what that classical algorithm does is that basically we have us we have address obviously with the ad with a weight right and we sort the edges from this with the hatch have is a weight from the smallest to the biggest and then we'll try to do a union with uh with each of the edge right so we with each of that we have uh and the v right so we only you uh we only uh union when those two are not connected okay and then we that's when the unit is success then we'll accumulate that cost right and by the time every all the nodes is see they're all union together and then the final the answer the final cost will be our who will be our answer right so basically we'll be using the cross cut algorithm plus union find to solve this problem but there's a like there's another thing we have we need to consider here is that no we have two options to connect the house we can either use an edge right or we can simply build a well inside the house directly so what does that mean let's say we have three houses right and let's say between each of the house we have a pipe okay and each pipe has a cost of 100 right but let's say the cost to build the wells in each of the house is it's just 10 right 10 itself then obviously the minimum cost to supply water to all houses is what is 30 which means will not use any of the ad but instead will build or build well for each of the house directly right so if that's the case then seems like we can now there's like issue here because we have some unaccounted uh factor here other than the edges then how can we utilize this crash car right and with edges so the solution is that we have to sync it out of the box outside of the box which means that we have to convert it into a regular cross cut uh problem right which means that you know if you think about this right how can we convert this like separate a mouse right uh to a edge so that's the problem we want to stop right so the way we're converting is that you know let's say we have another node here right so this is another node n here and if we build an edge right so this node n represents the other well a common well okay if we build an edge this well to each of the node okay with the weight of this wells right then we're basically converting we're converting this uh single value into a edge right by uh introducing a dummy a while note here right i mean if we do that you know we have now we have three more edges with the weight of 10 right after utilizing applying the classical algorithm obviously will basically will have 30 because after union these three edges all the nodes have been have already been united together union together and so that's it so that's the only thing we have we need to do here by introducing more dummy edges to this graph okay so i think that's everything and let's start coding then so since we're going to use the union find right so let's implement the unit find template first uh i've already implemented this union find many times so i just go ahead and type it in here type it down here so we have a union we have we'll find if x does not equal to the parents of x right then we have parents of x equals to the fine of parents right and then we return the parents of x so this is the u defined with a path compression right and then we have a union right unit is going to be an x and y right and then the r one equals to find root one equals uh find x and the root two equals to the find of y okay if r one does not equal to r two right we set the parents of r2 to r1 again right so here i skip that you know the weight the basically i skip that a ranking uh comparison here so if you really want to make both the both uh if you really want to make the union one time complexity uh besides the parents we should also introducing a ranking array here so basically we always every time we always assign the uh the component with a lower ranking to the components uh with higher ranking that's why we try to con make this a union or make this tree balanced right but here i've simply just simplified it right okay so that's that basically that's the union fine pretty straightforward right uh simplified version of unified and then uh we have edges right so let's uh do the address here so for edges let's uh add ideas from the pipes first so we have a u v and the cost in pipes right address dot append uh so since we're going to sort by it so we're going to first one is going to be a cost second is going to be a u minus 1 the v minus one right remember you know uh see so this pipes they're the one base but you know since we are you know let's do this end here right so since in the wells they're all zero base that's why i'm converting this one based house to zero based okay and then address right to sort it okay again right so here we're only uh we just took care of the pipes but not but we haven't had the edges for the wells right you know for that you know we are going to introduce like a dummy node right which not we can simply uh that's why i have to have what n minus one because the house is from n to zero to n minus one so i'm simply using the node number n to represent the dummy well right so which means we're gonna build diamond edges right from each house to the dummy node n right so that's why for i in c enumerate of wells right we built we added also added the edges right for this dummy well free for each of the house okay so we're going to be having c dot i under it's always n right so now we have completed the graph now we after sorting we can simply uh do the unit here right so first for c dot u and v in address right oh and one more thing since we are going to accumulate the cost which means that we only accumulate the cost when the unit is success right so that's why the union here will return like a boolean value here so which means if this thing is if union has been uh executed then we return true here otherwise return false right so basically we do a unit so if union of u and v is a success then that's when we accumulate the cost okay and then in the end return the answer right so i think that's it okay submit cool so it passed right because uh like i said so the time complexity for both the union find is should be a theta o of one okay so we accomplish theta of one by applying this uh for fine where by applying this uh path compression and for the union by compliance applying this uh ranking right but i skipped that ranking here and that's why the uh the time complexity for this one is simply just a three four loop here right and it's just like o of n i think right so that's the time complexity for this and i think that's it right so it's this one is i think it's pretty uh straightforward except for the wells right i mean the only difference tricky part for this problem is that you have we have to convert this well into a bunch of dummy adjectives right so that we can utilize this union find plus classical algorithm to build the minimum spinning tree right cool i think that's it for this problem and thank you for watching this video guys stay tuned see you guys soon bye
Optimize Water Distribution in a Village
duplicate-zeros
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Array,Two Pointers
Easy
null
1,090
the intended function of a program or part of a program can be specified by making general assertions about the values which the relevant variables will take after execution of the program welcome everybody it's amel and today we're going to solve largest values from labels we have a set of items the item has value values of i and label labels of i then we choose a subset s of these items such that the cardinality of s is less than or equal to num wanted so this means that the size of the subset cannot be bigger than unwanted for every label l the number of items in s with label l is less than or equal to use limit so this condition means that we can pick items that have the same label but those items that have the same label they cannot be more than use limits so for example if use limit is one then we cannot pick more than one item with the same label then return the largest possible sum of the subset s for example here this is example one these are the values and these are the labels so you can think of these five as the value for the first item and the label for the first item is one the four is the value for the second item and the label for the second item is also one and so on so we have these values non-wanted equals three and use limit non-wanted equals three and use limit non-wanted equals three and use limit equals one so the output is nine so we want to maximize the value and we want to make sure that we follow these conditions so the explanation is that in this case we can choose this item that has value five and we can choose this item that has value three that's eight five plus three is eight and we can also choose this item that has value one so five plus three plus one in total nine so this is the maximum value that we can get so in this particular case we cannot choose 4 after choosing 5 because 4 has the same label as the 5. the item that has value of 4 has a label of 1 and the item that has value 5 also has a label of 1. so after picking the one that gives you 5 we cannot pick the 4 because they have the same label and the used limit is 1. so that's the reason so how can we solve this problem this is an optimization problem and we want to maximize the value so whenever we have to solve optimization problems we can think of greedy algorithms agree algorithm is an algorithm that makes decisions that are locally optimum at every step and it never changes a decision so in order to use this approach in order to use the greedy approach we can use the priority queue so we can use a max heap or priority queue because we want to maximize the value we always pick the largest value and we also use a hash map because we want to establish a mapping between each label and the number of times that the label has appeared how many times the label appears in the data because we want to make sure that we follow this condition here for any item that we pick we need to make sure that we don't pick um more items with the same label than we are allowed that's why we have to use a map or a hash map to establish the mapping between the label between each label and how many times the label appears so without further ado i'm going to write the code so as i said i need to use a priority queue or a max heap the max heap is going to maintain the largest value at the root it's going to maintain the largest value at the root of the heap so i'm going to have a priority queue and this priority queue is a priority queue of item gets a value of new priority queue and by default the priority queue is a mean heap that means that the value at the top will be the smallest value but i want to use a max heap so in this case i'm going to say item 1 item 2 and item 2 that value minus item one that value so i'm doing this here i'm passing this lambda function because i want to make sure that we compare each item based on the value of the item not on the label and i also want to make sure that we use a max heap so the item that has the biggest value will be at the top now this class item i have to make this class so you can go down i can say private class item so i'm going to have a integer label and also the value and then i'm going to define a constructor for the label and also for the value so i can say this that label the label for this object for this item gets the value of the label that i passed and this that value gets the value of the value that i passed so now i have this class in order to hold information for an item and i have the priority queue and this is a max heap so it's going to compare by value and it's going to have the item that has the largest value at the top so now i just need to populate this priority queue so i can traverse all the items so for integer i because the value of zero i is less than labels that length plus i then i can say for each item right so make a new item so priority queue that offer i'm going to insert a new item in the priority queue the label for the item will be labels of i and the value for the item is going to be values of i so now my priority queue has all the elements so it's going to maintain the elements um using the property of the max heap so the value at the top will always be the maximum value um or the maximum item that contains the biggest value in the heap so now i want to have a variable max sum so this is going to be the final result i'm going to return it at the end and i also want to have a hash map because i want to maintain a mapping between each label and its count so i'm going to have a map from integer to integer map gets a value of new hash map now i need to have a while loop so while not priority queue that is empty and the other condition is that the size of the subset cannot be more than three so i need to make sure that num wanted and it cannot be more than unwanted so number one is bigger than zero so the other condition is the size of the subset cannot be bigger than one thing so i have to say num guantana is bigger than zero right because every time i'm going to subtract one from the quantity so each time i want to get the current item from the priority queue and remove it so that's going to give me the biggest item or the item that has the most value so i'm going to say item current because the value of priority queue.paul and now i want to make sure that i establish the mapping between the label of this item and its count so i'm going to say map.put curd.label map.put curd.label map.put curd.label map that get or default curve that label zero plus one so in this case i'm mapping each label to its count so for example here i'm going to get the count um that i already have and got one to it however if it's not there if the label has not been seen before then um i just get zero by default so the first time i see the item the count will be one the next time it's going it's gonna be one plus one is two and so on so after i put this mapping here i can check if map.get if map.get if map.get cur that label so the other restriction is that it cannot be bigger than use limit so it's less than or equal to use limit then that's okay i can pick this item so this is the item that has the most value and i know that i have not picked the label more than use limit because i'm checking here so because i haven't reached the limit for this label then i can choose the value of this label which is the maximum that i have in the priority queue because this is a max heap so i can simply say max sum plus equals the value of the current item and because i picked one more item i have to decrement num wanted so minus num wanted so now i'm going to run the code i'm going to submit my solution is working perfectly so the time complexity is big o n log n where n is the number of items and the space complexity is big of n where n is the number of items if you like this video please press the like button don't forget to subscribe and see you next time
Largest Values From Labels
armstrong-number
There is a set of `n` items. You are given two integer arrays `values` and `labels` where the value and the label of the `ith` element are `values[i]` and `labels[i]` respectively. You are also given two integers `numWanted` and `useLimit`. Choose a subset `s` of the `n` elements such that: * The size of the subset `s` is **less than or equal to** `numWanted`. * There are **at most** `useLimit` items with the same label in `s`. The **score** of a subset is the sum of the values in the subset. Return _the maximum **score** of a subset_ `s`. **Example 1:** **Input:** values = \[5,4,3,2,1\], labels = \[1,1,2,2,3\], numWanted = 3, useLimit = 1 **Output:** 9 **Explanation:** The subset chosen is the first, third, and fifth items. **Example 2:** **Input:** values = \[5,4,3,2,1\], labels = \[1,3,3,3,2\], numWanted = 3, useLimit = 2 **Output:** 12 **Explanation:** The subset chosen is the first, second, and third items. **Example 3:** **Input:** values = \[9,8,8,7,6\], labels = \[0,0,0,1,1\], numWanted = 3, useLimit = 1 **Output:** 16 **Explanation:** The subset chosen is the first and fourth items. **Constraints:** * `n == values.length == labels.length` * `1 <= n <= 2 * 104` * `0 <= values[i], labels[i] <= 2 * 104` * `1 <= numWanted, useLimit <= n`
Check if the given k-digit number equals the sum of the k-th power of it's digits. How to compute the sum of the k-th power of the digits of a number ? Can you divide the number into digits using division and modulus operations ? You can find the least significant digit of a number by taking it modulus 10. And you can remove it by dividing the number by 10 (integer division). Once you have a digit, you can raise it to the power of k and add it to the sum.
Math
Easy
null
83
And here we are attending question number 83 which is remove duplicates from sorted list. Here we have given a list. Here we have a linked list proper and from the listless we have to remove duplicate elements from it. You have here. Sorted and you have to remove duplicate elements like we have linked list here one you have one and one duplicate in it then one duplicate you have to remove one if you want to keep one then one and you have to return unique elements here like you have here You have been given a head of Linchas in which the elements are one and here you have to return one tu. This is a simple question, if I explain it a little more, what is actually happening here that you have here. There is a box, okay, and what do you have to do? Out of this one is loaded, which is a duplicate note here, this one has to be removed here is one thing, let me try to explain to you, the basic difference is one in one and one. What happens in a linked list? Hey, what happens in the list? If you have to create a support one, its size is 10, okay, you have to create it with 10 elements, then the memory that will be allocated to your Eric will be contiguous. If it is on memory allocation, then first the first element gets the memory 1001, second gets 10, third gets 103, 4th gets 104, fifth gets 105 and so one, then here the link from the contiguous memory location is not in the list like this, if you here Take this one complete memory, okay, where it is supposed to be 1000, there is a space here, where one mode is getting one space, okay, you are doing it like this, let's do assam, so here is the memory, it is supposed to be in linkless. You have got memory for each element, one has got support for Rs 101, another has got support for Rs 203, one has got it for Rs 400, one has got yours for Rs 650, one has got your support for Rs 980, one has got it for Rs 750, so like this. So, this is the basic difference between a linked list and an array. The memory allocation in an array is contiguous. Contiguous memory allocations mean that everything happens simultaneously, but in a linked list it is not like that, all the bins are in the link place. They are different, okay, so what do you get here you get the address of the head, meaning where is your first note in this entire memory, first note support, your 10 notes which are yours. The third note is at 203, now your fourth note is at 257, the fourth mode is at 404, so you will get its address, okay, this will be your head here, you get the address of the first note, where is the first note and which is the first note. There are two parts in it, one is your right here part on the left which has the value and one is your next part which has the address of the next note because it needs to know where the next note is, so here is the support. If yours is at 203 then this is what is stored here at 203 so that you know where the next note is, otherwise here you will not know where is the next tour in such a huge memory pool, so you You know, hey, you know that if the first one is at zero one, then where will the fourth one be, the fourth one will be at 104, there you know, because of this, you directly pick the elements by doing indexing here, if you suggest. It is starting from zero, so the four element is here, it will be taken out from three, so here you know, if you have to fit the third element, then you link here the address of the third element, the address of its previous mode. Pass is here, the address of this note of yours is on 3, this note of yours is on 257, its address is stored here, so in the same way, using the same logic, we will do this question here which is remove duplicate from. And you have to delete all the duplicate notes, okay, now how to do it here, you just have to do a simple one less here, you know if both of these are duplicate here, okay yes, both of these two notes here. If it is a duplicate then you have to remove this note. To remove this note, what will you have to do here? Do n't do anything. Its address is 203. Now by pointing to it, you will see here instead of 203. If you write dog here, if you want to remove it from the middle, then you have to put the address of this one here, like this, if you write dog here, then this node in the middle here will be removed from here and we will get absolutely This is what you have to do here, if this element is your head element here, then you have to do just one more thing here, you have to check the value of your head element because your No, you get two things in it, first you get the value, as I told you that yours is a box, it is divided up into two parts, one part has your value and the other part has the address of your next note. What happens is that you get the same two things, here you are getting the value and in the other you are getting the address of the next, only these two things you are getting here if it is equal to you, the value of the next of the head. Dot well, what has to be done is that the value of head is if it is equal to this. If your one which is equal to one here then nothing to do. You have to assign the next of the head to this head because it is its next. If you want to find its next then next dot next will come, then the value of the next of the head means its address, you have to put it in the next of the head. Next of the head means this one, so what do you have to do here in the next of the head. I have to insert the next one next to the head, just this little bit has to be reduced and there is nothing else in it, just this little bit is less, so let's do this question. Okay, first of all, I have to reduce one thing and then I will add some things from here. I'm going to remove it, okay, so nice, okay So let's reduce it by one here, take a little space, take it down here, the function will come up a little bit here, so sir here, let me reduce it first. What I have to do is that I will have to create a temporary load here because what I am doing here is that I am [ __ ] directly with the head here, [ __ ] directly with the head here, [ __ ] directly with the head here, anytime you want in Link Lee, if you have a head life then you have to try to make it with the head. Don't do that because the head is the address book of your first note and if the address of your first note gets lost then everything you have modified the head and the address of your first note is gone then in this you will get here You will not know where the first number was, so we always try to reduce it here, we create a temporary mode here which is pointing to your head, okay, so what did I do here sir? I am making a temporary mode here, this is my head here and this is where I have to run the point, okay next, your point here should not be equal to null because I am reducing the temp here also with the next point, okay. If both of these are here, if you open here, then you do not have to do anything. The address that you have to enter in the next part of the template is not of the next note, it is of the next note of your next one and the date seat. What happened here, a note in between. If it happens here that here I am, I have a node in which there is one, here I have a mode in which you are, here I have a mode in which there is three, so if everything is said, your here is on time. Okay, next the tempo and tempo are equal, otherwise what will I have to do, I will have to increase the tempo by one step, now I don't have to skip, I have to skip only when on my yes, which are these two notes here, they are equal. So how can I bring it to my place, what should I do, the temp which is pointing to this place is mine, it should be pointed to this, but if these two are not here, you are here, then I will bring the temp here. So to bring the temp here, if it is not equal, then I will have to go here and I will have to write here 10 tan Here the address of the first mode has to be returned because the link list that I have is to start your tempo, so I gave it bigger ahead, okay but the head of yours is still pointing to the first node and we always start from the first mode. If you link only then all you have to do is this much less, if you do it here, then you see here, both of them, these have been accepted on your place, submit, I have submitted this here, you can ask the question here. The solution will be clear
Remove Duplicates from Sorted List
remove-duplicates-from-sorted-list
Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. **Example 1:** **Input:** head = \[1,1,2\] **Output:** \[1,2\] **Example 2:** **Input:** head = \[1,1,2,3,3\] **Output:** \[1,2,3\] **Constraints:** * The number of nodes in the list is in the range `[0, 300]`. * `-100 <= Node.val <= 100` * The list is guaranteed to be **sorted** in ascending order.
null
Linked List
Easy
82,1982
1,704
hello everyone welcome to this new video we are going to go through determine if string Hales are alike what does that mean that means you receive as input a string like this and you're supposed to split it into half and find out if you have the same number of VAR in the left and in the right if it is the case they alike otherwise they are not Alik this is an example let's say you have this array or you have this string in this string you can see that the first half consist of a b d e you have a and e which are actually V and in the second half you have Au U which are V so the first half has a number of which is equal to the second half does they Alik now that we are aware of how the thing is working how are we going to solve it so I'm going to solve it using two approaches the first approach will be to have a counter which is going to move from left to right and whenever you're going to see a varal if you're in the first part we just increment our counter if you're in the second part we decrement our counter and the second appro will be to use two poter the first one is incrementing the second one is decrementing okay so let us start with the first approach will be as follow I'll have a string which will have I'll maybe call it like V which we have value of a e i o u right then area okay now should have like integer the count which initial zero and I also need like the size n which will be equal to S do the size once I'm here I just need to look for I want I have this value I just need to check if um V find if V find um to lower of s of I if this is actually different from no this is not how this is not where I'm comparing this is where I should compare if it's different from um string and plus if it's the cas now getting that means I have a VAR now I have a VAR I need to check if actually I is actually less or less than n / 2 then actually less or less than n / 2 then actually less or less than n / 2 then what I should do is that I should increment my counter otherwi I should just my counter the end here I can return C is equal to zero so like I was saying you have a Vari here the list of VAR now you have the counter and the total element now you look to the element if you found in the VAR the element you are on need that means it is a VAR I'm to lower it because I just have the lower case here that's why I need to lower and then if I check it is a VAR now check if it's the first half I increment otherwise I decrement see what it gives so everything you can let us submit clean performing really well now um let us take it in a second way like the second approach I was saying in the second appro instead of like having this double check here I will not do it that way I will have two counter let's I have I moving from zero and G moving from nus one and then G moving for nus one I will check if I is different for is less or equal n / 2 and then yeah I just need or equal n / 2 and then yeah I just need or equal n / 2 and then yeah I just need to decrement my G and here what I should say is that I will just say if V do find SD is different from this what I should do is just increment and then I should do the same for the second one but instead for S of G and this one should decrement and at the end of this I'll just do the same return c equal to Z let us run and see what it gives uh I have an error somewhere this is not this is a comma here everything is going to submit yeah this one is actually performing better than the previous one uh just because we are looping half compared to what we looping previously so this my Approach of solving this I hope do enjoy it feel fre to leave me any input I'll be really happy to interact with you regarding this see you on the next video ciao
Determine if String Halves Are Alike
special-positions-in-a-binary-matrix
You are given a string `s` of even length. Split this string into two halves of equal lengths, and let `a` be the first half and `b` be the second half. Two strings are **alike** if they have the same number of vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`, `'A'`, `'E'`, `'I'`, `'O'`, `'U'`). Notice that `s` contains uppercase and lowercase letters. Return `true` _if_ `a` _and_ `b` _are **alike**_. Otherwise, return `false`. **Example 1:** **Input:** s = "book " **Output:** true **Explanation:** a = "bo " and b = "ok ". a has 1 vowel and b has 1 vowel. Therefore, they are alike. **Example 2:** **Input:** s = "textbook " **Output:** false **Explanation:** a = "text " and b = "book ". a has 1 vowel whereas b has 2. Therefore, they are not alike. Notice that the vowel o is counted twice. **Constraints:** * `2 <= s.length <= 1000` * `s.length` is even. * `s` consists of **uppercase and lowercase** letters.
Keep track of 1s in each row and in each column. Then while iterating over matrix, if the current position is 1 and current row as well as current column contains exactly one occurrence of 1.
Array,Matrix
Easy
null
1,287
Hello everyone welcome to my channel code sari with mike so today we are going to do video number 74 of our playlist, ok it is marked easy but we will make it with three approaches and we will get to learn a lot, very good approachable appearing more than that 25 But in a sorted, okay, so let's see what the question is trying to say. The question says that you have to find one such element and show that yours is sorted. In non-decreasing order, you have to show one such element In non-decreasing order, you have to show one such element In non-decreasing order, you have to show one such element which is That more than 25 off time is coming is fine in itself and there is exactly one integer it is good that there is only one integer which is more than 25 off time is coming and you have to find it for example Look at this, first find out its size. Let's see how much n is. 1 2 3 4 5 6 7 8 9 is nine, so if an element appears nine times, it means it is 100% present means it is 100% present means it is 100% present in the entire array. There is only that number in the entire array. Any number, if any number is coming 9/2 times then 9 number, if any number is coming 9/2 times then 9 number, if any number is coming 9/2 times then 9 means n is my size. If any number is coming more than 9/2 times, it means it is coming more than 9/2 times, it means it is coming more than 9/2 times, it means it is coming more than 50 times. Okay, now for 25. What to do is n / 4 means for 25. What to do is n / 4 means for 25. What to do is n / 4 means n / 4 means 25 but it is n / 4 is n / 4 means 25 but it is n / 4 is n / 4 means 25 but it is n / 4 is 25 so what does it mean that we just have to find which is the element which is occurring more than 4 times in n. Okay, that means its frequency is greater than n ba 4. Okay, so within a few minutes seconds the solution must have come to your mind, which is going to be our approach one. Okay, we have to count the frequency, so what will we do in approach one? What we will do is simply find a frequency of elements, store the frequency in a map and the one whose frequency is greater than n/4 will be frequency is greater than n/4 will be frequency is greater than n/4 will be your answer. As simple as that is the simplest solution. This is your approach one. This is what is going to happen, so its time complex. What will be o of n because you will go to each element only once? What will be the space complexity of n because you are storing all the elements in the map. It is okay to store their frequency, so look at this example. I have taken a map. Okay, let's store the frequency of all the elements. One, which has come once, two, which has come twice. It should be more than n / 4 then how much is n mine should be more than n / 4 then how much is n mine should be more than n / 4 then how much is n mine a 2 3 4 3 7 8 9 ok no ok now see how much is 9/4 so now see how much is 9/4 so now see how much is 9/4 so which element is coming more than two times That is ss that is that way, its output is six and n is coming more times than f times i.e. it is coming more times than 25 times. i.e. it is coming more times than 25 times. i.e. it is coming more times than 25 times. Okay see here I have stored the frequency in the map so this is my approach. One is a very simple approach. Now let's look at our second approach. Now let's look at approach two. Approach two is also very simple and approach two. Do you know what is taking advantage of the fact that it is already sorted, so it is an obvious thing. The elements which are same will be stuck to each other like this, see 6, all will be adjacent to each other because it is obvious that this is the same element and it is sorted. This 2 is same, so you see, only adjacent ones appear. If that is okay, then first of all we find out what should be the frequency of an element. Okay, that is, n/4, if it is 25, Okay, that is, n/4, if it is 25, Okay, that is, n/4, if it is 25, then n/4. If something is coming more often than this, then that is then n/4. If something is coming more often than this, then that is then n/4. If something is coming more often than this, then that is my answer. If it should be 9/4, how much is it, that is, should be 9/4, how much is it, that is, should be 9/4, how much is it, that is, any element which appears more than twice will be my answer and there will be only one element, that's fine, now let's see, look here, I am standing on i. Okay, if this one comes more than twice, okay, then it will come here once and next to it once more and after that it will come once more i.e. after that it will come once more i.e. after that it will come once more i.e. till the index number two and 1 would have been the same. If this one had come more than twice, then the index number would have been up to two. Okay, so you pay attention to one thing, I will just check that if it is equal to what it is off aa plus, see what is the value of frequency. Hey Aa P 2 Okay Hey Off Aa Look So What Is One Is It Equal Hey Off I Aa What's My Now Is Zero 0 Plt Hey Off Two Okay But Hey Off Two Look So What Is Hey Off Tutu Hai Ch E Neither is 2, because if the number of two is also one, then it is definitely one because it is sorted, it is, now see, has it come more than two times, then we catch that this is our Culprits, not more often. It will come, okay, very good, okay, now what do we do, now let's take i forward, okay, we took i forward, then we will check the same, what is off i is equal to what is, off i is still one, right, 1 p 2 t e 3 Are of th Tak Are of two what is to is a if there is sis in ath then it is not equal, if it was equal it means there would be two here also then see it is an obvious thing ya see it has come more than twice then it is the same I would have been a candidate but this is not so, no problem, I have moved ahead, okay, now I have come here, so here also I have come here, whatever is there is two and here I am off i P 2, that is, 2 P 2 are off 4 here. This is six, both are not equal, meaning this T has not come more than twice, now come here, now look carefully, are off, come, now it is three, isn't it right, is it equal, are off i + 2, that is, i Now there is 3+ 2, that is of off i + 2, that is, i Now there is 3+ 2, that is of off i + 2, that is, i Now there is 3+ 2, that is of 5, let's see, what is there in off th, there is six in phi too, do you know what it means, brother, this is what has come more than twice, so twice. Right, he has come one more time, because look, from Aa to F, he is right till F, it means he has come more than twice, that means he is my candidate, I will return this guy at the same time, hey off. If I return Aa at the same time, then its code is also very simple. First of all, what we have to find is what is my frequency, if it comes more times, then we will catch it. If it comes more than A, Ba, F times, we will catch it, then this should be my frequency. Now look, pay attention, there will be a simple loop for aa, I remember it started from zero i &lt; n, I am doing it now, started from zero i &lt; n, I am doing it now, started from zero i &lt; n, I am doing it now, i Pp, okay, we just remember, what we check here is that if it is off aa, which is it. It came out equal. Are of a plus remember the frequency remember i p 2 why did you do it here because the value of frequency n ba 4 that is 2 is right i ps frequency is right if it came equal to this means do you know what happened that i This element will be present from 1 to i plus frequency i.e. from twice to twice does i.e. from twice to twice does i.e. from twice to twice does not mean more than n/4 times it has appeared more than n/4 times. not mean more than n/4 times it has appeared more than n/4 times. It has appeared more than n/4 times than Culprits. It has appeared more than n/4 times than Culprits. It has appeared more than n/4 times than Culprits. It has appeared more than n/4 times. Okay, it is quite simple but now appeared more than n/4 times. Okay, it is quite simple but now appeared more than n/4 times. Okay, it is quite simple but now notice one thing, do you look at i here? Is i &lt; notice one thing, do you look at i here? Is i &lt; notice one thing, do you look at i here? Is i &lt; n? Do i need to be taken to lesson n? No, you Take it easy till n minus frequency, take it till n minus frequency because look, we will check till aa plus frequency, neither take i till n minus frequency, otherwise it will be out of bound, no, this is right, otherwise it will be out of bound. It will be bounded, like see here in this example, if we assume that you have taken a here till n-1 and now you are taken a here till n-1 and now you are taken a here till n-1 and now you are checking i ps this 2 then 8 p 2 then it is out of bounds. Okay, so that's why what I am saying is, how far to take Aa, less than n minus frequency, so n is my Na frequency, how much is two, 9 value 2 becomes 7, then go only till less than 7, that means take Aa only till here. Go because look at this, if you do plus two, then come here, this index will come, which is in bound, not out of bound, okay, that's why I am saying lesson n, not lesson n, minus frequency should be enough. It is simple and if this mistake is not caught here then there must not be any element which must have appeared more times than A Sorry frequency n Ba If it has appeared more times than F then it is okay to return -1 in the last then it is okay to return -1 in the last then it is okay to return -1 in the last then this is our Approach four is done, I am very sorry, approach two is done, I liked this one very good approach, now coming to the best approach, which came in my mind at the very beginning, do you know why it came because here it is clear cut that brother If yours is sorted then brother, if it is sorted then why are you not thinking of binary search? Hey, if you are sorted then think of binary search, then you simply come and solve it with your binary search. So see, there was an approach but why do binary search come to anyone's mind? Will come because it is sorted, okay and you have to find out the frequency of one element. Okay, so think to yourself, hold any element. Let's assume that you have caught one. Okay, so this is the starting index of one. Right now right. Most, we have to find out where else the forest has come on the right most, now the forest has not come anywhere on the right most, the forest has come only here, so the forest has come only once, okay now let's come here near two. Look, here we have come here on index number one, meaning now its left position is one and right most position, we will find out by binary search where it came, meaning we will do binary search in so many parts and see where is the last position of two, then two. The last position I can see is index number two, so let's see how many times right has come from left, that is, it is right minus left + 1, that is, times right has come from left, that is, it is right minus left + 1, that is, times right has come from left, that is, it is right minus left + 1, that is, it has come twice, it is 2 - 1 + 1, that is, it has come twice, it is 2 - 1 + 1, that is, it has come twice, it is 2 - 1 + 1, that is, this is two. That is, that has come twice. Okay, now look, since this is two, which is the right most. Where has the index number come? Here, two has come. Okay, now next since this, how many times has this come? Look, it has come only twice. Which is not greater than? n / 4 Okay, so this is not greater than? n / 4 Okay, so this is not greater than? n / 4 Okay, so this is not our candidate, so where will we move i next, where did it come last time, it came at index number two, so we will just move one forward from that, we will bring i here, okay because two is mine. If there is no candidate then we have seen it, now let's come to six, okay, which is the left index of six, the left most index is on three, we have got it on 6th, right, we will find out the right most index, we will do binary search, it is here, right? If you apply binary side then you will get right mode index 4 5 6 7 8 right mode index I have got this, right? If six has come then let's see how many times right minus left has come 6 - 3+ 1, how many times it has become three. Gaya Vach 6 - 3+ 1, how many times it has become three. Gaya Vach 6 - 3+ 1, how many times it has become three. Gaya Vach is greater than n Ba 4 So this will be my candidate, so see how simple we thought, what we did is that brother, we are going to each element, right and that is its first A currency, right, the first one of that element. Is array and its last array is taken out from binary number, then in binary search we will take l of n and we are going to each element and then we are doing binary search, so it will be n * l n. Okay, n * l n. Okay, n * l n. Okay, this is the time complexity. It is very simple and it is very easy to find out the rightmost index of any element through binary search. You must already know it is okay if you don't know it, then if you code further, it will become clear. Okay, but you are looking at the time complexity. n l n It has been done, Which is not very good, so how can we make it better, how can we make this binary search better, I want to show you now, I liked that approach very much, so see here. But if you pay attention, what is the problem in this approach, is that you are going to each element and then doing binary search, then this is why there is no time competition and why is that, now I will show you the proof, look here, I have This is an example. Its size is nine. Okay, its size is nine. Now look carefully, what will be the frequency. At 25, A Ba 4 i.e. 9/4 i.e. 2 i.e. At 25, A Ba 4 i.e. 9/4 i.e. 2 i.e. At 25, A Ba 4 i.e. 9/4 i.e. 2 i.e. if any element appears more than twice, right? So that is our Kalpetta, cover the entire range, see, I will definitely choose it, I know why, because if this guy was my candidate then it is possible that he would have been here XXX, had he come all the three times, then this range would have been covered for me, okay And if X was not there then he would definitely be here. If he is a candidate then if my If it happens to be fine, then I draw with another pen. If my candidate was this, then let's assume that it is Yva, then if it comes more than twice, then it may come on the right side or Wawa, or it may come on the left side, it may not come here, it may come here. Okay, so look, this range would have been covered, and this range would have been covered, okay, if we go by the values, this is not my candidate, this would have been dead, so what would have happened, this would have come three times here, that is, if he is my candidate, this is dead, this is here. If it had not come on this side, then that z root would have come on this side. Okay, so you noticed it is overlapping three times, one here and what is that index, I am writing here A 01 There are 2 indexes, this is my four and this is mine, look at it is six, okay, so you know that if you just check this candidate and this candidate, that is my n times more than 4 times. Are you coming or not, otherwise your work will end there, you will not need to check all the elements, okay and why and that too I have told you the reason because if this guy was a candidate then he would have given me this range and this range. Okay, so this range of mine is covered. If this guy was a candidate with index number four, then he would have covered this range and would have covered this range. Even then, look, I am getting covered and if this person is a closed candidate, then he would have covered this range. So this will cover this, so you are seeing that if I check these three position index elements, then my entire element is being covered, its entire element is being covered, okay, to check all the elements. It is not needed, so now look at this index. How could it have come from n/4? index. How could it have come from n/4? index. How could it have come from n/4? What is 9/4? If it is 2, What is 9/4? If it is 2, What is 9/4? If it is 2, then I will check the element with n/4 then I will check the element with n/4 then I will check the element with n/4 and look at this one. What is n ba 2, this is 9/2, how much will come, 4 will come and this is 9/2, how much will come, 4 will come and this is 9/2, how much will come, 4 will come and this index which is 3 * n ba 4 will come, you take another example, 3 * n ba 4 will come, you take another example, 3 * n ba 4 will come, you take another example, see there also, 3 * n will come from baat, n see there also, 3 * n will come from baat, n see there also, 3 * n will come from baat, n ba will come from 4. 3 * n ba 4 is how much is 9/4 ba will come from 4. 3 * n ba 4 is how much is 9/4 ba will come from 4. 3 * n ba 4 is how much is 9/4 i.e. 2 6 Look here the index is Si i.e. 2 6 Look here the index is Si i.e. 2 6 Look here the index is Si so we will have to check only these three indices because if I hold these three indices and check then I will get the answer because these three These indexes are covering all my entire array, their range, whether it is repeated on the left side or on the right side, look at this, if it is repeated on the left side. Be or right side repeat, the whole of the whole is going to be covered, these three positions are the best positions for us to catch which one is the Culprits of n Batu, sorry, n Ba 4, okay, after that, the names of n Batu. After that, who is one more and which element is the numbers of 3n ba 4? These are the three elements, these are the three candidates, only one of these three will be my answer. Okay, now I don't need to go into all the elements. What do I do? What element is there in Nams Ba? So let's take this example. Let's run this example here. Move it down and run on this. Okay, it is best understood by dry run. Okay, look, let's erase it carefully. First, let's do indexing so that clarity comes. 0 1 2 3 4 5 6 78 Okay, so numbers n ba 4 means index is this n mine. If there is no then n ba 4 means which element is there in the numbers of two, this element is ok, catch it and the index number is four i.e. catch it and the index number is four i.e. catch it and the index number is four i.e. n / 2 means the index number is four, it is n / 2 means the index number is four, it is n / 2 means the index number is four, it is ok and which one to catch, 3n ba 4 means catch this. Okay, look, if I catch these three, first two will come to me, neither will this two, okay, I will find out the left most index of this two, from binary search, which is the left most index, which is one, and I will find the right most index of this two, right. What is the most index? Two is okay. Look how many times it has come. Right Manas Left P1 2-1 Pv has come only twice so this is P1 2-1 Pv has come only twice so this is P1 2-1 Pv has come only twice so this is not my candidate. Okay, no problem. Now let's come to this one. Come to six. What is the left most index of ? What is the right most index of 3? six. What is the left most index of ? What is the right most index of 3? What is the meaning of n/4? It is What is the meaning of n/4? It is What is the meaning of n/4? It is coming more than n/4, so this is coming more than n/4, so this is coming more than n/4, so this is our candidate. You see, the answer is right from here, so we do not have to do anything, we will just iterate over these three candidates and hit all the elements. But we will not use binary search, okay, so three I will write a for loop for int and candidate and the candidate that I have created which has three elements, there will always be only three elements in it because these three elements will cover the whole thing, right? Hey, it will be completely covered, okay, and I have guaranteed that one element will be there for sure, right? It has been given in the question that one element will definitely be there, which has come four times i.e. more than n or 4 which has come four times i.e. more than n or 4 which has come four times i.e. more than n or 4 times. Okay, so candidate. If I find it, what will I do? I will take out its left most index and take out the right most index. I will take out the binary search. I will take out the left index from here and here the binary search will take out the right index. Then here I will check that right Minus left 1, okay, if it is greater than n/4, that means it has n/4, that means it has n/4, that means it has come more than 4 times, then I will return that this candidate is my answer, till now it is clear and will return outside. Because we will definitely get the answer here, OK, this was a very good approach and the normal binary search which was giving log n, look this time, normal here, binary search here, log n will be found here, but look outside, it will run only three times. Which binary search will run three times? Log of n, then the time complex will be approximately log of n. If it is clear till now, then yes, pay attention to one thing, whether it is to find the left most index of an element or to find the right most index of an element. I will show you that also through easy binary search. Let's code quickly. But in the first approach, what I said in the first approach is to store the simple frequency of all the numbers. So, first of all, I took out the size and made a map. Made in which frequency will be stored and what should be the frequency. It should be more than 25 i.e. n should be i.e. n should be i.e. n should be more than 4. It is okay for int and num in a RR. Okay, first of all put that in the map MP num plus. Plus updated the frequency and if MP of nam is greater than frequency then it is ok then return nam and if it is not so then return -1 in the last while this will not happen, it is return -1 in the last while this will not happen, it is return -1 in the last while this will not happen, it is said in the question that there will definitely be an element. Whose frequency will be more than n times 4, okay, this is our first approach, now let's come to our second approach, okay, so our second approach, you will remember what I said that it is simple, when it is sorted, then we take advantage of it, right? Like int n = add size, first let's find out the frequency int n = add size, first let's find out the frequency int n = add size, first let's find out the frequency n ba should come more than 4 times, okay for int i = 0 i &lt; n okay for int i = 0 i &lt; n okay for int i = 0 i &lt; n i+ p and what I said that if these i+ p and what I said that if these i+ p and what I said that if these are off aa then this is my candidate. If it turns out, it will definitely be up to the I+ frequency. to the I+ frequency. to the I+ frequency. Okay, so this will be my candidate. I have returned A. Okay, return MIVE at the end, but pay attention here, we are accessing the I+ frequency. We are the ones who are either we are accessing the I+ frequency. We are the ones who are either we are accessing the I+ frequency. We are the ones who are either A or minus. You can take the I only till the frequency, otherwise it will be out of bounds, let's see after submitting, this should also pass, after that we will come to our best approach which is Lagan approach, isn't it, using binary search, this is also enough. It is simple if seen then let's clear it quickly and come to binary search approach. First of all find out int n e ad size what is frequency n ba f if it comes more than time then it will be ours Kalpetta and A R Off 3 * n ba 4 guy, these are the and A R Off 3 * n ba 4 guy, these are the and A R Off 3 * n ba 4 guy, these are the three candidates we have okay int and candidate will look at these three elements okay now let's see right int left index equal to find left index okay off whose this candidate is okay zero to n Hey, this is my int, find out the right index. Similarly, find the right index using binary search from zero to n below. Er is right. And if right is minus left plus and if it is greater than the frequency, then return that this is our candidate. Is cuprate is return my last is ok now only find left and find right index is left ok it is very easy to see simple binary search first let's write how to find left most index int is candidate int is left index is int is right index And the vector of int and a is RR. Okay, first of all, let's store the result index equal to my. Okay, now let's start our binary search. It's a very basic binary search. Now look, pay attention, if my are of mid is equal to i is equal to which is my candidate which is the target, then it is possible that this is my left most index, is it the result index? Okay, so store mid in the middle. Stored the result in the index but since I want to find the left most index then I will go left and hit try so how to go left r = try so how to go left r = try so how to go left r = mid mine one used to do ok else if a r off mid if error off mid which is And this is from my target, so yes, we have to go right. To find our target, the target is not the name of the candidate, so we will go right. Do you remember how to go right? Do you remember from LE mid PSV and what will happen if else? What is mid is greater than mine, meaning candidate will be my left side, how did left go? Aa e mid myv ok and in the last we do not have to do anything, we have to index the return result, ok this is my find left index, similarly find. Right index will also be calculated in exactly the same way, here we would go left and there we would go right, just see, here I will write the same function as find, here instead of going left, I will do the right index, okay and see here if it is equal to the candidate. If the result gets erased in the index then it is stored that maybe this is my possible answer but I should go right so that I can get it in the other right. l = mid pv used to go right. l = mid pv used to go right. l = mid pv used to go right. Go right and remember here. But what we used to do was go left is fine, everything is very simple, we have done exactly what was told here, let's see by coloring, first example test cases should pass, right minus left plus and here left index will be right index. Will happen let's see indeed yes by submitting let's see hope fully shown cases any doubt raise it in the comment section I will try to help you out see you will go in next video thank you
Element Appearing More Than 25% In Sorted Array
distance-between-bus-stops
Given an integer array **sorted** in non-decreasing order, there is exactly one integer in the array that occurs more than 25% of the time, return that integer. **Example 1:** **Input:** arr = \[1,2,2,6,6,6,6,7,10\] **Output:** 6 **Example 2:** **Input:** arr = \[1,1\] **Output:** 1 **Constraints:** * `1 <= arr.length <= 104` * `0 <= arr[i] <= 105`
Find the distance between the two stops if the bus moved in clockwise or counterclockwise directions.
Array
Easy
null
48
welcome back to our channel in this video let us see the solution for rotate image given an n by n 2d matrix representing an image rotate the image by 90 degrees in clockwise direction directly that is without using another 2d matrix for example consider the input of 3x3 2d matrix here the first row becomes the last column and last row becomes the first column is our intended output so we will achieve this in just two steps step one is first row is moved to the last row and last row is moved to first row this is based on reversing the matrix in the second step that is last step the first row is moved to the first column and the last row of step one is moved to the last column and the middle row is moved to the middle column this is achieved by transposing the matrix now without much delay we will see this implementation in python as mentioned this is an optimal solution for rotate image with two steps step one being reverse the matrix and step two transpose the matrix i have taken the same matrix example that we saw in our explanation let me define a function rotate image which shall take matrix as the input parameter moving to the solution first step is to reverse the matrix so we will call a reverse method applied to our matrix and also we will invoke this function by calling rotate image and pass the matrix as its parameter having a print we can see the results immediately so at the end of step one we got our first row as 7 8 1 which is nothing but the last row of the input matrix and similarly first row of input matrix becomes the last row of our output matrix so we have done the step one with reversing method provided by taita the next step and the last step is the transpose of the reversed matrix for this we will do a nested for loop for i ranging to the length of matrix and j to the range of i and here we will do the transpose by swapping the values of matrix i of j from matrix j of i and matrix j of i with the value of matrix i of j so this does this simple transpose that is rows and columns of the matrix are exchanged and this transpose is applied on the result of step one so this is a very simple method optimal solution to rotate the image and we can see now the first row of our input matrix 1 2 3 becomes the last element that is last column and the last row becomes the first column we can test this by providing another matrix values let me take 4 by 4 matrix 5 1 9 11 2 4 8 10 13 3 6 7 15 14 12 16 and as such we can execute it and see if the solution is compatible we could see that first row 5 1 9 11 of our input matrix becomes the last element which means last column of the resultant matrix and similarly all other rows are moved or transposed to the column starting from the last hope you like the video please subscribe if you have not already subscribed and share with your friends
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
142
all right guys so welcome to another problem in this series for Linked list um this is problem 142 link list cycle two okay um so I'm assuming and I hope that you guys have done linked with cycle one and you guys have some basic intuition basic knowledge on link problems that contain linked lists okay and how to solve those problems so this problem reads given the head of a linked list return the node where the cycle begins if there is no cycle returned null okay I'm not going to read this paragraph here this is the same thing that is done in um linked list cycle one they give the same paragraph here it just basically explains that um that there's a cycle if you know by following the next pointer in the list if you keep going um that like you'll reach a position again okay so like in this case obviously the cycle is true here because you know that when we reach the end of the list the next pointer of negative four points back to two and it goes back to four eventually and it goes back so we have like this closed loop okay and I did this in terms of uh showing you guys explaining by like you know these Runners on a track right if you have a track you know it's just like a 400 meter Loop right despite of how fast the two runners or the three runners are running despite their Pace they're gonna eventually meet because it's a closed loop right if it's not a closed loop and obviously the faster runner will reach the end first okay so um taking that intuition and taking that knowledge that we learned from the first problem that I did and the serious link with Cycle One let's go ahead and Tackle this problem okay the follow-up for this problem okay the follow-up for this problem okay the follow-up for this problem is that we want to solve this using o of one space right we want to solve this in constant space um okay so using no additional memory right and we're going to do the same approach that we did previously okay so in linkless cycle one we said that we're going to have these two runners okay assuming that this is the first example here where we call them slow and fast okay slow is going to move equal to slow dot next it's going to move one position at a time but fast is going to move twice as fast as slow okay let me move fast not next on X okay so they both initially start here okay after the first iteration what's gonna happen slow will be here I'm sorry slow will be here and fast will be here okay the third iteration low is here and fast will be at five okay the next iteration slow moves one position okay so slow moves here uh let me put this up here just so it's better for readability and fast moves twice so if we follow this Arrow moves one to three and then the second time would be there okay so following that we see that there is a cycle here why because like I mentioned in the first problem fast and slower at the same position okay so that means that there must be a cycle because they meet okay this is known as our intersection okay this right here is called our intersection right where they meet okay what we want to do is find the node where the cycle begins in this case we want to find this position okay how do we do this when we have an intersection well it's very simple right we can think of after we find our intersection right which will be done in a different function we then go to our main function I would check the node where the cycle begins what we can do with this intersection is either grab s right we can grab s or F right or slow or fast pointer return that and then in our function that determines where the node the difference the node where the cycle begins we can then have another pointer right we're going to have these two new pointers again right or head right or our beginning of the cycle or beginning of the list will be here right we'll call that pointer one okay what is point of two gonna be well pointer 2 is going to be either slow or fast depending on which one we return and you're going to see that it doesn't matter which one we return slow or fast in that first intersection function okay so then P2 would be here okay this is P2 all we got to do now is move each pointer one position at a time okay and you'll see why if we move pointer one spot after the first iteration well pointer one will be here and pointer two will be here okay on the third iteration enter three will be here okay one two will be here on the third iteration sorry pointer one and where's point two going to be well pointer two is going to follow you know that it's here right what's gonna do is it's gonna follow this Arrow this is the end up in this same position and notice this right here is where the cycle begins okay and this is going to be able to solve any problem that has a cycle okay so let's go ahead and talk about the time complexion space complexity and complexity of course is over van Where What Where n is equal to the size of the linked list LL for short our space complexity well this is done in constant memory why because we only have additional memory for our slow in our fast and we also only have additional memory for P1 and P2 okay let's go ahead and solve this okay this is of course assuming you guys have basic knowledge with the first problem okay so we're going to create a new function which we'll call it get the intersection okay this is going to pass in as a parameter the link the head of the linked list right this is in return a node right this node that it's in return is going to be the quote-unquote intersection okay so of quote-unquote intersection okay so of quote-unquote intersection okay so of course we're going to go ahead and uh do our first check right if head is none we return none we have a slow and a fast that both start at head okay while what while fast is true and it's next pointer is true okay while these two things are true we're gonna move slow one position at a time and we're gonna move fast twice as fast okay when one of these conditions break we know that there's a cycle in the link list right this is the same this is the way to solve linkless cycle one while one of these break fast or fast on next there's a cycle but instead of returning the Boolean value we want to return the intersection which could be either slow or fast right because again here slow is here okay and fast is here they're both in the same spot so we can return either or it does not matter in this case let's just return fast right so this function is done now what I want to do now with this detect cycle function right the main function that the problem gave us is let's get that intersection value okay so intersection we know that it's this function and pass in the head why is that true because when we pass in this when we go to this function pass in the head over here it's going to come down here this will detect that there's a cycle right and it's going to spit out fast there's one thing here that I did not uh do is after updating these pointers right the main the Crux of this just to check if slow is equal to fast slow equals fast then we return fast okay sorry about this little typo at the end we return none because um when the loop breaks sorry for the confusion right when the loop breaks that means that there is no um cycle right if fast dot next points to none there is no cycle right it's a linked list without a loop we return none but if fast on X is true and fast is true and at some point slow and fast meet and we know there's a cycle and we're gonna return fast okay that's what this is going to do give us intersection okay now we need to get two pointers right well first let's check something else let's do another base check here right similar to what we did here but instead of the checking head we're gonna check if intersection is none return then right there is no intersection return done okay cool now what's the next thing to do okay well the next thing to do is to get our two pointers we know that pointer one will be equal to head pointer two will be equal to intersection I don't know what the problem is here that's weird okay um good oh I see I spelled this wrong intersection there we go and I spelled this one wrong again okay so P1 is head P2 is intersection how does this look in the drawing well that's this right we said that um in our drawing right he too or our intersection right will be at the value let me erase these right here I don't want to have too much on the screen so we said that intersection is going to be what's here whatever is highlighted will be intersection okay either the fast pointer or the slow pointer doesn't matter one of these is intersection okay and that's going to start at this position so I'll just put an i here and where does um the uh the first pointer start at well we're gonna say our first pointer is gonna start at the head of the list oh that's gonna start here intersection is going to be equal to P2 is going to start here all right hope that makes sense so let's go ahead and move these pointers one at a time because again going back to the drawing by moving the pointers one at a time I'm just gonna put P2 here P1 here I'm moving these two points one at a time what's gonna happen P2 will then go here after the first iteration and P1 there on the second iteration right P1 will go here and P2 of course following this Loop right here will end up where at the same spot as P1 so this is as I mentioned earlier the point of intersection so let's go ahead and do that while what while P1 does not equal to P2 that's gonna be this while loop okay right because if they do equal then we know that we can break out of this Loop and just we return either or okay so while they don't equal which initially they will not equal P1 will be at the head and P2 is at that intersection that we found E1 will equal to p1.x and P2 equals to E1 will equal to p1.x and P2 equals to E1 will equal to p1.x and P2 equals to p2.x p2.x p2.x good when this Loop breaks what happens P1 equals P2 well that's what we want right we want P1 to equal to P2 because that is the node that's intersect so what we can do is just return P1 okay we can similarly return P2 right it doesn't matter which one we return because they're both going to be at that node all right and this is the end of the problem right notice that this right here is and I'll put this in a comment linked list cycle one right that's finding the intersection and this right here is the main function that they gave us the detox cycle and this is getting that node value okay we run this is passes the test cases let's go ahead and submit this thank you guys for watching please be sure to like comment subscribe share it to your friends I hope this is informative for you if you guys have any uh concerns or comments on the way I'm explaining these problems please let me know via comment um so I can go ahead and try to fix that for you guys okay thank you guys so much have a great day bye
Linked List Cycle II
linked-list-cycle-ii
Given the `head` of a linked list, return _the node where the cycle begins. If there is no cycle, return_ `null`. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to (**0-indexed**). It is `-1` if there is no cycle. **Note that** `pos` **is not passed as a parameter**. **Do not modify** the linked list. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** tail connects to node index 1 **Explanation:** There is a cycle in the linked list, where tail connects to the second node. **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** tail connects to node index 0 **Explanation:** There is a cycle in the linked list, where tail connects to the first node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** no cycle **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Medium
141,287
138
hey everyone today we are going to show the little question copy list with random pointer so this is a quite wrong description so in summary so you are given like a link to this of links n and like this and each node has two pointers so one is a next pointer so pointing to next node so that's simple right and uh each node has another pointer So Random pointer is not always pointing to next so for example this pointer pointing no right and uh London pointer of second node is pointing first point all right something like that and then all we have to do is construct a deep copy of the list the Deep copy should consist of exactly and brand new node so yeah very straight to our question so we create in this case five node and then so create a completely brand new node so important thing is that Nano pointers in the new list should pointing to nodes in the original list so we can't create like a disk Point uh and this next Point has to be like this and this random Point does should be so original null here so we have to completely run new node so that's why our next notes should be like this something like that and uh random pointer is pointing to here so here is a node and then I got pointing like this and the random pointer of second node pointing this node something like that okay so this is a very straightforward question right so we just create the exact and brand new nodes so we start creating the node from beginning to rust so in this case first null and second node and the first node um next pointer on Fast note pointing to next and the random pointer pointing like I know something like that so right back here new oops and then so in the second node next node should be the next Point does pointing next node and a random node pointing fast mode right it's easy right but the problem is look at the South node so next points are pointing to next that's fine right but a random pointer pointing last node one but uh we still don't have a rational right so we can't point last note so this is a problem so how can we solve this problem to solve this question I use a hash map and we keep all nodes into the hashmap so now hashmap has regular seven oops seven thirteen eleven ten and the one and also we need the no right oops so now we have all values in hashmap and then um starting creating from beginning to last and so first of all so current should be seven so we access D7 and then so let's say oh like a seven and then um the next node in the random node so next node is starting right and then we have already starting so how can we access this setting so it's simple so I'm like a here hash map and uh so let's say current so current is now seven dot next should be next node right it's simple so next node should be starting so we can access this as in and then so next so this is a next so starting and uh random so this is a random pointer should be no right so how can we access after it's saying like a has map and uh current dot random yeah um yeah it's hard to write everything so let's say around so Random um yeah so and then so Random point the pointing no so we have null so that's why we can access null and set new um as a like a random pointer it's simple right and from starting so next pointer so we access like the same way again next uh node should be so current node is now starting and the current dot next and the random node access record current or random so next node should be 11. so 11. and then um next on London pointer is pointing seven so I think our current total rundown right pointing seven so we have seven so that's why like this and yeah here is a problem right so next node is 11. and so that's why current node is now 11 and the next Point next point of pointing 10 so this is a simple and then so London point of 11 is pointing last Node 1 right but we have already one so if hash and the key is current dot random is pointing one so we have one so that's why random pointer point in one right so that we can solve this problem yeah and later so we do the same thing and let me stop here because it's same explanation and then I think we can create a like a deep copy of the list and then all we have to do is just return like a hash and the key is a hit yeah so that is a basic idea to solve this question so let's jump into the code okay so let's write Circle first of all create a hash and uh initialized with like a long unknown so this is a four no and the current node should be head and there so we use a head again so I copy head to current and uh start looping why so first of all current so if currency exists so we keep the current node in the hashmap so hash energy is current equal so node in the current bar and uh current equal current dot next oops so now we don't have any link between nodes and then uh reset current with net and then start iterating again and then first of all let's say copy equal hash and G is a node so ending um adding a next in the random node and then copy dot next should be as I explained for you hash and uh current dot next right and then copy Dot random equal hash in the current dot random so after that update current equal current dot next and then in the end we return hash and add yeah that's it so let me submit it yeah looks good and the time complexity of this version should be order of n so that's because we edits all nodes in the linked list twice so o n plus o n so that's why time complexity is or n and the space complexity is also order of n because of a hash map yeah so that's all I have for you today if you like it please subscribe this channel hit the like button or leave your comment I will see you in the next question
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
53
let's all leak code 53 maximum sub-array let's all leak code 53 maximum sub-array let's all leak code 53 maximum sub-array so we're given an integer array of gnomes and we want to find the contiguous sub array containing at least one number which has the largest sum and then we want to return only the sum so this array has in positive numbers and it has negative numbers so that's what we have to keep in mind in this case the largest sum is 6 and it's just this middle portion of the array so the first thing you might try is just compute every single sub array right so let's first compute every single subarray starting at negative 2 there's one sub array there's 2 sub arrays there's 3 sub arrays and then we keep doing that until we got to the end right and then we could repeat the process for the second number so the sub array starting at 1 here another sub array starting at 1 here all the way until the end now we could repeat that same process for every number in the array so let's just write the pseudocode to see what that what kind of complexity this would yield so let's say we're starting the eye is gonna represent the starting value it's gonna be it's gonna range from zero all the way to the last number n minus 1 or the last index and minus 1 and then we want to get the ending index so I'm going to use J for the end of this sub array so we're gonna start at I and we're going to keep going until the end of the sub array or until the end of the entire array and minus 1 so this represents the start I represents the start J represents the end now we actually want to compute the sum of this sub array so we're gonna have a third loop for that right let's use KK is gonna range all the way from I to J right because that's what represents the sub array and then in here we'd compute the sum right now obviously this is really inefficient right the time complexity is n cubed it's obvious because we have 3 for loops so let's try to expand upon this let's see if we can make any shortcuts to improve it so the most obvious thing you'll probably notice is that we can save time when we're computing a sub array so if let's say we computed this sub array right and we want to compute the next sub-array we want to compute the next sub-array we want to compute the next sub-array was just one added element well we can save the result of this right and say it's our current summer or whatever and then to compute this sub array we just have to add this number over here right so we can just say current sum plus negative 1 and so this can save us time let's take a look at the time complexity of this solution so we're going to have another for loop which is going to represent the start so start is going to range from 0 all the way to n minus 1 and we're gonna have another loop for the end of the sub array J is going to range from I 2 the last index n minus 1 and then inside of the loop we're going to maintain our current sum and simply just add the number J each iteration of the loop right so this is a little more efficient o of N squared it's a pretty easy optimization to make and it improves your solution a lot but can we do even better than this so now the question you should ask yourself is do we have to compute every sub array starting at every single value in the array right do we have to start at every single value and compute every sub array that comes after it I don't think we do remember we're trying to find the maximum sub array we can use that knowledge to help us make a shortcut so let's take a look at this we have a negative 2 right so when we're starting here that's gonna be our max sum so far then we get to negative 2 plus 1 so this is negative 1 so far right do we actually need this negative number the negative numbers don't contribute anything in this case right so we can disk we can basically ignore that value right once we get here we can basically say this negative value this negative prefix that came before positive 1 isn't gonna help us at all so let's not even consider it so next do we get to this negative 3 now up until here our total sum is negative 2 right so then we get to this 4 this is a negative prefix that came before negative too right so we can say up until this point we're not even gonna consider what came before so this one and negative three aren't gonna help us at all just ignore them now we get to a negative one so the prefix that came before this was a positive four so we're gonna not delete it from our list we're gonna keep that positive four and add it to this negative one so now we're gonna be a three so far now we get to a positive two right even though there's a negative one that came before it well there was a positive forward that came before that so if we get rid of this negative one we also have to get rid of the positive four which we don't want to do remember we have to keep the sub-array contiguous so I'm not gonna sub-array contiguous so I'm not gonna sub-array contiguous so I'm not gonna chop this portion off I'm gonna keep it now we're gonna add two to it so now we're gonna be at five then we're gonna get this one we're gonna add it and get our sub array of six and this is the result so far but let's keep going and see what happens next will have a negative five right so minus five now we're at one so obviously we decreased our sub array but we know this negative five is not going to be deleted because we had a positive six portion comprised of these four elements that were that came before that lastly we get a positive four again add that our sum is still five so we see that the max of our a was this portion of these four elements which totaled to six now this was a linear time algorithm it's kind of like a sliding window right we keep incrementing our right pointer as we go through the array right but our left pointer keeps getting shifted if we ever have a negative prefix like this negative two or this negative two portion comprised of these two elements so anytime we get a negative prefix we remove it and for me it kind of helps me to think about this as like a sliding window and since it's a linear time algorithm the overall time complexity is Big O of n we didn't need any extra memory we just had to go through the array removing any negative prefix as we computed the total sum okay so now let's code it so we can initialize our Max sub-array so we can initialize our Max sub-array so we can initialize our Max sub-array to the first value in the array that's like the default value that we're going to give it because we have to give it something and it can't be zero because we know we have negative values in this array and we know the array is non empty so the zeroth value of the array is always going to exist and we're going to be constantly computing our current sum so I'm going to initialize that to zero so let's go through each number in nomes now remember if we had a negative prefix we're going to remove that portion from our current sum so the way that we can check this is just check if current sum is at any point negative if it's less than zero we're just going to reset it back to zero and then after that we can add our current number to this will make sure that we're always computing the maximum that we can now this current sum could be the possible maximum so we're just going to update our max sub array to the maximum of itself as well as the max that we just computed after we're done with that we'll return whatever we computed as the max sub array I hope this helps show you kind of the intuition behind the solution of this problem if it was helpful leave a like and subscribe and thank you for watching
Maximum Subarray
maximum-subarray
Given an integer array `nums`, find the subarray with the largest sum, and return _its sum_. **Example 1:** **Input:** nums = \[-2,1,-3,4,-1,2,1,-5,4\] **Output:** 6 **Explanation:** The subarray \[4,-1,2,1\] has the largest sum 6. **Example 2:** **Input:** nums = \[1\] **Output:** 1 **Explanation:** The subarray \[1\] has the largest sum 1. **Example 3:** **Input:** nums = \[5,4,-1,7,8\] **Output:** 23 **Explanation:** The subarray \[5,4,-1,7,8\] has the largest sum 23. **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` **Follow up:** If you have figured out the `O(n)` solution, try coding another solution using the **divide and conquer** approach, which is more subtle.
null
Array,Divide and Conquer,Dynamic Programming
Easy
121,152,697,1020,1849,1893
309
so welcome back to this another daily code problem so today it's called best time to buy and sell stock with cooldown and so it's a dynamic programming problem where essentially you're given this array called prices and these represent a certain stock price at a particular day and so on day Zero it would have a price of one but then on day one it then has a price of two and then on the second day it then has a price of three and so essentially and this is kind of a common problem-only this is kind of a common problem-only this is kind of a common problem-only code I think there's a lot of variations here um all to do with like yeah buying selling and this is the second version so I think this is like the third version um with this edition of like a cooldown and so essentially you want to maximize so this is a maximization problem where you can either buy and sell the stock but you can only do like one operation at a time and so you're either like um one you're buying or you could be selling or you could be like in the cool down state okay and so essentially at any point you can say Okay I want to buy this but once you've bought it you then have to either sell it at one point but if you're selling you can't like buy something while you're selling so essentially you can only perform a one operation at a time or it can only be at one state at a time uh what this cooldown means is just that after you sold your stock you have to wait one day until you can start buying again okay so say if you bought here and then you sold it for two here you would then have to skip over this where it's at three and then kind of consider onwards from this point on another option is you can just like skip you don't have to buy or sell or cool down at any point in time like you can kind of wait a few days before you buy or sell or what whatever so um but yeah so let's go ahead and implement this so essentially what you should do is you should think about what the recursive relationship would look like and so you start at like Day Zero and at Day Zero you're kind of in the buying state and there's kind of three or really just two different paths at this point that you can go down one is you can either buy it or you can skip that day and so since you're at index 0 you can say okay why don't we go ahead and buy this and so at that point we're kind of subtracting one from here so since it has a cost of one and now we're going to increment to the next uh location and now we're going to be in the selling state or you can just kind of skip to the next step which is kind of zero because it has zero cost and so now you're at the next index but then you're still in this buying State let's just expand One More Level here so okay at this point on you kind of have two different paths you can either sell this for two so plus two and essentially that would then be okay now you move on to index two and you're now in the cooldown state and then from this point on here you could either also say Okay rather than selling it and getting two why don't we just skip to the next step and then say okay now we're at index two but we're still in this selling State okay I won't go any further but you can kind of imagine that this goes on further this cool down state after you wait a day you would then be say on index three and in the buying State now all right and so let's go ahead and implement this so if we look at that kind of top-down approach kind of top-down approach kind of top-down approach um typically what you want to do is you define some DP function here which we're going to return the result at the end of here and so what you wanted to find like your base case here and so okay what would that be in this case well that's okay what we're going to be having to keep track of is exactly what I was showing you at each point in time we're having a particular State and a particular index and so let's keep track of that so the state is going to be basically three possible things which is you can either be buying or selling or in that kind of cool down wait one day state and so essentially then now that we have this information we can Define our base case wherever kind of we're at the very end of time here where we're kind of hitting the end of this length of the prices well there's nothing you can do any more so you might as well just start propagating your answer upwards so if I is equal to or greater than the length of this input array let's just go ahead and return zero and we're just returning zero in this case because well there's nothing else we can really do here um we simply want to start returning our answer and kind of propagating those results up the chain um you don't there's no added cost or added benefit of reaching this NK so you just return zero otherwise then you want to be kind of considering these decisions that I showed you in that kind of recursive relationship and so let's just quickly fill this out though so we start at index zero and initially we're going to be in this kind of by state all right and so essentially we're going to use uh kind of this switch case in Python here for matching these possible states that we could be on and so essentially the first case that we could have is okay what if we're in the buy state right we could also have the cell state um and then finally there's just the kind of default State here um which will be kind of the cool down state all right and so to handle the cooldown state what that's going to be is well we simply want to move forward in time and so that just means okay let's just increment to the next step and then now we'll be no longer in the cooldown state but we'll be back in the buy state all right but we also want to fill out the buy and sell cases here and so the buy case is going to be okay there's two different paths that we can have same with the cell case and that's going to be okay we want to take the maximum here so let's return the maximum of these two possible paths and so the two possible passes we can either buy the whatever the current stock price is or we can say why don't I just skip this current day and look at buying maybe the next day all right so let's say that so let's go to the next day and let's say that we did buy this day so now we'll be moving on to this cell estate but then also we want to be basically since we just bought subtracting what it costs to buy that stock and so that's going to be the prices at the current index but naturally the other choice is we just stay in the Spy State and we don't buy anything here all right so we want to do something very similar but now for the sell State here and so what that's going to be is okay say we're in the cell State we can either say that all right what if we did sell we then move on to the cooldown state right because I have to wait at least one day or we can simply say that okay rather than gaining these benefits of selling at this purchase price why don't we say that we're still in the cell state and instead just remain there but simply say Okay won't we move or try to sell at a later date all right and so this is pretty good but the only thing that remains here is that we have to Cache this and that just helps with the time complexity here and helps with minimization all right and uh success so yeah that's uh today's daily legal problem so I hope that helped a little bit and good luck with the rest your algorithms thanks for watching
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
42
hello boys and girls and welcome to another episode of your favorite algorithm channel my name is Ryan powers and today I'm gonna be taking you through leet code 42 trapping rainwater so let's introduce the problem given n non-negative integers representing an non-negative integers representing an non-negative integers representing an elevation map where the width of each bar is 1 compute how much water it is able to trap after rain so we have this beautiful diagram over here which depicts the wall heights which is represented by our input array here so if we look at our input array 0 corresponds to a wall height of 0 1 correspond corresponds to a wall height of 1 and then another 0 here corresponds to a wall height of 0 and then because this wall height here is lower than the one to its left and it's right on the Sun a hint because this 0 here is lower than the wall to its left and it's right it is able to trap water right so I mean visually that it's an easy way to kind of think about this problem we can look at it and I sect it from a visual standpoint and understand where the water is going to being counted but the tricky part is how can we programmatically figure out a way to find all of the water that is trapped by all of these different walls so that is the challenge that I am giving to you that was forwarded hard that I am forwarding on to you that was given to me by leaked code that's the problem gonna be a tackling today and as always I suggest that you try to figure out the problem on your own first and if you can't figure it out or you just want to see how I solved it then check out the video otherwise if you're ready to get started come with me the white board on the screen here I have a visual representation of our example problem I will be it a slightly worse visual representation but a visual representation nonetheless so what I want to talk about is what is the important information that we can gather to solve this problem so and we just look at an individual square let's just look at one so we're gonna look at this square right here and figure out how can we figure out every square that we are at how much water couldn't hold so we'll look at this square here and just to make sure that we're on the same page here this down here is our array which represents our wall Heights and this here just tells us how high the current wall is it's pretty approximate but that's about what it is okay so let's look at this square right here how can we tell how much water it has well the water that is contained at any given space or this space more specifically is the minimum of the left wall and the right wall - of the left wall and the right wall - of the left wall and the right wall - its own wall so the wall at that index - its own wall so the wall at that index - its own wall so the wall at that index - index wall okay so if we look at that what are these values well this is one here right so that's a one this here this is a two okay and then this right here is a zero so using this equation right here we can decipher that the wall height here the minimum is one okay - zero minimum is one okay - zero minimum is one okay - zero okay that equals one great so we've figured out a way to find out how much water there is at any given space so let's just add these up here so that first one is one we'll put that over there okay all right so that first one is one we'll put that over here and now let's look at this space right here just this box right here how do we figure out how much water there is well let's look at the Maxwell to the right the Maxwell to the left and then subtract its own wall height to figure out how much water could hold so what's the max wall to the left well that's two what's the max wall to the right well that's three so what's its own wall well that is one right so we'll take the minimum of these two which is two and we'll subtract one so that's one so we know that we can only hold one unit of water here great so we figured out another one we'll add that one over here okay plus one great okay what about this spot right here okay Maxwell to the left all right well that's two Maxwell to the right okay that's three so what's the minimum of that okay it's two great so now we need to just subtract its current wall its own wallet its own index well that's zero okay great so we figured out that's too awesome so we'll add that up actually get rid of that arrow we'll add that up all right and now look at this spot right here what's the max well to the right well it's three right here what about the max wall to the left well that's too awesome so we know that it can hold a minimum wall height of two and then its own wall height is one well that equals one great let's add that up to our current water can water holding capacity okay let's check this last one right here well what's the max wall to the right well that's two Maxwell to the left that's three okay what's the minimum that's two okay - its own wall height that's two okay - its own wall height that's two okay - its own wall height which is one great okay one so we figured out that one so we know what they all are now so we can add these up so one two three four five and six awesome so we found our answer so what's the information that we need at every index all we need to figure out is what is the left wall height and what is the right wall height and then we can subtract the wall height of the current index and get our answer so this is the strategy we're going to use to solve this problem and we're do it in end time so we could we can easily just figure out at each position just by iterating all the way to the end figuring out with the maxes and iterating all the way to the left figuring out what the max is there but we can do this programmatically and store some of this information and use dynamic programming to solve this problem and that's what we're gonna do so let's go over how that's going to look in the next section on the screen here I have three arrays so I have a ray for storing our left wall height max well height values we have the heights array which is just the array representing the wall height at every index and then we have a right array here which is going to store the values of our max right wall at every index so how are we going to do this how are we going to programmatically fill in the values for the max left wall and right wall as we iterate through this heights Heights array well if we look at our Heights array all we need to do is look at the value to the left of every number and just check to see what is the height of the wall directly to my left and we can fill that in well there's nothing here to the left so the first value we're going to fill in is zero right so we're gonna fill in zero and we'll move on to our next value here and we're gonna look to the left here and we're going to say okay well what is the value of the wall directly to my life well it's zero but we also have stored up until this point the max wall height that we've seen up until this point right so that's comparing B sorry that's terrible that's comparing these two numbers right here right so right here it's just zero and zero so at every iteration we're gonna take the max of these two numbers this number right here is the maximum value that I have seen to this point and then this value right here is what is the height of the wall directly to my left so as we fill this in you'll see that we are keep we're updating our max left wall height at every iteration storing that at every index which will allow us to solve this problem when we go back through subtracting the left taking the minimum of the left and right while height as we discussed before and subtracting from the current index to get the amount of water that we could trap at that specific index so let's go through a round of solving this problem just get a better idea of how this is going to work okay so we've already decided that we're going to store a zero at this index here and we're going to move on to our next index and we're going to look to our left and we're going to compare these two numbers this number being the maximum wall height we've seen to this point and this other number here being the max or the value directly to the left of the current index row well one is greater than zero so we're going to take the maximum which is one and store it at this index okay and now we're going to go to two and we're going to check the value directly to its left and we're going to compare it with the value the maximum value we've seen to this point well one is greater than zero so we're going to keep zero or keep one and move on to our next value comparing it to the value in our left and the maximum wall we've seen at this point well 2 is greater than that number so we're going to keep two and we're gonna move on to our next value looking to our left and comparing it to the maximum value we've seen to this point well that's two and one well two is greater than one so we're going to keep two and we're going to move on to our next value looking to the value to our left comparing it to the value the greatest value we've seen at this point two is greater than zero so we're going to keep two and we're going to keep doing this looking to our left comparing it to the greatest value we've seen at this point which is two so we're going to keep two moving on again comparing to the value to our left with the greatest value we've seen at this point well 3 is greater than 2 so we can update our max wall height at this index to be 3 for the wall to our left and we'll look at this value comparing to our left comparing with the greatest I'll be seen at this point well 3 is greater than 2 so we're going to keep 3 and we'll this index comparing to the valley to the left and the greatest value we've seen at this point which is 3 &amp; 3 is seen at this point which is 3 &amp; 3 is seen at this point which is 3 &amp; 3 is greater so we're going to keep 3 and then here we'll look to our left again and we'll compare with this value and keep 3 great so what have we done here well first of all it looks like I've kind of run off the board here with this array I didn't line that up very well but um so we'll just put that there okay so what do we have here well in this left array now we have stored at every single index a reference to the greatest wall height to the left of that current number so now we all we need to do is go through our right wall index or go through our Heights index again iterating this way looking at the value to the right and updating our max right wall so let's do that really quick so we'll start here and we'll look - all right and we'll see we'll look - all right and we'll see we'll look - all right and we'll see there's nothing there so we'll fill in a zero will go to here too - looking to our left too - looking to our left too - looking to our left well that's a 1 that's greater so we'll keep the 1 now look at this index well 2 is greater than 1 so we're going to keep - and now this index well 2 is to keep - and now this index well 2 is to keep - and now this index well 2 is greater than 1 again so we'll keep 2 comparing again three and then what's to the right of our three here well that's a two and our current Maxwell height is two so we'll just keep two and we're going to do this comparing these numbers at every iteration so let's go ahead and fill the just fill these in so we have one and three we'll keep three we have zero and three we're going to keep three again now we have one and three so we'll keep three two and three keeping three zero and three still keeping three and we'll just fill in three all the way to the end so now that we have gone through and filled out all of the values for the left which is right here and our right ball our right wall values which is here well we can compare these three values together these three values and we can get how much water we can store this index well we've already said that we want to get the max or the minimum value of the left and right wall and then we want to subtract that from the or we want to subtract the index from that value so what do we get here well our minimum height is zero so this is gonna this is going to evaluate to zero so we don't have anything here our minimum height here is also zero so we're not going to get anything from this index either well what about this spot here well our minimum height is one right because one and three the min of one and three is 1 and then we have a height of zero so we'll set so we'll do one minus zero and we'll keep one okay so moving on to our next index our min height is one but our height at this index is 2 well that's going to give us a negative number so we can't store negative water so we'll just move on to the next one so what's the minimum height of three and two well that's two so we can subtract one from that and that's going to give us a value of 1 so we'll store one that index so what's the minimum height of three and two well that's two and we could subtract zero from that well that's going to give us a value of 2 and what about here three and two well that's two subtracting one that's going to give us a value of one and then here we have to and to put our height is three so that's gonna give us a negative value we can't store anything there similarly here that's going to give us a zero value so we can't store anything there what about here two and three well the minimum value is two and the height this index is one so if we subtract one from two that gives us one so we can fill that in here and then what about here we can't store anything here and we also can't store anything so what is this what does this all add up to well this is one two three four five and six which is our answer okay great so now that we've kind of gone through a round of solving this problem and we have under a better understanding of the strategy let's go ahead and see what this looks like in code on the screen here we have our trap function so we're going to build out all the functionality for this function in our trap function so the first thing we need to do is create an array to store all of our left wall maxes right our array of left wall references so let's create a Const of left to store all those left walls and we'll just initialize it as an array with a value 0 so 0 is just going to account for that first index where when we look to the left there's no index there it's undefined like it's off the array right so we're going to initialize it to 0 and then we also need to create a variable which we'll call right for storing our right wall mix so our right well max we're just going to update it in real time and calculate our values as we go because we don't need to store the right wall max we already had the left wall max so as we're going back through the array calculating the right wall max we can get the amount of water at that index so we only need to loop through this two times so we'll store that in a variable right and then we also need a variable total for tracking our totals right as we're calculating our sums along the way we need to total them up so we'll store that in a variable total and then we need to loop through our array so we'll let I be equal to 1 because you don't want to start at that first index we want look to the value to the left to get these left wall values so we'll start at the first index so we'll let I be equal to one and then a while I is less than height dot length well we want to keep looping so what are we going to do at every iteration well we're going to push to left the maximum of the left at I minus 1 so the value to the left or the highest wall value that we've just seen is left at I minus 1 so that's the last value we've pushed to our left wall values and then we want to evaluate the current height that we're looking at in the array so that's going to be a height I minus 1 so we want the maximum of these two values and we want to store that in our left wall array so that's all the logic we need for storing these this left wall this left will value so now what do we need to do well we need to loop back over our a from the other side and get our right wall values so we'll let J will define a variable J so we'll let J be equal to pipe dot length and we want to start at minus 2 because you want to start the very last index that's why we're initializing right to 0 we want to start at the very last index minus 1 right which is going to be height dot length minus 2 so well J is greater than or equal to 0 we want to keep looping so we'll do J minus and now we need to recalculate right so what's right going to be equal to well right is going to be equal to the math dot max of right and then the current wall to the right which is height at J plus 1 so that's going to give us the maximum wall height at every iteration and now we can calculate a sum right so we can let some be equal to the minimum right we need the minimum of these two walls so it's the math dot min of write our right wall and our left wall so that's just going to be our left wall @j and then we need to subtract the @j and then we need to subtract the @j and then we need to subtract the current height of the wall that we're on so that is going to be height at J so that's going to give us our sum so now we just need to check to see if our sum is greater than zero well then we want to add it to our total if it's not greater than zero then we just want to let it pass because we can't collect negative or zero or rainwater so we're only going to be totaling up our sums of numbers greater than zero and at the very end we just want to return our total so just to do a little bit of recap so we defined a variable left and we initialized it to zero so zero is accounting for that index to the left that is not inside of our array and then we initialize a variable right to zero to account for our right wall and we're going to be tracking that as we go then we have a total initialize to zero so we're looping over the array pushing in at every iteration the maximum of the last wall height that we've seen the max last wall height we've seen which is our maximum and then the height at I minus one which is the value directly to the left of the current index that were iterating on and then we collect the right wall max so at every iteration where we're reassigning the right wall to be the maximum of the current max right wall which is right and then the wall directly to the right of the current index which is height at J plus 1 because we're iterating from the back and then at every iteration we are going to calculate the sum which is just going to be the minimum of the right wall and the left wall minus the height at that current index so after we calculate the sum if it's greater than zero then we're going to add that to our total so let's see how we did okay great 88 milliseconds let me run that one more time just see if we can get a little bit better okay all right 80 I like that looks a little bit better that makes me feel good so as always Lee code has a conspiracy against me a conspiracy against all of us because we're learning way too much about algorithms the word that we're not going to need them anymore so they make our run times look terrible so what are we going to do we're going to rip the best code to ever grace the presence of leet code and we're going to run it against our code and see who comes out on top all right so here we go let's see this is this looks like this looks pretty good here so let's grab this and go back to our code all right great and we'll paste this in here and run it ah all right they beat us this time we're just fine for milliseconds it's okay I could I can handle it maybe we'll just run it one more time to make sure they're super good okay great 84 milliseconds we're in the same ballpark here anyway so I think what I want to point out here is let's get back to our code because it's cleaner but what I want to talk about well we didn't really talk about the runtime complexity so what's the runtime complexity of this problem well we're looping once to get me the left max wall right and then we're looping again to get the right max wall so we're doing two loops through which is a time complexity of 2n right and n is in terms of the array that we're passing in the height array that we're passing it but what about the space complexity well the space complexity is also n right because we're storing all those references to our left wall right we had to store all of our left wall references so we could calculate the amount of water that we have at each iteration so our space complexity is also in the order of N anyways I hope you enjoyed this video I hope you learned something and I hope to see you in the next one
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,325
hey everyone uh today i'll be going over a problem uh 1325 on leak code delete leaves with a given value so we're given a binary tree and we need to delete all the leaf nodes that have a value the trick is when you delete a leaf node uh if another node becomes a new leaf and also has the target that needs to be deleted that one needs to be deleted as well so it kind of like bubbles up so naively because of this like condition here uh naively what you might want to do is if we look at this example right here you might want to just like go through the tree find all the leaves check the leaves if they have the target and delete them like return null on them and that's kind of what you do but the problem is you have to like bubble up right so like if you look at the example we remove this two but then this two became the leaf and we have to remove that as well so you also have to like prune it you know you have to prune everything so moving on if we delete this here so the trick is actually pretty simple and we can do this recursively uh just to keep things easy uh so what we actually want to do is as always you need a base case right so if the root is null we're just going to return null uh the reason being is if we come across a null node even after deleting this entire tree that node is still going to be null so that's why you do this um so what you want to do and i actually don't want to uh change anything yet or build the left and right some trees let's handle the logic of whether this is a leaf or not so let's just check if this is a leaf so if it's a leaf what does that mean it means it has no children nodes and it neither left or right that means it's a leaf so if root.val equals no so if root.val equals no so if root.val equals no and sorry not root.left and sorry not root.left and sorry not root.left is equal to null and root.right is equal to null and root.right is equal to null and root.right is equal to null and also root.value is equal to target and also root.value is equal to target and also root.value is equal to target so basically this is just asking is this a node that needs to be print if this is the case then we're going to return a null why do we return null because this node should be deleted and deleting it just means that this node becomes null so and you can do this and you can even like uh return root the thing is that now we need to figure out how are we going to recurse down the left and right so trees and figure out this logic and where should we put it for that matter well if you think about it we're actually having to bubble up so we want to delete everything in the left and right sub trees prune everything in the left and right subtrees before we can figure out if this is going to be a node we need to delete like if you look an example this one got pruned and this one got pruned so what does that tell you that tells you that you have to actually build the left and right subtrees before you do any of this logic here so we'll do exactly that we'll do it right before so let's build the left subtree or prune it and we're just going to take this here and go down the left side and then target and we'll take that again and uh do it for the right side so we'll go like that and then this actually should be good right here so let's run this and looks like it's pretty good let's submit it and yeah a hundred percent uh it's pretty good uh the space is thirty percent uh because it's done recursively so uh the requisite call stack user space so let's talk about time and space so time is actually going to be worst case of n uh the reason being is the worst case is that we have to actually find every single node right and we do have to search every single node to find the leaves so we have to reach the end so it's going gonna be o n where n is the number of nodes uh space is worst case going to be o um depth of tree and that's just for the recursive call stack right it's just gonna be the max depth of the tree uh so yeah and that's pretty much it uh just a really easy problem even though it's medium apparently yeah just wanted to go through the solution thank you for watching
Delete Leaves With a Given Value
path-with-maximum-probability
Given a binary tree `root` and an integer `target`, delete all the **leaf nodes** with value `target`. Note that once you delete a leaf node with value `target`**,** if its parent node becomes a leaf node and has the value `target`, it should also be deleted (you need to continue doing that until you cannot). **Example 1:** **Input:** root = \[1,2,3,2,null,2,4\], target = 2 **Output:** \[1,null,3,null,4\] **Explanation:** Leaf nodes in green with value (target = 2) are removed (Picture in left). After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). **Example 2:** **Input:** root = \[1,3,3,3,2\], target = 3 **Output:** \[1,3,null,null,2\] **Example 3:** **Input:** root = \[1,2,null,2,null,2\], target = 2 **Output:** \[1\] **Explanation:** Leaf nodes in green with value (target = 2) are removed at each step. **Constraints:** * The number of nodes in the tree is in the range `[1, 3000]`. * `1 <= Node.val, target <= 1000`
Multiplying probabilities will result in precision errors. Take log probabilities to sum up numbers instead of multiplying them. Use Dijkstra's algorithm to find the minimum path between the two nodes after negating all costs.
Graph,Heap (Priority Queue),Shortest Path
Medium
2090
485
question number 485 max consecutive ones we're still on the easy problems here given the binary numbers return the maximum number of consecutive ones in the array okay so let's look at the an example here so what does it mean so if you look at one zero one you'll figure out the maximum ones is actually three here because first you had um two once and then after that you have three ones so you basically two ones you uh you ha you see the zero and that's why you stop there because it's not a consecutive one anymore then you count again from one and then you go to three here so um what we want to do is take the max or the first of all the count of the consecutive ones so that's one thing we want to do so like if we have here something like let's say um 1 0 1. first we start with counting one so i'm going to say count equals to zero um so when we look at one it will add one then we look at the next one add another one so it will be two then here it just stops then again you start with counting again so here when you start it means like you're making count zero again so that's an important thing uh so let's uh write a loop here for num in nums if num equal to 1 then you basically say count plus equal to 1. so if you see that you're just adding to it else what do you do so there's another thing i want to um basically uh bring to the picture here and that is a max value so we have the count we have like the count of the consecutive ones but we also need to store a max value there so like if you hit the zero you check if that count is bigger than the max value or not if it's not you don't care about if it is you put the max value uh that particular account value so for example let's say max value i'm going to say max val okay my spell will be um zero here yeah we start with uh zero here so then we say if you see a zero let's just put let's say uh max value max val equals to max of uh nice val and count and you can see that this works very i mean let's just uh finish this up and then i'll show you that if it works or not uh so then after that what we want to do is uh make count zero because we just hit zero here so we just wanna make that zero there so that works now that we have this we wanna say that um okay so there's one uh big problem with this uh you can return let's return this sorry let's return this next valve but that's not going to give you the uh the actual value here and the reason is that uh when you hit the end of it you didn't really see a zero here so you just have to check before this um if a count is not equal to zero so there is a there's a count that has been like uh at the end of it there's been like let's say one or two ones or three ones or whatever ones then you we want to check um with the max value with that count number also so the last one so we do this part again we just say here max value equals to this i think this uh yeah so this works now so you basically have that uh you have checked the last uh count also and saw if that's bigger than the max value or not so this should work and yeah that worked here um so uh there is so instead of this you could have said something like if the max val is less than count uh max val equal to count but you could have said this instead of that and it wouldn't have made any changes here so like if you just comment out this you'll see that works uh perfectly yeah so that works also and but i don't want to do that this one's a one liner basically um so i'm just gonna stick with this another thing that you could have done in the whole thing the process is that instead of taking a max value you could have done uh you could have like put all the counts in a list and then look through the list at the end and taken the max value of that list but i mean that's a kind of like a two um parts like uh like two sections to do and as opposed to this one which is like you're doing it in one shot basically looping through it one time uh i think uh inside uh somewhere i read that maybe it said like do it in one shot but basically i wanted to do it in one shot anyway even if you didn't ask it so you're basically looping through the whole thing taking uh track of the counts and also the max value checking it with the max value with the count updating it again and then also checking the last one and then just returning that max value that's how you do this question number 485 max consecutive ones yep so
Max Consecutive Ones
max-consecutive-ones
Given a binary array `nums`, return _the maximum number of consecutive_ `1`_'s in the array_. **Example 1:** **Input:** nums = \[1,1,0,1,1,1\] **Output:** 3 **Explanation:** The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. **Example 2:** **Input:** nums = \[1,0,1,1,0,1\] **Output:** 2 **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterward is to find the longest such window and return the size.
Array
Easy
487,1046,1542,1999
622
hi today i'll be talking about my circular queue from lead code and i'm going to approach this solution a bit differently now how do i know how many variables i have to declare well i'll start by looking through these methods in the class and start to see which are the ones are the easiest to solve so if we want to check if a queue is empty well basically we need to get the current size of the queue so i need a variable that checks the current size now if i want to know if a queue is full i can take that current size so i can take that variable that checks the current size and then i can compare it to the full length of the queue that has been initiated in this case it's k so in this problem they're going to tell us that the size of the queue that they want to be implemented is k so compare the above variable to the size of the initiated queue so just like that i already know that i will need two variables the first variable will be simply the size so i can do as i know that the self.size as of now as i know that the self.size as of now as i know that the self.size as of now is zero and as i ink q or dq this chart this um this size will change so i've already done a method return self.size equal zero so if self.size self.size equal zero so if self.size self.size equal zero so if self.size equals zero this variable will become true and therefore is empty is true tick now what did i say here i needed something to compare the above variable to the size of the queue well okay what is the size of the queue let's call that max size and the size of the queue is simply k then we can come down here and say hey you know what if the size equals the max size okay then it will return true and just like that i have finished two methods so and i got my two variables here now let's look at the ink queue enqueue is basically adding a variable to the queue and we will solve this using an array so what's the first thing we can check well we want to check that it's not full so if is full so if um the method down there tells us that this q is full then we simply return false because it's full similarly we can do this to the dq if it's empty then i have nothing else to remove from the list then again i can return false because in the question it says i assume you read the question says it returns for true if it's able to do a method or false otherwise so we have now populated the next i need a variable that gives me the value in the front and i need another variable that gives me the value at the rear so simply i can do self.front equals zero self.front equals zero self.front equals zero and self.trigger and self.trigger and self.trigger equal minus one well zero is the front and minus one is at the end and then these have to be pointing at some sort of array so i can then create an array call itself dot array and the size of that array will be 0 times k and k is the number of items in the list so if it's 10 items then i'm just going to create a list with 10 items with the value of 0. so i would like you to give me the value in the front of the array well the first thing you want to do you want to check that it's not empty because if it's empty obviously i'm not able to give that array so if it's not empty and again i'm going to call the other method i had here then i want you to jump into that array and give me the value in the front so in this case if there has been no inque or dq and there or and there's a value in there so that will be zero so self. front will be zero and whatever array you'll have in this case it'll get zero and the same thing let's do this else minus one so basically if it is actually empty then just give me back minus one and here you would see it is in the list get the front item from the queue if the queue is empty return minus one same thing with the rear if the rear is not empty then please give me the value at the rear else return -1 and i forgot to return as specified by the question here so now i have solved four methods um now let's see so now in the inque if self is full then return false but what if it's not full what if the inque is not full well basically i will want to add this value to the queue to the array so what i can think of from these variables right here well the first thing that's going to happen my size will increment by one okay and if it increments by one i also need to add the value so in this case the self dot array some index i'm just going to keep it here for now will equal the value so this value here will be added to the array but where will i exactly add it well i'm going to add it to the rear well why not the front because if you imagine an array they don't have a diagram here but if you imagine this array or q the front will stay on the left side while the rear will keep on incrementing as we add values so we will increment the rear by this value but since the rear is minus one we cannot keep on changing this minus one as we increment this rear value should also change every time we enqueue a value so what will we change it with well basically we're gonna add it with one so this minus one here we'll just add it by one in the first iteration that will be zero obviously where the front and the rear will be the same and we're gonna add this modular operator which ensures that we are not overflowing more than the end so what does that mean if my max size is 10 and my rear is pointing at 9 and when it reaches 10 then i would that will be the end so then you would want to add at the beginning of the queue so let's say my max size is equal to 10 so let's just do it that way and i have now reached the end ten well obviously your array goes from zero to nine so when it's at ten it should add at the beginning so in this case it will give you zero if the self rear is eleven then it will become one but as long as you're under the max size then you would always get the exact location this is the modulus operator in python and then you want to return true as specified by the question if this function is returned true if the function executes correctly then you would like to return true similarly we're going to do the same thing in dq but instead of changing the rear you want to change the front so again off the top of my head when i'm dq'ing well obviously the size is going to go down by one and wherever the self.front is pointing at i'm going to increment it with one and i want to make sure that i'm not overflowing so i'm going to do the same exact thing now if i hit submit i have few errors let's see well obviously first thing i have not returned through here i click too early and let me quickly scan i see i have a spelling mistake here and it's finished and one can ask me hey when we're dq-ing why is the front when we're dq-ing why is the front when we're dq-ing why is the front getting iterated by one well basically because this is a queue which follows the principle of first in first out the values that were added first have to be removed first so when the pointer of the front iterates by one so in our case it goes from zero to one then we have removed the first value that was added to the queue please hit like and subscribe to this channel if you have any questions please leave it in the comment section below thanks for watching
Design Circular Queue
design-circular-queue
Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer ". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. Implement the `MyCircularQueue` class: * `MyCircularQueue(k)` Initializes the object with the size of the queue to be `k`. * `int Front()` Gets the front item from the queue. If the queue is empty, return `-1`. * `int Rear()` Gets the last item from the queue. If the queue is empty, return `-1`. * `boolean enQueue(int value)` Inserts an element into the circular queue. Return `true` if the operation is successful. * `boolean deQueue()` Deletes an element from the circular queue. Return `true` if the operation is successful. * `boolean isEmpty()` Checks whether the circular queue is empty or not. * `boolean isFull()` Checks whether the circular queue is full or not. You must solve the problem without using the built-in queue data structure in your programming language. **Example 1:** **Input** \[ "MyCircularQueue ", "enQueue ", "enQueue ", "enQueue ", "enQueue ", "Rear ", "isFull ", "deQueue ", "enQueue ", "Rear "\] \[\[3\], \[1\], \[2\], \[3\], \[4\], \[\], \[\], \[\], \[4\], \[\]\] **Output** \[null, true, true, true, false, 3, true, true, true, 4\] **Explanation** MyCircularQueue myCircularQueue = new MyCircularQueue(3); myCircularQueue.enQueue(1); // return True myCircularQueue.enQueue(2); // return True myCircularQueue.enQueue(3); // return True myCircularQueue.enQueue(4); // return False myCircularQueue.Rear(); // return 3 myCircularQueue.isFull(); // return True myCircularQueue.deQueue(); // return True myCircularQueue.enQueue(4); // return True myCircularQueue.Rear(); // return 4 **Constraints:** * `1 <= k <= 1000` * `0 <= value <= 1000` * At most `3000` calls will be made to `enQueue`, `deQueue`, `Front`, `Rear`, `isEmpty`, and `isFull`.
null
null
Medium
null
968
That a hello everyone welcome to cases questions ministry cameras in this question in the treaty between stock subscribe camera on it subscribe mirva subscribe to that first limit tay apna hai shark slide show a binary k amrit liquid 96 subscription avenir with oo bluetooth settings of first World Immigration Question Set Up Dhund subscribe and subscribe the Video then subscribe to subscribe our Iyer Numbers Camera Tarzan subscribe The Channel ko subscribe and subscribe the Channel Please subscribe and subscirbe The Universe Was No Different Sections And Index In This Case Width Shiv Webcam Hidden Adhir Wa Subscribe To Please Talk About Another Possible Solution Of The Same Tree Jai Hind Is Caffeine Spoiler Camera Habit Shoulders President Will Cover This Particular Node Thursday Open Subscribe To Jism Doctor Discovered By Death Penalty Mode Number Two But Still Bihar To Install Camera Art To Consider Places Of Two Consecutive Levels In The Same Free K Far Eastern Possibilities Vyas To-Do Far Eastern Possibilities Vyas To-Do Far Eastern Possibilities Vyas To-Do List Instead Of Going For Alternative Approaches Alternative To Avoid This Possibility Of Subscribe To Relax Talk About How In Reality Thursday Morning Govinda Bottom of the Pyramid 5th Rich and Information from 0 To Avoid the Political Fog Plane Mode Subscribe So Let's Move to the Calling That I Will Fight for the Valuables The First One Means the Difficult Meter Camera Means the Not Already Subscribe And like and subscribe to is so let's process altery and lips coal get chamra status for it's not possible udhar hai ki problem reduce to writing this happen midnight correctly and will follow two poster reversal subscribe do subscribe screen brightness to instrumental tune for this sutra ko stags of life is the what is gold channel subscribe written notes subscribe and subscribe the 12345 note ang vishesh only need and camera flash light of that sequence tunnel and daughter is equal to null fog camera status that and the time calculate 21 seats of The left side and with oo main left status hai Click to get camera status for its nod a deft positive vibes status the great camera from tiffin odd one subscribe and subscribe the Channel ko subscribe karna hai ke liye staff quarter k is Effigy letter terms aur kabi khas camera e dil dekh sak tree already this camera and the rights of tree aur bribe scam alert this camera sleep subscribe do subscribe yo aur lay frees one camera 100 gram research aur vivar ki in this case is particular not Get cover snow become camera here enemy and enemy on Thursday that if difficult written statement veer want neat camera status that aunty is there let's talk about one particular case status love a specific for Jind switch only one or both of children and subscribe to the channel what Will happen in this matter will invoke and celebrate the leaves means camera pic want and will remember me that indresh cases where needed to camera pic Vindhya system ko subscribe jaur kare se kam salt current status comes between its camera on top most root level will not born In Camera Cuticles That Camera Account Plus One Study Select Riders Of Bus That Looks Godwit That Accepted Voter Time Complexity Of This Approach Time Complexity Is Order Of Incentive And Tree And Space Complexity Video Subscribe Enjoy Dissident Forget To Share Comment Subscribe Channel Subscribe do it
Binary Tree Cameras
beautiful-array
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return _the minimum number of cameras needed to monitor all nodes of the tree_. **Example 1:** **Input:** root = \[0,0,null,0,0\] **Output:** 1 **Explanation:** One camera is enough to monitor all nodes if placed as shown. **Example 2:** **Input:** root = \[0,0,null,0,null,0,null,null,0\] **Output:** 2 **Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val == 0`
null
Array,Math,Divide and Conquer
Medium
null
1,349
hello everyone today I went to solve a lead code problem it's called maximum students ticking X hunt and stuck is hard it's a hard problem that's going to be the first bullet I went to solve the code I have already submitted my solutions and hours ago now I'm going to record a thought process out cold well this problem it's very interesting never going to give us a great with M rows and columns which is described by hashtags and dots a hashtag means that there's no seat to make possible as to be in there a dot means that you can sit still in there also they told us that if sample in this case you have a student he students tend to be cheater so they are going to look it's life or it's right or to the - look it's life or it's right or to the - look it's life or it's right or to the - it's the diagonals that are in front of him I mean to the left corner the right corner and the for example we have absolutely they're asking us which is the maximum number for students what kind of seat in the govern such that we're not going to have cheers and in this case what can they do to my answer is for we're going to put my still here because of their always that they have so they have told us we can't put string here because she's there this is to catch it soon dick some of that moisture given my position he is able to cheat here to his left is 501 of him to their internal so know what makes problem not so her is that we said that they're going to be at most eight rows make problems so we have and then and this first one okay so the first detail that we can see is that I'm not supposed as we're analyzing the first button anyway always in the first column okay we can try to match our on the possible ways of Syrian people you here so let's suppose that have someone there or no out there so this place has two possible ways of putting someone I put in someone that one too so if we have an seats the number of ways to put people in here is two to the N so we can put for us all the possibilities hello because yes that's right listen quality name on their utmost to T which is 128 mm 56 256 also if we have only the first row going in this case the answer is going to be immediately after analyzing all the cases a grade a function that's going to check if our law is correct why not so we've how are all these lengths the length of our role is equal to n the check is going to something is going to sweep older in their row so it's meant to be we have to generate all the possibilities in a row so we are going to have o 2 to the N way so arranging the room and then finalizing it and to trillion but this is only for a synchro so if we're analyzing this room we're going to have our two trillion and tank of laxity to solve the problem here the same here as in here but we want to maximize when all of them are no lies at the same time so how can we manage or deal with that well let's analyze no we have two rows of had judgment sometimes we have this role we know that if we have solve I know let's suppose that I'll have more things before I don't know what the half more with but I suppose that we're in that in this rope you were checking all the possibilities in here the only thing that is going to make this arrangement impossible is going to be if we cannot arrange someone here for example this is impossible because they are going to cheat but if you even you wasn't here this could be possible for example so it's only going to be possible if there's no problem with the previous row because they can cheat catch it from here over here this is impossible in depends on this guy well it was done before you know the roles before them you know it's not going to be relevant to analyze the analysis of their foreign rule because we're going to need to deal with that puzzle role for the conditions that are making our problem so our only to check the cheating in two adjacent rows so how could we analyze these cases well you can see here we have solved the problem until the position I minus one let's suppose that we have solved the program and we are in the position I we have to check for each Posse water Irishman which is the maximum number of students that we can have until I minus one and why does it work well you can see that if the program has an optimal solution until I am minus one if we add more students for example if I get K is students in here they can probably increment the answer for some Irish map in a 5-1 and suppose that I write know in a 5-1 and suppose that I write know in a 5-1 and suppose that I write know what this I don't care about the purpose one let's suppose that we have the number stored in water Richmond and I minus one so we're going to have the solution let's call our soul in I minus one particular arrangement and irishman sub J plus K this new number is represent their original height are so fellow suppose this Irishman this top layer watchman one person love one person don't with a nourishment of I'll cancel my to be two students plus number of students with having a solution I minus 1 with some particular Irishmen that it's going to be possible let's suppose that for all the way that we are going to put people in here it's not going to be possible to increase the number it's not going to be possible to create this erection because it's going they're going to cheat with the previous students in the other row so in that case probably the solution is all the people there they're not going to be people in there that variable so the answer is going to be when we have the regiment 0 20 the first arrangement it's going to be the previous the maximum produced because for the I plus 1 rule we are not going to deal with that and it's like starting a problem game so it's not going to interfere but we are going to do it for us in the current and in the previous one if we are in the row I will cast a role a humongous one coming your way for each nourishment and here we have all up to TN ways to arrange the current role and off to you ways to well I have 2/3 n off to you ways to well I have 2/3 n off to you ways to well I have 2/3 n ways to arrange the previous row for each of these we're going to look but so what's happening when we have all the combinations all the arrangements in the previous one so we're going to have we're going to make two to the N times 2 to you icicle doctor to operations and for each operation we have already solved the problem we have a start in the rain so it's going to be our form to retreat from the previous value in each case in which case um to check if that solution is possible we have to sweep all the than you erase so it's going to be falling and to you and this is going to pass because would have at most in estimate for the age where I would have a net worst case total 16 just to let see plus 3 so sorry so 90 is less maple up to 20 and it is very well done 10:06 because it is approximate because 10:06 because it is approximate because 10:06 because it is approximate because 2 times 1,024 please almost into other 2 times 1,024 please almost into other 2 times 1,024 please almost into other so if we Square this we are going to have to tell you something so 6 nice very small compared to 1 second and we have to think about 10 to 8 operations approximately so this condition is going to work right now I have to think how to represent irishman you say we started from their previous position we're going to use dynamic power me so I suppose that we have 5 so that's 1 2 3 4 5 I can use a number I have one two three four five slots I know that if we if I check all the numbers from zero it's about 0 not equal them hi well strictly less than 2 to the 5 we're going to have 0 another number I think the last one everyone because you know 2 to 5 which is everything is what we this no so we can see that we can represent all the states we suppose that 0 means no student in the world still there it can be there are no students in this arrangement there is one student in the position 5 so if we have for example I don't know well 0 1 this could mean we have one student here young student in won't throw us a new 5 so we can represent our students our seat by using the binary representation of numbers between 0 &amp; 2 to the N where n numbers between 0 &amp; 2 to the N where n numbers between 0 &amp; 2 to the N where n is the number of students or seats that we have so I'm going to call it first of all I'm going to make a piece you see it's hot variable global variable in this class take your seats then have the number post-it be the then have the number post-it be the then have the number post-it be the sides in this case one two three four five rows you have three rows columns five elements Monsieur previous proximal number of states that have the word world Frenchman East is what we have an epidural also we went for a solution that's what we are going to calculate which step that means we're nice and high I'm going to have the maximum solution anticipate okay bro in this arrangement and they're processing on all the arrangements in I'm going to store it in DP and then I'm going to pass the next column we are going to use DP to know what was salt before and India we're going to let the maximum nobody's been dipping because and we have finished analyzing order rose the solution is in the last row it's going to contain from 0 to all possible arrangements before starting this first column first we're going to analyze in the position in the preventable so I'm going to you know China is in the right all the videos was a big mask but I was going to miss you we have zero students in this position or I'll tell this position there we're going to analyze all the possibilities we have said that in the first only in the first in this case first of all we are only going to annex what happen here so for Row is for it's quite brave every label check I'll always put point about the must withdraw ionizing follows that I have so that's where I'm going to say nothing reach me how many students have to pay other picture so obviously the mask well this is our first week but we're not in first row I'm going to compare with all the combinations of all directions we was in the current is zero first I'm going to check if that's possible so I'm going to use the same expression that I have created people that previous one which I thought well that's if it's possible not both rows I'm going to make most grants to cheat us check house I'm going to send the previous reference so if that's possible stairs point we have this Irishman in that Corrine bow Oh mr. exit was here got a word here or get that maximum between in step we remember we have here or we have in the pressure and until that previous row that's after realizing all the possibilities going to take BP away because we're going to get out the last analyze secretive have no that Polly Oh Indira which is going to be all their arrangement in the last row because if I start other buddies so now I have been doing these functions but nah can't oh sure mr. that a fashion Americans using various pieces one but suppose I don't have zero wounds the number is bigger than zero until tender the last does digit in binary so that means if we have sorry binary is follow me we make that person operation it's like say one here see one here if this form is going to be 1 0 in the other places um these what in the last characters are sewer I will make one it's going to be several very much sorrow in to be sOooo so we're always boy do have the last leave it so I'm going to eliminate the last if you divide the number by 2 it's always going to finish because of most it has sir it's this case it has 8 bits a nice the sure that it's called Chabot invite odd because we have slots for let's suppose I am a stupid fine I have this guy is right here I'm here good faith an array of n plus two elements like that's showing 0 6 he that remove codes is equal to 5 I mean to make this always there is no as to answer here so I want to put yeah I'm going to make the same process as counting that the how many numbers how many wants would have a number but if we have I want like to put one guy here of this there's no one go to be 0 this case is 1 0 after playing these students in the places I want to check you their sister I have to check in the original classroom we have hushed hashtag means that soon can't be there so if aster can be there this is not the way to be possible if he can't be there I'm going to check there are no students to his left and do we survive because she's quite a treat so let's call it so I keep it close I have created them they are a big 12 and then for each column for the last column this is if I have 5 columns so in close position if there is flow and edges you convolve in service to offloads give back is and then vanish if all the places it's Rose is happy possible meters by the way to do the same as with already chat if I can leave this friends they already diagnosed now we have to check if both on the same time finality so that's let's check it's great library or referees have close buttons their best other ones so I'm repetition zero little it was very next issue I'm going to do case the previous one and got the story on the opposition and X 0 the kernel in like this one so have checked if those we have graded their insurance and then check if the airport last one I'm going to say if we have arrived in this column in the control so if lo so form in the purlins cousin this is true so we have a little fun doofus left corner on that corner definitely do possible South Bay below zero one or both so working is because of the cases this guys and for each other of Toad that's call us I'm depositions work from zero to cause minus one yeah we have Carl answer in a for example that's a bit yeah so Jeb Bush was correct for watching
Maximum Students Taking Exam
check-if-it-is-a-straight-line
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition. **Example 1:** **Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\], \[ ". ", "# ", "# ", "# ", "# ", ". "\], \[ "# ", ". ", "# ", "# ", ". ", "# "\]\] **Output:** 4 **Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam. **Example 2:** **Input:** seats = \[\[ ". ", "# "\], \[ "# ", "# "\], \[ "# ", ". "\], \[ "# ", "# "\], \[ ". ", "# "\]\] **Output:** 3 **Explanation:** Place all students in available seats. **Example 3:** **Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\], \[ "**.** ", "# ", "**.** ", "# ", "**.** "\], \[ "**.** ", ". ", "# ", ". ", "**.** "\], \[ "**.** ", "# ", "**.** ", "# ", "**.** "\], \[ "# ", ". ", "**.** ", ". ", "# "\]\] **Output:** 10 **Explanation:** Place students in available seats in column 1, 3 and 5. **Constraints:** * `seats` contains only characters `'.' and``'#'.` * `m == seats.length` * `n == seats[i].length` * `1 <= m <= 8` * `1 <= n <= 8`
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Array,Math,Geometry
Easy
null
222
in this video we are going to see the layer code problem number 222 count complete three nodes let's get into the problem so the problem statement is you are given a root of a complete binary return the number of nodes in the tree according to Wikipedia every level except possibly the last is completely filled in a complete binary and all nodes in the last level are for us left as possible it can have between one and two coverage nodes inclusive at the last level Edge this is in an algorithm that runs less than because of end time capacity so yeah let's define a problem so the first step to solve any problem is to define the problem clearly so we will be given a root of a binary entry it's a complete binary so this is the input and output should be the number of nodes in the tree so before moving our doubles we need to know what is the term complete binary image what is binary is nothing but a tree which consists of nodes are nodes will have maximum of 2R 2 Chain maximum of 2 Chain Max of nodes child uh count of nodes say let's say account so it can have zero child it has to have no child or one child or two child so this is the possibility for any number in the binary tree so let's see what is complete binary tree is nothing but a binary tree which consist of notes but except the last level the notes are completely filled so when we take a binary let's say is a binary so this is the first level the second level the third level so first level is having one node second level having two nodes with the other line forwards so this is the uh completely biometric so let's consider other question so the definition of complete binary is nothing but all levels entry or filter so this are this means the arteries are filled with nothing but every node has two child two children this is the meaningful field so all the levels in the tree are completely filled and final level that is the last level may or may not be filled they are may not be filled so this is the definition of complete minority but the when the tree is filled there is no problem so if there's the tree is not filled it should be in order of left to right so let's say what does this mean so let's consider uh binary so we'll consider this first this is first case that is give us again and test it so and we for each uh trees we are going to find whether it is a complete binary or not so when we consider this string so for each node so we will uh name the levels first level second level and the third level so you can see that the first one notes are filled and second level nodes are filled are not filled so we have to notes are present if we know of previous level sorry I have mentioned around so even also previous level has two child so this is the meaning for field and the root as a single cell so a root is uh does not have a parent so we consider the first root known as competitive field so the definition of complete validity is nothing but all levels in a tree are filled and last level may or may not be filled if the t is not filled the nodes are ordered from left to right in the last level so this is the 11 currently this is the definition and two children so yeah we'll consider the first level so we'll check whether the previous level is uh two children are not so in this case of first level we consider this as true so the in first level already has one node so we'll continue so in second level we will check the other previous notes have two children another so previous notice previous 11 nodes are only one node just root so root has two child so it is complete the 11 is completely filled so we'll move on to third level so in third level we'll check the previous node previous travel nodes so there are two previous travel nodes that is one and two so I will check for the one so one has two child so this is uh Computing cell and we'll go to next node so in this node it really says see that there is no child so this is considered to be not finished so this area is not filled so uh and we can clearly see that the last level notes are ordered from left to right so I'll also lots of field form left to right so we can say this as complete binary so now we'll move on to an extra three so in this tree the first or last Monday or not so the root node is considered to be uh so we move on to export X level so in the next level you need to go through the previous travel mode so previous travel node has previous level does not have two children that's only one child which is truly right so we can say that uh the last level is not filled so now if the last level is not filled we'll check whether the so you can clearly see that there is no node in the uh left of the previous uh not slipped so that's a note to become before this node which is not present so we'll consider this as a binary 1D so it's not a complete binary so now we'll move on to that space so in this case we will control the first flower as completely free and second largest comparison because the previous travel modes root so it has two chain now go to third level internal we'll check the previous downloads so previous downloads does not have two child so here is No Child and here special after this you can really see that last notice now last level is not filled so I will now check whether it notes Orange from left to right or not so that is node nodes in between the uh nodes so we'll cancel this as non-complete binary tree so it's only a non-complete binary tree so it's only a non-complete binary tree so it's only a binary are not a complete binary so this is all about the binary so yeah what are the values expression so we need to find the power case so the other case is what happens if the root is null so this is the current location and what are the other connotations so what are the values presented the nodes values units so we will check for the current pictures so they have said that the number of nodes will need 0. so that's possibility of null nodes so if the rotational what we need to return so we need return zero so there will be no nodes right and uh what are the values you notes so what are the valuation notes value of range 0 to 520 by 4. so but they have mentioned that E3 is guaranteed to be completed so there won't be any invalid cases so this won't be present here so only the valid completed here present in the input so how are you going to find this cover of course so that's all about the problem definition now let's move on to approach so the second step is approach so how can you approach this problem so first approach that comes to everyone's mind is to go right hovers over each node and keep track of the count variable so come on so travels each node using any of the methods traversal method like in order post order and keep on incrementing count if not null node is present so finally we return the account so this is the first approach and the time capacity of the approaches law of M and the phase complexity that it takes is so in regression the call stack may go up to size of height of the tree so we go off 3 height so this is all about this space and time complexities so now let's uh check if there is any other approaches available it is very efficient than this current approach so can we use the property of complete binary so complete binary it has notes complete nodes right so we'll check for each node we'll check whether the left and right are having a percent each I mean the same level or not so is the left and right loads are passing at the same level we can find the number of nodes using a formula so what is the formula nothing but number of nodes n equal to toe into so and you can answer the first hour there is one second level there is two third double that is four so you can leave it here directly number of nodes is equal to 2 power so the total will be seven right two power level minus 1. so in this case the 11 is 1 2 so levels are especially as one two three so 8 minus 1 which is 7. so this is the formula to find out the number of modes of a perfect binary so let's see what is perfect by energy tool chain and leaves the definition of perfect variety so if please nothing but 2 to the power last level minus 1. so this is the formula so how can you apply this formula so what we're going to do is we'll uh for each node we are going to check the whether the nodes are in the left and right notes are at same level or not so if the left and left right left motion like monster nodes are at same level it is the case so what we will do is nothing but return the level from top to bottom minus one so R is what we'll do so answer this case so what we'll need to do so in this case what we do is we'll just add up the uh what to say we just added the number of nodes in right to the right so in here when you are present at the node we inject uh the number of modes in the right so in another version right is nothing but 2 to the power the maximum that is the least level so in the left and right detect this I think but uh left has fifth of four and I start with the three so we can have formula of 2 to the power 3 minus 1 by 2. so what happens is we are considering this as a tree so while we are considering this so because we are choosing the least uh level of current nodes left most and right so in this case you can see that left as value as 3 and then it has depth as four so we are choosing list so in this list so what we are trying to do is we'll just add the so what will be count of notes in this started uh notes so it will be 2 to the power 3 minus 1 9 so we are ignoring we are going to include only these nodes so what can how can we improve only this not so or required to do this we'll find the answer so it will be 7 we'll divide it by 2 which will lead us to 3 and add it by 1. so what we can do is you can just ignore this so 2 to the power 11 by 2. will give us the result of this nodes around so finally after finding this will go to the left node so again we'll apply the same formula like this so finally we'll be able to get the answer so O2 to the power 3 is 8 by 2 will be four so abstractly our steps for our approaches nothing but find the for each node Traverse each node first it happens travels nodes find right depth so yes both levels are equal that is L left side left width is equal to right hand what will return is to the power L minus 1 or else what we do is we'll return the number of nodes in least level that is for 2 to the power list of Min of L comma r Plus is for the minimum is left node what we do is return find off let's say find C of if the mean value is right it'll pass left node or else will pass right now so this is the formula we are going to use so how can we use this form or use this steps in our approach so let's get on to 40 section so let me come to a node we'll check if we notice foreign equal to right fail return dot power of 2 comma left minus 1 so RS what we do is if left steps is less than right well return math dot power of 2 comma left depth by 2 s count nodes of row Dot so virus will return and Dot power of 2 comma right that by 2 s count nodes of so do not left so how can we find the depth of anode creatino so left depth can be calculated by using so we'll have helper function left there and also write depth foreign depth is zero while node not equal to none will increment the depth one more to left and you will return it so this is the same formula the same step for finding right depth I did nothing but two more to write so let's take this so what happened here so we'll convert the string let's check this out so we'll add it here too so we got a wrong answer so what is the problem here so we have left it turn right left right so if left at this greater than writer so change this condition why you are changing this because if the level uh so what we can do is if left depth is equal to write it will return this answer or else what you can do is failed it 1 plus common nodes of row dot left s or not after that so what I have made mistake in the previous step so I told that uh when the fire is node let me check with the depth if the left has four and right down Delta 3 so we'll uh just add this and return address and go to left but this doesn't work for many test case so what we can do is when we find the imbalance in depth we just add current node and return the node number of node count of left and right so yeah we'll check this up so we need to park the roots working fine let's take the form the test case that's where we find it's a minute yeah accepted and as I previously discussed so the time complexity of the approaches because um what to say so what would be the information so for each node it will check for left and right so it will go here but in terms of time competition but not least I mean uh not exactly because seems for some cases uh some mini test cases it will be decreased to end login since uh when we reach this condition so we can reduce this condition we don't go further checking up so we will just return the number of notes with otherwise we'll go to each use so yeah actually I'm not sure about the temperature so I'll discuss an update in the description and this based complexity is of um login so it's because uh you will find the depth of a node we'll go from top to bottom so it will be the point of okay disability is complete the stack space will go up to the size of that is the height of the tree so approach for this problem it's a question so yeah right that's all about this problem so thanks for watching this video have a great day
Count Complete Tree Nodes
count-complete-tree-nodes
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree. According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. Design an algorithm that runs in less than `O(n)` time complexity. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 6 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[1\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[0, 5 * 104]`. * `0 <= Node.val <= 5 * 104` * The tree is guaranteed to be **complete**.
null
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
270
20
hello guys welcome to algorithms made easy today we will be discussing the question valid paranthesis in this question we are given a string containing just the characters that is open in close brackets of three types and we need to determine if the string input is valid or not a string input is valid only if the open bracket must be closed by the same type of brackets and open brackets must be closed in the correct order we are given some examples with the problem and it shows which all strings are valid and which all are not now there are three hints given in the problem the first hint states that a valid parenthesis expression is that a sub expression of a valid expression must also be a valid expression hence 2 states that what if whenever we encounter a matching pair of parentheses in the expression we simply remove it from the expression and this would keep on shortening the expression and the third hint states that the stacked data structures can come in handy here in representing the recursive structure of the problem the basic idea that we get from the three hints is that we can use stack in order to solve this problem so we will use stack but how can a stack help us so let's see how this problem can be solved using stack some of you might already know how to use stack and how to solve this problem with the help of stack but there is a follow-up problem follow-up problem follow-up problem to this question which is mostly asked in the interview and we have discussed that in the later part of the video so if you are well versed with stack and how to apply it you can directly skip to that part for rest let's see how we can use stack suppose this is the example given to us that is this is the string given to us and we need to find if this is a valid string or not we'll start off with having a key value pair the key will be all the closed brackets and the value will be all the open brackets we'll also have a stack now we'll start iterating this string and for every open bracket we need to push that into the stack somewhere in the string we will encounter a closed bracket now when we encounter a closed bracket we need to see if the top of the stack is the open bracket for this close bracket or not we can check that using the map that we defined we know that these are the pair so what we need to do is we need to pop this value from the stack and then move our pointer to the next position we again do the same these two are the pairs so we pop them and then move ahead and we will continue doing so till the stack is empty if by the end of the string the stack becomes empty that means this was a valid string and we will just return true consider at the end the bracket is square brackets and these are angular open bracket that is in the stack so this do not form a pair so as they do not form a pair we will simply return false as the string is not valid now let's see how we will code this so as discussed we will have a stack and a map will contain all the key value pairs so we'll first define that now as we discuss we need to iterate over the string we will take the current character into a variable now as discussed we know that if the current character is a open bracket we need to put that into the stack else we know that it is a closed bracket as it is a closed bracket we'll check if the stack is empty because if we have a closing bracket right now and the stack is already empty that means it is a single closing bracket and there was no open bracket in the stack right now that means the string is invalid so we'll return false one other condition that we discussed already is if the map dot get of this closing that is the value is not equals to the top of it so we'll return false otherwise at the end we just need to check if the stack is empty or not if it is empty then it is a valid string otherwise it is not a valid string let's run all the test cases so it is successful let's submit this so it got submitted successfully the time complexity is of n and also the space complexity is of n as we are using stack in order to store the value now comes the follow-up the value now comes the follow-up the value now comes the follow-up question to this problem which has been asked many times in the interview for many of the candidates interviewer in this problem when you solve this using stack will ask you to solve it without using any data structure to store the value that is they want a solution that uses no extra space we know that when we need to improve one of the two complexities we need to increase or degrade the other complexity so we will now see how we can solve this problem without using any stack so change the same code will remove this stack altogether from this coding now why are we using stack so let's again jump back to the example that we saw earlier we were here whenever we encountered any of the closing bracket we turned our attention to the stack and saw what bracket it holds at the top of it so effectively we were holding the top of the stack how we can change our program to get this top element without storing all the values in the stack itself for that purpose rather than using a stack we need a pointer so we need to have a top pointer which points at what value should be the top of the stack we are talking in terms of stack so that it is easy for you to connect what we were doing in the stack part and what we are trying to do over here without using any of the stack so suppose we have the top pointing at this particular index which was also the top element in the stack so we check if the two pairs perfectly align with each other as they do from the mapping we can see that we need to move our pointer to the next index now that part remains the same the only part that changes over here is how to find that top because we do not have stack so that next top will lie in between index 0 to top -1 index 0 to top -1 index 0 to top -1 we are sure of that in this example if we need to find the next stop it will be top minus 1 and that will create confusion in your mind as to how will be the real top is calculated so in order to clarify those doubts we'll take a little complex example so that it is much clearer to you as to how we are calculating the top and why we are calculating the top like that so suppose this is the example and we are at this position and the top lies next to it since the character at the top and the index make a pair we need to move the index to the next position but before doing that we need to find the next stop and the next stop will lie to the left of the current top pointer that is top minus one so how do we search the new top as shown on the screen the new top is at zeroth position so how do we come to know that we'll have one more variable which we call right starting from the index zero and we have now top shifted to top -1 in this area shown in between top -1 in this area shown in between top -1 in this area shown in between brackets we need to find the next top now we need to update the right pointer according to the conditions so if the top is now pointing to a closed bracket we add one to it and if it points to an open bracket we subtract one from the right i'll clarify why we are doing this and how this helps us in finding the top let's first apply this operations so as we see the top is a closing bracket so we add one to the right now we decrement the top now the top becomes an open bracket so we decrement the right we again decrement the top now the top is again open bracket so we decrement the right and the right now becomes negative that is minus 1 the right pointer becoming -1 means that we have encountered -1 means that we have encountered -1 means that we have encountered from the top minus one till the new top position more number of open bracket then there are closing brackets which effectively mean that the top is now pointing to a open bracket for which we have not encountered any closing bracket and that's how we find the new top let's see how we will implement this in our code and it will be more clear to you when you see that so as we know we need to have a top which will be -1 which will be -1 which will be -1 minus 1 telling us that the stack or the top is nowhere that means that there are no elements so this stack is empty can be now replaced with if the top is minus one at both the places we pushing the value in the stack effectively means we updating the top to whatever index that we have and now the most important part is finding the new top so the stack dot pop is nothing but it gives the current top value so as the top contains the index we need to find what character does it hold at this top pointer so if it is false then we are good but if it matches then we need to find the updated top so we need to call a function which will give us the top now in order to find the top we need two arguments we need the string and we need till where we need to find the top value and we discussed that it will be existing between 0 to 1 minus 1 will pass top minus 1 in this method now it all boils down to implement this method so we'll start implementing it as discussed we will have a variable called write and now till this index is greater than or equals to 0 we will apply the logic so we'll take the current character into a variable now if this current character is a closing if ch is closing bracket then we increment the right otherwise we decrement the right and we discussed whenever the write becomes less than 0 that means we have found the value and whatever value is there in the index will return it we will be decrementing the i and even if at the end we do not find any value that means there was no top present and the stack is empty and we directly written -1 now written -1 now written -1 now in order to check if there is a closing bracket you can check with the help of or conditions or what we can do is we can make this map a class level variable so what we can do is we can take this out now all we need to do is map dot contains key for this character and that's how we implement it without using stack now let's run this code okay so let's run it again so it gives us the right result let's submit this so it also got submitted and ironically it is giving us a less run time than the previous approach but the time complexity of this approach is of n square because in order to find the next top in the worst case we need to go all the way from zero to n minus one the space complexity however becomes o of one do let us know your thoughts in the comments below thanks for watching the video see you in the next one
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
189
all right so this problem is called rotate array and so basically what they're doing here is they're going to give you a k value and then uh your job is to essentially rotate a portion of this ray that many indices to the right so uh when they say three you shift everything to the right so seven falls off the end six falls off the end five falls off the end essentially they end up at the beginning here so you have five six seven 1 2 3 4. also keep in mind i don't see it here but you do have to consider they could give you something like let's say a value larger than how many actual values you have here so they could give you eight and in that case we just want to basically mod our value get the remainder of k because it would be the same so if you rotate this eight times you're just doing a full rotation everything goes through you have the exact same uh order after seven rotations then you'd be left with one left and that final rotation would shift that seven to the front right there so now that we know what we need to do let's think about the different approaches we could do that are used to do this whether maybe we sort it well we don't want to do that we do need to keep the original order so we can eliminate that maybe we take an extra array that we store values in and maybe we start uh you know moving values from here to another array that's extra memory space and i'm not really sure if that necessarily helps us where we want to go so maybe the better way to approach this would be uh considering other ways that we could tweak numbers and so uh you know you'll get used to this as you work with array problems sometimes reversing an array might help you do something that's a little bit uh you know different so let's see if we reverse the array you'd have seven at the beginning one at the end and then that actually looks pretty similar as to where you know we want to go almost so if we reverse it completely seven six five four three two one then in that case now we're left with almost what we need but what if we reverse it again so this is not something that would necessarily be intuitive to you right away but as you start to work through these array problems you'll start to learn different tricks and ways to try to manipulate the data to get what you want so when i say this is that you have seven six five four three two one if you then reverse only the first three so if you had seven six five and you reverse those you get five six seven and then at that point you'd have four three two one and you would have one two three four if you reverse that back so you can see how this works so let's just go ahead and implement this now so we're going to need to update our k when it's larger than our list size and we also know that our list size will at least be one so we don't want to worry about checking to see if it's null or if it's zero or anything like that so k will equal k and then mod so modulus the size of our array alright so that makes sure that if we had a size 7 array and k was eight after we do this uh modulus operation here we'll end up with one so like i said set full rotation through everything and then we're back to where we need to be so additionally we know that our approach is going to be to reverse the numbers so we should write a function that reverses numbers so we'll just say void and then we'll take a function where we take an integer array and we'll say just array and we want to also know our start and our end so after you know that uh one of the common ways to reverse an array is you just use a while loop when you know the start and the end and you can say while the start is less than the end and now you can say that you have to store keep in mind a temp value because otherwise you're going to try to swap indices and you'll lose track of those values so your temp value can be the start or the end in this case we'll just make it the start and now we'll reassign the start to the end and then we'll also assign the end to 10 because that's what start was and now all we need to do is increase our start and decrease our end and that will end up causing these to eventually uh break this while loop so now the final thing we need to do is we're just going to reverse the entire array so we will do reverse and then it will be nums then we'll do 0 and nums dot length and it'll be -1 because we don't want to and it'll be -1 because we don't want to and it'll be -1 because we don't want to go an index out of bounds for our array because obviously your last index in your array is not going to be array uh nums.length it'll be minus one and uh nums.length it'll be minus one and uh nums.length it'll be minus one and then now that everything has been reversed we're just going to reverse that front piece and we'll reverse that last piece so now uh you're going to want to start at k because up here uh well you could do either one but you're into c so like i said we want to reverse this front half and the second half so this first one would be reversing the second half so indices zero one two and then three this is where we'll start to reverse this piece so we'll say from k to the end of the array which we already have there and now we just need from zero to k minus one that's it because that will reverse that first half as well now we'll go ahead and submit this all right and as you see it was accepted so your space complexity will just be constant space because you're using for the most part all the space you already had for the array and the only thing you're really doing is just using the existing array to rearrange the elements and you have that temporary integer pointer but other than that uh you're not adding any additional space especially not using another array because you could have had n space if you were storing all these values in a separate array or if you used more than one array or anything like that and then additionally your time complexity is just going to be end because you're iterating through all the elements when you first swap all of them and then after that less than that so you know you could even start saying you know this is like some fraction of a value times n or like one you know one and a half times n or something like that but all that still ends up ultimately simplifying to n and so that is your time complexity all right if you have any questions about this problem let me know in the comments below and please take a moment to like and subscribe for future content you
Rotate Array
rotate-array
Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative. **Example 1:** **Input:** nums = \[1,2,3,4,5,6,7\], k = 3 **Output:** \[5,6,7,1,2,3,4\] **Explanation:** rotate 1 steps to the right: \[7,1,2,3,4,5,6\] rotate 2 steps to the right: \[6,7,1,2,3,4,5\] rotate 3 steps to the right: \[5,6,7,1,2,3,4\] **Example 2:** **Input:** nums = \[-1,-100,3,99\], k = 2 **Output:** \[3,99,-1,-100\] **Explanation:** rotate 1 steps to the right: \[99,-1,-100,3\] rotate 2 steps to the right: \[3,99,-1,-100\] **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1` * `0 <= k <= 105` **Follow up:** * Try to come up with as many solutions as you can. There are at least **three** different ways to solve this problem. * Could you do it in-place with `O(1)` extra space?
The easiest solution would use additional memory and that is perfectly fine. The actual trick comes when trying to solve this problem without using any additional memory. This means you need to use the original array somehow to move the elements around. Now, we can place each element in its original location and shift all the elements around it to adjust as that would be too costly and most likely will time out on larger input arrays. One line of thought is based on reversing the array (or parts of it) to obtain the desired result. Think about how reversal might potentially help us out by using an example. The other line of thought is a tad bit complicated but essentially it builds on the idea of placing each element in its original position while keeping track of the element originally in that position. Basically, at every step, we place an element in its rightful position and keep track of the element already there or the one being overwritten in an additional variable. We can't do this in one linear pass and the idea here is based on cyclic-dependencies between elements.
Array,Math,Two Pointers
Medium
61,186
1,183
hey everybody this is Larry this is me going over the weekly premium problem uh I already saw that earlier you know I gotta do this and reverse order because I do get a lot of comments and I tried to be you know uh accommodating but in that the video is very long uh it took me about an hour this outfit is a very hard problem for me uh may not be hard for you but you know and for full um let me not have it block my face but for full disclosure you know you can watch or part of it you could kind of see how I come up with each part and how long it takes right I think we just talked about it yesterday or the day before we talk about how long it takes for Larry to solve a problem and when to give up and stuff like this and yeah and so yeah now you know that you know I will grind it out um it also turns out that I solved as an O of one instead of there's some like simulation that's all of analogano of n or something like this I don't know didn't really look at it because I did it the other way but um so the structure of this is going to be a little bit different in that I will explain my attempted solution um and then we'll go over the code and uh and all this stuff and then if you still feel like you know you won't you just want to see live you struggle or you know just kind of see how each piece built on each other um and how I kind of came up with it at the end then you know you could watch the live portion of it for sure um cool let's get started then and yeah so basically the first thing I did um to be honest and I said this during the live version as well is that if I kind of did some like visualization here maybe this thing is actually blocking the screen I did some sorry hang on this thing is still marking the screen uh I did some ASCII odd kind of explanation visualization because normally I would do it on paper but yeah I just want people at home to kind of see it right it's not a contest I don't have to do it but basically I just can't play around with some more examples and the first observation is that given um given an N by n thing um R times C Fang um you know let's say and this is going to be a square right uh and then you know and then you maybe have let me change the colors up a little bit real quick right this actually took me a long time to be honest so don't feel so bad if uh if you feel like you know like the benefit of me doing a video and other people doing videos as well is that they have infinite amount of time to understand and come up with these things uh and then you and then I could you know if I was one of those people I would try to sound really smart I'm like ah yeah look obviously the next thing you do is this and then you're done with five minutes you're passively learning uh but what I always say is you know you should actively learn because learning is not you know um learning to understand a solution isn't the same as doing it and learning how to do it right it's like I always use a geminology because it's a very I don't know most of the time is already a good analogy is that like you know just because you've read up on you understand how an exercise makes your muscle do better doesn't mean you're gonna gain muscle you still have to go out to the gym and do it and really kind of put in the work right anyway for this particular case but it took me a while you could watch the live version there's nothing hitting anything uh you know the first observation that I would make um is that uh assuming that Max wants is smaller than a square um in some parts of it doesn't matter what you do what I mean by that is that let's say it's three by three right so you have one two three on the red and then four five six seven eight nine right and then now if you look at just one shifted over unless you're doing something silly or unreasonable then your next one is going to be one four seven and if you look at only the um if you look at only the blue ones then it contains all the numbers from one to nine once right maybe this is obvious maybe this is easy maybe this is a an observation that people make very quickly I did not so it took me a while so I think this is in sight for a little bit so then now of course if the length of the entire thing um changing colors if you know uh this is C no this is RSI whoops number of rows and this is number of uh there's a c this is the number of columns right if all Mach C is equal to zero or you know if R divides what is the Divide symbol again man oh is it this right if this is you go to see if all divides oh no whoops uh I always see for this but what is let's say as for the side of here right if all divides into s uh and see divides into s then we're pretty much done right I think that's the divide in the symbol if not then um I spent an hour on this I have no more not many brain juice steps I apologize but let's just say you know this is if this might as this equal to zero then right you know uh you get the idea don't want to I mean I don't want to get too pedantic um well I mean it's not pedantic to get wanting to get the symbols away but uh but without wasting more time on Google and stuff right so then we're done but let's say we're not right then that means that there is some leftovers and what do the leftovers look like I'm choosing a color so hang on so you know you're going to have something that looks like this and basically the idea is that now you have some leftovers this could be the leftover um uh wait let me rephrase this real quick everything in inside here it doesn't matter right because everything inside here it is even right like it has a even multiple of uh s um you know so then that because that is just the remainder you divide out the remainder and so forth right so that's fundamentally the um so then now we have to figure out oops how to fill out the stuff that's not the remainder right um because yeah uh and we just to kind of be I feel like I wasn't super clear so to be clear uh what I mean here is that because inside we have all these rectangles and it'll fit okay I drew them terribly but let's say that this you know uh this fits perfectly right pretend that you even right so then now you this fits perfectly and yeah okay poor drawing aside you get the idea so that means that of course you can do the math on this and we'll do the math on this later but you can assume that um it doesn't matter how you check out the pattern you have the same number of ones in there right so then now that we get that out of the way the hard problem is coming out of the remainder or what's on the extra stuff right so then now so there's two cases or there are a couple of cases maybe not two uh I think they're three right um well not cases is the wrong word but there are a couple of things to consume let's put it that way right uh there's this orange bit right this orange bit well what is this orange pit or this orange bit is the overlap of the extra stuff uh here and here so that means that any one step belong in there um gets doubled up uh gets counted twice uh what I mean by that is that maybe I'll phrase another way right so let's say uh you know we're trying to figure out the pattern right now we're trying to figure a pattern on an S by S triangle or sorry uh square that optimizes for the over uh not the overlaps but the leftovers sorry the leftovers but in the leftovers there is this overlap in that you know for example uh another way to think about or visualize it first is that let's say you know uh this is the square right and you know and I'm gonna label them one two three four five six seven eight nine right and let's say if you have ones I'm just gonna write an X for the ones right uh you know it your goal here is to optimize this such that uh oops yeah this is a terrible uh drawing but you know or proportions but yeah that's it these are the leftovers right and then now basically the pattern matters because for example if you have a pattern that uh looks like this and if you during the live portion I go over this a lot then that means that uh you get to use something like this part right uh let me change the colors real quick and of course only this part is actually used and in the same way you use this part and the entire thing is used right um and then here you can think about and I skipped the box which is here of course then now you have uh one two three four five six seven eight nine and we have this pattern then you know here right but so the idea here there are a couple of things one is that um you can see that each some cells appear more than once right and even an overlaps uh and basically whoops uh basically here and you do the calculation but you can see that cell one and four they will appear in the overlap so that means that they appear a lot of times and what I mean by that is that uh it's gonna appear so this one it's gonna appear in all over as kind of times or something like this um of course you have to you know uh and we'll go over that in fully but one and four will appear the most right and then the second question is after that what numbers appear the most and that's basically the idea behind the rest of the problem is that uh well if you have a longer side let's say C is longer than let's say C what happened here let's say C is greater than or if C is greater than or then if you kind of you know let's say we figure out the pattern differently right instead now we kind of you know greedily choose what we want so good it choose what we want we start out with these two one and four because well one and four appears the most right and then now what appears the most next is it two or three or five or six or is it seven or eight or nine right and here that's basically uh you know the case analysis part uh basically if C is greater than R then basically that means that there are more twos because if C is greater than r that means that they're just more spaces to fill in so then now you want the twos uh and then the next number is three and you know that it uh this increases the number of ones by either C or C minus well C over s minus one time or something like this give a tick you could do the math at home right but the idea is that because they're more C's uh they're more full boxes just by definition um because they're more columns that than rows so then now you want to add to here so then now you prioritize the two and the three and the five and then the six if all these are done then the entire row uh the entire bottom thing is filled then now we can prioritize say seven and that's pretty much it that's pretty much the idea um it's really and obviously there's another case for r is greater than C and you know you just do it the other way around because now you want seven first um and then that's it really because that it only has one space um that's basically the core idea behind this problem and yeah and then I will go over the code and during the live portion I kind of went over and that's basically what this tries to explain uh hopefully this part is a little bit better but yeah and the idea well all this after that is just math so here what the first thing I did is that I actually uh instead of kind of having an if statement about RNC I made sure that c is greater than r that's it no questions right um here basically this is the number of full things with no you know you can think about this as uh like a div mod thing this is the number four boxes that we have on rows my full boxes are on the columns and then the max one these are just um let me actually pull the drawing back real quick uh let me see if I can minimize this a little bit hang on hmm uh how'd I move this okay I cannot select it to move huh oh excuse me sorry friends um I cannot select it for some reason I there we go a little bit I'll have to remember to move it back but yeah but basically total uh this part is just everything that is uh this portion right uh the part that isn't the leftovers all right let me redraw that basically all the stuff that is in the leftovers is this part the math you can do pretty quickly and usually and this is what I do right because we assume that for each box uh you complete box we have the number of Max once uh here I count the double overlap and that's basically um just this box here in the port that has overlapping the both the sides I call it double overlap I don't know right so if the two cases and you probably don't even need to split them out but I just wanted to kind of in my head make it simpler but uh yeah you'll need to spread them out actually but I think it's similar to it to go but basically we have fewer ones than this box uh you know in the one four if you only have one number to fill and you have two rocks then we're done right and this is it basically the number of Max ones and then we just kind of count the number of rows and columns because by definition um this is smaller than the available space anyway otherwise um you know here we do the math on the overlapping point and then now we have you know the number of ones that we have left and here we go with the bottom space first because remember C is greater than R so we just do some math to kind of count the number of bottom space the spaces on the bottom in this case is basically uh the one to the six I'm drawing on the side I don't know if you could see it's a little bit cut off but you get the idea right basically it's just like the box that's here or whatever um yeah it's still cut off okay fine um and then of course how many we actually put on the bottom is just going to be the minimum of the number of spaces or the number of leftovers whichever is fewer um we and then we just do the math this is the number of four columns and then we put it to the bottom uh we subtract that from The Leftovers because we use them and then we do the same for the right side uh yeah that's all I have with this one this is all of one or uh or one time or one space and yeah um what else is there to say um I think in coming to think about it um the way that after I just talked about it now uh I guess the more the so one thing is that the constraints are only uh riff and height is only 100 of course if you have all one time or one space well it doesn't matter what the within height is but I think what happens is that for um you can actually um in a greedy kind of way and this is a very greedy problem um you can just count the number of times a cell appears and then just greedily put it in like in the example that we have uh you know you can just kind of go like one two three four five six seven eight nine and then basically draw boxes and human can get overlaps and stuff like this and because it's at most uh 100 times 100 you're gonna have at most ten thousand entries so then you're just sorting the ten thousand so it's gonna be R times C Times log or times C and that will probably be the solution for like the sillier one that is an over one but uh so I this isn't necessary per se but that's what I end up with um yeah let me know what you think let me know how you did it and let me know if you enjoyed this video it's very loud um but you can watch me solve it live during the uh well the lifestyle portion now hey everybody this is Larry this is me doing the last premium weekly problem for um August I forgot the month hit the like button hit the Subscribe button join my Discord let me know what you think about this poem uh like uh you know it's a problem that we haven't seen before or I haven't seen before so you have seen it let me know but uh yeah that's good to it that's uh and it's a hard one so hopefully it won't take me too long because it I kind of started on this one a little bit late uh all right 1183 maximum number of ones okay so you have an M Matrix or Matrix M with Dimensions with times height such that every cell has a y zero one and any Square sub Matrix of M of size um of some side length times side length has almost Max one ones we turn the maximum number of ones that the Matrix can have what does that mean uh let's see uh I think I have trouble understanding this but look at the constraints real quickly that it's small enough that I don't know well 100 to the fourth it's gonna be too slow so no Booth first but beyond that let's see okay so three by three any Square sub Matrix M of size side length times side length has the most ones um to be honest my initial intuition is greedy but I don't know that's true because um this is definitely a problem that I think normally I would go on my paper and notebook to kind of draw it out uh like a lot of scenario and see if I could kind of disprove greedy or at least find a counter example like that's which is disproving it um but but I'm gonna do it you know I'm bored to kind of um yeah because I think it um well I mean so that other people can see so I'm like stuck trying to think about this one so I don't know how to resolve this one off my head other than maybe some idea of greedy um let's say you have uh some big number when you have twos right and let's say you have two by two that's two um then technically the first world would be all filled then and then you have all zeros and then that would actually be pretty optimal so I think in this case that would work no matter what the height or width or whatever it is um I'm trying to think right so let's say it is more sparse let's say we have a three by three uh effectively the way that I think about these pants is gonna be Infinity but let's say if I would read byte when we limit by one so it's always going to look like this right like it doesn't matter which of the nine and in fact this has to or not has to but it is more optimal here because if this is here then it can only lead to a worse solution because obviously you just move it here and then the next one is here right and so in that sense really makes sense but I think there is like weird cases let's say n is four or you have four cells in a three by three then I would start throwing them out like this right and maybe so this looks good so far in the first three rows but where we get in trouble Maybe it's something like this is that because this is four maybe that's still fine I was thinking maybe there's some I um optimal way to kind of well we know that this has to be zeros just from here so I guess maybe the greedy is fine because you always want to optimize for one of the toward the edge because if you kind of analyze it by one dimension first right you want it towards the beginning of the one do away because then now in theory it always leaves you with more room to go in the future and then if you kind of extrapolate that to 2D um that said that argument doesn't always work with respect to like oh every work to one day then it works with 2D kind of thing um and that will always be the pattern I guess and then the question is okay so this is with it's perfect right so like what happens if it's something like this what if it's not instead of not uh having three by three but on a in a board of nine we have a part of eight right then now the last cell is actually a little bit The Last of Us a little bit sketch isn't it do we do this is that right no because this cannot happen because this two these three by three would have five cells so whatever one here does that work no because these three by three would also have five cells so it has to still be zero so there's no way to get so these all have to be zero because of the constraint proposed by these in either case I mean you could do obviously move one here but that does not change does that change the outcome no because this store is three so it doesn't matter okay um to be honest I don't have a great proof here or like a word of tight proof per se but I think I'm okay with being convinced because there's really no way but because basically um the last three by three I mean I think I'm kind of convinced but okay and then the question is how would you solve it right well then now you don't even have to cut I mean you could construct it with some sort of like dynamic programming lookup thing uh or even with like set tree or some something like that but I think now then foreign and then you have just one more it has to go this way I mean the tone of us this is a zero but then that's even that's clearly worse so okay um yeah so then it just becomes distilling right so you just do the math on the telling because this will always be like um the only tricky thing is about maximizing it uh when the input of width and height is not a square because then it depends on the orientation of how you uh fit these things in I think I mean I kind of chose greedy as the pattern here but I think any pattern with like with um M inside of uh M inside of the this oh wait no M so any max ones inside a square of M is going to work so give you a solution right uh any pattern that is smaller than that will give you a solution because just by um you can kind of prove that because of like you could kind of just think about um almost like a sliding window because we did sliding window the problem of java M by m Matrix and then you know you shift one but then you can think about it as shifting one as maybe I might write it like this as you know uh you just have one some one two three four five six seven eight nine if you kind of think about shifting it really just goes to two three one four five uh sorry five six four eight nine seven so it will always have the same M by m cells uh with and therefore with that math it will always have exactly uh Max One's number of ones um yeah so that would so it always fits constraint it might not be maximal the maximum comes from the fact that uh yeah so you have to kind of figure out how to do leftovers and the two ways to do the leftovers right so let's say you have something like this uh and yeah and maybe something like one more world right and then the other way could do it is just rotate it vertically so you have something like this and then in this case it would look something like this and then you just do the math on both I think in this particular case they are the same because of you know you just move where is it yeah because you just moved this one to this one and oh wait maybe not huh well besides that I mistrew it to be honest but yeah but either way that's why so but those are the two possibilities I think and so then we can test it after that so let's try that I mean to be honest right now uh even though maybe I sound confident I'm not confident at all so um but especially for a contest uh you know I'm not on contest right now but for a contest that's what I would kind of thank you that's what I would try to do okay yeah uh so now we have this right so for R is equal to with high uh in someone like this right and the reason why we choose this pattern versus like a random pattern is as we said we want to shift everything to the left and we want to ship everything up is that even good enough Maybe I'm Wrong here though let me think about this let's say we have five elements right in three five like we have five so oh and a three by three right so it looks something like this it's not convincing that this is more optimal than say I can't do this one right I mean if they divide evenly this is fine if they don't then what happens let's say that we might want uh we have one uh remainder or two way then you definitely want one ones here and not as opposed to say like one zero and whatever right uh let's say about my two then does that matter as much no then you want five to be like this instead of like this because then now you can do something like this right versus if you have this then it doesn't quite work is there a case where this would be more effective advantageous I guess not because I think the idea is that you fill out you minimize the number of rows um you know or the inversion of it you want to minimize the number of rows because then now uh your remainder will get as juicy as possible I guess right but it's not even true because yeah well I mean it is true if you don't think about one dimension but if you have two dimensions then now so then now the problem becomes okay let's say you have all my side length and c-mod side length all my side length and c-mod side length all my side length and c-mod side length right so then now and they could only fit you know so then these only goes up from zero which we don't have to care about because that means that it is optimal or like any possibility is good uh or if and we're just thinking about side length of SQL for three for now I'm just trying to visualize cases in my head as I'm solving this um so then now um so then let's say about one left over we have one left over we all want everything to be one right but and we have two left over we run you know everything to be on the first two rows for obvious reasons and that's the possibility but what if we have but this is now two Dimensions right as we say so what about one by one left over well we have one by one left over then it doesn't really matter because then now our so on the last row and last column we have right is that true well no yeah this is the case where you want it to look like this because then now you maximize your last usage of the last one last column and this will be sub-optimal because then now you're less sub-optimal because then now you're less sub-optimal because then now you're less row would look like this but then your last column would look like um one zero or whatever right and then alternating or whatever uh well not alternating but in that pattern so it would look something like this so that now the Palm is actually how do we fill out these right um so that's so for one by one we actually won this particular case because then now the last will be one right um yeah wow this is a hard problem I don't I thought maybe we could brute force it and maybe we still can in a smarter way but not in a naive way a good thing to know is that n is equal to 100 so maybe there is something that doesn't have to it doesn't have to be super efficient um yeah and then if it's two by two that or two by one first right then the first thing doesn't matter um right but then the last two rows uh or two by we do two by one then we actually want something yeah actually this is just this but right uh and so then here this is four or five and this is all three right for height and then now it's two by two then now you get into this trouble of um this is just one uh how do this look this is this uh one zero is that true foreign something feels a little bit off for five I think I messed this up uh the last this is also one zero I think four five yeah uh well maybe it doesn't have to be if this is uh but then if then now it becomes like what if it's this oh okay I'll use two different things that is a little bit clearer because I'm just confusing things now uh right something like this so you have to choose between this or using this pattern again if you use this pattern what will you it will you uh it's basically the same except for uh but now this part is much smaller right and so for mod 2 is leftovers two and two um you actually won this thing again I think yeah I mean I think this one is strictly less than because um you can move all the one from here to here as we did but here we just on the roads we strip excuse me we strictly subtract one hmm I guess we can just can we simulate how do we simulate um so we know the mods all right if we know the mods then we can just see if we can fill it up um so then we know that the longest side okay so we know the longest side of or the height of Riff whichever is longer um in that case we filled that up foreign well in that case we basically feel we can calculate this overlap in the corner and then filled that first right so that means that for here we want to fill the things that double counts right so which is a two by two so we have two by two mod then that means that um four of them are the overlapping bits and therefore we want this corner to be four by four because we know that by definition those are used by two things so then that's here and then after that it doesn't really matter what the uh what I mean matters but like it either goes from either here or here and it matter okay it actually matters because it's clear but then now we just fill up the rows instead okay I think this makes sense I don't know if that I explained it very well it's a way Ace for me is a very tough problem um so it's earning it's hard hardness um well let's see right Okay so and we're basically here it's just enumerating for b side so it doesn't really matter though maybe the way that I wrote it doesn't really matter maybe I don't need to do this depending on um we can actually just do this in a different way in that ribbon height doesn't matter because everything else is a square so basically we can do something like this is Max of the fight and then uh um I like it the other way around actually so that this is a longer so you have a longer Matrix than it than whatever right so then now what does this mean that means that we have two by two cells so uh yeah so max ones right Earth okay so now we're just counting the chord part which is the stuff that's inside right so and that part is easier because uh full R is equal to r divided by side length for C is equal to C so this is just a number four uh squares that are basically in the parts that doesn't matter um because it will always have Max one once so then now um so total is equal to times Max ones so far right but then now we have to count the extras and here we will fill this as much as possible right so this is the double count of piece it's so easy to get wrong that's why I'm trying to slow down a little bit and hopefully get it right in the first try and not you know Silly wrong mistakes it's something that I'm bad at so I'm trying to you know uh yeah um how do I do this actually well I mean basically the double overlap say is decode two on my side length times see my side length right if Max once is greater than double overlap or if this is less than double or equal to then we're basically done because that means that we have no or everything that uh well we put all the ones down in the places that dub overlap so then it also goes uh expands out as well which means it's good um then basically we have um let's see that means that we have another full or so how many uh extra column squares are there well it's just yeah for c times four or four times four C uh times Max ones and then because we have double lab so this is this minus one maybe this minus one right and that should be good just add an extra to correct all right else which is the hard part else um let's see right else I mean obviously I mean it's not that we only conceptualized and visualized it's just I'm really bad at math so I have to really think about uh or I'm really slow at it uh okay so basically the column ones right so the column ones will have the 4C number of them and as we said um there'll be more C than us that's by Design so the Sea of them 1080 C minus one for the double counting one but we'll keep it C uh let's just do c minus one so there these are the ones um even before that we want oh it's not quite enough is it because just because um so in this case well we have a two by two so it doesn't matter and it's five doesn't really matter but if this is we must we delete this Row for example uh you will this is longer it is not the decision maker right what is the decision a decision making love space available right for so how many spaces are on here uh in and we assume that this is going to be all filled because well that's just the definition of hue so then basically the amount of available spaces here is what we're trying to optimize because we can only by the definition of um we cannot fill uh by definition of that we have overflow so that means that over the double overlap part is all ones so then we have extra stuff so it either goes here to the left or the right and this is a heart uh so that means that the number of available space is going to be basically now we're just trying to figure out how many zoo um what is the impact of adding one zero to the longer side right so then now we have um so Z series SD code two the number of columns times I mean this is this minus one times um the mod of it's like side length minus besides it uh time citing minus um or something like this maybe because basic oh no column no yeah column my it's going to be it's something like this but also mod silent so that if it's because you can have silent number of holes so if this is um zero then you're done anyway but in that case I think that double I don't think this is possible to be zero just because then the double overlap would be um zero so then oh wait no that I guess it always wait what wait did I mess this up I think no I think I messed up the sign that's all basically this is saying that we have Max once anyway inside the overlap wait what is this part saying I'm kind of confused now this is just wrong isn't it huh basically what I wanted to no this is oh I see yeah okay yeah no this part is right because then now when we don't have enough for the overlap then that means everything doubles okay yeah well if it's equal then we everything still doubles because it's fine okay yeah so that means that here we have more max ones than overlap so that means we have extra ones but and the number of possible zeros I mean that's fine but I'm trying to think like I mean it is greedy I for sure but I'm trying to quantify the exact choice that we're trying to make here which is that okay let's say we have everyone convert one of the zeros on the longer side or one of the zeros on the height right and then we just basically iterate on that um no that's no okay yeah I think that's this is why I had it originally like this by definition of that's why I wanted to okay I think I got it so basically now we're trying to uh figure out how many um okay yeah sorry I have to thank for a lot of stuff but basically every time we add we take we have a Max one left over and we put it under the longer side well that will add 4C minus one right so basically this is the impact of uh adding one to the C side and this is impact of adding one to the column side so I think this part is fine and we know that this is bigger than this so we always want to follow it uh for the first One X um and you want to keep doing that as long as you can until this is full so when is this full so this is for when um so we have full column length but trimmed uh height so that means that and the column length is just going to be well wait what no I mean yeah um wait what give me a second uh well the full color the length is the same is side length that's why I got a little confused I'm confusing a lot of things this is kind of a hard part uh all right so basically we have side length and yeah so basically we have okay I see silent times side link is the number of space total spaces that we have to add right and or that we have space to add Max once um so let's calculate this so left over is to go to um max once minus double overlap right um and of course Total Space is equal to side length times side length because you can think about it as a thing and not all of them actually uh is attributed to the long left side but this is fake man watch I look at the solution afterwards and there's like some Yeezy like five liner and I'm just like oh did not understand it as well but I'm trying to work for it so hopefully this is helpful uh it's helpful if you even here so I don't know but okay so this is the total spaces this is the ones left over and so we have to figure out um you know calculate for uh to fit is equal to Total Space minus well it's once left over but it's basically uh okay so Total Space is this minus double overlap right yeah and then now we take the Min of the total spaces or once left over because I guess in theory you can have someone just write uh Max once you go like a billion I don't know I guess they actually limit this so that's not a possible case so I think that's fine then um so this is the total space left and then well I guess we don't have to do the total space left then because by we can assume that it wants left over is enough given that constraint okay so we have once to fit right and we're gonna put it on the full C minus one first because that's the impact that we get so um how many times can we fill it before it fall right so that's side length times length right so we can do so that's the number of extra rows that we get factored in right so that is the square well not Square rectangle that we have on the extra so it would be like maybe this or something like this uh oops so if you have something like this um it would be one of the three by twos is what we're trying to do here and yeah and basically okay we'll try to fill um we have to subtract that from so we have to subtract this so this is um bottom space I'll call bottom space so you go to this minus the double overlap because it's a double overlap of ones so these are the number of bottom spaces we have on the bottom and then so total we added to bottom space or we want the Min the bottom space or once left over times uh okay so here maybe I'll write put to bottom let's go to this and then now put to bottom times uh that's the number four things so put that and then now we can do one left over we subtract put to bottom and then the rest we just put on the column because we know that by constraint um it cannot go over nope and that's it I don't know if this is right it is of course not right but uh all right we made some good tough fun time so let's see what's up so max once is one and we return one so we got so this part I think is right uh the Double overlap what is the double lab oh the double overlap is one right yeah I mean we don't need to do that do we both might too okay so the double lap is so this is true did I mess this up so uh for all we have one for R times one oh is one times one but this isn't right this is Plus yeah this is Plus for each okay yeah um this is why I tell you those things all right I mean better um is this right no uh yeah no because it has overlapped it should be right so what am I missing so it's giving two so this is giving one plus one oh because this is full I think I messed up the country um because this is full r this is the extra one so you have to factor in the wait what okay so we have one full uh on the overlaps no this I mean well it's not so we have one plus another there should be two we have to round oh okay we have to round up because we don't count the overlaps or this doesn't count overlaps because yeah so we don't have to do subtract one in fact we add one because now we can't overlap extra okay yeah got that one fine uh that's tricky though okay so here we have two but we expect six okay so we have Max once is two um what is our code tell us I mean this is still even so this is good I suspect we have a lot of wrong answers on this one but yeah so this is one by so the max one is going to be one by one times two so this is two the double overlap is going to be one by one uh so the double overlap is one right yeah one by this is also one isn't it oh no this is right we have one full cell yeah so this is two um the overlap the double overlap is going to be less than so we have to do this for yeah all right that's good I mean try to get the wrong answer during examples then you know afterwards but okay so the one left over we have so max once is two the double overlap which we would put on everything did I maybe I missed I think I missed um a step yeah okay I see why because I didn't actually count the double overlap part uh so then now we have the double overlap right and you have to do this thing okay it's still wrong but maybe it's a little bit closer okay so the double overlap in this case is going to be one for the corner fair enough you have four r4c so that gives us one two three four five so then now it has to find this so then initially we put the bottom so maybe this is where it gets a little clunky so side length is two times where do I get times from this one was just wrong oh wait no I was thinking of something else this is where I had before okay so a number of bottom spaces so this is one decide and this is the other side right so R minus on my side length uh the number of rows is I mean this is going to be one as always is one and then the side length is two so this is two by one which is true so we have two spaces the double overlap is one so bottom space we only have one space left over uh put to bottom is gonna be so we have one and one overlap one left over uh it's gonna be one right so this is one times four C minus one um yeah so this is one four C no I confuse I named them four C they're full so this should be good like I don't know like I keep on adding one because uh subtracting one because I double count the overlap but all right I think with Gucci here let's give it some oh no I mean that I was gonna say my ideas but uh oh my implementation finally matches the idea but maybe we're off by a little bit and only 61 out of 105 cases so we did a lot but not enough um okay huh well rather that means that our algorithm is just fundamentally a little bit incorrect because that means that we're because if you're doing better than the answer it means that you have an implementation error somewhere um the reason being that um yeah you can do better than optimal um unless you know your logic is just well your coding is wrong if you do sub-optimal it may mean that your sub-optimal it may mean that your sub-optimal it may mean that your strategy as well but here it just means that there's some it's probably the mathematical part that as well I mean it could still be both but that is at least the first part right okay yeah okay so hmm I guess we just have to print a bunch of stuff so double overlap is eight um and once left over bottom space Maybe let's start with that and then we'll see so biome's face is 12. uh why is that um my source four by two wait what why is it 12 if it's just 10 it's in the four by two where do I get 12 okay so I which one is all again oh it's the minimum one so then now you have 52 by 74 so then you have two oh I see I'm um so basically it's a two by ten and then the double overlap is eight so that means that you have um okay so you have 12 left over well there's a lot of ones left over well I guess that's fine to be honest oh I messed this up that's why because we have to do um I see I assume that you cannot go over but I'm Wong here because it cannot go over um side length square but it can go over uh this so okay so I'm actually happy and in a sense that like this is tractable right like we can figure it out or this is the same ideas here which is that okay fine right space is equal to sign length times uh c-match side to sign length times uh c-match side to sign length times uh c-match side length minus uh double overlap right so then now we well we might move that first and then put to right is equal to Min uh write space one once left over and then now okay I was just being lazy to be honest I thought that uh that made a constraint but I just was wine and now it works or at least for that test case um that was a silly optimization that's a uh wow I mean that was a very hard problem I ended up spending 15 minutes here um the long probably the longest I've done in a while for a problem that I ultimately solved anyway um yeah I mean this is just case analysis I think and it becomes greedy uh this is a very interesting problem I don't know that there's a tldr for me um other than kind of constructing everything step by step um I'm gonna re-record the beginning of um I'm gonna re-record the beginning of um I'm gonna re-record the beginning of this video so or if you're watching this you'll actually get this video with an intro so if you're still here let me know what's your favorite um what's your favorite sports that you've been playing lately it could be outdoor sports baseball softball hockey or uh skiing snowboarding whatever let me know in the comments I've been doing a lot of softball and a lot of hiking uh yeah and I'll give you some like mental props for next time or something I don't know um but yeah uh this is all of One right so it actually didn't need things to be 100 by 100 maybe there's a simulation one uh maybe that would make it easier but everything I just owe by of one so maybe there is a simulation one let's take a look real quick uh basically the same idea I have so far oh yeah and then they okay so they did it this way that's why it was much easier because they simulated it um or like yeah okay but yeah I did it with all of one so I don't know yeah this is probably the same as this person so yeah um oh at one time of one space let me know what you think and yeah stay good stay healthy to go mental health I'll see y'all later and take care bye
Maximum Number of Ones
statistics-from-a-large-sample
Consider a matrix `M` with dimensions `width * height`, such that every cell has value `0` or `1`, and any **square** sub-matrix of `M` of size `sideLength * sideLength` has at most `maxOnes` ones. Return the maximum possible number of ones that the matrix `M` can have. **Example 1:** **Input:** width = 3, height = 3, sideLength = 2, maxOnes = 1 **Output:** 4 **Explanation:** In a 3\*3 matrix, no 2\*2 sub-matrix can have more than 1 one. The best solution that has 4 ones is: \[1,0,1\] \[0,0,0\] \[1,0,1\] **Example 2:** **Input:** width = 3, height = 3, sideLength = 2, maxOnes = 2 **Output:** 6 **Explanation:** \[1,0,1\] \[1,0,1\] \[1,0,1\] **Constraints:** * `1 <= width, height <= 100` * `1 <= sideLength <= width, height` * `0 <= maxOnes <= sideLength * sideLength`
The hard part is the median. Write a helper function which finds the k-th element from the sample.
Math,Two Pointers,Probability and Statistics
Medium
null
509
That a special welcome back to new video english video soaking explorer problem english course wishes in number and if you are not aware of ignore sequence it's something 40 number in bed with a sum of two pieces take vansh vacancy this line gear solid explain sequence understanding 40 Number one official numbers which where is the number of birth like subscribe and subscribe like two in one two three 500 600 hai subscribe like two in one two three 500 600 hai subscribe like two in one two three 500 600 hai to vihar two boys phimosis noida the 1957 can just enter because f30c number istri look saudi right direction begusarai just give like A Comment Share and Adjustment in Two Variables with 6000 to 2018 Me to the Stars in Adheen Wear Heavy Sorry About That Behavior Wing One Hair OK Services 0999 Having Amazing OK Abs Ko Song So They Can Just To This Software Uses Made in India Two Variables v54 620 Alien 621 Initially And Where Have Enough To Fear For Even Reach Backup Code Friendly In Recent Years After Reading Through N And This Changing Friend img2 JNI Plus Ne Jis Vishesh I TooJ Special I TooJ 100 Judges In The Largest Change And Dos This one ok this one is the result of some of two ok subscribe to hello viewers miding like this first wear heavy 04 having one legs having one to front and activation like a miding 281 times and where lost of the like underworld punjabi this Is returning back side which is the hero just heard no evil deed the number to 1658 and the soldiers eligible discus show science committee tourist office jhal that also postal discus indigenous southerner this problem box is aka 's marriage Ravindra Dishes 201 from which 's marriage Ravindra Dishes 201 from which 's marriage Ravindra Dishes 201 from which is The famous events and wheres change the best to variables in to-do list best to variables in to-do list best to variables in to-do list vegetables like a setting i2c ka to ujjain cylinder J2 i plus ne jo live wall this account deficit begusarai whenever this is the end stop sirvi and sister dai develop will be The Number Services Student Will Not Drinking In The Inside The List Or Something So Will Not Storing Sequence Of Opposite Numbers They Are Not Registered In The Space Extra Soviet System Using Condoms Pace And I Can Just Two Days After Using Near Time Like Appeared Jhal Doing In International Research Linear Time Was Asleep Decide Box Services You Can But In Comes Under To Tube Screen Will Be In Page Link In Description Play List To In Which Were Doing Its Problems And Interviews And Videos Vitamin E
Fibonacci Number
inorder-successor-in-bst-ii
The **Fibonacci numbers**, commonly denoted `F(n)` form a sequence, called the **Fibonacci sequence**, such that each number is the sum of the two preceding ones, starting from `0` and `1`. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given `n`, calculate `F(n)`. **Example 1:** **Input:** n = 2 **Output:** 1 **Explanation:** F(2) = F(1) + F(0) = 1 + 0 = 1. **Example 2:** **Input:** n = 3 **Output:** 2 **Explanation:** F(3) = F(2) + F(1) = 1 + 1 = 2. **Example 3:** **Input:** n = 4 **Output:** 3 **Explanation:** F(4) = F(3) + F(2) = 2 + 1 = 3. **Constraints:** * `0 <= n <= 30`
null
Tree,Binary Search Tree,Binary Tree
Medium
285
1,764
hey everybody this is larry this is me going with q2 of the bi-weekly contest 46 formed away of the bi-weekly contest 46 formed away of the bi-weekly contest 46 formed away by concatenating sub-array of another by concatenating sub-array of another by concatenating sub-array of another array so this one conceptually might not be hard um but hit the like button in the subscriber and join me on discord um but conception might not be hard as in if you know if someone tells you the algorithm you might be like okay but the tricky part is coming up with the complexity and analyzing this problem so oh why is this in squarespace uh so the thing that you might think about is that you know n is less than a thousand so you know the worst case is going to be something like um you have a group that's like you know a lot of ones and then you have numbers that's it there's a thousand ones right and you have a group that's like a thousand one but like ten in the end right so this would never match anything so this has like you know let's just say 999 ones and 110 and this right um and then your worry is that you know the complexity doesn't work out but it turns out that this is okay that it is n square because um this is n squared because sorry i'm just trying to think about what's the best way to explain it but n squared because if you think about because the thing is that you know you um the first comparison it's going to take all of this and then you know all of this uh and then it fails on the last one right and then the second comparison it's going to take all of this and then you know starting from this prefix is going to compare all of this and then you know you're going to get it and then it's going to be an n squared because that's just how you know you shift um because for each comparison you do all of n comparisons and you have o in the o of n indexes so together that's going to be of n squared um comparison and that's the complexity of the algorithm given that n is equals to a thousand that's good enough um so there may be some concerns where you know that may be too slow but when n squared is actually fast enough and the hard part again is to make sure that this is bound by n square and you may think okay but there are so many groups right so the key thing to note is that the sum of the groups length which is very easy to miss because i missed this a little bit is less than a thousand so that you know and there's a sort of you know the worst case is if they don't match right so that this is the worst case because as long as they match if they match we go forward this many items so then we never do those items again so no matter what happens um you know we always move forward on the bottom away so at most at the worst it's going to be n squared so that's basically the idea behind this algorithm and as long as you know that then the um or you know the algorithm makes sense if you are able to do that um in a way um uh and do that uh complexity analysis uh yeah and we'll go over the code now um so basically index is just so in essence you have a sort of a two pointer algorithm um so you have one pointer on the groups you have a pointer on nums and then yeah so index is the pointer on nums and then current oh there's the current why did i put them away so current so two pointers uh pointer on groups pointer or nums right and now you have two pointers well what do you do right well you move you do a comparison which takes over n times so this is a comparison and it does all end time in the worst case and if they match well then you move the pointer or nums you know by the length of the group's length you know you also move groups and you know we return true we're able to get to the end of the groups otherwise we move the nums index by one so that's basically the two pointer um and because you know this while loop is going to be o of n and this inner if statement is also going to be of n together it's going to be oh uh loops so o of n squared complexly together and in terms of uh space uh you could say that this creates a slice and stuff like that but if you but you can do this in uh constant space because you can just think about more pointers so you could do this comparison with just two more pointers or something like that and that's just like you know string comparison uh i think not gonna go through that but that's the basic idea um yeah cool um now that's all i have i think yeah and square time over one space hand wave beyond that one but you can do it in once all of one space so yeah uh let me know what you think and you can watch me solve it live during the contest next toast to belong and destroy someone say what okay well that's hard that's weird i would have to be in the same order okay that's what makes it easier or do a bow anyway there's a kind tricky one to do correctly so is that even white syntax i don't know okay this so hey thanks for watching hit the like button hit the subscribe button join me on discord and i hope you know you take care of yourself take care of others if you get the chance you know stay good stay well uh to good health and to good mental health i'll see you next time bye
Form Array by Concatenating Subarrays of Another Array
maximum-repeating-substring
You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`. You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`). Return `true` _if you can do this task, and_ `false` _otherwise_. Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array. **Example 1:** **Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\] **Output:** true **Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\]. These subarrays are disjoint as they share no common nums\[k\] element. **Example 2:** **Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\] **Output:** false **Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups. \[10,-2\] must come before \[1,2,3,4\]. **Example 3:** **Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\] **Output:** false **Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint. They share a common elements nums\[4\] (0-indexed). **Constraints:** * `groups.length == n` * `1 <= n <= 103` * `1 <= groups[i].length, sum(groups[i].length) <= 103` * `1 <= nums.length <= 103` * `-107 <= groups[i][j], nums[k] <= 107`
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
String,String Matching
Easy
1689
1,679
hey everyone this is Alex welcome back to my video series on solving lead code problems it's 1 in the morning I've been surfing all day and doing lead code problems and I'm tired but this is the last one so this is problem 1,679 max number of K some pairs you're 1,679 max number of K some pairs you're 1,679 max number of K some pairs you're given an integer array nums and an integer K in one operation you can pick two numbers from the array whose sum equals K and remove them from the array return the maximum number of operations you can perform on the array so if you have K = have K = have K = 5 you have 4 + 1 and then you have 2 + 5 you have 4 + 1 and then you have 2 + 5 you have 4 + 1 and then you have 2 + 3 so you can remove you can do two operations you can remove both all these two you can remove two pairs of numbers so how shall we do this I don't know well actually no okay so this how we going to do it let me get this example let me open paint and let paste it so we have this going on so what can we do we let's just iterate the array once and do something like hey for the first position is this number bigger than what we have or equal then if it's if so let's ignore it we need to find two numbers at sum so we found three okay so free smaller what would be the complement of it's actually free so we store free here and okay cool great and so this is like a set so we say free then we continue okay we have one is one on the set cuz it would be enough for the sum no it's not okay so 6 - 1 is for the sum no it's not okay so 6 - 1 is for the sum no it's not okay so 6 - 1 is 5 so let's put five on the set CU that would be nice that would be good so then we find free is free on the set it actually is so hey great um so let's remove free from the set and let's add the number of operations it was zero and now it's one because we did one operation okay let's move next number four uh it's smaller yeah good it's on the set no is it is the complement so 6 - 4 2 is two it is the complement so 6 - 4 2 is two it is the complement so 6 - 4 2 is two on the set no okay so let's just put four here then we find three again uh is free on the set no and well we can add it to the set but then it's over cool and we just did one operation which is yeah output one I think this was pretty simple so first of all we create um complement which is a set and now for um number of operations is zero so for uh num in nums if num is smaller is bigger or equal then K continue uh if uh num in complements then we say we do complement. remove uh no and number of operations that plus one plus equals one okay else um actually compliment shouldn't be a set because I want it to be a counter want to make it a counter so complements of numus equal 1 so complements of num bigger than zero if it's not bigger than zero then I think we just need to increment the K minus num because we want and then return number of operations submit well it works one shot one kill this was a quick one okay guys see you later going to sleep
Max Number of K-Sum Pairs
shortest-subarray-to-be-removed-to-make-array-sorted
You are given an integer array `nums` and an integer `k`. In one operation, you can pick two numbers from the array whose sum equals `k` and remove them from the array. Return _the maximum number of operations you can perform on the array_. **Example 1:** **Input:** nums = \[1,2,3,4\], k = 5 **Output:** 2 **Explanation:** Starting with nums = \[1,2,3,4\]: - Remove numbers 1 and 4, then nums = \[2,3\] - Remove numbers 2 and 3, then nums = \[\] There are no more pairs that sum up to 5, hence a total of 2 operations. **Example 2:** **Input:** nums = \[3,1,3,4,3\], k = 6 **Output:** 1 **Explanation:** Starting with nums = \[3,1,3,4,3\]: - Remove the first two 3's, then nums = \[1,4,3\] There are no more pairs that sum up to 6, hence a total of 1 operation. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 109` * `1 <= k <= 109`
The key is to find the longest non-decreasing subarray starting with the first element or ending with the last element, respectively. After removing some subarray, the result is the concatenation of a sorted prefix and a sorted suffix, where the last element of the prefix is smaller than the first element of the suffix.
Array,Two Pointers,Binary Search,Stack,Monotonic Stack
Medium
null
331
hey everyone so welcome to another mock interview video I guess this one is on pre-order string something validation pre-order string something validation pre-order string something validation something it's a pretty good problem I encourage you to first do it and then watch this video I guess the thing is I'm warning you that I didn't finish the problem I had to do it a couple factors like C++ not having it a couple factors like C++ not having it a couple factors like C++ not having split function and sometimes they're this question just has a trick and at this time I didn't get kinda see the trick I can keep giving excuses but yeah just so yeah try out the problem first then you can watch this video it's very painful and there's a lot of dead silence with me just thinking but if this was a national interview that would have been actually how I would performed badly but I still think the solution was actually pretty cool so if you don't if you just wanted to get all the like mumbling a fumbling around I'll leave a timestamp below so that you can skip to the part where actually like try to explain the solution because it's pretty elegant and you there's like a pattern and a lesson that you can get from it so that in future problems is it's definitely likely that you'll see a future problem that you can implement the same pattern or apply the same pattern as the solution so yeah without further ado keep watching or skip to the explanation of the solution but you should definitely do the problem first alright let's get started hey everyone is time for another mock interview let's just cut to the chase okay so this is a very verifying preorder sterilization of a binary tree so one way serialize the binary tree is to use preorder traversal we enter a non null node we record the notes value if it is no we record using a sentinel value such as hash so the above binary tree can serialize nine three four hash one Baba okay and then given a string or comma separated either by whether it is a correct period of traversal sterilization of a binary tree find an algorithm without reconstructing the tree okay so we're given a string and we're supposed to see if it's valid pre-orders supposed to see if it's valid pre-orders supposed to see if it's valid pre-orders serialization can this change wait but then so it's asking if so it's not asking if the sterilization mash is a tree it's just asking us if it's valid okay I'm gonna read this again for example verify whether it is a correct Credit River Sol sterilization of a binary tree so pre-order is like parent then left then pre-order is like parent then left then pre-order is like parent then left then right and then oh I know parent left right so parent then 3 is another parent 4 is another current then child of 4 to the back to 301 which parent of two hashes ok so then yeah this is true and then this is false because we need two hashes after the one and this is false because after two hashes you don't need you can't have another number because yeah like the parent is the nine then you have a hash thing you have the left child it has to the right child hash so they're both no so there can't be another child okay so the other they don't wants to reconstruct the tree I'm wondering if we can just do one pass and just go through the whole tree yeah let's try this out so we take the first number then we take the next number if it's if the next number is um if it's a number then the next number is the child of this number okay I'm going to try to come up with some cases just so that I can like sort of develop a pattern come up with a pattern so a number let's just have numbers be one and then hash so this true but then if it's three houses in a row it's false if it's let's see size of the hash number hash and then another number so that's your right nerd and then yeah so then at this point we don't really have to care about anything on the left side anymore because this is just the right child and then everything past this point it's going to just be the children of the three so maybe it's just a matter of like having the right number of hashes and numbers after that make sense so okay so I'm starting to get like a general idea but I'm still going to try to come up with a concrete pattern so three hashes in a row is that a definite no a number and then two hashes and then anything another number two is also know now if it's a number a hash and remember then it resets then anything can happen again so after a number it can be two hashes and stop I sure the time the thing is okay there is there's actually where I said earlier is invalid because mmm if I have a number and two hashes but there's like another number over here so I can still have more over here because this is the love child and this is the right child so you can't reconstruct the tree so this is again I have to come up with the rules for taking the string or processing the string so that I can figure out if it's a valid pure traversal mmm the idea of a stack comes to mind Oh oh yeah maybe else is a stack yeah a sack is pretty good okay so and to explain why I think using a stack is good is because there are a lot of levels and just having a stacked sort of helps me keep track of every level or like the next level without worrying about two levels deep or three levels deep or whatever meaning if I had like a binary tree that was like açaí height of 20 yeah I wouldn't have to care about like all the different notes above the level I'm worrying about okay so how to use the stack though so let's use this example I would print the nine print it 3:22 for then when I reach the hash I pop so this is the sack m9 is the head so when I have a hash I pop and then on the second hash one is the second hash I pop the four okay how is having a stack different from just allocating a tree is there any way I can just do this just by looking at the string yes so the thing with the interview questions is like sometimes there are a lot of options you can consider and I guess in this situation when I don't really know which option is the best option I can just think about each option really quickly so right now I can go back to maybe trying to figure out a pattern from just test cases or I can keep trying to figure out how to stack so I'm going to go back and just quickly try to see if there's a way to just look to just process this and then yeah see if it works so if I just process it one by one yeah I need to know how many levels are up there you know because 9 3 4 that's 3 levels in so that's why the double hash marks still work whereas if it was just for hash and 1 the two hashes would have counsel to 4 and then the 1 would make this false so yeah maybe I do need a stack so now that I realized I need a stack how do I actually use it flip it as a 9 I put in the three echo in the for the first hash mark doesn't do anything or it does turn the hash and then the second hash would take out the four at the same time if it's a four and hash and then another number then I have to complete this tree you know so what if this 5 also has like two hashes this hash okay so the second hash would take care of the 5 and then taking care of this 5 would take care of the 4 and at the very end I just have to check of the hash or if the stack is empty I think that's a valid but I think that's a valid algorithm I just have to figure out how to signal that I could pop off the stack and even before that I need to find out a way to parse the string I don't know how to do that easy recognizer for syphilis string dot find okay I guess we have to do count plus 1 okay and it stops ways such as the streaming first occurrence specified by the arguments what happens if there's no I there no matches your terms so this is what I'm proposing one while a pre-order dot find okay and we're trying to find okay I don't know if that's still what I'm looking for I'm trying to split it C++ strings split like home alright I'm just going to copy this okay so this code with okay so um is basically my wallet that just goes to the next item and right well this actually work so put the string in and then put peak we hit the song sure numbers this wasn't happening on a real interview okay this lot this one seems better how much time do I have left all right 20 minutes I got this all right so now the word or wherever is going to be in token so let's also need a stack and it's going to be a stack containing a string and plus is our STD stack should be okay so the stack now I'm just checking it's X methods so there's push so all and at the very end we return s dot empty because if it's empty then that means it's valid if there's still something in there then something messed up okay so now we just process the tokens one by one if token is equal to hash sign do something else we just have to push the token on to the stock now in the case that it is a hash mark what do we do well so if there's a first one then we don't do anything but if it's the second one then we have to pop the first hash mark and also the number yeah - her pump okay so then the problem is how first of all there's a lot of education through my mind like what if it's just two hash marks and that's it or if there is no number at the beginning how do we catch that but even before the so - I'm also thinking how do you chain - I'm also thinking how do you chain - I'm also thinking how do you chain stuff up because if you have to hash signs and you have to hash signs you get rid of them and you get rid of the number above that might be your right node which also gets rid of the number above that and gets rid of the number about that and so on so how do you know whether you're on the left side or the right side I could push a number I could push it into a pair so that's like a stack which is a pair and it's pair to the string and then a character that says our fly this is left or right and as long as it's a right node then I would pop that one too nice thinking stirring easier way to do this I don't know I can't see an easier way at this moment so I'm just going to let's say I'll pass on a character so um when I push I'll be making a pair string care and it's going to have a token and so but then how would I know if it's the left side or the right side why is this problem so hard I thought was a medium day okay well if I don't if I'm not able to solve this question I'll definitely make it explanation video for the so right now I'm just thinking like is there going back like is there a way to just derive some rules to just parse the string without having to use a stack I guess first you can see that there's the correct number of items wait no so the number of items isn't yeah it's not predictable because you know paths that don't go all the way down if they're just cut off in an old so what are the rules are that you go all the way left until you hit a hash and move up and go right and you go back all the way left until you hit a hash then you go up and then right and all the way left in this case we go all the way left we hit hash we hope we go right to hash then we carry that and go right and make all the left hit hash we go right hash okay I think it's probably easy totally there just needs a house let me use a stack so going back um if we want to push this pair o we push the string and we push a token in but then how do we know if it's the left side or the right side yes up 93 and 94 well I guess if you check the top of the stock oh wait you can check the top of the stack and then check to see if it's a left or right if it's the top of the stack all right so I'm the child I look up and my parent is a lot and I really don't know I was if I start at nine then I'm neither left or right so I'm like a center if I go to three how do I know what to left well if my parent is the center then I'm going to be my parent center and a character before me it's a hash isn't a hash so picture to perform use the center then know for sure on the left and then if I'm on another number and the number behind me as a left then on the left okay but if so let's say there's a hash and then there's a number okay so if the number before it the token before me is a hash the number right if the token before me is another number then the left and that is because yeah just every time there's a number it's always going to be on the left side but then after that let's say there's like a lot of hashes so these hashes will finish up that tree so then we get another number that number is going to be or right because if there's a hash before you know that a tree just got finished up or a subtree just got finished up and now I'm starting the right much time I have left five minutes our time sprint so is so that the s dot at the top is equal to hash sign then I'm going to push and I'm going to push sing that it's alright oh I stop push terror stream select routes okay and then after knowing that so if I reach a hash sign the first one I just ignore so the so if it's the one before means a number and don't do anything but if s top isn't or if it is equal to a hash then I want to pop and want to keep hopping until so while s sighs so while there is something to pop and esta top the second and cool to are so it's right then I want to pop set it like I'm missing something okay well if my token is a hash and then the one before me it's a hash then I also want to Hostel and that's before me this does no error-checking though sort of there's error-checking though sort of there's error-checking though sort of there's three hashes all this if it's a hash okay well what if there's a tree that just has a hash is that an empty tree or is that false I don't know that's something shafts I enter here but for now I'm going to say if it's a hash and there's nothing left in the tree so if that size is equal to zero return false okay four seconds I'm just going to submit it I see what happens a man killed bad what's happening you surprise hey everyone so yesterday I finished this problem not really but I ran out of time and I wasn't sure if I should have like just not posted this video because I just like failed or if yeah or if I should just post it anyway and I think I'm still going to post it because there's value in seeing me struggle I guess and I think the solution is actually pretty cool too so this is solutions like right here but first I want to evaluate my performance yesterday I think that yesterday I was debating between singing if there was like a way to process the string in order to solve the equation or if I actually had it like use a stack using the stack had like a lot of complexity and I'm not sure if so me making the stack that's basically sort of me allocating the whole tree again so I'm not even sure that approach was okay and I think one thing that really got me stuck was that C++ doesn't really got me stuck was that C++ doesn't really got me stuck was that C++ doesn't really have a split function like I think Java and Python a split functions where you give it a string and you're like split it by commas or split it by semicolons and it'll automatically like return a an array of that strip all the tokens split by that stuff like that character you give it or whatever so yeah looking back I spent a lot of time just getting that to work and then in the end it didn't even compile because I need to include something I think and yeah I don't know if you can include Stephanie code but apart from that yeah I couldn't figure out a way to process a string in order to solve this question and after looking at the solution I'm like oh I mean yeah the solution so obvious but at the same time I'm not really sure how I would have been able to arrive at this at like on the spot so this goes into how like you might not get all the questions immediately but then if you look at solutions now I'll remember the solution and not just for the sake of oh if I see this problem again how I am like oh I know how to do this it's more like there's a certain pattern there's a certain theme that this solution would has that other solutions in the future will also have what was the question I did before so the question I did before was the triangle question and I feel like this solution kind of has two shares the same pattern as a position for the triangle problem Banaras anyway so let's get looking into the solution and yeah okay so first of all basically the gist of it is you start processing from left to right and then every time you get a node you add to right no every time you how - no to right no every time you how - no to right no every time you how - no you - one so you have like a capacity you - one so you have like a capacity you - one so you have like a capacity and then what is this I want adding an unknown node and music the heck is an unknown uh all right I looked at this last night sir yeah so yeah um if it's not null you add - so yeah um if it's not null you add - so yeah um if it's not null you add - because it's a parent all right the goal at the end is I have zero capacity um but when you add a parent so something that isn't null you add to the capacity because in the if everything works out later on we finally when you see a null node you subtract one and then you see another one you subtract one because a parent has two children I think if you look over here on the top so let's see it's like five hash 15-5 the capacity it's like five hash 15-5 the capacity it's like five hash 15-5 the capacity would be two and then the hash would be minus one so now capacity is one and then at 15 per let's say it's a hash then capacity would be zero and you're good anytime that capacity goes to negative then it's false right because if you have another hash then yeah then that's not valid or if you have another number that's also not valid because I guess capacity is like how many seats you have left and if you have no more room to have children then you can't have any more right and you have any more than that's false and so when let's say instead of a hash you put 15 you still subtract by one because it fulfills the capacity given by five so it's like plus two minus one but because of this 15 you have to add two again so yeah so I guess you can think of it like you're processing the string as if you're building the tree again and you're just singling out whether or not it actually follows like the capacity whether on whether parent nodes have their children filled and whether or not there are no extra nulls or not enough nulls and yeah so I guess we'll walk through the solution so first you check if it's empty just returned false because I guess that's not valid then I guess this is like - this line is then I guess this is like - this line is then I guess this is like - this line is to guard against - off I winner then to guard against - off I winner then to guard against - off I winner then they just loop through the biggest loops through the whole string so what I also did was I try to tokenize a string but you didn't really need to do that all I needed to do was go to the last character before so the comma and then have the hash then it was a hash then cap has a null if it wasn't hash it doesn't matter if it's like a three-digit number or one digit number I three-digit number or one digit number I three-digit number or one digit number I just care if it's a number or not yeah so capacity is equal to one at first then they look through the whole string and if so we always just keep going until we hit a comma afterwards we hit a comma regardless if it's a no or a number we used to track money from capacity because it fulfills the capacity from above then we check if capacity of less than zero because if so then this node doesn't fulfill doesn't fill in any children of any parent node from above so return false otherwise we look at the detector from before and if it's not null that means it's a number which means where we need to find two more children below us so we had to the capacity and if all this works out in the end capacity will now equal to zero and we just check if it's not equal to zero then that means that the traitor network and yeah that's solution so I think it's very simple I think it's fairly elegant my takeaway I guess from this is when I'm thinking about problems this is sort of like an abstraction and to be able to see this abstraction is okay that might be like too broad but I guess I could say this like from now on I'll keep in mind that if I see a problem similar to this I'll know to count you know they're just I guess you could say there's this pattern where as you're taking more elements you have a count a counter and if that counter ever goes below zero then you know it's false or something this can be like a validator I know there's a similar problem dealing with you're given a string and it's like parenthesis and you're just trying to see if the parenthesis are valid like all the open parenthesis match with the closed parenthesis actually gave the solution to my friend a couple years ago for like one or two years ago he was like doing all this all the stack stuff and I was like why don't you just keep track of how many open parenthesis there are like you just count them and then when you see new open parenthesis you add one and then when you see a closed parenthesis you - Oi and if at the end parenthesis you - Oi and if at the end parenthesis you - Oi and if at the end you're at any point you're number of open parentheses goes below zero because you're closing too much and you return false and at the end if your numbers still positive that means you can close all your open parentheses so you also return false and looking back at that problem this problem is very similar instead of closing open parentheses we're trying to fill out all the children of parent notes so yes hopefully that explanation makes sense cool so after this video I think I'm going to make another to another video do another mock interview video yeah let me know if you guys like this video like a video even though I didn't solve the question is this so valuable to you this is another examine other example of like how even though I got so many internships I'm not exactly the best at doing algorithms and yeah like I already said this before but on the job you're not really required to come up with this it's either this one is like either did you see the trick you done it's kind of a trick right to be able to know so oh I should count the capacity or whatever yeah so yeah just let me know and hopefully I'll see you in the next video Thanks
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
113
hello everyone so today's lead core challenge is path some too so we have given with a binary tree and our goal is to find the every path which sum will be our Tower kit sum so here as you can see in this example number one our Target sum is 22 so path that become a 22 is 5 4 11 and 2 as same as 5 8 4 and 5. so let's jump into the code so first of all what we're gonna do we store our result in a list so for that we create result list so res r e s equal to empty list and after that we check if there is a no root node so for that if not root will return result after that we store our path in our stack so for that stack equal to we store a root value and sorry we store a root and root value root dot value now we iterate through our stack so for that while Leno stack is greater than 0 what we're gonna do we pop the value from stack so for that node and path equal to stack not pop now we check if not DOT left and not DOT right and our sum of path becomes Target value sum of path is equal to Target sum so what we're gonna do we append the path to our result so result dot append our path now we check if there is any right node remaining so for that if node dot right if it is what we gonna do we just append the right node to our stack so stack dot append node dot right and the path value of the node so path plus node dot write dot value and the same steps go for the left side of the tree so if node dot left I got append node but instead of right side we gonna append left side node dot left and path plus value of left side of our node so node dot value sorry node dot left dot value also I forget to add a column here and then we're gonna return our results so return result so let's try to copy and paste the code into the site so let me run the code oh I just misspelled the right so right and also here right and right now let's try to run again run the code and here as you can see our code is get accepted let's try to submit it submit yes our code is get submitted thank you for watching see you soon here is a full code
Path Sum II
path-sum-ii
Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_. A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children. **Example 1:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** \[\[5,4,11,2\],\[5,8,4,5\]\] **Explanation:** There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22 **Example 2:** **Input:** root = \[1,2,3\], targetSum = 5 **Output:** \[\] **Example 3:** **Input:** root = \[1,2\], targetSum = 0 **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-1000 <= Node.val <= 1000` * `-1000 <= targetSum <= 1000`
null
Backtracking,Tree,Depth-First Search,Binary Tree
Medium
112,257,437,666,2217
389
hi everyone welcome to my channel let's solve the problem find the difference in this problem given us a two string s and t where t is formed from the s plus adding one extra character and we have to find that character so how we will solve this so one of the easiest implementation is just we will use the character frequencies and increment while we are processing string t and decrement while we are processing string s and in the end the similar frequency like same character will be subtracted out their frequency will become zero while the extra character will have the frequency one so we will just quickly implement this is very straightforward problem and very easy i guess say and we will need a character array for 26 size and then we iterate for character c in t dot 2 care array and we will increment the frequency for c minus b will normalize to the index from like small a is on 97 ascii value to 0 so plus for t and same thing we will do for s we have to basically subtract it minus and in the end now we will index i from 0 and then we iterate in the for loop for i less than 26 basically and i plus and if we find any frequency of i is equals to 1 which means we found that extra character and we will break here and then in the end we just return the ah that character so that integer we will convert into the character i and then we also need to add the back a because we ah normalize the indexes into the ah 0 base so let us compile this code so code is getting passed so let's submit this code it's going on and it is accept it so what is the time complexity of this solution is o of n as we are just scanning two times what this string which has length one over n plus one which is when and this phase complexity is of 26 which is o of one but some people may argument like it's why it is taking 26 but if you carefully observe this problem like this snt has all same characters except the extra character so if you see this problem is like a similar to the another problem single number where like all the numbers exist in arrays two times duplicate and only the one number is exist in once so how we solve that problem we can use the jaw of the problem so let's solve using which also let's say i define a jar so initialize from 0 then we can do the jar of all the characters of care c in s dot 2 care array first then jar with jar so this will become the and random position this is a more letter and edit letter so this will become the java with c similarly we will do for with the t all the character of t which this will remove all the duplicate character and in the end we just left over the extra character and we will typecast it and return that character so that is another solution let us compile and directly submit it i guess it will pass so it is accepted now it is straightforward the space complexity is of one we are just using this variable so if you like my solution hit the like button and subscribe to my channel and if you still have any questions ask in the comment section also try to solve the single number problem i have video solution expel on that but i don't think after solving this you can solve all the problem thanks for watching
Find the Difference
find-the-difference
You are given two strings `s` and `t`. String `t` is generated by random shuffling string `s` and then add one more letter at a random position. Return the letter that was added to `t`. **Example 1:** **Input:** s = "abcd ", t = "abcde " **Output:** "e " **Explanation:** 'e' is the letter that was added. **Example 2:** **Input:** s = " ", t = "y " **Output:** "y " **Constraints:** * `0 <= s.length <= 1000` * `t.length == s.length + 1` * `s` and `t` consist of lowercase English letters.
null
Hash Table,String,Bit Manipulation,Sorting
Easy
136
51
okay so question 51 leak code n queens the end queen's puzzle is the problem of placing n queens on an n by n chessboard such that no two queens attack each other so we're 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 end queen placements where q and period both indicate a queen an empty space so the most important part about this question is the output and what format it's in so we've got strings containing periods indicating empty spaces and a q to indicate a queen this is going to become very important within the recursive backtracking function where we have to reformat this and i'll go through that in a bit so let's move over into the explanation so with this question what we need to do is we need to place queens within each row such that the queens are not attacking each other in any position now a queen can go up down and diagonals we need to account for this in our constraints so we'll have some kind of is valid helper function that's going to check the columns and the diagonals we don't need to check the rows because what we're doing to simplify is to make sure that queen is on each row and we're just going to loop through those rows because we know for a fact that two queens cannot be on the same row so in order to work out how to calculate a negative diagonal and a positive diagonal we need to look at the indices of the rows and the columns so a positive diagonal so at this point here we have three and zero at this point we have two and one at this point we have one and two and at this point we have zero and three what do we need to do across these in order to keep them constant we need to add them together so this indicates the positive diagonals let's do the same the negative diagonals and work out how to calculate those so here we have zero and zero we have one and one two and two three and three if we add these up like we did with the positive diagonals we're going to get different values here we have zero here we have two here we have four here we have six so we can't do that so instead what we'll do is we'll subtract them zero minus zero is zero one minus one is zero two minus two is zero three minus three is zero so to work out the negative diagonals it's r minus c so now we have those constraints we can create that is valid helper function so firstly we'd create that kind of recursive call we'd start looping through so we check to see if we can place q1 here we can because there are no conflicts there's no attacking queens anywhere else on the board so we go to the next row so we check can queen two go here no we have an attacking queen can queen two go here yes so we leave queen two there and we move on to the next row can queen three go here no we have an attacking queen can queen three go here no and it can't go here either so this is the point where we need to backtrack we need to clean up our recursive call so we need to remove q2 from this position and we need to place it at the next position in line there is no attacking queen so it can go there then we repeat the process so queen three can it go here no can it go here yes it can queen four can it go here no it can't can i go here no so we need to backtrack again q3 we need to remove that we need to place it next along can't go there and it can't go here so again we need to backtrack we need to go back to the previous one q2 can go no further along this row so we go back to q1 and we reposition q1 next along q1 goes here so q2 can q2 go here no can it go here no can i go here no can it go here yes q2 can go there q3 can q3 go in position one yes it can q4 can't go here because there is attacking queen here q4 can't go here but it can go here and we are now in the last row so we are at now with this question what we need to do is we need to push this into a result array and reformat it so that it is all string values so we'll add that into results we'll create a copy of it because we still need to use this board to check for any other solutions so i won't bore you with the rest of it but the whole idea is these are going to be removed again q1 is going to move over and then we're going to repeat the process and the result is going to be two separate boards that mirror images of each other okay so that's enough of the explanation now i think we should jump into the code and see how it's implemented so firstly we have an example here where n is equal to one let's just solve that straight away so if n the length is equal to one we can return an array with q as a string so with this solution a really efficient way of looking to see if the column or either diagonals have an attacking queen is to use steps to store this information so cold is equal to a new set positive diagonal is going to equal to a new set next diagonal is going to equal a new set also we need to have a result array to store the results in and we need to create a 2x2 board that we can eventually manipulate add values into and then push into results and the way we do this in javascript or one way we do this in javascript is like this and this will create a 2d array where each value has a period in it as a string so the bulk of the question is going to rely on a number of different helper functions so firstly we need to check if the current position is valid we're going to take in row and column i'm going to check if column doesn't have an attacking queen we're also going to do the same for positive and negative diagonals and we need to check whether it has r plus c as we stated in the example the negative diagonal is the opposite r minus c so that's checking if the position is valid we also need to add the queen so we need to add the queen to a position again we're going to take in row and column we're going to add column to the col we're going to add the position to positive diagonal and we're going to do the same for negative diagonal as well and finally we need to add the letter q to the board at rc now we need to remove the queen and this is for the cleanup so the recursive call is going to have backtracking in it and in order to backtrack we need to clean up the board so we need to actually remove the queen from the board so that we can check other possible solutions and when resetting the border rc we need to equal it to the period okay and that should be it for the helper functions now we just need to create the recursive backtracking function so remember backtracking is just a recursive function again we're going to be using dfs in this approach but backtracking just means we're going to be popping off so we're going to be cleaning up afterwards in order to check all other potential solutions so function recurse we're going to be recursing over the rows so if we call it passing in 0 as our starting row inside all recursive calls as a template we have a base case and a recurrence relation okay so if rho is equal to n we need to push into results now this is the most important part because we need to create a copy of the board because we're going to be using the original board to check for all other solutions and then we need to map over that board and join with a string create a copy of the board so we spread out the board map over the board grab the row and join biostring and that will give us valid output now we can carry out the recursion so we need to loop through the columns so column is equal to zero column is less than n because it's an m by m board increment the columns we need to check if the board is valid so we can use our helper function now if it is valid passing in row and col we can add the queen now add queen helper function pass in row and now we need to carry out the recurrence so recurse we're going to pass in the function so recurse and increment the row last but not least we need to backtrack so we need to remove the queen and clean up and finally at the end we can return res so let's give this a go and see if it's work okay it's been accepted let's submit it and there you have it now time and space complexity uh time complexity is o n factorial space complexity is on squared where we've used extra memory for the three sets to store the board state and also the recursive call stack however to keep it at this complexity space used for the output does not count towards the space complexity
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
284
okay so how's it going ladies and gentlemen so today we are going to solve another coolest problem uh lead code 284 picking iterator okay so the problem statement is saying like we have to implement a picking iterator class and that class has three main functions to do okay when the next one you can see over here and the another one is a peak one and uh we have one hash next okay so these three of them have different tasks to do right okay so what the next will do the next will return the value at current iterator and then increments the editor okay and the hashness will tell us is there any element after the current iterator and the peak will only return the current element will not implement the iterator i hope so like you don't get the idea but don't worry these are main things these uh three things we'll do okay so for example we will take this similar example over here one two three okay and my initially my uh what will happen so initially my pointer will be at on one okay so i will give the peak value initially will be one so what the peak stream is saying we have to only return the current element uh when we will it will not wanna increment it so initially it will be at one in the beginning it will be at one so we will written the one over here on the peak okay on the next one so when we see the next one first of all what we'll do we will written the value first of all currently and then we're going to increment the uh iterator what that's what the definition i have told you okay so we're going to increment it over here and now it will gonna move to two okay so and we get one now again we get the peak so the peak will give the only two value the current value and it will not gonna increment now we have has next so hashtag hasn't it what it will do it will check do it has next element present if it has prison next element then it will gonna return two for us otherwise it will go right at four so like two has yeah we have three so it has next and one so we're gonna get two okay the next one so we get we find the next so next what it will do it will gonna give you two and then it will gonna move to three like this way now again next what you'll do it will gonna first of all give you three then it uh it will gonna move to the furthermore further we don't have anything and we are good and has next so has never changed do we have anything uh further on from three it will say no so we're gonna get false over here so that's how the basic uh approach to understand this problem i hope so this thing is absolutely clear so now let's just talk about like how we're gonna uh solve this problem okay so uh like uh we initially in the code we have given a class something like this whatever present over here okay and in this one first of all my job is to create one iterator i will create one iterator which you're gonna iterate on to the current uh complete array okay so let me uh i will initialize with iterator of integer and let me call it idea which is initially null okay then what i will do i will create one uh integer called let's say called next and this next one what it will do it will gonna written me it will gonna written with the peak value and gonna move to the next okay but first of all it will gonna written the peak value only okay so to move to the next we're gonna use the help of idea which we have it we have created over here initialize over here okay then we go to something public function so the public is like peaking iterator okay we're doing something like this over here so don't worry about the code the core in java's uh available in the description section just check out the link from over there okay so we got something iterator integer and iterator okay i-t-e-r-a-t-o-r i-t-e-r-a-t-o-r i-t-e-r-a-t-o-r something like this now in this one now okay honestly now in this one what i will do i will first of all uh initialize my iterator to iterator idea er2 iterator okay so we go the current position which will get initially at one okay we get initially one okay now what will i do i will check if has next if i have the next value then only i will gonna increment my uh the peak value i will gonna give my next one okay so next we will go i t r dot next it will move the next value of the iterator okay so that's how we are doing now after doing this job what i will do uh what we have given we have to uh written the peak value so to return the peak value i just have to simply return my next which i have created over here integer peak so i'm gonna simply return my next so which we have created over here okay and uh finally we have something a public item next okay so i uh i have to uh public integer next so i have to move my next pointer to the next value so for example initially we are at one so we want to move to the two okay so for that one we have to do some task over here okay guys so before moving to that next value first one i have to retain that value the current value so for that one what i will do i will create one integer and let's just call it current value which is giving me the peak value initially on which the next is pointing okay then what i will do i will check if we have the next one if it has next has the next if we go to the next value so how we're going to check using has next if has next is true if sorry if i d er if i t er.murli dot has next i t er.murli dot has next i t er.murli dot has next is true then what we have what will happen i'm gonna uh move my next pointer to the next value okay so that's how we are moving it else as if we don't have and if we don't have the next value then it means we have simply null so we're going to simply initially next window and finally return our current well so the current value we have created over here we have written over here i hope so this thing is absolutely clear ladies and gentlemen okay and finally the last thing what we have given us something like public boolean has next so again something like public boolean has next we have to check we have to like have that what it is dope is don't check like whether we have the uh next value present or we have null present okay so how do we gonna return it so we just simply say if my next not equals to null so for example like uh over here we are on the three so three is not equal to null okay initially so uh but it is not equal to number but it later dude has next is pointing to null so what are we gonna get we're gonna get the phones so or uh i t e r dot has next so uh if any of this is get uh true we're gonna written true otherwise you're gonna get fours from over here i hope so even gentlemen this thing is absolutely clear so that's the all complete queries and yeah if you still have any doubt just do let me know in the comment section and thank you very much for watching this video and again saying the java code is available in description section just check out the link from over there sorry for my bad handwriting and thank you very much for watching this video take care bye
Peeking Iterator
peeking-iterator
Design an iterator that supports the `peek` operation on an existing iterator in addition to the `hasNext` and the `next` operations. Implement the `PeekingIterator` class: * `PeekingIterator(Iterator nums)` Initializes the object with the given integer iterator `iterator`. * `int next()` Returns the next element in the array and moves the pointer to the next element. * `boolean hasNext()` Returns `true` if there are still elements in the array. * `int peek()` Returns the next element in the array **without** moving the pointer. **Note:** Each language may have a different implementation of the constructor and `Iterator`, but they all support the `int next()` and `boolean hasNext()` functions. **Example 1:** **Input** \[ "PeekingIterator ", "next ", "peek ", "next ", "next ", "hasNext "\] \[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 1, 2, 2, 3, false\] **Explanation** PeekingIterator peekingIterator = new PeekingIterator(\[1, 2, 3\]); // \[**1**,2,3\] peekingIterator.next(); // return 1, the pointer moves to the next element \[1,**2**,3\]. peekingIterator.peek(); // return 2, the pointer does not move \[1,**2**,3\]. peekingIterator.next(); // return 2, the pointer moves to the next element \[1,2,**3**\] peekingIterator.next(); // return 3, the pointer moves to the next element \[1,2,3\] peekingIterator.hasNext(); // return False **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 1000` * All the calls to `next` and `peek` are valid. * At most `1000` calls will be made to `next`, `hasNext`, and `peek`. **Follow up:** How would you extend your design to be generic and work with all types, not just integer?
Think of "looking ahead". You want to cache the next element. Is one variable sufficient? Why or why not? Test your design with call order of peek() before next() vs next() before peek(). For a clean implementation, check out Google's guava library source code.
Array,Design,Iterator
Medium
173,251,281
334
foreign name is increasing triplet subsequence so the question is given an integer array nums written true if there exist a triple of index i j k such that I is less than J and J is less than K and nums of I is less than nums of J and nums of J is less than nums of K if no such indexes exist return false so in simple words what we have to find subsequence of three numbers which are increasing in order if we are if we will able to find then we will return true if we can't find then we will return false so subsequence means we can the subset of any array which the subset of any array where the numbers are not continuous their indexes are increasing but the numbers are not continuous like one three four I can take this subsequence this has subsequence 1 2 5 this is subsequence so any subsequence we can take but what we have to return true if that subsequence that triplet subsequence is increasing so how we can find so this is uh this is an array two one five zero four six how we can solve this question so the idea is we are taking two integer C1 and C2 because we have to find triplets okay we have to find triplet so I am taking 2 integer one I am I will when I will go through this array so this I will go through this array and I will compare this number with these numbers I will compare this number with these two numbers if I will find this number as greater than both of them if I will find this number is greater than both of them then I will say the I have found the triplet then I will see I will I have found the tablet just see first I will take C1 and c2s into max first I will take C1 and C2 as into mix okay so now I am at two so it's uh 2 is less than I 2 is less than c 1 yes it is less than so I will update now C1 is 2. okay now I am at 1 if 1 is less than C1 yes 1 is less than 7 I will update C1 again now C1 is 1 okay now I am at 5 is 1 is less than C1 is 5 is less than 7 No 5 is not less than 1 okay now I will check 5 is less than C2 here it is less than C2 so I will say update this I have updated okay now I am at 0 I will say 0 is less than 1 yes it is less than so I will update okay I am 84 I will say 4 is less than 0 no 4 is less than 5 yes I will update again I have updated okay I will check and I am at six I will check 6 is less than zero no 6 is less than four no so 6 I found a number six which is greater than both which is greater than 0 and which is greater than 4 which is greater than both of them so means I have found one subsequence so I can return true so idea is very simple now we will code what I have done I have taken two integer C1 and C2 and I have taken their value into Max and what I am doing I am just running a for Loop in which I am going through this elements going through this numbers so what I am checking if this number is less than or equal to C1 updates even okay if this number is not less than equal to C1 then I will check else if it is less than or equal to C2 then update C2 if it is both if it is greater than both of them then return true and if whole for Loop is run but I have I haven't returned true it means there is no subsequence so I will return false at last so it is running
Increasing Triplet Subsequence
increasing-triplet-subsequence
Given an integer array `nums`, return `true` _if there exists a triple of indices_ `(i, j, k)` _such that_ `i < j < k` _and_ `nums[i] < nums[j] < nums[k]`. If no such indices exists, return `false`. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** true **Explanation:** Any triplet where i < j < k is valid. **Example 2:** **Input:** nums = \[5,4,3,2,1\] **Output:** false **Explanation:** No triplet exists. **Example 3:** **Input:** nums = \[2,1,5,0,4,6\] **Output:** true **Explanation:** The triplet (3, 4, 5) is valid because nums\[3\] == 0 < nums\[4\] == 4 < nums\[5\] == 6. **Constraints:** * `1 <= nums.length <= 5 * 105` * `-231 <= nums[i] <= 231 - 1` **Follow up:** Could you implement a solution that runs in `O(n)` time complexity and `O(1)` space complexity?
null
Array,Greedy
Medium
300,2122,2280
1,980
hey how's it going find unique binary string 1980 uh leak code given an array of nums containing n unique binary strings each of length n return a binary string of length n that does not appear in nums if there are multiple answers you may return any of them okay uh first off we're going to make a tree class and then it's going to be uh def in it self. D equals dictionary you know what I don't like that uh default dict of type tree okay and then we're going to have a root equals tree and then we're going to have 4S in nums then for C in s and n equals root and we're just building the tree so it's going to be n Dot N equal n do uh I don't know uh D of C and uh that should be good so how big can it be and is less than 16 so there's always one right all right so we just got to go find one that isn't uh isn't used and that should be easy so defr of N and oh current string I guess sure why not uh H result equals none if result is not none then return we're not going to do anything else that means that one of our uh fellow threads found something we're going to do a simple depth first search uh yeah R so if what if length of n equals 1 then it's perfect we have found uh something so this is going to be our branch and we are going to return current uh string plus uh give me a python here uh o Rd of Z One um C HR one oh that's perfect beautiful uh so we don't even have to know what it is uh cs plus CHR of O Rd of list of n.d. n.d. n.d. keys and uh zero no it goes right there um and then of course one so the opposite of whatever we have right um let's see otherwise uh if the length is zero then I don't think we need to pursue it unless the length is less so yeah let's do it so if uh length of Cs is less than length of nums of zero and not length n then that means that there's nothing below it so uh nonlocal result what I didn't mean return I meant um result equals and then return and otherwise uh result equals cs plus doesn't matter what we do cs plus zero um and return now if length of Cs + 1 equals length of nums of zero and Cs + 1 equals length of nums of zero and Cs + 1 equals length of nums of zero and length of n equals two then we're done there's nothing more that we can do here um so this covers if it's one this covers if it's two this covers if it isn't finished um I think that's it um so let's see while length of result is less than length of nums zero it doesn't matter what it is result equals result plus and then return result objective type non type has no length you see the problem object of type tree has no length where is that length of n d plus Z so wait what if it's two and it's not the length then we have to recurse if length of n equals 2 and it's not the maximum length then we need to do uh both r n. D of0 comma cs+ cs+ cs+ Z right yeah wrong key one and one please work this is really a stupid problem objective type tree has no length line 20 length of have a real problem with that okay I wish it were easier to declare a recursive relationship of just default dict of type default dict and then you wouldn't I wouldn't have that problem that I was just having uh anyways that was kind of a silly problem but uh whatever
Find Unique Binary String
faulty-sensor
Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_. **Example 1:** **Input:** nums = \[ "01 ", "10 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "00 " would also be correct. **Example 2:** **Input:** nums = \[ "00 ", "01 "\] **Output:** "11 " **Explanation:** "11 " does not appear in nums. "10 " would also be correct. **Example 3:** **Input:** nums = \[ "111 ", "011 ", "001 "\] **Output:** "101 " **Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct. **Constraints:** * `n == nums.length` * `1 <= n <= 16` * `nums[i].length == n` * `nums[i]` is either `'0'` or `'1'`. * All the strings of `nums` are **unique**.
Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1.
Array,Two Pointers
Easy
null
1,675
hello everyone let's solve the problem minimize deviation in Array you are given an array Norms of n positive integers you can perform two types of operations on any element of the array any number of times if the element is even divided by 2 if the element is odd multiply it by 2. the deviation of the error is the maximum difference between any two elements in the array return the minimum deviation the array can have after performing some number of operations let's see the example this is our given array and initially we have a maximum difference or maximum deviation so what is the maximum deviation here it's the difference between the maximum element and the minimum element okay that is 19. so initially our maximum deviation possible is 19. our task is to minimize this maximum deviation our task is to minimize these maximum deviation there is a bit improper phrasing in this problem we are supposed to not supposed to return the minimum deviation we are supposed to return the minimum possible maximum deviation after performing these operations any number of times all right now the thing is how do we lower the maximum deviation say this is our maximum deviation right how are we supposed to decrease it we can only decrease it if we increase the minimum element and if we decrease the maximum element then only the gap between them is going to decrease and our deviation is also going to decrease right now we are given two types of operations that we can perform if an element is odd we can multiply it by 2 if our element is even we can divide it by 2. so this thing is given and this idea of increasing the minimum and decreasing the minimum you are going to use this idea okay now let's try to apply this operation on the elements of our array currently our maximum deviation is 19 okay we can increase an odd number by 2 multiplied by two what is what are we going to do we are going to increase the minimum and decrease the maximum okay so let's increase the minimum we have one let's multiply it by two we get 2 and let's decrease our maximum what is maximum it's 20 it's even we can decrease it by two it becomes 10. now what is our maximum deviation or maximum deviation is maximum minus minimum that is 8. fine now let's do it further let's increase our minimum element is 2 but 2 is even and we can't increase our number which is even we can only divide it not multiply it right so we can't perform any operation on this one let's leave it as it is now what is the maximum it's 10 what can we do 10 is even we can divide it by 2 and make it 5. now what is the maximum deviation possible the maximum is 5 and the minimum is 2 5 minus 2 is 3. okay can we do anything further let's see our minimum is 2 maximum is 5 2 is an even number we can't increase it or multiply it by 2 the maximum is 5 that is odd we can't divide it by 2 anymore so this is where we stop if we try to alter the other elements let's say we can increase three to six we can decrease four to two it's not going to help us right because 6 is a bigger number and two is a smaller number our deviation increases to 4 so that's not useful right so this is where we stop so let's try to observe something what did we do we increased our minimum at each step and we decrease our maximum at each step that's what I told right initially so what does it mean we are going to need access to the minimum and maximum at each step right we are going to need access to the minimum and maximum at every step and if we can then only we can alter it right for this purpose we are going to use a tree set that is an ordered set right it will provide us the access to the minimum and the maximum at constant time right we are going to need Min and Max at each in each step right so we are going to use a tree set now what will be our algorithm at first we will initialize our preset right then in the set we will add the elements from our array but if the if an element is even we will add as it is what if an element is odd we will at multiply it by 2 Double it and then add it now why are we doing this see our first type of task is to turn the odd numbers to even numbers by multiplying it by 2 and the second type of task is to divide the even numbers by 2 okay now we know how are we going to achieve the minimize the maximum deviation by increasing the minimum and decreasing the maximum so by multiplying the odd numbers by 2 we are increasing the minimum possible values in nums which are possible to be increased right so if you have one if you have three we increase them to two we increase them to six right we are doing exactly this thing right so we at the very first we complete this task now our task only remains to perform this one that is minimize the maximum values that are present and by performing all these operations we will at each step keep calculating our difference and one of them would be the minimum we will keep track of that okay now let's see the code initially we are going to have a preset integer let's call it set new tree set okay what are we going to do we are going to put the elements in nums in the set if it is odd and modulus 2 if it is odd we are going to add its double set dot add n into 2. otherwise we are going to add the number as it is if it is even I have made this part shorter by using a ternary operator if the number is odd if it is true at the Double otherwise add the number itself okay now let's initially have a minimum difference let's uh initialize it with maximum value okay now let's start our work while true we will do that as long as we are able to do let's see int min set DOT first this is how we extract the minimum right it's at the it's the first element in the set which is uh minimum and Max equals to set dot last the last is going to be placed at the last position because it's sorted okay minimum difference is going to be math dot min imum difference and the difference between current maximum and minimum okay if our maximum is still an even what we will do what did you see we initially turned all the odds to events now we are trying to divide the even numbers and made the make them odd we are trying to minimize the maximums okay if the maximum is an even let's decrease it how we will first remove this element we'll first remove the Max and add its half Max by 2 say for maximum is 20 we will add 10. we will remove 20 and add 10. otherwise if the maximum element that we are looking at is no more even number let's see in this example see the maximum element in this case is no more even number right we have an even number here but if we divide it we are still getting a 2 right this is not going to make any difference right we are supposed to look at the minimum and the maximum so we can't change the maximum anymore in that case we will break out and at the end we will return the minimum difference now let's try to run it fine now let's quickly do a dry run of our approach so this is our example what did we do we first turned the odds Loop double right 2 10 20 remains as it is 3 becomes 6 now we will perform our task in this one okay so what is the minimum it's true what is the maximum it's 20. what is the deviation 18. is the maximum even yes half it divided by 2 it is 10 but since it's a set we have unique values so this is what finally remains okay now what is the minimum two what is the maximum 10 what is the difference it's 8 fine what is the maximum is it even yes divide by 2 at the half what is it's 5. now again what is the minimum it's two what is the maximum eight six okay what is the difference it's four now is the maximum even yes it's even remove it and add its half pull now again what is the minimum it's two what is the maximum it's five what is the difference it's three okay is the maximum uh even no maximum is not even that's where we stop because all as already said if we alter the remaining elements that's not going to help us this is where we stop okay so this is our minimized maximum deviation fine now what is the time complexity initially we are running a loop and adding all the elements to the set that would take an into login time adding takes a login time and here what we are doing we are extracting the minimum maximum which takes big of one constant time then we are removing and adding elements to the set again the text login time but how many times are we doing this see what we are doing here exactly is we are turning the maximum element to minimum that is we are dividing the maximum element by 2 as long as we can and to bring a element even element to 0 by dividing it by 2 at each step takes a worst case time complexity of log 2 of say that number so we are doing this much time right say we are decreasing our Max so that will be a log of Max time and into log of n because at each step we are adding and removing so this is our time complexity and our space is definitely big off and we are storing all the elements in that reset initially right so yeah this is pretty much the solution it is a bit complex I would say definitely a hard one so that's all if you like this video do hit the like button share this video And subscribe to my channel if you haven't and I will see you in the next video bye
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
779
Hello everyone Welcome to my channel here we solve problems Lead code today task number 779 kata symbol in a line we build a table of N lines numbered from one we start by writing zero the first line now we form the sequence of each line as follows we replace each zero of the previous line with sequence in a new line and each unit is replaced by 1 0 for example for N = 3 the first line will be but the second for N = 3 the first line will be but the second for N = 3 the first line will be but the second line will be 0 and the third will be 0 10 0 Given two numbers n IR it is necessary to return the th character of the Noh line of our tables, this problem can be solved straightforwardly in a loop each time receiving the value of a new line from the previous one, but in this case, if we look at the limitation of the problem, we can have up to thirty lines, respectively, the thirtieth line will contain d to the thirtieth power of elements, despite the fact that we need to store the previous line, we can hit the limit on memory, so we need to find some more efficient solution, let's look schematically at what we have in terms of data. We have a zero line, which is always zero, so more precisely, we start with one, so we have this first line, then the next line is obtained. According to the rule, zero is replaced by 01 we write it indented in this way and the third line is similar zero is replaced by 01 one is replaced by 1 0 we get something similar then under the third line we sign the indices of the elements they also start from one we sign them as K1 K2 K3 and 4 now let's look at our tree if we consider that this is a fragment some kind of large structure, that is, it is not necessary that Etoka 1 And maybe f tables, for example, there from Ritz rows we will look for a solution recursively, that is, what we have if we consider the last row then what can we do here how can we get the elements here that is, for each element we can look at what parent it has to find out the parent given the element number, that is, 1 2 3 4, we can get the parent by dividing the current index by two and rounding up the larger side, that is, 1 by 2 is 05, rounding we get about 2x 2 is one does not need to be rounded because it is already an integer and Similarly, the two subsequent elements are rounded to two, respectively, the index of the previous element is one and two, then what we see is now for each element of the previous line, for example for zero. How can we find out what its child element is? here Everything is enough. We just need to look at the even or odd child element, if it is odd, that is, one, then we see that in our case the element itself is zero, for even it is equal to one. Similarly, if the parent element is one, then the child is the opposite, for odd one, for even zero. Thus, we get the value of the child elements recursively on the contrary of the parent elements until we reach the first line in the first line we can explicitly return that in the first line We have a single element - this is zero for comment Let's write in the code our bass case first That is, if N is equal to one this we immediately return the first line, but then we need to return the Parent value, let's call it Pan, for this we call our function for the previous element, that is, N -1, as I already -1, as I already -1, as I already said, we need to pass the key equal to rounding up, defining it in two, to rounding up, we use the cil function from the library we pass K to divide by 2, then we need to understand whether the current index is even or odd, let's call the variable from that is, the variable will be if the current index is odd for this K, the remainder of division by 2 is equal to one now, as I said earlier, we will look at the parents elements That is, if Pan is equal to zero, we will return zero if the current element is odd since we begin to connect then odd is the very first element, otherwise we return one for the case when the parent is one That is, this is the right side, we will return one if the current index is odd otherwise Zero by idea, this should be the whole solution Let's try to run the tests, passed, check the result, decision made, Thanks everyone for watching, Bye everyone
K-th Symbol in Grammar
max-chunks-to-make-sorted-ii
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`. Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows. **Example 1:** **Input:** n = 1, k = 1 **Output:** 0 **Explanation:** row 1: 0 **Example 2:** **Input:** n = 2, k = 1 **Output:** 0 **Explanation:** row 1: 0 row 2: 01 **Example 3:** **Input:** n = 2, k = 2 **Output:** 1 **Explanation:** row 1: 0 row 2: 01 **Constraints:** * `1 <= n <= 30` * `1 <= k <= 2n - 1`
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Array,Stack,Greedy,Sorting,Monotonic Stack
Hard
780
304
so lead code practice in this video there are two goals the first goal is to see how to solve this problem and then we are going to do some coding work and the second goal is to see how should we have in a real interview so let's get started so in the real interview the first goal is always try to first understand the problem if there is anything unclear please bring up the question and also at the same time think about some ash cases that you need to choose especially in the next step so let's see range some query 2d immutable so given a 2d matrix find the sum of the elements inside the rectangle defined by the upper left corner and the lower right corner so the valve rectangle is defined by row one row two with two one and row two sorry row one car one as two one you're able to call today as uh 4 3 which contains some as eight all right so i think it's pretty clear about the question let's think about if there's any ash cases so let's see the notes you may assume that the matrix doesn't change and there are many calls to the sum region function and you may assume that row one is smaller or equal to row two and columns smaller equal to column so we don't need to worry about the illegal row one row two stuff but there's still some question i think uh that's unclear so for example is the matrix uh going to be empty like uh the number of rows is equal to zero or the number of columns is equal to zero uh and also if row one and row two and column one column two are within uh the within the number of the rows or and the corresponding number of the columns within the matrix so if the row one row two column one column two could be out of range so that those are the questions in my mind but let's assume that we have a matrix which is not going to be empty and also let's assume that uh the row one row and columns the upper left corner and the uh and the bottom right corner are within the range of the matrix so let's start with that so that we don't need to worry about those special ash cases so the next step is about finding solution so how to solve this problem so the solution wise um what i can think maybe we could use some dynamic programming to record some status uh so let's see how to do it so the first thing that comes in my mind uh is uh we could so for each row we could calculate the prefix sum and then when we are trying to call the sum region then we just need to because we have the prefix sum of each row then we just need to uh for each of the row uh within the sum region then it is going to be one regarding the calculation uh so for example for this uh specific matrix we have the sum row prefix sum for the row 2 3 and 4. so for calculate this region you just need to calculate you just need to use prefix sum for this cell minus the prefix sum for this cell and then we are going to get um you're going to get the sum region uh within all of uh n and is the number of the columns within the subregion but let's see if we could do it any better than this um so let's see if um so this is defined by two one okay so let's see if um if we so okay so i think we can have a better way to do it so what if we start so we trade so first of all we define this as the origin so what if we compute the so for a certain point what if we compute the sum of the sum region from the origin point to the current point so for example we compute all the numbers within this uh rectangle uh and we put the number for it to be here uh and by the way we need to define a dp array a dp matrix for this so the number put in the dp matrix for this index would be the sum of this uh this part and similarly we are going to compute all the elements within the dp metrics we defined to compute the sum region of this we just need to get the corresponding number from the dp matrix of this index and also this index so it will be like dp here minus dp here plus dp here so then it will be we will be able to uh calculate the sum region of the corresponding of the defined sum region so for this one to calculate the constructor um the constructor would be o m n so m is number of the rows and n is a number of the columns and for some region call it will be all of one regarding the runtime so let's do some coding work on this approach i think currently this is the best approach i could we could find we could think of so the next part is about coding so how to sell how to code uh so in the coding part you need to care about the speed don't be too slow and also the correctness of the code and the readability of the code so let's see num metrics first of all we need to define private number let's say we define a column sum from origin and then in the so in the constructor we have rows as equal to matrix uh less remember we have the assumption that the matrix is not going to be empty so this is matrix 0 without lens so we are having sub from origin uh as you call the new in row and uh columns so uh you're going to have eyes for starting from zero i smaller than so how so if we yes i think first of all we could do is you could assign the value for the first row and the first column then it will be easier for our computation but let's see if it's yeah then i think it would be easier for our uh other competition let's say i is equal to zero smaller than the row and plus i so you're going to have matrix uh i zero as equal to uh this is sum from my region as matrix i zero similarly for the first row uh j is equal to zero j is smaller column plus j and uh 0 j is equal to matrix 0 2 j okay so this i would be starting from one to row and j would be starting from one to the column so to compute so the sub from origin uh i j it will be equal to uh sub from origin first of all it is uh i so it is i minus one so this is the last row stuff plus the sum from origin i j minus one stuff i j minus one which is the next column yeah so what i was trying to do is to compute this cell so for example to compute this let's say for to compute this cell we need to so we could get the sum from origin of this and some of the region of this and get them together plus it minus some range in this plus the matrix value of this so minus the sub from origin i minus 1 j minus 1 plus the matrix i j yup that's a sum sub from a region computation of that and then to compute the corresponding region we just need to return so let's assume that row one column one row two column two it's within the range of the matrix so this will be just the return sum from origin uh row two call 2 so minus 7 from origin this is so this is row two column two so this way we should have the so we should if this is uh so if this is so if row one column one so this is the row one column one this is row two column two so we need to do is we need to subtract this part so let's see um int sun has equal to this is uh for sure to be good i would say if row one is larger than zero then we need to subtract minus equal to sub from origin uh a region okay so this is sub from origin row 1 column 2. and similarly if column 1 is larger than 0 which means if the column one is larger than zero but like here if the comma is smaller than zero then we actually have nothing to minus the sum minus equal to sub from origin row this is row 2 column 1 okay so this says let's take a look at this example this one would be okay so this is actually minus one and this is also a minus one so if it is this is the row and column you're going to subtract this part is uh this part is row 1 minus 1 column 2. this part is uh row two this is row two column one minus one okay and also uh we need to have take a look if row one is larger than zero and uh real and the column one is larger than zero then we need to have some plus equal to sub from origin this is uh this is row one minus one and then this is column one minus one and then finally we return sum because we have subtract this area twice so we need to add it back so uh i think that's pretty much it about the code uh remember after we are done with coding it's time for us to do some testing for testing uh it so the one way is to just uh go through a simple test case is and at the same time do some sanity check and explain how this piece of code is going to work so let's see if the matrix is something like this let's compute the so the first row subprime or region is going to be uh exactly everything from the first row and first column is going to be everything from the first column so to compute let's say to compute this one what we are going to do is we have a subframe or region uh i minus 1j which is this so and then sub uh from a region i j minus one which is this here so minus the sub from a region i minus one j minus one which is this and plus uh the corresponding thing i hear so plus minus this so this one will be three uh sorry it is five plus zero minus three and plus six yeah so i think the yeah this is the logic for to compute the sub from a region and let's see if we are going to calculate something uh we are going to call them a region api so here let's say this is a row two column two this is zero one column one so we are going to have row uh row two column two uh which is a the sum of this region and we are if because the row one is larger than zero we are going to subtract the row one minus one column two so row one minus one which is this row column to this column so you're going to subtract the this region from it and we are going to minus row two column one minus two so this is row two and the column one is this so column one minus one is this so we are going to subtract this region and also because 0 1 is larger than 0 column 1 is larger than 0 we are going to add back this area because we essentially subtract this one this area twice so let's see i think it works it looks good uh let's uh yeah let's fix some typo here so line 11 here all right so it seems like it's accepted let's give it a submission it's run timer array index autos okay so it seems like uh our previous assumption that in the matrix is not empty is not it doesn't apply in this system so we definitely need to deal with that kind of case especially so if i would say uh if row is equal to zero then we just return and if um column is equal to zero then we simply return they should handle the empty metric stuff but i'm not sure if there is any like uh out of the bomb so okay so output is none minus five minus four minus five minus one so let's see why we have the matrix as minus four minus five and uh when we call the zero one we are so okay so when we call this zero one we are actually returning a minus 5 from our output but how oh okay so actually when we try to get the sum from a region we are actually wrong uh we should it should be instead it should be um uh so okay so this one should be starting from one say sub from origin so this definitely the bug so zero as matrix zero because we are defining sum from a region as the sum so we cannot simply set it as the original number from the matrix instead we should be uh is equal to sub from a region that says uh i minus one zero something like this and similarly we are going to have this as j uh minus one so i think this is going to cover the yeah so this is going to cover the bug yeah so that's it for uh this coding question um if you have any question about the solution or about the code please leave some comments below if you like this video please give me a thumb up and help us subscribe to this channel i'll see you next time thanks for watching
Range Sum Query 2D - Immutable
range-sum-query-2d-immutable
Given a 2D matrix `matrix`, handle multiple queries of the following type: * Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. Implement the `NumMatrix` class: * `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`. * `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`. You must design an algorithm where `sumRegion` works on `O(1)` time complexity. **Example 1:** **Input** \[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\] \[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\] **Output** \[null, 8, 11, 12\] **Explanation** NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]); numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle) numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle) numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle) **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `-104 <= matrix[i][j] <= 104` * `0 <= row1 <= row2 < m` * `0 <= col1 <= col2 < n` * At most `104` calls will be made to `sumRegion`.
null
Array,Design,Matrix,Prefix Sum
Medium
303,308
368
hello waves welcome to algorithms maidenly today we will go through the day 13 problem largest divisible subset please like the video and if you are new don't forget to subscribe to our channel so you never miss any update given a set of distinct positive integer find the largest subset such that every pair si comma SJ of the elements in this subset satisfies the condition if there are multiple solutions written any subset in first example both 1 &amp; 2 &amp; 1 &amp; 3 are first example both 1 &amp; 2 &amp; 1 &amp; 3 are first example both 1 &amp; 2 &amp; 1 &amp; 3 are valid pair so we return one pair now in example 2 we can see every pair of elements satisfies the condition so the whole list is a result let's see how we do it we will take a bigger input to understand all cases we will start from first element and keep on iterating till the end let's consider there is only one element in the list and number modulus itself is always zero so we add one to the list for 1 now let's consider there are two values as we've already calculated list for one we will now calculate list for two we will check two with all previous values and as 2 mod 1 is 0 we will copy the list of 1 into 2 now as no more elements are left to check for 2 we will add 2 to the list now there are 3 elements we will check for 3 mod 1 as it is 0 we will copy list of 1 to 3 now we will check for 3 more 2 as it is not 0 and also no more elements are left for 3 we will skip it and add 3 to its list now there are 4 elements as for mod 1 is 0 we copy a list of 1 to 4 now for mod 2 is 0 so we compare the size of the list a size of list 2 is greater we override it on the list of 4 as 3 is the last element for 4 and is not a mod of 4 we skip it and add 4 to its list moving to next element we calculate 8 mod 1 as it is 0 we copy a list of 1 to 8 more to is also zero so we compared the list size an over at list of two on it eight more three is not equal to zero so we move ahead 8 mod 4 is zero so we again check for less size as list four is bigger we override it on eight at the end we add it to the list now the last element we checked for one and copy list of one as nine mod 2 is not zero we move ahead 9 more 3 is zero so we compare size of list and over at least three on nine now 4 &amp; 8 both does not satisfy mod nine now 4 &amp; 8 both does not satisfy mod nine now 4 &amp; 8 both does not satisfy mod condition so we skip them and add 9 to the list and then we are expected to return the list of maximum size in our case it is the list of eight now what if initially the input was random and as our approach works for assorted input we will first need to sort our input and then apply this approach as we have broken down the problem in smaller problems and then use the result from smaller problems to get the result of our original problem the approach we use is called dynamic programming here is the actual code snippet from the method also check out the link to the java code in the description below the time and space complexity is o n square thanks for watching the video if you liked the video please like share and subscribe to the channel let me know in the comment section what do you think about the video
Largest Divisible Subset
largest-divisible-subset
Given a set of **distinct** positive integers `nums`, return the largest subset `answer` such that every pair `(answer[i], answer[j])` of elements in this subset satisfies: * `answer[i] % answer[j] == 0`, or * `answer[j] % answer[i] == 0` If there are multiple solutions, return any of them. **Example 1:** **Input:** nums = \[1,2,3\] **Output:** \[1,2\] **Explanation:** \[1,3\] is also accepted. **Example 2:** **Input:** nums = \[1,2,4,8\] **Output:** \[1,2,4,8\] **Constraints:** * `1 <= nums.length <= 1000` * `1 <= nums[i] <= 2 * 109` * All the integers in `nums` are **unique**.
null
Array,Math,Dynamic Programming,Sorting
Medium
null
60
hey hello there today's liquid in chinese questions called permutation sequence we have a set of n different numbers uh for number of conveniences i actually want to add uh we want to consider all the unique permutations we can do with this set of n numbers so it's a n factorial in total because for the first position that we decide the number it will be n choice the second position it will be n minus one all the way to the right elastic position we just have one choice so multiply those together we get a factorial so that's the number of permutations we can do with n numbers if we sort those permutations in the lexical graphically order you know from the smallest to the largest a giving example where n equals three we're dealing with a number one two three the permutation sequence in the sorted order will be one two three one three two uh two one three two three one two three uh three two one so uh if we actually obtain the sequence of permutations we won't find the case one from the sequence so if we actually just generate all those we can just directly take the case one from the list from the sequence but it will be really time consuming and the space inefficient to generate to actually generate all those sequence and to think about it n factorial subtractor one sequence is totally useless in our case so we want to find a way to directly generate the case one so how we're going to do this we want to try to look at the permutation sequence and look at the look for look out for patterns now we're dealing with n equal to 3 and we see that there are distinct three different groups inside the permutation sequence they are indicated by the first digit here so the first group of size two uh their first digit is the smallest among all the choice we can do at the time one two three the second group they all started with the second largest element we can choose from the set of uh numbers we can do uh there are elastic group it's uh starting with the largest one the reason that they are grouped in sequence is that if the first digit starts uh is two the second largest one it has to uh anything any sequence that we can form with this smallest number has to come before that so how many are those uh if we fix the first digit the remainder problem basically is uh n equal to two problems so the total choice for there for that is uh two factorial so it's two so that's uh telling us uh um the sort the permutation sequence of uh grouped uh in different groups indicated by their first character and the first character or first digit first number in that sequence is sorted order if we just don't want to group these groups by uh grouped all this sequence by the first character it will be one two three that would be in the sorted order as well so this tells us instead of generating all those we can try to do this one character one number at a time so if we looking at k equals 3 here it's larger than 2 so it's definitely not in the first group it's smaller than 5 so it's definitely not in the third group the only group it can belong to is the second one so we can make sure we are sure that the first number in this case sequence uh the requiring uh it's going to start with two so we can just iteratively figuring that out and populating this required sequence of one character one number at a time uh all the way towards the right so it will be a divide and conquer kind of pattern here so just a little bit concretely what we're going to do is to for a given size at n we want to calculate the group size so here it's a 2 factorial that's n minus 1 factorial and use the relationship between k and the group size to figure out which group it belongs to if it belongs to the ice group it will the first character for the case sequence we are looking at is going to be the ice smallest element number we can choose at that time and once we made this choice we exclude this number from the available numbers and also updating the k because the k now should be the new k for the problem that's one size smaller and what's going to be the new k it's going to be the k that uh we skipped the first number of groups that has the first character smaller than an hour so we skipped some of the all the groups that's before us so that's why we subtract the prior group number of prior group multiplied by group size from the k to update this to be the new k then the problem becomes a n minus 1 problem with the updated k and also the updated number choice we have so basically we're just going to maintain the three things and iteratively shrinking them while the same time each time we shrink the problem size smaller by one we adding one more digits to the sequence we are building out so it's just going to be looking like that so let's just start code this problem up so obviously we won't generate n numbers so it's going to be a loop running end times and so the first thing we do is to calculate the group size let's just call this group size it's going to be factorio uh maybe we will store the pre-calculated the factorial number pre-calculated the factorial number pre-calculated the factorial number ahead of time or using some function it doesn't really matter which is going to be n minus 1 and the eyes the choice about the group identifier number and the new k is going to be the doing this division modular between uh the current quarry k and the group size uh let's just call this size s then or i can just put it in here so if we have a something that holds the result we will basically append the eyes smallest choice that we have at this time to this result list and actually once we put it on there we have to pop it out from the available numbers because it's been used in the subsequent step we can no longer use that number so it's uh let's call this digits or something uh in the end we just stitch together this thing to be a string again um yeah all the left is basically populating this digits and the factorial function here is just uh yeah for convenience we have uh just a one to n and for the factorial uh it's starting with a one and we're populating up to n minus 1 because n minus 1 is the largest one that we will be getting from here which is iteratively appending the number multiplied by the last factorial number so that's uh that generates the factorial array so three two one zero um so should i be n minus one right so this will still run this will not run when it's zero so if it's uh three it will run three two one then the first time you will skip up so again it's end yeah let's see if it works uh no we are generating two three one instead of uh two one three um what's the problem oh it's uh the it's a the key here is the index the front one so um i should just decrement k by one then i think we are good to go yep uh is it accepted okay so yeah so this is the code uh it's a the divide and conquer approach um we notice that the sequence are sorted the permutations in the sorted sequence are grouped uh grouped together and for the lines we're looking at we're gonna just have that many corresponding groups to the end we are looking at uh so based on the relationship between k and the group size we can figure out the leftmost card and shrink reduce the product size to be one smaller but still the same problem so that's the code it's a pretty it's not difficult today surprisingly alright so that's it for today
Permutation Sequence
permutation-sequence
The set `[1, 2, 3, ..., n]` contains a total of `n!` unique permutations. By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`: 1. `"123 "` 2. `"132 "` 3. `"213 "` 4. `"231 "` 5. `"312 "` 6. `"321 "` Given `n` and `k`, return the `kth` permutation sequence. **Example 1:** **Input:** n = 3, k = 3 **Output:** "213" **Example 2:** **Input:** n = 4, k = 9 **Output:** "2314" **Example 3:** **Input:** n = 3, k = 1 **Output:** "123" **Constraints:** * `1 <= n <= 9` * `1 <= k <= n!`
null
Math,Recursion
Hard
31,46
24
what is up guys the Tiffany line here today I am going over swap nodes in pairs I've been learning about linked lists today so it just reads giving a linked list swap every two adjacent nodes and return its head and we made not modify the value and list nodes only nodes itself may be changed so they want us to return the original list with just the pointers moved so they just want us to swap the two and then go to the next two and swap the two until we're done so I did this on the whiteboard what we're gonna want to do is we're gonna want to loops call this one first and second and then we're gonna put preb here so let's do that we're gonna want to let me it's easier when I just told you that there's no so we're gonna have a dummy node move node which is gonna point to the original head so let's put the value 0 and tell me that next people's head so right now our list looks like we just added a 0 so this is dummy and dummy dot next is right here okay and so let's create a prep mode equals and we're going to set it equal to dumb so we're going to want to loop through the entire list while had this one equal no and head that next step does not equal no because we need to swap two so if there's if head dot next is no there's nothing to swap so that's why we have that so let's create our first nodes equals head and with no second head stop Knicks alright so now we have to do the actual swapping so swapping on the whiteboard we're going to want to point probe dot next to second so we're gonna want probe that next they prove that next to point two and so now we have prep dot next is right here prep next we're going to want to move second dot next is going to be first but we have to make sure we do it in the right order so let me think about it real quick what's the right order because I believe first we got to do first dot next equals yeah first done next equals second dot next because we have to set first next equal to 3 right here because if we move second that next it'll mess everything up already so it was second dot next if we lived on second thought next first it would have messed everything up so you got it the order is pretty important so now we can do second down x equals and so let's go back to the drawing board so second dot next is supposed to be first so right here second this is still second and we're gonna point it towards the first so first and that's how we swap and now we need to move Trev and head along so let's move grabbing them head on the drawing board so right now we have 2 1 3 4 so we want preb to be here and head to be here so right now we can see that probe so let's do press equals first and head equals first dot next first stomach first thought next because first is right here still we haven't updated it so we want to put head at first dot next so that's that um dummy dot head is still all the way back here so dummies out head is - or dummy here so dummies out head is - or dummy here so dummies out head is - or dummy dot tell me dot next is still at the back so it's still right here oh I'm sorry I don't have it up on the board it's still right here so that's what we're gonna want to return that's like our pointer to the beginning of the list so let's return that return tell me next and that should work nope whoa oh wow that was like the stupidest mistake okay perfect so we got a hundred percent it's open run time and then it's I believe it's on and space complexity because we have to create new nodes so let's see no I guess it's not it's all it's linear because we're not creating it oh we're not creating a new list that's why if we do it recursively we have to create a new list so iteratively it's actually easier and it's more efficient I had trouble understanding their cursive so I'm not going to be going over that but thanks for watching guys
Swap Nodes in Pairs
swap-nodes-in-pairs
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.) **Example 1:** **Input:** head = \[1,2,3,4\] **Output:** \[2,1,4,3\] **Example 2:** **Input:** head = \[\] **Output:** \[\] **Example 3:** **Input:** head = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the list is in the range `[0, 100]`. * `0 <= Node.val <= 100`
null
Linked List,Recursion
Medium
25,528
497
hey guys welcome back to another video and today we're going to be solving the lead code question random point and non-overlapping random point and non-overlapping random point and non-overlapping rectangle all right so in this question we're given a list of non-overlapping given a list of non-overlapping given a list of non-overlapping axis aligned rectangles write a function pick which randomly and uniformly picks an integer point in the space covered by the rectangles so in this question there's two uh key words that you really need to understand in order to actually solve this question so the first one is non-overlapping so how many other is non-overlapping so how many other is non-overlapping so how many other rectangles were given these rectangles are non-overlapping so they're not on top of non-overlapping so they're not on top of non-overlapping so they're not on top of each other one the area of one rectangle does not cross or intersect with the area of another rectangle so that's one of the first things we have and the second really important point is the word uniformly so over here we have a function pick which randomly chooses a point and uniformly picks an integer point so the word uniformly is very important over here and this word actually changes how we approach this question completely so what i'm going to do is we're going to start off by looking at how we could solve this question and what possibly could be the best way to solve this and finally we're gonna implement it using python all right so okay so over here i'm gonna start off by drawing two very basic rectangles so over here i'm gonna call this one over here r1 and i know i'm not drawing it on the axis but the whole point of it is to show you why one method is actually not valid so this is going to be rectangle one and this is going to be rectangle two and i know they're not perfect by any means but what i want to show over here is the fact that r2 is clearly bigger than r1 so what you need to understand is r1 is smaller than r2 as simple as that and what i'm going to do over here is i'm going to have two lists or sets right so the first set is going to include so i'm going to call this a p1 sorry so p1 and it's going to include all of the points inside of r1 so what is this going to look like we're going to have this point all the way until we get all of the points inside of r1 so this is going to have a length of x so we have some points right and it's going to have a total of x points so the total number of points are x for rectangle 1. similarly let's have all the points for rectangle two so in p2 i'm gonna store these values and similarly we're gonna go get all of the points the same way until we get all of them and over here you need to notice that we're still gonna have points right and they're gonna be different to p1 obviously but the fact is that we're going to have more points and the reason to that is well we have a larger surface area or area covering r2 and it's just bigger so the length of this is going to be y and let's define the variables x and y over here so i won't give them values yet but what we know for a fact is that y is going to be greater than x no matter what since r2 is just bigger than r1 and now what i'm going to do is let's try to think about what is the most intuitive way to solve this so what i thought of the first solution is well what i'm going to do is i'm going to pick a random rectangle so in this case i have two choices r1 and r2 so i'm either going to pick r1 or r2 and after i pick one of them i'm going to pick a random point and this actually sounds pretty valid sounds like a good option but this is actually not the case and we have to go back to the word uniformly over here and that's very important and doing this is not going to give us uniform results why is that well so let's take a look at this what is the possibility that we get a point from p1 so p1 has a total of x points so one of the points getting up one of those points is a possibility of one by x similarly when you have p2 what is the possibility of getting one of those points well it's going to be 1 by y and that's because x and y are different we have different amount of points so these over here are actually two completely different probabilities so by doing this by just doing our naive approach we're not going to uniformly distribute all of our points just to make this more clear let's say x has a value of 20 and y has a value of 40 then in that case the probability of getting a point from x is going to be 1 by 20 versus getting 1 for y is going to be 1 by 40 and obviously 1 by 40 is lesser than 1 by 20. so now let's see how could we actually come across this problem and how could we solve it all right so to come across this problem we had we can do one of two things so let's go through the first solution and what this is basically as it is we have two different sets right so one for all the points of rectangle one and on one which has all the points for rectangle two so what we could do is we could add these two into one some sort of super set right which holds both of these subsets inside of it right and in that way we're going to have the same probability and uh in that method the probability for choosing one element is going to be 1 by x plus y so the chance of getting any element is going to be the same to do that the problem is you need to add all of the possible points for rectangle 1 and you also need to add all the possible points for rectangle 2 and that could actually add up to being a lot of points so that's going to take up a lot of memory so let's look for a better solution so the answer to solve this is to use something called weighted probabilities so for x over here we have a value of 20 and y has a value of 40. so let's start off with the very beginning what is the possibility that we get one point from p1 well it's just going to be 1 by 20 and the possibility that we get one point from p2 is 1 by 40. okay so now let's look at it's complete this is the overall probability and to do that we need to find what is the total number of points we have well it's just going to be 20 plus 40 which equals to 60. so 60 is the total number of points we have and now let's calculate for p1 what is the probability from 60 points that we get p1 and the answer to that as well is 20 by 60 which is equal to 1 by 3. and similarly for p2 that's going to be 40 by 60 which is well it's just going to be 2 by 3. okay so now that we have this these represent the weights so what we're doing is we're giving rectangle 1 a lower possibility that we choose the smaller rectangle and we're given the big and we're giving the bigger rectangle a higher possibility that we're choosing that rectangle and if that still doesn't make any sense how this might be working uh let me just show you real quick so let me just get rid of this okay so over here we for p1 to get a single point from p1 we have a probability of 1 by 20 and for p2 to get a single point it's 1 by 40. so what is the weight of p2 it's 2 by 3. so if we multiply this by 2 by 3 and let's say we multiply the value of p1 by its weight which is one by three so multiply that by one by three over here you get a value of one by sixty and over here you get a value of two by one twenty which when you further simplify it's just 1 by 60. and notice that these two are the exact same values so what is happening is that by adding this weight each of the points have the same probability of getting chosen so this is going to make our search a lot more effective and it's going to give it a more uniformly distributed probability so let's see how we can do this in code and i think it's pretty simple once you understand how this actually works or the theory behind it all right so let's start off with our code and before i do that i want to show you two things so one of them is that in our rectangles list we have several different rectangles and this is how each rectangle is represented we have a x1 comma y1 value and this actually corresponds to the bottom left value and then we have an x2 comma y2 value which corresponds to the top right coordinate of our rectangle and another point that i want to point out is the fact that a point on the perimeter of a rectangle is included in the space covered by the rectangle so the parameter whatever if a point is on the parameter it is considered as one of our points okay so keeping that in mind let's get right into our constructor okay so let's start off by uh saving the rects of all of the rectangles we have so self.rex equals to red self.rex equals to red self.rex equals to red right and after that we're going to find out all of the weights so i'll start off by just initializing an empty list and we're going to add all our weights to that and simultaneously we're going to have a sum so i'm just going to do some underscore and what this is going to hold it's going to hold cumulative sum of all of our weights and this is what we're going to be using for normalizing the values and if you don't know what normalizing is it's basically we're taking our values and we're going to convert them from 0 to 1 and we're going to basically get a percentage okay so now this is going to start off with the value of 0 and let's iterate through each of our rectangles so i'm going to do for x1 comma y1 comma x2 comma y2 and rex so over here sorry so over here we're actually going through each of our rectangles and what we're going to do is our first step is going to be to find out the number of points that are possible in a rectangle well how could we find this well it's pretty similar to our area function we take x2 minus x1 so we take the sorry length and we multiply that with the width sorry i meant to say this is the width and we're going to multiply that with the length so in this case y2 minus y1 well this is just our area and one thing we really need to be careful about is the fact that we can include the parameter so what i'm going to do is i'm going to add a value of 1 for our width and for our height in order to include the points on our parameter so now with this we're going to do one of two things first we're going to append this value to our weights so self dot weight start append and we're going to append num points and we're also going to do one more thing which is that we need to add this value to our sum so self.sum underscore plus equals so self.sum underscore plus equals so self.sum underscore plus equals to uh well num points okay so now we got okay so we're going to iterate through all of our rectangles and at the end of this we're going to have our weights and to show you let's just do print self.weights do print self.weights do print self.weights and one more thing we need to do is now we need to normalize those values right which is to get those values down from values between 0 through 1. and how are we going to do that well we can just use list comprehension to do that so self.weights we're going to change so self.weights we're going to change so self.weights we're going to change its value and i'm going to do x divided by self.sum i'm going to do x divided by self.sum i'm going to do x divided by self.sum since that's the cumulative sum for x in self.weights for x in self.weights for x in self.weights sorry i can't type okay there we go okay yeah for x in self.wait and now again let's print in self.wait and now again let's print in self.wait and now again let's print self.weights and let's see what happens self.weights and let's see what happens self.weights and let's see what happens okay so i'm just going to click pass over here and let's run our code okay so as you can see we first got four comma three so basically what that means is our first rectangle had four points second rectangle had three points and after that we normalized those values and basically what it's saying is that the first rectangle now has a weight of 57 so it's given a higher weightage since it's a bigger rectangle and the smaller rectangle the second rectangle is given a lower weightage of 42.85714 percent of 42.85714 percent of 42.85714 percent which is smaller since the rectangle itself is smaller okay so now that we have this we can move on to our next function which is the pick function i'm going to get rid of the print statements okay so in our pick function our first step is going to be to choose our rectangle and to do that we can use the random module in python so let's start off by importing that so import random and over here we need to pick one of our rectangles randomly but we also need to make sure that we account the weights and to do that all we can do is we can do random dot choices so we can use the choices method and we need to give this a few parameters so one of the parameters that we need to give it is the population so our population is going to be what we want to pick a value from in this case we want to pick a rectangle so we're going to give it a list of all of our rectangles and we're also going to give it the weights and in this case weights is just going to be self.weights to be self.weights to be self.weights and we also are going to give it a k value which is going to start off we're going to give it a value of one and what k value basically means is that it's how many outputs we want we just want one rectangle so we're just going to give it a value of one and we're gonna index at the zero with uh whatever's at the zero index okay and just to show you how this looks like let's print rectangle and actually i'm going to remove this thing of the xero index just to show you further more why we're going to the zeroth index so i'm running our code and for each iteration we're going to have one of these so as you can see we got one list so for each time we call the pick function and note that it might be confusing why do we have so many well that's because we call the function one two three four five times so we have five different lists each corresponding to one of the occurrences and each time we're picking a randomly based uh rectangle based upon our weights so these are the rectangles that we ended up choosing and there and this is also why we're indexing to the zeroth element because well it's a list inside of a list okay and just to show you uh let's run it again and you should notice that like as you can see here the rectangles that were chosen are again completely different now so it's completely random okay so now that we've got our rectangle let's iterate through each of the points inside of it so we got x1 we got y1 and then we got x2 and then y2 and that is equal to rectangle okay and now that we have this we can we need to come up with two random values so we're going to come up with a random x value and we're going to also come up with the y value and just to save space instead of storing them in a variable again let's just like directly return that so what is our x value going to be well what we're going to do is we're going to use the rand int method from random so random.rend and we're from random so random.rend and we're from random so random.rend and we're going to give it two parameters we're going to give it x1 and x2 and what this is going to do is going to pick a random integer between and including x1 all the way to x2 and including x2 so we're going to get a random integer between that and that between the two x boundaries so that's going to be our x value and for y we're going to do the same thing we're going to do random dot brand int and we're going to find something from the y value so y1 and y2 so anything between those two bounds we're going to find a random integer and this should be it for our solution so let's submit this and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know what you thought about the video and don't forget to like and subscribe if this video helped you thank you
Random Point in Non-overlapping Rectangles
random-point-in-non-overlapping-rectangles
You are given an array of non-overlapping axis-aligned rectangles `rects` where `rects[i] = [ai, bi, xi, yi]` indicates that `(ai, bi)` is the bottom-left corner point of the `ith` rectangle and `(xi, yi)` is the top-right corner point of the `ith` rectangle. Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle. Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned. **Note** that an integer point is a point that has integer coordinates. Implement the `Solution` class: * `Solution(int[][] rects)` Initializes the object with the given rectangles `rects`. * `int[] pick()` Returns a random integer point `[u, v]` inside the space covered by one of the given rectangles. **Example 1:** **Input** \[ "Solution ", "pick ", "pick ", "pick ", "pick ", "pick "\] \[\[\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, \[1, -2\], \[1, -1\], \[-1, -2\], \[-2, -2\], \[0, 0\]\] **Explanation** Solution solution = new Solution(\[\[-2, -2, 1, 1\], \[2, 2, 4, 6\]\]); solution.pick(); // return \[1, -2\] solution.pick(); // return \[1, -1\] solution.pick(); // return \[-1, -2\] solution.pick(); // return \[-2, -2\] solution.pick(); // return \[0, 0\] **Constraints:** * `1 <= rects.length <= 100` * `rects[i].length == 4` * `-109 <= ai < xi <= 109` * `-109 <= bi < yi <= 109` * `xi - ai <= 2000` * `yi - bi <= 2000` * All the rectangles do not overlap. * At most `104` calls will be made to `pick`.
null
null
Medium
null
897
hey how you doing guys it's ilya bali here i'd recording stuff on youtube share description for all my information i do all legal problems uh make sure you subscribe to this channel give me big thumbs up to support it and this is called increasing order search three uh given binary search three rearrange the three in order so that the leftmost node in the tree is not the root of the tree and every node has no left child and only one right child let's look at this example we got these three initially and we return this modify three the root which is one uh the number of nodes in the given tree will be between one and one hundred each node will have a unique integer value from zero to one um go ahead all you need is return this helper message you pass root and no uh and here we implement that helper method uh 3 node right here is the root and three node right here is the next uh node that we're gonna visit in the case when the root is equal to no then we return the next node that we're gonna visit otherwise uh we create uh right here the node which is the result and we call this method recursively this helper method um and we do the depth for search in order traversal so we need to get to the leftmost node which is one in this case and then we start by dragging and we go here right then we uh check whether it's child on the right hand side is equal to null or not if is if it's not then we go here but it is so we go here and then we go here right again we check uh whether any of its child is not null then we go left and right you know or right or left and right here we got four and its children are no so we uh are equal to no so we go here we go one two three four five six seven eight and nine um yeah that's it so right here as i said before we pass through dot left we go left and we uh are gonna visit the root as the next node uh then root dot left is equal to no we need to modify that connection and uh root dot right is equal to we call this helper method again and we pause root dot right we go right and the next node that we gonna visit finally return this result that's it that's the whole problem let's run this code accept it let's submit good um so you know we are already explaining to you anyways here we start you know we go left until uh we got we get to the left most note then we start backpacking here and we um go right yeah we go right um and return this result that's it thank you guys for watching leave your comments below i want to know what you think i do all little problems uh give me big thumbs up to support my channel if you need some help please um contact me directly whatever and see you next time bye
Increasing Order Search Tree
prime-palindrome
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\] **Example 2:** **Input:** root = \[5,1,7\] **Output:** \[1,null,5,null,7\] **Constraints:** * The number of nodes in the given tree will be in the range `[1, 100]`. * `0 <= Node.val <= 1000`
null
Math
Medium
2202
102
hey everyone today we're going to be looking at binary tree level order traversal now this is a breadth first search problem it says given the root of a binary tree return the level order traversal of its node's values i.e from left to right node's values i.e from left to right node's values i.e from left to right level by level well okay what if we had some sort of system where we could look at each level individually move kind of we go from three and then we look at all of its nodes and then we go to nine and we look at all of its nodes there's nothing in this case we go to 20 and we look at all of its nodes well fortunately there's an algorithm for that it's called breath first search hey i just noticed i didn't put in a joke here well um maybe we'll get to a joke later but for now try to concentrate okay what we need is uh let's just kind of intuitively do this as we go along okay so first we'll do our little sanity check if root equals null if there's something in the root return the two accolades and that's standard language in order to do the breadth first search you need a queue so we're just going to be queuing each level up and whatever's in the queue is going to be whatever we have to look at that part at the particular level at any given time if we stacked up three in the queue we're done for level zero then we stacked up all of three's associated nodes and the next time we look at the queue we iterate through everything that's in the queue it will be the 9 and 20. at that point once we iterated through that we're going to have stacked up all of its numbers and then the next level will be all of those numbers in order so that's how we're going to proceed so let's come up with first our return value which is they ask for a vector of integers and we know that after all this we're going to have to return my return you know if you have nothing else to do during your interviews you might as well get the setup right in any particular situation so what we need for the breath for search is let's say a queue which is a first last sorry first in first out so there you go um type of structure which we're going to call my q and actually this q is going to hold not integers but nodes okay so it's going to be a queue of nodes next we're going to immediately put in uh put in the first node and we could do this as follows we just push in the root now here's the crux of it while the queue is not empty so we keep on doing stuff until the cue stops being empty let's see how we do this so since we're going to be adding stuff continuously to the queue and we're going to iterate through the queue we want to get the size of the queue immediately so uh why is that because the size is likely to change if you're iterating up until the end of the queue and you're at three and you already stacked up nine suddenly it's going to get confused so let's just immediately mark that down cue size equals um my q dot size um now let's see oh yeah and we need something to which we're going to push into my return at every level and that's a level um which is a vector of integers that's what they asked for current level okay so we have everything we need for that and now we could iterate through um through to through the queue according to the size of the current level of the queue which we marked on cue size over here so i smaller than q size i plus now the first thing we're going to want to do is get the current node that we're looking for so tree node current node equals okay for a stock you're looking at the top on a queue you're looking at the front so you just want to immediately push back the current node.val so that's going at our current node.val so that's going at our current node.val so that's going at our current level we just stacked up three over here and now we want to add to the queue those related nodes so we just want to check so if we just want to check if 3 for example has related nodes so if um if current node dot left not equal null then myq dot push current node dots left okay now we could do the same thing with the right just do a little copy paste type of thing here and when we're done with this particular node in the queue well we could just pop it likewise for every time we're done with a particular level we use we got the cur every time we got this particular level we filled up that level vector and therefore before moving on to the next level we have to push back the current level into my return and i think that's it let's test that and we have a winner that's it everyone thanks for watching
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
345
welcome to little JavaScript channel will be solve every single liter question using JavaScript today we have a 345 reverse vowels of a string this is an easy question let's begin given a string s reverse only all the variables in the string and return it the vowels are a i e o u they can appear both in lower and uppercase and this may be important later so pay attention no it was take a look at the first example we see you have hello and the output is going to be holy simply because o and E in this case sub places now this seems relatively simple to understand however you can probably realize that hey this is an abysm like to dislike ratio I think this is a good question so you gotta give it a like and of course it also has a terrible acceptance rate something like 40 which is unheard of for Miss equations this is something you may look at a hard question and the reason being is this is a 2.3 and the reason being is this is a 2.3 and the reason being is this is a 2.3 problem uh two pointer problems are very particular you just kind of have to know the way to solve it so I gotta teach it to you so you don't have any other issues the first thing we're going to do is required variable SE and that's going to be as that split with an empty string what am I doing here so I'm taking s which in this case is hello and I'm using the split to convert it into an array of characters in this case you have h e l o what do you need why do I need that because you might think hey it's JavaScript I can just iterate over a string with no issues and that's true however we do need to make some traps in place which are hard to do or harder to do with strings and you're welcome to try to do it yourself it does add a bit of complexity but you do not end up using the array in that case now we need to pointers the first one just gonna be end and it's simply going to be S that length minus one so it's going to be the last index of SE or SC rather and then we can have another it's gonna be the start index that starts at zero it's going to use a folder but it's not called it I as usual and we're going to check whether I is less than n and then when you do I plus now that we have our two indexes that start at the beginning at the end this problem is actually super simple if you really think about it so you have an index that points to start and one to the beginning and what you want to do is find the first occurrence of a vowel and this one's going to be o and then e and then swapped in and then keep increasing I and decreasing end and then the end we end up being the same value and in that case we're finished and we don't have to do anything else now how do we know whether something is a vowel there's a couple ways to do it um some people like to use regular Expressions have hash tables or even some string lookups but I think we can do it in a very simple way using an axillary function and we're going to call it is a vowel and it's vowels is a function that's going to take a single parameter I'm gonna we're gonna call the s um we're going to have a character C we're gonna call it s that uppercase what uppercase because as you can read here the vowels can be either lowercase or uppercase it also saying the constraints can be any ASCII character so we're not really concerned whether something is uppercase lowercase at the end of the day we just need to know where something's available itself so by making everything up because we can do the checks extremely simple I'm gonna return the following and this is a bit longer it's no way complex we can say whether it's c is equal to a or C is equal to e or c equal all right see if it is equal to I or if C is equal to l or finally C is equal to U so this is super simple we're simply going to check for all of the five vowels that there are and since C is always going to be uppercase we just write it uppercase to simplify the way we check and now we get a check it is vowel for the current one so it's going to be s i and C of I so if the current index I that we're looking at is available then we need to look for the first occurrence of nth or Savannah vowel and what you do it's using a while loop so we do it not this vowel scn however there's a caveat here s and always has to be greater than I and this is not guaranteed to occur here so we could do another condition if we do the end I is less than n just to make sure n is always greater than I in this case and while we do that we're going to do M minus until we find the phrasal currents of a vowel all right now we have to check whether I is not equal to that because imagine you have a string like above and what I and N are going to be pointing the same vowel and there's no really want to change anything so we're going to ignore that case now we're gonna be swapping two indexes on the way to add super simple we're going to use a temporary variable temp is going to be SC of I then we're going to do seoi it's going to be equal to SC event and finally s c of n is going to equal to temp in this case we simply change s i for S and when you did this actually right we'll just do the change then we do n minus so and keeps decreasing for the purposes of the for Loop okay so up to that we need to up to that we have an array that has this satisfactory answer but that's not what we want is a strength and how do we compare this array into a string that looks like this well this relatively simple we're simply going to do return SC the join and give the amplitonous parameter let's run this code to see if it works and it does now there's a couple things you may need to think about first some interviewers may ask you do not use split or joint you have to use a for Loop just to show you actually know what split and joint do and in this case would be a simple Ford Edge Loop and you simply add to an empty array you would start with an in theory you would simply append every single value of C or of s every single character to be a one and enjoy it would also be a voice look and this schedule would be adding to an empty string rather so that's something you may want to keep in mind if you find sprawling interview you may not be able to use split and join these are just shorthand so you can simply do with a for Loop now let's just submit this and there you go the runtime is quite fast of 85 faster than all other JavaScript submissions but about the time a space complexity the time complexity actually in this case is oven because in the worst case we have a string with no vowels actually something like this then we're just going to be looking at every single one and realize that there's no vowels to be found so that's it so oh then is the time complexity and the space complexity is going to be also off and while we're using this um array SC well thank you very much for watching don't forget to like subscribe
Reverse Vowels of a String
reverse-vowels-of-a-string
Given a string `s`, reverse only all the vowels in the string and return it. The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once. **Example 1:** **Input:** s = "hello" **Output:** "holle" **Example 2:** **Input:** s = "leetcode" **Output:** "leotcede" **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consist of **printable ASCII** characters.
null
Two Pointers,String
Easy
344,1089
20
According to the business, inside we are going to spend a little money in auspicious works. This is a very famous question. Office meeting problem on everything. Okay, this is basically you also counter mix. Then we have asked that okay, so a very important question. This is what you guys have done by expanding the basic in which you can have 16 characters inside the thought opening and closing racket opening did the packets on places toe sacrifice and openings for residents and to tell you that this is making an expression this is stitch matching on a belt and here But how will you do it, like here you have made the heart prince open, man and this one is open marital rituals and customs and here you edit the form, you will do the previous here to you for different or do not match the die and see it properly, I am approaching it for open. This one is actually for Open, this one is not Kalyan Singh Renu, okay, so here you are for this one, for this trophy, for sliding verification and lobbying for the English language, see it here and here. But it is okay classification question topic but here the opening which will not be this project is okay here if you listen then here sit in the morning till Pingla then here with your sign here the gift will be returned so that is why it is very simple for you. You will show off how simple it is, you will give it to the people, if there is a question, they will say ok - how will you solve the question, they will say ok - how will you solve the question, they will say ok - how will you solve the matching problem, after that don't think that suddenly this site can be 35, what scanner price can there be some more characters besides this, now we have How do you have to handle me, this kind of nutrition? You people will ask whether I will give you the back portion. Well, you had given me the winter vacation. If you want to tell me something about all the troubles, then is it okay for them whether you have given that time or you have character. In what way, what all is the heart line giving, preserve is done by you guys, after that the pure sequence and it is very easy and the steps that you guys have, the questions will be soaked in the fund, is there any other method other than that? Just think, what without? How could the tax askers ask questions, think about it, you people can decide the destruction of Miss Pooja, there is a very good way, the person might be using recording and you people could have done it through questions, but there is a vacation stacking area inside the decoration. So there the ultimate you guys increase then use track how can you get stronger just understand you guys will use cigarette and just like you guys get a proof cigarette for the person with your opening, similarly you guys track the software out. If it comes out then it's fine, it's going to stay inside, how do many of these dryers do it, so your tag first is okay, here is the step, after this, whenever someone gives you feedback, you put it in the check. Okay, if anyone finds yours, then in the first place. I got this one, so I got this one, then I got this one, I put Kunis in it too, then I got this one, so we put this one in the set too. Okay, after that, whenever you get a project, what you have to do is that there is a limit in the Olympics. And the point of this one is that it is matching with both the hands, meaning if you got the kar, then now you have done the real kar, you have added the crossing, you guys want this one as yours, otherwise you guys tell me to open the kar. If it is closing, then pick up meeting, if it is prince, we are Kaliyug, then it is okay for Kalyug ones, pause it, okay for Kaliyug ones, chant I and after that you will go up to the next album, if element oath is using back, then it is a project, then classification. What to do is pick it and there are four stop elements, is that one of the same course quiet or not, then this one is normal, Roshni is going to sit, Holi is going to be on your pick, it was normal to bring back, okay, so both are matching, so chop this one too. Take it apart, this is the pizza bread, so we will check for it, yes, if this also has to match, then we will put it in the shop and the file which is the entire spring is finished, then you have to select your technique. It is over, if you come back after this time is over and the technique will end then you people will return the proof as per your return gift. Okay, just react to Kishore Sagar Mishra, then first you are bad, then he is interested, then his statement will come next. Looted it and rented it from Next 9 News Room, so we had the problem of our last seven cycles, it is matching, if not matching, we will nurture it, okay, then by matching, it has topped, facing the next one, anger is also expressed in the next one, get it fixed. This one is also matching right at this point, yes, this is matching magic, so you turn it off too, after that, play the next main graduate post graduate course messages. If you click here, then it is grinding, you are getting an album, it means this is the first project, so life. Voting happened before, I do n't understand very much, so here you will do it with the people, okay, then here, if this person does it through a call, then you put this person first, okay, his constipation, you, this is our front, this is the chief, you are this. Badha Shakti Singh, if you got it then you check this match and took it out, you got it exactly like this, for this you launched a new yes, you took it out, so here I am, the media took it out, landed, caught the morsel and you got this and but its correspondent is this person, right He wants to open the Jhalawar racket but he got it here, he has made the bread, okay, so message me this, you will also distribute fruits here for some time, so you will be doing biological work in this way, by the way, you people will use stock and there will be two noose in the tractor. Pass two loops, what will be the first, if there is open interest then portion stock, if daily investigator then check with top. See this in this way, you guys will write the poetry of your lover and after that it is your full right from here, wherever you go for travels then What will you do Strikes MP, so this is the gold fall of 100 grams, I make fun of this and if you click the button, then you understand well, people quote the logic here itself and it is very simple, the code is more difficult, you people. Made a balance track, ok only character and you will string end one by one, I took the spread, here I made two metros, first one is this opening and second one is this matching, I made it different because what I saw here is quite lagging behind. So I kept both of them separate, so first of all we correct the character, I subscribe, the first thought is that it is correct and you check that the character is opening, do not do anything for opening, now return it, basically if any of these three If the back foot also does 15 right then you have a pin code here then you must have this experience right because the opening batsman gives you the feedback when you guys put it in this is okay then you used to make a step here. By doing Westerners Evening in Law Minister, he put the exam, gainfully goes to the next actions, which is this character add, then this conductor is opening, if not open, then it means this is a project, then coming from us, is this our step, if not, remember our laptop. Do it, this means that it is an everyday thing, before that you are not only frustrated, you also have to do the first end, okay, but it is not with us, for the time being, you will express your anger here that both are matching, what is the current and what is the point. Okay and the current one is that there is matching here that there is no support for each other, if there is then it is okay then do it from here, so for this I have given this matching question here which takes two quarters, maybe That both of them are sending back messages, what is the matter that even if this one is a prince then this process should be done or even if this one is on the family then this one is Singh or even if these allegations are true then this one will be suffering from the disease. If there is any other condition for certain then it is as if we have taken Singh Ravana in this, so here I have updated my vote because as you can see, the judgment in the pick is ours and the front is our rotting and what I have made is yours. All the opening day matches are in character, that's why I requested you, so it's okay, Nadal is doing fine, this one and the current one is ours, if we keep it, then this is ours, the opening is also ours, we are one, so if both match, it means you are done from here. So, because it is returning true, it means that this condition here will not match, then here I have put a note, then you will send SMS here and you will do this, then you have made this limit that they are only for employment. If you have an opening key then put it in the set and if you are worried about the abundance of employment, then this is the waist audio mp3, if we tele then tomorrow it is matching both, if both match then it is okay, if both do not match, then post from Do it, if both match, then you waive off the electricity bill, okay, then our ticket has become stagnant, now even after refusing the next point, this is the cigarette, if you put some at your house, then I am second is in that promised prescription, it is pigmented, okay. If the element is given in this website, if our Kalyan Singh and Akshara Singh super actress will match, are they working in MTS Happy New Year, then this one and this one are matching and this one is talking about it, then you can get this from here. Gone this fight ok you are forgiven after that will add next now element is our placing your love back once is in then it is not yours ok after that you have more matching here if this youth match then you will pause it And if we go to you and it is always effective for that and after that we are returning, B.Com after that we are returning, B.Com after that we are returning, B.Com will be the 3rd step, after this we will return to drops, so the camera and remain effective, our Ghaghra must have been heard, so we have started with this practice match. Target form, giving a little bit of support from the example, this would have been here in the beginning, got on action packed, so if you go to this opening here, then this which prints only appropriate action, but what will you do, what will MP advance, this is our from here, this fit We will do it, ok, let's take some time, let's give Sapoch such an example, so what would you have been, if you got his interest first, yes, Leo, tell me this message about him, ocean, yes, this one, so why don't you check soon, are you a match? This is the limit for the current limit of getting me on pickup. This is our planet. Both of us will do the match. For you, I will do this. We will post this mark here and if you follow all these, then we will get the source from here. We were not doing cricket match. And note meeting return form is okay, from here we will go to the force which should happen, both the princesses are mature, the lace is very simple, the tube should stop and you guys can see the power of that track by freeing it, okay now this track Above there are more big fun try children ho yaar infrix to postfix and the previous one is according to express is educational and will see in the upcoming videos ok then its tuned for this video, below the uploaded version will be found, I have some questions that you guys after sleeping If you like this video of ours, itna apne billon special yoga for practice then do like my voice nahi rahe sakte bye a hua hai
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
805
123 456 Topic Middle Sudhi-Budhi Shabd * 1st End Set It Is Obvious To * 1st End Set It Is Obvious To * 1st End Set It Is Obvious To Make Two Of Three And Condition Your To-Do Make Two Of Three And Condition Your To-Do Make Two Of Three And Condition Your To-Do List Menton Friends Subscribe Channel Radhe-Radhe At Channel Radhe-Radhe At Channel Radhe-Radhe At Least To Power In The World I Heard That India Which direct tweet so now we do it this way this episode 132 A suite desperate unit certificate and will be a gallery with computers for office Mercedes for everything and forgetting the absence of name body they can deposit in the development and give it from YOUR BLOOD CIRCULATION QUALIFICATION YOUR MIND IS INFECTED INCH SO HERE DIRECT OIL FREE EDITING SWAMI AND YOU WILL FIND A WAY OF LIFE AND DEATH AND FIRST LOVE YOU TOO 203 LENGTH AVAILABLE A GREAT WAY TO BE ADJUSTED FOR EVERYONE SHOULD NOT BE BUILT INTO EVERY Citizen should appoint s soon s all of this will be a reminder for this study put the latest ring soldiers carried points length punishment plane 250 million train will get updates get water world om number phone number and co check weather of the element pimple two-day visit to this place was two-day visit to this place was two-day visit to this place was not able to find any possible to mention all of oo loot fog and another thing 100 Do n't forget to subscribe thank you all possible songs play elements on then you and you can easily fold your Number of this remedy 's foreign and press the city MP Singh 's foreign and press the city MP Singh 's foreign and press the city MP Singh and 134 A and Sukh and will be doing this app you and why does a phone number set lootati and doing a great actor whose element side directions to contain all possible MP and 2% MP and 2% MP and 2% Election 2014 a b option of measurement says pe voice mail set up to date - pe voice mail set up to date - pe voice mail set up to date - management for events and the lord will be silent and took it only possible for its subsidiary will be win-win more elements subscribe to the Page if you liked The Video then SUBSCRIBE to New Delhi North 13 wash Bluetooth robbers have come to the country of the bigg boss chart model minute, so come in the country that the picture of Punjabi Video is Navi Body, but it is Plus B Plus CAB Plus TV Paste and Sau Its The object is the formation of this defect during a better of than not sure what will be our people these people are just friends the body bluetooth settings also and possible to receive notifications after to entertain available a person likes the video if there is a question That Blue Extra Money Set Loot Looti Ho Madam Ki Noida Set this sentence of doom 3 that is after adding a the question that not dry offices but real difficulty is the reason behind Saw Me To Go Quite Possible Size of a Small Cars 24 Parganas Prime 4G Proximity Sensor Board has made a Loot 5 Minutes Chapter Note 510 Do Hai Sam Easy Garlic Naan And Units Last Year Total Loot Do Loot Directly Song HD Should Not Be Positive A 's Member Recruitment Note Hey One 's Member Recruitment Note Hey One 's Member Recruitment Note Hey One Environment I Check Weather This Present In The Calling Set Do That In this film ki checking kisne point option hai ko sunne gayi hun loot police force deployed host sirf present in the bodies of cassettes present tense vitamin e looter film decade of wall painting and commission for a positive change in the difficulties and tried to check weather Divide of loot that 24 pimples festival monk select radhe ajay ko that I am safe from this MP3 song all loot fidgit send loot a t-shirt to ji a t-shirt to ji a t-shirt to ji vitamin C mistakes like this loot video and listen
Split Array With Same Average
escape-the-ghosts
You are given an integer array `nums`. You should move each element of `nums` into one of the two arrays `A` and `B` such that `A` and `B` are non-empty, and `average(A) == average(B)`. Return `true` if it is possible to achieve that and `false` otherwise. **Note** that for an array `arr`, `average(arr)` is the sum of all the elements of `arr` over the length of `arr`. **Example 1:** **Input:** nums = \[1,2,3,4,5,6,7,8\] **Output:** true **Explanation:** We can split the array into \[1,4,5,8\] and \[2,3,6,7\], and both of them have an average of 4.5. **Example 2:** **Input:** nums = \[3,1\] **Output:** false **Constraints:** * `1 <= nums.length <= 30` * `0 <= nums[i] <= 104`
null
Array,Math
Medium
1727
152
hello i'll be covering question 152 maximum product subarray let's get started so i have a given input and i want to keep track of maximum positive value and minimum negative value i see default value is one for beginning so how do i find uh maximum positive over here is negative times two or positive times two which one is maximum it's just two and two so my positive value is gonna be two and about negative i'll take a minimum of a current paused the neck of the current value and just two so it's gonna be two my result a two is the highest number we've seen but now before moving on to the next stage um you know negative value 2 is hey it's positive 2 and we don't want to keep track of this so i'm going to rewrite it to 1. so i'm coming here so we see zero so what's gonna happen is my pause i'm gonna be zero my neg we're gonna be zero so um if we don't do anything about zeros um we'll just keep multiplying zero and we'll lose track so we have to make sure if it hits zero we want to update it to a default value i get uh what positive of negative of uh maximum of uh pause meg times current it's negative two and negative is minimum of um minimum of a plus times negative of current value minus two so going to be minus two and we see um that's positive hey it's actually a negative number right now we should be um bringing it back to our default value which is one okay so i'm going to next negative eight so what's my uh positive is maximum of what this one right this one of course one times the current value negative eight or minimum negative i've seen which is negative two so far right yeah times negative eight then hey we'll get on positive 16 right and what's my minimum negative value hold on that's negative 8 and 16 right so i'm just taking minimum of it so it's just a negative 8 and since we're getting 16 uh we want to update result to the 16. uh let me erase some all right now we're looking at negative 10 so positive is well max of what's my previous positive uh it's 16 times my current is negative 10 or it's um what's my neg current negative 8 times current is negative 10 so um it's either negative 116 or 80 so 80 is maximum so positive going to be 80 how about minimum so and these two minimums gonna be negative 160 so bmw 160 and we see hey we need to update on our results right it's a result of the ad um i wish um giving uh some you know example and uh walking over was you know by putting our values inside and see what's happening um helped your understanding thank you
Maximum Product Subarray
maximum-product-subarray
Given an integer array `nums`, find a subarray that has the largest product, and return _the product_. The test cases are generated so that the answer will fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[2,3,-2,4\] **Output:** 6 **Explanation:** \[2,3\] has the largest product 6. **Example 2:** **Input:** nums = \[-2,0,-1\] **Output:** 0 **Explanation:** The result cannot be 2, because \[-2,-1\] is not a subarray. **Constraints:** * `1 <= nums.length <= 2 * 104` * `-10 <= nums[i] <= 10` * The product of any prefix or suffix of `nums` is **guaranteed** to fit in a **32-bit** integer.
null
Array,Dynamic Programming
Medium
53,198,238,628,713
404
hey it's cooper codes today we're gonna be taking a look at the lead code problem some of left leaves this was recently a feature daily problem on leak code so i thought i'd go over it and kind of explain my solution first things first we can take a look at their example to get an idea as to how we can solve this problem ourselves it's important to realize in this example the left leaf nodes are 9 and 15 and so we can take a look at these and kind of answer the question what is a left leaf node when thinking about what a left leaf node is we can kind of divide it into two different problems the first one is what is a leaf node well a leaf node is a node that has no children so you can see in this example over here we have 9 and 15 9 has no children 15 also has no children and then the other thing we have to consider is what is a left leaf node so a left node is a node that is left to the node above it so that's kind of the simple way of thinking about it is a left node is to the left of the node above it something important to recognize there is that our root node technically can be a left node if you think about it because there's no nodes above it so let's take a look at a simple binary search tree to see how we can take a look at what a left node actually is so we can make a simple tree here maybe put the value 3 here to the left we can say 5 to the right we can say 10. and so in this one we can see that the left leaf node is going to be this five but it's important to think about y so we can look at this five and you can see that a leaf node is a node that has no children so it checks off that constraint the five has no children here and no children here right and then a left node is a node that is to the left of the node above it so we have three and you'll see this is going to the left and so it also checks that constraint in our solution we're going to want to try and solve the problem in a similar way to how we just did it on the paper here we can kind of simplify this problem by thinking about an algorithm that's going to work at every single node so we looked at the 3 and we saw that this 5 was a left leaf node it's important to think about why so from the 3's perspective we know that we can check if there is a left node so for example if we're over at three and we're going to five we can say okay we're at three there is a left node and then we can check if that left node the five has no children and that checks both of our basic constraints here it's a leaf node is a node that has no children and then a left node is a node that has left the node above it and so if we're at the node above it we can kind of think about it like this we're at this three and we can check the five um to see that it's a left node and then the final part of our algorithm is probably the most important is if it is a left leaf node so meeting both constraints add to a total sum all right so hopefully this gives you a basic idea of how to approach this algorithm and kind of understand things let's get into the actual leak code and code this out all right so now we can actually get into coding some python here to help us solve this problem so the first thing we're going to want to do is think about a recursive solution to do this the simple idea of considering recursion when you're looking at a binary search tree is that you start with your root node and then you make decisions based on the value of that node as you move through so as it becomes you know the dot left the dot right as it moves down you make decisions based on the new value of your node as it's moving down so let me explain that some more first of all we're going to want to make a recurse function that passes in the node whatever the current run we're at is all right and we'll just get this done with early we're going to want to recurse based on our root node first so it's going to start at the 3 and then if 3 has a dot left for example it's going to go there if three has a dot right it's going to go there but that kind of all depends on our logic a base case we can kind of set up here is if node is equal to none we can return zero this is going to be important because of how we're going to chain our recursion statements at the bottom here and let's just do that so pretty much we're going to do something like this return recurse of node.left like this return recurse of node.left like this return recurse of node.left plus recurse of node.right of node.right of node.right so as you can imagine recursive no doubt left let's just look at this three right and let's just keep on going through the dot left here we're gonna say three okay go to the dot left okay we're at nine now with the nine go to the dot left eventually under this nine there's going to be a zero there and so at that zero we can kind of see that it's going to pretty much say zero plus zero and then this becomes zero and then zero plus zero and then zero up here there are better videos out there explaining recursion and depth and so i can make some if wanted but this is just a basic idea of how we're going to solve this problem and then we're going to pretty much see if there's something we can add on top of these zeros because right now we have no other logic besides just zero it's going to be zero plus 0 right and so now let's take a look at this comment i put up here a left leaf node means new two constraints it has no children nodes and it is the left node to the node above it so if we're at the node above like in the example from the whiteboard on before we can say if no dot left which means the node.left exists means the node.left exists means the node.left exists and we're gonna make a little complicated statement here that node.left.left that node.left.left that node.left.left is equal to none and that node.left.right node.left.right node.left.right is equal to none so if you were to look at this three example if we're at the three this nine is the node.left right is the node.left right is the node.left right then this nines node.left.left is going then this nines node.left.left is going then this nines node.left.left is going to be the value to the left of it which is none and then this node.left.right is none and then this node.left.right is none and then this node.left.right is going to be the value right here which is also none and we know that this 9 is a leaf node because they tell us pretty much here and so what we can do is do something like this add is equal to 0 and then add plus equals node.left.val and then add plus equals node.left.val and then add plus equals node.left.val and then in our return statement we can chain this extra addition so if this statement becomes false add is still going to be zero it's not going to change our overall value right but when we add the node.left.val it's going to we add the node.left.val it's going to we add the node.left.val it's going to put this you know whatever value of this recursion statement here or whatever value of node.left is here right it's value of node.left is here right it's value of node.left is here right it's going to add that to our overall recursive addition so in that happening you're pretty much going to have you know 9 plus you know zero plus zero which is going to you have a nine that's going to kind of bubble up in your recursion so this is pretty much going to work right here see we can run this and we can submit this and yeah it gets a pretty good run time um hopefully this video was helpful in kind of understanding the basic concepts here i know i didn't go super in depth into the recursion and how it actually bubbles up but i would recommend you know doing print statements and kind of understanding how it's actually working that way and kind of seeing how these no doubt lefts eventually become zero for example a great thing to do would be when a print whenever it equals node is equal to none print here inside of this if statement and kind of see uh how many zeros are being returned and yeah hopefully this video is helpful thanks for watching
Sum of Left Leaves
sum-of-left-leaves
Given the `root` of a binary tree, return _the sum of all left leaves._ A **leaf** is a node with no children. A **left leaf** is a leaf that is the left child of another node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 24 **Explanation:** There are two left leaves in the binary tree, with values 9 and 15 respectively. **Example 2:** **Input:** root = \[1\] **Output:** 0 **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
1,976
welcome guys so let's solving this 1976 number of ways to arrive at destinations okay so this problem is very easy uh you got some uh graph and uh and initialized at zero and there are total minus one vertices and the problem is that given all the uh if the number of all the shortest paths from zero to uh to zero to a minus one okay and so you start from zero and you go n minus one so this is the single source shortest path and uh very good is that this is time right so there is no uh these are all the graphs found down non-negative so simple graph so you down non-negative so simple graph so you down non-negative so simple graph so you can use the dagger okay so uh there's the same problem that uh similar problem right but the usual so this is the usual digestion okay so ideally let me quickly review so the technical idea is that uh you first have some physicist and uh you have some weight and uh you uh pass so this is uh if you want to know the shortest path if you don't know if you don't want to know then you can delete every pass where there's a queue and the weights and so initialize the source set to be zero and then you push you create a heap okay so i create a heap epq and push and then you uh you take it you take the smaller one and uh put into physicists and uh if not your visit you try to do the so-called relaxation okay so this is the so-called relaxation okay so this is the so-called relaxation okay so this is the usual declare step okay and uh if f which is uh the distance plus the weight less than the v then you uh just push back you just push okay and then finally you can return the path and weights so weights will be a matrixes which is a single source okay so uh i will put this into my uh i will put this uh below if you want to copy this code okay but basically all you need to do uh usually is to create a graph which is for each vertices you given a list which each element is a two pole vertices and weight then you can use the usual decker okay but the problem in this one is that we need to count right so we need to do some things do something non-trivial so first part do something non-trivial so first part do something non-trivial so first part uh still very just create a graph okay so here's a query graph and for this one uh i initialize the circle count so this count is that given vertices and i need to return the number of the shortest path okay so count for source is one right because zero goes to zero must be one okay and the difference is that if we find a new weight so we will find a new smaller path then count v equals count u otherwise that we find another directions which count v should add count u so this is the only difference you just copy the original dagger and then write these two codes okay so write these two parts and the final you can return past weights and count so you just recall uh call our answer take extra and zero g so n is the number of nodes zero is the source energy and finally we return counts of minus one marginalized so this is the this is not important right but just module okay so these problems are very simple that just use a simple deck extra and the only difference is that you mod out your mod list to uh you add some you at least to condition so it's very simple that uh you can eat this up okay see you guys uh next videos
Number of Ways to Arrive at Destination
splitting-a-string-into-descending-consecutive-values
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with **bi-directional** roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer `n` and a 2D integer array `roads` where `roads[i] = [ui, vi, timei]` means that there is a road between intersections `ui` and `vi` that takes `timei` minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the **shortest amount of time**. Return _the **number of ways** you can arrive at your destination in the **shortest amount of time**_. Since the answer may be large, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 7, roads = \[\[0,6,7\],\[0,1,2\],\[1,2,3\],\[1,3,3\],\[6,3,3\],\[3,5,1\],\[6,5,1\],\[2,5,1\],\[0,4,5\],\[4,6,2\]\] **Output:** 4 **Explanation:** The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes. The four ways to get there in 7 minutes are: - 0 ➝ 6 - 0 ➝ 4 ➝ 6 - 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6 - 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6 **Example 2:** **Input:** n = 2, roads = \[\[1,0,10\]\] **Output:** 1 **Explanation:** There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes. **Constraints:** * `1 <= n <= 200` * `n - 1 <= roads.length <= n * (n - 1) / 2` * `roads[i].length == 3` * `0 <= ui, vi <= n - 1` * `1 <= timei <= 109` * `ui != vi` * There is at most one road connecting any two intersections. * You can reach any intersection from any other intersection.
One solution is to try all possible splits using backtrack Look out for trailing zeros in string
String,Backtracking
Medium
null
1,171
hey guys welcome back to my channel let's solve today's problem 117 remove zero some consecutive notes from the link list okay so let me just read this uh not okay yeah let's solve this suppose uh what this question is saying I have um a few notes and just think of this numbers as a note okay now we have to remove all the consecutive nodes that sum leads to zero okay now think of this if I take this sequence it will give me a zero sum 1 + sequence it will give me a zero sum 1 + sequence it will give me a zero sum 1 + 2 - 3 = 2 - 3 = 2 - 3 = 2 zero so I have to remove this and make uh the link list like this okay this is the intu this is the concept this is what the question is saying okay so how can we think of like this uh the most basic approach I can think of is just like an array uh I will start from I and try to go till I find the sum zero okay now suppose I am at I then I keep on finding the sum till here but keep on finding the sum 1 plus 1 2 no this is not equal to 0 2 + 2 4 this is not equal to 0 2 - to 0 2 + 2 4 this is not equal to 0 2 - to 0 2 + 2 4 this is not equal to 0 2 - 3 is = to 1 4 - 3 = 1 + 2 3 this is not 3 is = to 1 4 - 3 = 1 + 2 3 this is not 3 is = to 1 4 - 3 = 1 + 2 3 this is not lead me to any zero so I am going to eliminate this and what I do is move the pointer to here right now again checking one first 2 3 - 3 0 I got a j so I am going to 2 3 - 3 0 I got a j so I am going to 2 3 - 3 0 I got a j so I am going to eliminate this and make the link list like this is the most root force that I can think of okay and this will lead me to 1 two okay this will be my link list then I will go from Two and keep on checking can I have a zero if I not I'll just simply return uh the head of this and it will be my answer okay now how can we optimally solve this okay I'll show you the code of this uh gr also in the ending if you want to see but let's just go for the optimal solution suppose I have 1 2 - 3 and 2 solution suppose I have 1 2 - 3 and 2 solution suppose I have 1 2 - 3 and 2 okay this is my n so if you have uh heard of prefix sum then it would be really helpful okay now what I will do is I will have a prefix sum okay and what is the last note that I had uh on this note okay suppose I got a sum two at which note uh one note okay I got zero some in the uh like this position so like this what can I do is just let me just take the approach okay so the key would be my prefix some and the value would be the last this thing see last node where I got the sum okay so what I do is I put a dummy note with sum equal to zero in the starting okay now I will start from this position okay now 0o equals to uh let's suppose uh this as a okay B what is the sum 0 + 1 I got a okay B what is the sum 0 + 1 I got a okay B what is the sum 0 + 1 I got a one sum uh add V okay now see I got a sum two at node C okay now D four at uh D now 4 - 3 = to 1 so I have four at uh D now 4 - 3 = to 1 so I have four at uh D now 4 - 3 = to 1 so I have a prefix sum till here as one okay so I'm going to replace this B and put e here understood the last node I'm saying again last node okay then I'll go for two it's three C some uh equals to F here A B CDE e n are the addresses of this note okay understood this is my hashmap okay let me just go do a different color this is my hashmap and I using a prefix and the last name okay understood um let's tell me just go for the code okay so I need a prefix uh hashmap okay and I need a dum note which would be in the starting zero and it's uh next will be head okay it would be like zero connected to head okay understood Zer is connected to head and this is my prefix some hashmap where the key would be the prefix St and the node address is a okay understood this is what it means this dummy is what negates okay so let's itate why now I need a prefix sir prefix some um in the starting it will be zero now prefix some Plus+ dummy do okay I added prefix some Plus+ dummy do okay I added prefix some Plus+ dummy do okay I added the current node value okay what I will do is if I'm suppose this is my domain node and this is my one node okay in the starting the prefix is zero okay when I come to this node 0 + 0 is some zero okay so it will be zero + 0 is some zero okay so it will be zero + 0 is some zero okay so it will be zero and what I will do is uh prefix comma prefix s equal to done okay I have put um z s a this is a okay now I have to move the pointer also okay this will calculate me the prefix sub okay let me just return print for you for better understanding okay see um okay I didn't print the 3ix see in the zero I have a list node of value minus 3 see zero it would lead me to a minus 3 okay because I have a different example just think of a different example in the starting I like this so and this the key would be the prefix sum and it would be my node in this prefix sum and the node okay now what I will do is um I will simply just move the pointers according to this what I will do is again I'm going to put dumy to uh like this again and prefix sual to Z and while dumy I will what I do is put Dy do next first I to find the prefix okay D next equals to prefix comma prefix s okay means what I did was uh I'm going to Mark the first node connected to the next prefix value now I will again move the pointer and return the head simple but I cannot use head in this I have to use rest and rest what's the shortcut of this uh the it's say Z using this zero then I have to find okay dot next this yeah it's been accepted the test cases are implying let's try to submit this yeah it's been accepted okay quite efficient okay now what I did was uh let me just clear this out okay I'm just finding uh in the hash map what is this which node has the sum zero okay which note has the sum zero and moment I have the zero I'm going to put its next value as my current next okay this is the main concept in which I use a prefix Su prefix HH map for the prefix sum and the last node okay the last in which I connecting the tummy with the head then I'm going for the tummy and finding the prefix sum and putting the prefix sum and the node here in the hashmap then I'm moving the pointer okay now same thing I use this as my to written the because in the head will never be the same so the prefix s then again I find the sum then I'm going to find the next okay this is my Approach hope you understand this and if you want to find you want to know about the iteration approach where I use I and G uh okay it's just to give you some concept okay so this is the approach in which I use a dummy Noe and I'm linking the head this is the same thing this C same in which I'm finding the sum from the I Noe and going till z and day if the sum is zero then I'm going to put the W next equation mod next and moving forward so this is the high prity but the Space is really Less in this okay as compared to this it will take space this will not take the space the timeform city is highest computer okay here are two approaches and if you understand this give a good like And subscribe okay see you in the next video
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
222
they are there today's liquor in challenge question is called count complete three nodes so we have a complete binary tree we won't count the number of nodes inside this complete binary tree the definition for a complete binary tree is that every level except possibly for the very last a level inside this binary tree has to be completely filled with nodes so if we look at example here we have a binary tree with 3 different levels they were first two levels are filled with nodes their last the level here is missing one of the nodes towards the very right side right hand side so if the last level in this complete binary tree is not completely filled all the nodes has to be as left as possible so you will look like this if Phi is the very last node inside this complete binary tree we are not allowed to have no 6 if for if or is there a loss the node inside the spine area complete binary tree will not allow to have Phi and 6 if we indeed have no 6 then we must have node 4 and 5 so that's the definition about the complete binary field so if we want to count the number of nodes inside this complete binary tree the simplest way to do so is to just treat it as any regular binary tree using whatever traversal strategy we can sync off and just content the number of nodes we see in the traverse and because we visit every node exactly once the run time for that simple approach is going to be linear with respect to the number of nodes because we visit every node once so that's the simplest way the problem about that approach is totally disregard the property of complete binary search a binary tree the property here if we just stick with the you know textual description about the complete binary tree is that if we can figure out the number of levels inside this complete binary tree we can do so by Traverse using the left hand side left child a pointer only and just see how many times we hop using the left child link until we get a null pointer here in this example we can do two jumps so we have three different levels if we index the level with zero so we have a zero level one level and two level that the two level is corresponding to the number of hops we can jump using the after child pointer from the root so if we can figure out a number of levels we know that except for the last one it has to be completely filled so the we can do some really simple mathematic to fill out to figure out how many nodes acceptor for the last level are there so in this case here it's easy to see it's two to the power of two subtracted by one so it's four minus one and that's three and to the power two is actually just the index for this flight the deepest level there so basically if we just do a single pass figure out the depth we already have solved the pretty much half of the problem the only thing remained there is to find out the number of nodes on the rail last level note that the notes has to be pushed towards left as far as possible so if we just if we can figure out a test to see do we have the first node in the last level do we have the second node on the last level do we have the certain nodes on the last level you know so and so forth if we have a function that can do so the result will be true to false so it's a sorted array and we're basically looking for the largest number there when this function will still return true that means that we find that the last node inside the real last level and then we can just you know add that number was the all the notes from the prior level to be and the result will be the number from the total number of nodes inside this complete binary tree so because it's a sorted array if we can actually have that test it will be we can use binary search to do so and the number of nodes inside the very last level has to be two to the power of the depth so we have this last level is two so we have a maximum possibly four levels here and so we're basically searching between one and four and try to find the largest number where we can still find a path from the root to that node and the hrunta for this binary search is going to be to log of n because the last level the number of nodes is half of the total roughly half of the total number of nodes and roughly half of n so the question then is just how can we efficiently derive such an answer do we have the first node do we have the second node we have the third node in the very last level so it's worse to looking at that using a graph here so this is a basically a deeper treat deeper complete binary tree and I just put the note index the first no on the last level second note on the rail last level sir note on the last level since so and so forth one thing we can realize that from the root to the node that's we want to verify do we have a pass or that the pass is basically a sequence of left and right choices so the first if we want to reach the first node inside the very last level in this particular example is the choice is left and left the second node there is left the right the third node is left or right left the fourth node is left or right so you get the idea if we convert those left and right into zero and once the first node is corresponding to a sequence of choice that can be encoded by the binary kind of format 0 if we convert this 0 binary number into decimal it's 0 it's exactly 1 less than the first node here just gonna pick another one notice 3 here so the choice sequence of choice we get we need to make to go from the root to this leaf node it's left right and left that binary representation is 0 1 0 so convert that from binary to decimal it will be 2 so it's one less than the third node we're looking at so that's looking from root to node and looking after the choice on the contrary it's exactly you know if we won't go if we want to go from the node number you know the two to get ca actual path it's a it's basically just the opposite right so we let's say that we want to verify do we have five nodes in the very last level all we need to do is to take that I subtracted by one to get forward and convert that for from decimal number into binary representation so that's one zero and that's telling us the pass the correct password route to this node if he indeed exists is to choose right left and left so now basically this gives us a relationship between the nub of nodes on the right hand side on the last level - - a pass to get to that very last note - - a pass to get to that very last note - - a pass to get to that very last note there so with this we can combine this we can use we can implement the binary search with this so we pick a pivot number you know educated guess about the number of nodes inside that there are lots the level and just gonna do a decimal number two binary conversion and that is pretty much telling us the path we can try to traverse front route and try to reach the leaf node if we can get there that means we want to search we want to do the binary search on the larger half otherwise we do the smaller half so that's how we can do binary search combined with this you know this path that's converted by converted from the number of nodes we are guessing so that's the solution here the solution will be taking log n multiplied by n log in the first log in is basically the binary search the second log in is the for every single time we want to test do we have that many nodes we have to do a single pass from root to leaf which is log n so that's that the other thing the other kind of a solution is that we can see that all we care is the last node in the very last level so if we know that the last level the last anode in the last level is only right-hand side when we look at the right-hand side when we look at the right-hand side when we look at the route if we so we can just do right left and get that answer if the left a node is indeed if the last note on the last eleven is indeed on my right subtree that means the whole left subtree including the root is actual there it's actually there so how many nodes are there in this particularly example we have the maximum level to be three index we and we find that the last of nodes on the right last the level is indeed on the right-hand side level is indeed on the right-hand side level is indeed on the right-hand side compared to the root then we can just count up the number of nodes from the left hand left child left the subtree including the root which is 1 2 3 4 5 6 7 8 so that's 2 to the power of the depth the level index max and that level index and then we basically add that to a counter from which initialize to be 0 and then the problem basically reduced to looking at a smaller complete binary tree and want to look at the how many nodes out there so the right subtree of this root is again a complete binary tree and the question now is to decide how many nodes are there in this complete binary tree we now know that we can see that the last node on the last level for this subtree is not on the right-hand side subtree is not on the right-hand side subtree is not on the right-hand side that means we want to look for it in the left subtree of this smaller binary complete binary tree and if we choose to go for the search for the left subtree that means the arundo for this subtree and all its right subtree is complete so we can add those to the two the counter and how many nodes are there that's one - that says that is the depth that's one - that says that is the depth that's one - that says that is the depth the level max level for this subtree which is - sorry which is 0 1 2 so it's which is - sorry which is 0 1 2 so it's which is - sorry which is 0 1 2 so it's 2 to the 1 - dili 1 so it's the so it's 2 to the 1 - dili 1 so it's the so it's 2 to the 1 - dili 1 so it's the maximum depth maximum level for this subtree subtracted by 1 and then once we added those we basically reduce the problem to even smaller on that smaller one is to consider this 2 node complete binary tree and try to look at try to figure out the number of nodes there so again the thing we do is to look at there where the last node and the last level is if it's on the left hand side we add the root node and all its right subtree here it's none to the counter and then look for the smaller problem there so it's a divide and conquer approach we can apply to solve this problem was that the code should be much simpler compared to binary search ended this conversion to be honest that the binary search is sometimes can be quite tricky and the conversion is not really that efficient because if we convert to 4 we're basically gonna using the maximum taps and probably shifting a bit mask with a1 shifting by the levels and do an end operator with the pass we get you know and try to figure out the do we go left and right so the code can be complex but the divide and conquer solution it's gonna be pretty nice so I'm gonna code to the divine conquer approach so but the wrong time for that is the same basically it's a still log n x log n for the divide and conquer because we each time we reduce the problem to have because we get rid of the you know if we choose right we get off the whole left subtree of the root and the root itself if we choose to go left we get rid of the node at the root and the right subtree so in total it's log n times we do this divided and each divide we have to do a pass trying to figure out the last a knows if it is that node on the left or is that on the right hand side so that can take login time as well so it's log n multiplied by log n it's the same runtime compared to binary search on the only number of nodes on the last level but the code is going to be simpler so I'm going to coat the divide conquer approach so let's coat this one thing we definitely need is a height calculation because no matter which version you go to you have to constantly calculating the height from the node are you looking at the height of the tree you're looking at so the height of the tree based on the node you're looking at so we definitely need a helper function to do this so we're gonna do that height is initially negative one and if there's a volume node we will try to use the left eye of the link to go further so with this if we have a single node just that rule node inside the tree this cook that's why it would run just once so the H will be bumped into zero and you can see this R in our analysis said the mass really works easier if we index the first level to be zero then you know the number of nodes on that way is just basically two to the power of that level index so for that reason if it's just a root node we bump the H from negative one to zero so that makes the math easier and then we're basically just gonna do this divide and conquer oh we the node is always going to be a root node for a complete binary tree in the very first beginning is the root node for the whole tree in the second iteration in this while loop is going to be either the left child or the right hand the right child of the origin root depends on can we find a where we find that the last node on the rail last level so the way to find that do we have the last node on the front in the left subtree or the right subtree is basically calling the height function on the right hand side the right child if the height of the right subtree is equal to the height of this whole tree subtract by 1 that means the last node on the master level has to be in the right subtree so we call this height function on the right child so that's the height of the right subtree if it's equal to the whole tree height subtracted by one you know getting ignoring the root that means we want to go right and we can add all the nodes on the left subtree including the root to some kind of counter and the mass is that it's two to the power of the maximum depth at a maximum level so it's two to the power of h and we move the root node to the right subtree the else branch will be that basically we find that the last node on the lost levels on the left subtree all we can do is to put this node and this node those number to the counter and that is it's basically this divided by two and we go to the left after this while loop but we have to decrement the height I want in the end we just returned the number of nodes we added the two discomfort so that should be the code I should grab a root here let me run some tests I want to test the some educators I think you should be able to handle all those one two three four five nope not working anxious reference to before assignment geez I should call this fight function when the rules first to get to the actual height no it seems alright so why is it being able to handle the case where we don't have a rule is that if we don't have a root H is negative one and this is not gonna be wrong at all and so we returned the default number of nodes which is zero so that explains this edge case then the other edge case is that we have just wondered if we just have one root node H will be bumped to 2 0 and number of nodes is 0 so we're going to test that this right the this is a null pointer so it's gonna be returned negative 1 is compare that to negative 1 it's true so we add this 2 to the power of 0 to number of nodes so that returns 1 so that adds this to 1 and just return that because we will terminate after the root node so that explains this one as well yeah I was arching to thinking that I should handle 0 and no Dada and it's just a root note separately but seems that the code should be able to handle that very nicely yeah so that's the divide and conquer solution to this question all right
Count Complete Tree Nodes
count-complete-tree-nodes
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree. According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`. Design an algorithm that runs in less than `O(n)` time complexity. **Example 1:** **Input:** root = \[1,2,3,4,5,6\] **Output:** 6 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[1\] **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[0, 5 * 104]`. * `0 <= Node.val <= 5 * 104` * The tree is guaranteed to be **complete**.
null
Binary Search,Tree,Depth-First Search,Binary Tree
Medium
270
1,206
but cool let's take a look the sign escape lists without using any built-in escape lists without using any built-in escape lists without using any built-in libraries are limb sudden links hi cool 12:06 design skip list the sign is 12:06 design skip list the sign is 12:06 design skip list the sign is skipped list without using any building libraries a skip list is a data structure that takes a whole blog and time to add you ate and searched compared with creep and a web Blackshear which has the same function first performance the code link of the skipper's can be compared in please Shawn an idea behind schemas are simple just simple like this you can see that there are many layers in the sky bless you today is a sordid like this with the help of the table layer add search I mean first of all we're improving the average time comprises of lager and a space compression our ban to be specific you should design search ad and UAC race is tricky actually doping that tiny weights before and we just have to implement it we don't have to worry about the complexity per se I mean like we don't have to do rebalancing this goodness which is well I think not anyway that could be well what if it is that it is like way harder forgot takes album what is this contra thing I said I'm like waiting for the animation to update so I could see what's going on nee belan with 45 - yeah ok coin flip to nee belan with 45 - yeah ok coin flip to nee belan with 45 - yeah ok coin flip to insert an element is finish what this is search this animated gif is very weird I see inserted there insert an element into the a Lea and I knew in skip on inserting you always oh that's what out sir now I realize what it's saying it's not tail of the list it's that you flip the coin is a tail so all heads I forget which one it is and you are insert to the level on top I mean it's just two of them it's annoying how do you insert into a to a given level I guess you just keep track of the search and then the last element yeah okay fine okay so let's just say so level elements there were two elements naming is high let's just make it a collection start I guess we really do need length list for this right of course I mean you could do other stuff but then like you get terrible performance as a Rizzo I wish there's a link in this class actually that's another story okay let's just have a node linked list node was in a node I should say value and that's just said next a second to none okay I guess that's all you need for a note and sub that levels this is also straightforward and mmm do i whatever yeah maybe I do one no it's okay all right what we'll play around with this is not final so let's just do the ad hmm how do these is it the trade is a linked list so then you can't even keep okay so now I'm thinking about how to keep track of the different nodes on different levels so I just or whether like I'm thinking whether I need a or shouldn't need an explicit in this person pointer or some kind of implicit Fang was definitely as part of the search like you could get them as polish but now you have to be able to go down so you definitely need a thing to know love them so let's just go next touch part of like a regular link this stuff and then down maybe you need up to but I think maybe we could do something with stack that cares about it we are search so okay so search we take the highest level what happens if like say we want to search for 20 hold this is kind of a not complete example right well like I don't remember their educators that's why I'm looking at this a little bit in the sense that like I said do you always put the first known in the list or is that just like lucky coin quo let's look at this make appear I mean this is the thing that they don't tell you're really not used to mmm it kind of we used our Wikipedia's Fang which is kind of dubious but okay like is this coincidence that the first one or is it not well now does it just tell you how to do it indexable skip this yeah I know that food filters also funding to men by the way if I just saw boom filter or sort of thing that once you've done it once you don't forget so I said this and I'm forgetting about this goodness that's search spot is a little annoying I just don't know the specs for a skip list and it's not really in here for whatever reason I guess it doesn't really matter except for some edge case performance rings mm I guess I could also keep track of yeah okay maybe I'll just combine these separate symbol like this and no it would be I'd like to say collection he thought well dick no it's not good yeah why not okay and now at know I guess what people were saying is you could I guess just like add a negative infinity root note and depends on how kind of like generic you want to be because for twenty thousand was twenty thousand to the fifteen it's like too small not 32 K 2 to 16 is 32 K most 6000k to need most state you say it's alright to 60 and 65 care that's just used 16 also because it's fun we can yeah that's just too soft type and what is it negative infinity yeah now we need a helper because we're full level and then just to say 16 which is max in theory will produce calcium somewhere and if like this is not that where that you may get more than 16 but I should say we don't have to worry about more than 16 because it's one in like 120,000 gets more than 16 which like 120,000 gets more than 16 which like 120,000 gets more than 16 which given 20,000 that means every like 6 given 20,000 that means every like 6 given 20,000 that means every like 6 test case of max test case you would have one element of more than 16 levels but that's fine but now that we have died with this add up like okay so well we need to add so we're just do coin flips until we write I don't know how to brand them and it's like random dog went into someone like that in Python sigh googling that word and could never win so I was right but they are inclusive which I don't remember my new while this is to go to zero which is not possible let's do this well I should say 1 no promotion I just I mean you could actually do this in one thing and then just take the path okay fine that is way too fancy but let's just get a random in from 1 to 32 and then novels is you go to the number of white most bits is that too hardcore is that not necessary I mean so then let's just say and while minus 1 is greater than 0 am I doing this right it's okay cool and then we just they say level is you're gonna main level in 16 stop down max level maybe just from double-checking and then now we can do double-checking and then now we can do double-checking and then now we can do itself well level the number and then max time level and then I wish to actually implement it so still using Python to permit wellthen decorations but I guess now I even need this level yeah maybe well let's actually initialize maybe instead of going to help them because we can make the help and not assume that in the range of us anyway sometimes levels level is equal to no I think that's we don't need this just sort out who is equal to this new node with negative infinity and it's max level I guess we could actually put this into the node itself and then we can instead of using tears we have it's not our next you go to it's just none times level something like that this is also no longer true fine level yeah because it's not good enough yeah I guess South was you know not getting promoted just like life okay and then now we start at the top in the route so let's say notice you got yourself good now we started to the top of level and then we just I know we start but we need to stop at the top so that we get that log and performance okay and then now we go down that's it sounds like a song but oka if know why us now we're trying to go if I didn't know what is to the next note that it like it tries to go to the fight as a can so okay if no Todd what so I don't would this would be obvious be smaller but okay but if this is smaller than the current value what it should then edge cases no dot know that value is that standard value then we try to go to the right of the current know or necks of the current node I'd their current level so I have to do some pound checking for us if level is so this needs for the first couple of it should be always true and then of node our necks and this is not none then notice your girl - no time next current notice your girl - no time next current notice your girl - no time next current level and let me keep going let's a while fingering in the wrong place so well just a destroy keep going right and then now we can go down notice every pick this kind of case and know that value is Wow and this is not done so we I should only this and then now when that's true that we could go down one level yeah and then just well couldn't that was waiting maybe just strictly greater than soon because once it's that see no that's okay having it so you still want to trash the right I mean to one of my what I don't like about doing these palms necessarily at least for learning purposes is that debugging is kind of hard but all right just do sturdy buggers but in theory there's a debugger so maybe we could take advantage of that but yeah so add for level so this should be on our way we don't actually add no so we don't go all the way down to zero so now we just go to the level maybe even this condom is too small then okay now that I do know the cone W you still want to go order it down it's just happy now to know is you got a level just to be and now this is the biggest no to the point in which we can add to the way so then we just use ya know dot next of current level is you go to as you go to this current note which I guess we have to vindicate know you know is equal to note of value and language is the input level yeah and you know now we wanted so that's at the top make sure I guess within cooperated part of this and then make this part of signal later put off having happen off by one this is destructive things oh so we want to get the previous such that this is not the case and also this is not enough because no doubt next maybe something else so we need to do order funding this stuff link design skip this you just implementing skip this so okay so if no dot next that well it's already not none but it's still less than well then we go okay and then now if current level just less than the input level and got it no we want to do this but not action well you have to add something like okay previous oh no is your gonna know that Knicks current level when you did this and then now new no next okay no okay mmm really not confident and also I wish I could just print out like the thing for kind of research but we could do that we could buy the help of effort that's just mr. pie so essentially I did a search I mean that's it maybe like refactor this but yeah alright let's just do a helper point for a real quick okay in range stop down next level no this equal to stop that start dear well no just not none no because no tap next like right next time oh but print along the way let's just play let's print level maybe I could you hadn't better at Python I should actually convert this into what you require right if you convert this into the elevator okay let's do that then that's for now let's print it out after every kind of in this order but always not confident about it just coming and this is where TDD it's really handy with your into wow I thought I fixed that because I keep on seeing it wait mmm there is seven yeah do I have a check but I guess I had a check here mm-hmm how many know now how mm-hmm how many know now how mm-hmm how many know now how actually now I should check it out maybe I have an off by one somewhere hey it's okay I mean I hope everyone's learning something like that oh yeah I think I start at 60 at the max that way instead of mass number minus one because I've been using the inconsistent in places okay 40 was 40 no I just said it's this okay they just want to code again see we actually crash okay so it doesn't actually play anything before hmm Oh course it was the test case does it off funky stuff okay let me put that somewhere else yeah don't put in a text file and now let's make this slightly straightforward and then because there's some randomization let's print that out for debugging cost level is kind of randomly decided listen print anything before that because I drink Lovelace before all right this is also print before and probably should do this in a faster manner to wow it's been half an hour in general but it is good for learning I'm learning a bit so 112 method number one at level 12 so what's growing about yeah I have enough I won in two levels again that's fine well it's not great but it is an easy fix with this okay because level could be zero but you actually wanted to have one release well like silver bring the bass level oh that's accepted because it doesn't do anything okay what is all just output okay one six and then zero at one two three four all the way - wow that's a three four all the way - wow that's a three four all the way - wow that's a very lucky road that we wrote 16 for the first time I was like why do we get wise everyone you know why Sam why's it add it everywhere but okay so that seems correct I don't know about performance now let's see if this is right on these things so I must be doing my math I think I did it i my counting is off that's why I kind of number one - not that's why I kind of number one - not that's why I kind of number one - not the number of bits I mean number of Trumpets so that's why this is always weird okay I should what I want to do is this okay so one is zero because it's just unlucky that's fair to get one which half the time which is make sense do we get zero again I mean I still wish it wasn't I mean we saw it in other cases that I was okay cool I mean I feel happy about that kind of my not I'm happy in general happy person okay cool okay Search we just pace it do the same thing here just without this part so maybe it is copy I think just by some abstraction we can do but I will think about that another time also if you're doing an indigo to say that okay what is search returned now just true force okay no it keeps on going node and then now after that we can just check no type next because this terminates the one right before well and also you're too I do need to think the current level and then now let's bring it the test case back but without the removal no you know what that's one do we move and see what happens I mean it will fail to remove or but the other stuff should be ok except for the last piece let's see if we let's see if it uh yeah adhere to where we expect it to be - comparing issues also target that's mmm never will yeah nothing type us know we also goes until there's none on the necks okay and that's fair well I don't I mean tennis I guess you get simulated but I got you mean you actually will do it right it's wonky so I mean this is the only change that must be the thing but how did I do here can this let's just do this just never trigger because I don't see how this terminates if you know dot no I guess it well if this is true but this is for standard never terminates so okay I was quick sometimes because actually you I want this to be this should be part of a loop actually it's just I thought it'd be too much it's like a eight line wound up or its statement but that's why I made more sense okay fine this with us get then didn't also Co repeating not great but okay let's see if this I mean it's not gonna be the right answer because even if it's the right answer that means we did something else wrong because that would not be when we expect but let's see we while in the good twice so there should be good we turned four so it's done oh I didn't know you're supposed to return on you race okay let's find out and four so we shall these get destroyed right then this part right no okay anyway so there's nothing and then search again it's force oh well force again but a search for one is true which is actually what we expected it so that's good in that's wrong in the way that we expect to be because one was not your ways because we never implement you waste okay so that's good yeah this implementing erase simplest logic here I think just wow dude I mean I think I'm retired today which is an excuse for being lazy but this is why you know when you work don't overwork us then you end up to amazing things that you regret in the future in terms of coding I mean maybe if I started part of life as well but anyway that's how the way we move stuff okay so is this entry like a search except for when this thing triggers we want to remove the sticker the force move this you go to true and then now we actually want to remove it so no dot next the current level is you go - no oh whoops go - no oh whoops go - no oh whoops yeah that's right that next current novel dot next this is a mouthful but this is a other than the mouthful is standard linked list stuff and we don't move - no okay maybe that's okay let's move - no okay maybe that's okay let's move - no okay maybe that's okay let's see how that goes fingers crossed how and why did they have different parameters for every one of these I think you wanna coin here different like that is not a consistent thing maybe okay I mean I definitely don't feel comfortable about this yet to be honest so I think on a normal day I would play like test this way more but today I'm a little lazy I'm just got something in and see what the edge cases are okay well sometimes your best laid plans get foiled by it being accepted on the first try okay can be a little bit faster performance-wise is pretty slow actually performance-wise is pretty slow actually performance-wise is pretty slow actually and usually I don't care about its tallest but this that is the truth there are this palm hmm this should be logarithmic let me see I mean we could check better like things went down or to the right on a search and everything else is kind of the same for that reason and I'm gonna use anything heavy everything of the smile loops and that's the only thing I could think just if I don't do anything in and logon how is this no performance wise I mean okay maybe I'm a little bit slower but not damn which other than cool people don't really fast like I don't think I'm like an O and slower maybe I'm just and I have a lot of weird conditioning right for that decided I know dysfunction so often I have too many numbers or too few levels something like that but uh well the prints don't do anything right well like I don't plant I mean I have to this is just uh I have to call this function for it to print I don't think calling this anymore as I commented out but yeah that was actually my first door as well to be honest but that's why I was able to point it out pretty immediately I mean I guess I could be slightly better about it but yeah I mean for now I'm not gonna worry about it maybe I'll look put a discussion let's look actually that's a good discussion see I feel like I see price is so much faster to time action nodes and I don't think this mmm it's weird maybe I'll take a look later I don't think any of these like changes how I did except for maybe I could have done this with another pointer instead of allocating memory all the time maybe I don't think you could do better than looking at each of dude sub nodes and none of my stuff is particularly slow that I could find because you need to do these and in either case most of these are just like enum number of times or maybe a maybe recover these I just - he thinks well recover these I just - he thinks well recover these I just - he thinks well cool oh yeah I mean I think this is how long did and I'm taking me about 40 minutes I mean it's not great but I think a lot of it was just under a lot of this was just in the conception stage of me trying to figure out how to well I think I spend like 10 minutes just reading up on some of these a little bit but even yeah I mean first of all I would not expect this on an interview maybe like you know work food different algorithms and stuff like this but not the coding portion this is a bit tricky maybe that's what I want to say I mean it's not on a 45 slash 1 hour phone interview but yeah I mean I think that's something that we like you could actually bring it up on in degree as well it's like well for performance I would quite like figure out the benchmark and stuff like this and figure it out I mean there's no way this is faster than oh sorry there's no way this is slower than generating and coin flips right so I don't know I mean it could be but I like it's fast and turn it around how much more I can optimize maybe this is a little weird maybe that over floats int in Python so there's some auto magic to lungs maybe I should've used 31 I don't know by the way these are like way minor things and things that made me think about but okay cool well yeah I wouldn't expect this and just one into it at least not like tears in the programming way maybe you get like some problem is like okay let's see you ever skip this you have to all this stuff can you discuss about the properties how do you do search why is it again Howard what is the worst case why is it only on average what you know and stuff like that I love stuff that wouldn't even necessarily be based off you having to know just data structure before because you could probably reason a lot of these maybe you wouldn't have a rigorous proof but you know we're gonna now is by reasonable but overall if I'm plan to practice of course excuse me you could implement most of this with the linked list and I think about implemented just another way I would have implemented a linked list also from to the right and to the downwards in that case you know my traverses will explain the different but not that much only the route looks probably to be honest and maybe some weirdness like that but uh
Design Skiplist
corporate-flight-bookings
Design a **Skiplist** without using any built-in libraries. A **skiplist** is a data structure that takes `O(log(n))` time to add, erase and search. Comparing with treap and red-black tree which has the same function and performance, the code length of Skiplist can be comparatively short and the idea behind Skiplists is just simple linked lists. For example, we have a Skiplist containing `[30,40,50,60,70,90]` and we want to add `80` and `45` into it. The Skiplist works this way: Artyom Kalinin \[CC BY-SA 3.0\], via [Wikimedia Commons](https://commons.wikimedia.org/wiki/File:Skip_list_add_element-en.gif "Artyom Kalinin [CC BY-SA 3.0 (https://creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons") You can see there are many layers in the Skiplist. Each layer is a sorted linked list. With the help of the top layers, add, erase and search can be faster than `O(n)`. It can be proven that the average time complexity for each operation is `O(log(n))` and space complexity is `O(n)`. See more about Skiplist: [https://en.wikipedia.org/wiki/Skip\_list](https://en.wikipedia.org/wiki/Skip_list) Implement the `Skiplist` class: * `Skiplist()` Initializes the object of the skiplist. * `bool search(int target)` Returns `true` if the integer `target` exists in the Skiplist or `false` otherwise. * `void add(int num)` Inserts the value `num` into the SkipList. * `bool erase(int num)` Removes the value `num` from the Skiplist and returns `true`. If `num` does not exist in the Skiplist, do nothing and return `false`. If there exist multiple `num` values, removing any one of them is fine. Note that duplicates may exist in the Skiplist, your code needs to handle this situation. **Example 1:** **Input** \[ "Skiplist ", "add ", "add ", "add ", "search ", "add ", "search ", "erase ", "erase ", "search "\] \[\[\], \[1\], \[2\], \[3\], \[0\], \[4\], \[1\], \[0\], \[1\], \[1\]\] **Output** \[null, null, null, null, false, null, true, false, true, false\] **Explanation** Skiplist skiplist = new Skiplist(); skiplist.add(1); skiplist.add(2); skiplist.add(3); skiplist.search(0); // return False skiplist.add(4); skiplist.search(1); // return True skiplist.erase(0); // return False, 0 is not in skiplist. skiplist.erase(1); // return True skiplist.search(1); // return False, 1 has already been erased. **Constraints:** * `0 <= num, target <= 2 * 104` * At most `5 * 104` calls will be made to `search`, `add`, and `erase`.
null
Array,Prefix Sum
Medium
null
138
welcome to february's lego challenge today's problem is copy list with random pointer a linked list of length n is given such that each node contains an additional random pointer which could point to any node in the list or null construct a deep copy of the list the deep copy should consist of exact blah so basically we have a linked list that has both a next pointer and a random pointer now this random pointer can point to any node inside of our list and it could also point to the null it can also point back to itself now if we want to make a deep copy here uh we need to make sure that this random pointer isn't pointing to the old list it's got to be pointing to the new list so what we can do is regenerate our linked list make a copy with just the next pointers and keep track of the old nodes to the new nodes inside of some sort of hash once we create generate our new list we could re iterate down our new list use our map to see what the next the random pointer is pointing to and then point that random pointer to the one that's pointing to the new node instead of the old um so i hope that makes sense it's going to be in two stages right we first want to generate our new list as well as keep track of the hash of old to new nodes and then we will update our new list with the new nodes for random so to do this i first need to start off by creating a couple pointers what i'll do is create a dummy pointer as well as a new pointer pointing to at first just some empty node here i also have a pointer for the current pointing to the head all right so first we want to generate our new list for that let's look up create a hash well i'm going to map the old value or the old node to the new node that we generate okay so while curve what we want to do well first we want to say all right new.next new.next new.next we want to generate a new node with the curve.value with the curve.value with the curve.value so now we have our new node now let's keep track of that inside of our old and new so all new uh using our pointer i'm sorry our current node is now going to be equal to the new dot next right and we will move our cur to qr.next as well as our new to new.nx to qr.next as well as our new to new.nx to qr.next as well as our new to new.nx so that we can keep generating our list so now if we finish this we should have a new linked list with the dot next point to the head of it all right so that's great but what about our random note random pointers well okay so to take care of that we first let's set our current pointer back to the head and we'll also set our new pointer back to the dummy dot next so these are pointing to the heads of the old node and the new node now while curve what do we want to do well if cur dot random exists okay we want to update our new dot random to equal the old new of the curve.random because now this is of the curve.random because now this is of the curve.random because now this is pointing to the new generator node that we stored here and that's going to update that linked list to now point to the new node so we just need to move our pointer now and move our new to nu.next finally we can just new to nu.next finally we can just new to nu.next finally we can just return our dummy.next which is pointing return our dummy.next which is pointing return our dummy.next which is pointing to the head of our new linked list so let's make sure this works okay that looks like it's working it's going to submit it so there now this is a of n time complexity even though we passed twice but we do use extra memory we use of an extra memory in our hash now could we avoid that now in the hints here they tell you why don't you try interweaving the nodes of the old and copied list so what that means is instead of using a hash what we can do is insert our new node or new list kind of like in between so now this kind of can be used as our hash instead of the old like if we want to know what the new node is all we need to do is get that old node and see what's pointing to the next and we can move our current pointer to go next instead uh to kind of move down the line to only point to the ones that are new so this is going to go in three stages right we first want to insert our new nodes into the old list then we want to go through and update the random pointers to point to the new nodes for the list and then we want to remove these old nodes and then return whatever is left okay so that's going to be in three stages uh it will be in stage one interweave stage 2 update random pointers and stage 3 remove old nodes all right so this is a lot trickier than i expected it took me a while to get the hang of this but uh let's just start off by generating our dummy list or i'm sorry dummy node and what we'll do is um we'll have two pointers again um we can say well okay let's first start by saying okay dummy next is going to be equal to the head and our current pointer is also going to be equal to the head so while cur what will we do okay so we need some sort of temp variable to store the information for the kurdon next and regenerate our node to now point to that so what i mean by that is we'll generate a node with the cur.value here now the let's see temp dot next is going to be equal to curl.next curl.next curl.next and curr.next is now going to be equal and curr.next is now going to be equal and curr.next is now going to be equal to 10. and after that we can just um make our current pointer equal to the temp dot next instead so that's going to interweave these new nodes inside of our old linked list okay all right so now stage two uh let's re-initialize our current uh let's re-initialize our current uh let's re-initialize our current pointer to the head we want to update our random and we can't we don't have hash anymore right but luckily the values are inside of our linked list itself so we'll say while cur if dot random what do we want to do we'll say curve dot next dot random is equal to the cur dot random dot next so this random one is the old node now the random.next is going to be the now the random.next is going to be the now the random.next is going to be the new node um and then we will need to move our pointer to not the next one but the dot next instead so that we don't update our old nodes okay so finally in stage three we want to remove our old nodes right okay so we should have a current pointer pointing to the um oh well let's start off with the dummy up here okay and we will have our um it's called new going to the head instead so while new do we want to do um we want the curve dot next let's point to the dummer dummy we want that equal to the new node this is the old node actually i should call it old so i don't confused and we'll say make this equal to old.next instead old.next instead old.next instead uh we should move our pointer then to the old and move our old to the current dot next instead um so what this does here is it's going to be updating our um our new pointer to point to the next one for from the old and removing the old nodes so after that we can just return our dummy.next dummy.next dummy.next hopefully i didn't miss anything here let's see if this worked okay great so that looks like it's working let's go and submit it oh okay there we go accepted so this is um i guess it's technically constant space because we're only updating our linked list i'm not completely sure if that's true but it avoids using the hash so i suppose that counts personally i think using the hash solution is completely fine but if memory was a problem then you could go with this solution all right so thanks for watching my channel and remember do not trust me i know nothing
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
525
hello guys welcome to another video in the series of coding we are going to solve the problem it's called continuous array so given a binary r in nums you have to return the maximum length of a continuous sub array with equal number of zero and one let's try to take an example to understand now there are lot of sub arrays in this and uh the brute force approach uh to solve this problem is um list down all the sub arrays right and if you list down all the sub arrays how are you going to list out so let's say you start with this i then you take this j this is one sub array okay next time j is here i remains the same this is the next sub array next time j becomes here i becomes here this is the next sub array and so on right so for every i you can take a j that will uh start from i plus 1 okay so let me write down so you have two for loops this is a brute force approach that we are discussing to first of all list down all the sub arrays so you are going to start with the first for loop i select and the next for loop you start with j ranges from i plus 1 to n right so you can list down all the possible sub arrays and it will be o of n square right uh to list down all the sub arrays now in any sub area right whenever you have listed down a sub array what will you do after listing a sub array let's say this is one sub array this is the starting i this is the ending j now in this you have to see if you have equal number of zeros and ones or not so the way to do that is what will you do this thing in the brute force way so we'll keep a count of zero and we'll keep a count of one so i listed down a sub array now i will count my zero and one okay so first i took two for loops for listing down a sub array if i am thinking in the brute force approach still what i will do i will keep a count zero i will keep a count one and inside the sub array again i will start a for loop and i will uh see whenever i see a zero i will add a count whenever i see a zero again i will change my account whenever i see a one i will add a count whenever i see a one again i will take ah again account and i will check if these two count are equal or not if these two counts are equal then that means that i have a sub array which has equal number of zeros and ones that means that this is one possible sub array and now we have to find the maximum length of satsang array so max variable declare kardini and we'll compare with that right this is the brute force approach that we can think of now let's try to think here what can we do better suppose we have a sub array right so instead of keeping a uh you know count and traversing again see in the sub array somehow we know a zero is cancelling with a one right so if we see a zero we need to see a one then only the number of zeros and ones will be equal for every zero you need a one to cancel okay for every one you need a zero for every zero you need a one if you have a zero if you can cancel with the one that means that you have equal number of zeros and ones okay so let's say we give the ones plus one okay and we give a zero minus one okay then while traversing itself see while traversing itself let's say i give the zero minus one i gave this one plus one i gave the zero minus one okay now what is happening now if i take the sum minus 1 plus 1 minus 1 everything becomes equal to 0 so somehow the sum is finally you know uh becoming equal to 0 so the sum inside the sub array is becoming equal to 0 because i have equal number of zeros and ones they are cancelling out so i can give up plus one and minus one correspondingly okay to any of the numbers i want take any of them as plus one take any of them as minus one and if they cancel out okay let's take one more example let's take this sub array example now here will they cancel out here they won't cancel out see for example this 0 is minus 1 this is plus 1 this is minus 1 okay in this case what is happening what is the sum when you are checking the sum minus 1 plus 1 is 0 but you have minus 1 it becomes minus 1 you have minus 1 it becomes minus 2 you have plus 1 n minus 1 it becomes 0. so finally the sum of this sub array is minus 2 so you don't have equal number of zeros and ones okay but if you had taken some other sub array right for example if you had taken simply this sub array with minus one and plus one they will become equal to zero okay now what is the logic or approach to solve so we understood why it's important to uh you know take them as plus one and minus one because they can cancel out and then we can easily check okay now let's see one thing so what we will do we will uh do a dry run and then build up the solution so let me give here plus one and let me give here minus one corresponding to a zero okay so whenever i see a one i'll get plus one whenever i see a 0 i am giving minus 1 again a 0 minus 1 again a 1 plus 1 ok now let me see something interesting okay so now see i have found this so now let me do one thing while traversing itself can i do it in o of n complexity in one traversal itself can i do now when i have plus once and minus one now one idea strikes me c let me while traversing let me just keep a sum of these okay so what do i mean by that uh so initially the sum is plus one now plus one the sum becomes plus two that means till now i have two ones okay now the sum becomes plus three okay now the sum becomes uh plus two because i have a minus one now the sum becomes plus three okay now the sum becomes okay wait now let me observe one thing before going forward see in this case what happens is sum has become plus 3 again i have already seen a plus 3 somewhere that means what see the sum up till this area was plus 3 the sum again up till this area is plus 3 up till this area it was plus 3 up till this area again it is plus 3 means in between that the sum whatever is there is canceling within itself 0 and 1 is cancelling because i have the same sum again i have the same value of the sum again so that means what zeros and ones in between these two boundaries are cancelling with each other i have equal number of zeros and ones in between okay i have equal number of zeros and ones how do i know that the sum up till this point was plus three sum again is plus three that means in between no matter what sum i had it got cancelled and now i have plus three again okay so let's build on this logic so this is how we can do it in single traversal in o of and complexity itself okay so let's continue and then it will be more clearer so let me um build again now um we took this sum one two three four five six okay let's build the sum now it's plus four okay here then uh if i take a minus one the sum again becomes plus three okay now let's note one more thing again the sum became plus three up till this point the sum was plus three right okay up till this point the sum was plus three up till this point also it was plus three okay but what happened again up after this point also the sum became plus three that means what that means in between here also it is cancelling see up till this point the sum was plus 3 again here it becomes plus 3 that means in between whatever zeros and ones are there i have taken plus one i have taken minus one all those are cancelling and my sum becomes plus 3 again which was the same sum here that means this length in this length boundary i have equal number of zeros and ones see i have zeros and ones that are canceling with each other so again i have one more segment which is having equal number of zeros and ones okay and this is larger than the previous segment that we saw okay so now let's continue so let's continue further so plus 3 plus 1 is equal to plus 4 and then again we have plus 3 okay then again we have now plus 2 and plus 2 plus 1 is plus 3 minus 1 is 2 plus 1 is 3 plus 1 is 4 okay this is our entire area now whenever sums are repeating right for example consider this case the sum up till this point is 4 okay and also what did we observe some up till this point is also 4 up till this point also sum is 4 right see you have 1 2 3 4 five six ones and you have two zeros okay six ones minus two zeros is four ones so sum up till this point is plus four again the sum becomes plus four that means in this segment also you have equal number of zeros and ones they are cancelling each other so whenever you have some that are repeating right whenever a sum is repeating that means inside that segment you are going to have equal number of zeros and ones okay so now uh the brute force approach to solve using this method is so once you have created this right while traversing you can create this in o of n right but uh you also need to store that you had seen a plus 4 before they know then only you can check now again if you see a plus 4 you also need to check when did you see a plus 4 last time okay because see here also you saw plus 4 at this boundary now this segment is better right this segment is better than uh the then this segment right so see the light blue and the dark blue segments the light blue segment is having a more length than a dark blue segment right so this segment is giving me a better length why is it giving me a better length because i saw plus 4 before here compared to the plus 4 that i am seeing here i so i should keep the plus 4 that i am seeing on earliest right on the best case i will get a maximum length of the segment only when i use the plus 4 that i saw previously which was the best left possible the left most possible plus 4 i should use that so i should store this plus 4 in the least index on which i saw the plus 4 right if i had stored this index and i know i am seeing a plus 4 again i know that in this entire segment i am able to get a better length okay so now let's use a map data structure that's why we need to store the index of a plus 4 that we saw already and then in just o of n traversal uh time and o of n space i can just solve this problem okay now let's solve this problem again so what i'm going to do let me just erase it is this so i am traversing this is fine now but also while traversing i am also going to store it in a map so that i can keep a note okay i can keep a note of the values that i see so first in the map what i will do i am seeing a plus one right so i will store a plus one and i know that i am seeing a plus one at the zeroth index so i will store that in the map okay next i see a plus two so i will store plus two at the first index next i see a plus three so i will store a plus three at the second index okay now next i am seeing a plus two but i already have a plus two that means what that means this segment is going to give me a sub array which is having equal number of zeros and ones right because i had seen a plus two here now again i see a plus two here that means this segment is going to give me a sub array with equal number of zeros and ones so i will see from the map itself i will see at the first index i had a plus two again at the again at this index right again at the third index i am having a plus two okay let's note this carefully so let me do one thing let me just erase this for once see now i am iterating over and at the third index i see third index at the third index i see that my sum is plus 2 from the map i see at the first index my sum was plus 2 that means what 3 minus 1 is equal to 2 right i have a sub array of length 2 which is going to give me equal number of 0s and 1 so my answer is 2 s of now i have a best case sub array of length 2 okay best case sub array of length 2 so let me store 2 in the answer and let's go forward to next iteration so as of now in my answer i have a sub array of length 2 okay now let's go forward now what is the next case i am iterating i get a plus three okay now let me check if i have a plus three already i have a plus three from the map i know that i have a plus three right from the map i know that i have a plus three and it is it was occurring at the second index and the index that i am iterating over now is the fourth index that means again i have a sub array of length four minus two of length two okay it is of the same length as my answer so i'll just go forward okay now let me go forward so let me just erase this and let's go forward now i see plus 4 right so plus 4 is not there in the map so i will store it in the map and it is at which index i will store the index number five okay now let's go to the next case next i see a plus three again next i see a plus three so i will check in the map when did i see a three i saw three at the second index again i am seeing a three at the sixth index so six minus two is equal to four i have a sub area of length four okay i this is the sub array sub area of length four this is the sub area of length 4 which is cancelling out because they have equal number of zeros and ones at the sixth index y light rating i found that i have a plus three at the second index from the map i found out at the second index i already had a plus three that means what that means in between the sum is zero that means my zeros and ones are cancelling each other so i have a sub array of length four currently now this is better than my answer right so i will change my answer and make my answer equal to 4 so my answer will become equal to 4 now let me go forward now i am at the 7th index i am seeing a plus 4 i already have a plus 4 at the fifth index that means 7 minus 5 two i have a sub area of length two it is not better than my answer so i will just go forward okay now i am at the eighth index i see a plus three i already had a plus three at the second index right so i will check eight minus two is equal to six eight is my current index two is the index from the map which is the left most index at which i saw three okay left most index at which i saw three this is the left most index at which i saw three this index right this is the left most index at which i saw three at this index and now at my current index which is eight right three four five six seven eight again i am seeing a plus 3 that means in between my zeros and ones are cancelling out with each other i have a sub area of length 6 which is better than my current answer so i will change my current answer and my current answer will become equal to 6 okay now let me go forward next i have um a plus 2 and in my map i had a 2 at the first index okay so 9 minus 1 is 8 i have a sub array of length eight which is giving me a better answer so i will change my answer and my answer will become equal to eight now let's go forward so now let's go to the 10th index at the 10th index i have a plus 3 in the map i have a plus 3 at the second index okay so 10 minus 2 is again equal to 8 which is same as my answer so i'll not change my answer i can just go forward at the 11th index again i have a plus 2 in the map i have a plus 2 at the first index so 11 minus 1 is equal to 10 is better answer so i will change my answer and my answer will become equal to let me just delete this so my answer will become equal to 10 okay my answer will become equal to 10. so i will change my answer and the best case answer that i have is 10 okay now let me go forward to the 12th index at the 12th index i again have a plus 3 i have a plus 3 from the map at the second index so my answer is again 10 which is already my answer so i will just go to the 13 index i have a plus 4 and i have a plus 4 at the fifth index so 13 minus 5 is equal to 8 so this is not giving me a better answer so my answer is 10 i have a sub array of length 10 okay and how did i get that sub array i got that sub array from here or here okay you can take any of the answer for example at the 11th index and the first index okay so let's see that so this is the first index so after the first next second third fourth fifth sixth seventh eighth ninth tenth eleventh so this is a sub array of length ten that is going to have equal number of zeros and ones you can see that zeros and ones are cancelling out all amongst each other okay now let's go forward to coding it so how to code this so we are giving a plus one okay we are giving a plus one whenever we see a one and we are giving a minus one whenever we see a zero okay so let's see so for end i equal to zero i less than nums dot size i plus whatever doing so whenever i see um whenever i see a one i am giving a plus one so let me take a variable sum that will keep track of this so whenever i see a let's say nums of i is equal to one right in that case what i am going to do in that case i am going to add one to sum in that case to my sum i will add one okay otherwise i will add minus one so whenever i see a zero i'm going to add minus one okay so now this is it now i also need to keep a map i have to see if i have ever seen a sum before so an ordered map into comma into m so first map will store the value of the sum first uh a key in the map will store the value of the sum okay and the value in the map right the second uh part of the key value pair in the key value pair the key will be the sum and the value right value will be the index at which that particular sum occurred in the left most place because we want to find the maximum segment length right so we will take the left most place so let's see that so first i will check if it is occurred in my map or not so auto id is equal to m dot find sum okay so if sum has already occurred in the map so if some not equal to m dot n that means sum is already there in the map in that case what i should do i should just compare it with answer so let me give an answer variable okay and now i will just compare it with answer so answer is equal to max of answer comma i is the current index and the second value in the map right i mean the in the key value pair the value is going to give me the left most index and i is the current index so this will give me the length of the segment in which zeros and ones are canceling out with each other okay so that's it this is a simple logic else we'll just insert it in map so else m dot insert we are going to insert the sum along with its index that's it very simple code this is the entire code and after this you can just return answer okay now there's one more uh thing in this which i forgot to add can you point it out what is okay if some so here i should give i t so first let's see this and then there is one more thing that yes so this is the uh case which i was uh going to talk about so this is very important for all why is it failing for this test case because okay let's see why is it failing for this test case so we have a test case 0 1 right so what is happening i am giving minus 1 here and i am giving plus 1 for 1 right so in this case what is happening so initially the sum is minus one and then the sum becomes zero so in the map you put minus one okay which is occurring at index number zero and you put zero which is occurring at index number one that's it you don't have any solution at all because sum is never repeating but in the zeros and ones are cancelling out so how can we find a solution in this case see you have to observe that 0 is the sum you should keep in the map already because see the sum is becoming 0 here that means you can consider a 0 that is there at the minus 1 index so if in the map you store a 0 that is occurring at the minus one index right that means the sum was initially or originally zero okay sum was initially or originally zero and then you gave a plus one and you gave a minus one and the sum canceled and became zero again so in the map there is a small trick that in the map you give that there was already a zero at the minus first index there was a zero and the advantage of that is what now when you are traversing over right when you are traversing over these values when you come to the first index you will observe that there is already a 0 at the minus first index so the length of the segment is 1 minus 1 so there is a length of so there is a length segment of length 2 which is your answer so in for these cases you also need to give a 0 at the minus first index so that is also very important so m dot insert zero consider it at the minus first index that's it now let's submit nc it should work okay i should give a bracket let's sum it again and see it should work that's it thank you
Contiguous Array
contiguous-array
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`. **Example 1:** **Input:** nums = \[0,1\] **Output:** 2 **Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1. **Example 2:** **Input:** nums = \[0,1,0\] **Output:** 2 **Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`.
null
Array,Hash Table,Prefix Sum
Medium
325