id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,616
hi everyone welcome back to the channel today let's solve the contest question split two strings to make palindrome and as i know this is a phone interview question asked by google so let's take a closer look the question statement so we are given two strings a and b of the same length and we can choose an index and split both strings at the same index so we can split a into two strings which we denote a prefix and a suffix and split b into b prefix and b suffix as well so we have to check either uh a prefix plus b suffix which is a concatenation of these two strings or b prefix plus a suffix either of one can form a palindrome so for example three we can split a here and b here so the uh a prefix plus b prefix will be ula alu which is a palindrome so for this case we'll return true and notice here that the data size can go up to 10 to the power of 5. so the algorithm has to do better than square times complexity and my initial thought to solve this question is to use like a brute force solution so just go through the string and split the string into a prefix and a suffix at every index and then get the concatenated string and then check if they are palindrome or not but this solution uh reversing the string will be big o of n times complexity and is inside the for loop so the overall time complexity will be square time so we will get a tle due to the data size so we have to think of a smarter way to solve this question an optimized way to solve this question is to use a greedy algorithm with two pointers we will greedily take a prefix and b suffix or b prefix and a suffix as long as possible if they are palindrome to each other and when we reach to a point that these two prefix and suffix they are not palindrome then we will check if the middle part of a and b is palindrome or not so now let's look at the code is pretty short and clean so there are three parts the first part is a utility function to check if the string is piling drum or not and the second part is the greedy and two pointers algorithm so we will define a left and right pointer and while left is smaller than right and the two characters in a and b when they are the same we'll just keep moving the left and right pointer and when we reach to the point that the characters are not the same then we will check if the middle uh part of a or b if they are believed or not so we'll run this check for a b or ba these two cases now let's see the code in action here is the example with some modification of example 3 in the question statement so the left pointer will point to the first letter in string a and the right pointer will point to the last letter in string b so at the beginning we will check if these two letters if they are the same and they are the same so we'll keep moving the left and right pointer next letter is l they are still the same so we'll just keep moving and here is a in both string so still good and next is g in string a and t in string b so they are not the same and we can see here that the prefix in a is ula and the suffix in b is alu so they are palindrome to each other so next we have to check if uh either the middle part in a or the middle part in b if they are palindrome or not if one of them is a paralympian then we just we can just cut that string and concatenate to the suffix of the other string to make the combined stream a palindrome so in this case uh gdg is a paralympian so we will concatenate the prefix of a to suffix of b so the concatenated string is a paralympian so we will return true for this case finally let's review because of the data size of this question the brute force naive approach doesn't work and we have to use an optimized algorithm which is a greedy algorithm with two pointers we will greedily take a prefix and b suffix or b prefix a suffix as long as possible if they are palindrome and then we will check if the middle part of a or b is palindrome or not and the time complexity of this approach is constant time we go of n space complexity is constant since we are not using additional data structure and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one
Split Two Strings to Make Palindrome
minimum-difference-between-largest-and-smallest-value-in-three-moves
You are given two strings `a` and `b` of the same length. Choose an index and split both strings **at the same index**, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bsuffix` or `bprefix + asuffix` forms a palindrome. When you split a string `s` into `sprefix` and `ssuffix`, either `ssuffix` or `sprefix` is allowed to be empty. For example, if `s = "abc "`, then `" " + "abc "`, `"a " + "bc "`, `"ab " + "c "` , and `"abc " + " "` are valid splits. Return `true` _if it is possible to form_ _a palindrome string, otherwise return_ `false`. **Notice** that `x + y` denotes the concatenation of strings `x` and `y`. **Example 1:** **Input:** a = "x ", b = "y " **Output:** true **Explaination:** If either a or b are palindromes the answer is true since you can split in the following way: aprefix = " ", asuffix = "x " bprefix = " ", bsuffix = "y " Then, aprefix + bsuffix = " " + "y " = "y ", which is a palindrome. **Example 2:** **Input:** a = "xbdef ", b = "xecab " **Output:** false **Example 3:** **Input:** a = "ulacfd ", b = "jizalu " **Output:** true **Explaination:** Split them at index 3: aprefix = "ula ", asuffix = "cfd " bprefix = "jiz ", bsuffix = "alu " Then, aprefix + bsuffix = "ula " + "alu " = "ulaalu ", which is a palindrome. **Constraints:** * `1 <= a.length, b.length <= 105` * `a.length == b.length` * `a` and `b` consist of lowercase English letters
The minimum difference possible is is obtained by removing 3 elements between the 3 smallest and 3 largest values in the array.
Array,Greedy,Sorting
Medium
null
1,870
hi everyone in today challenge we are going to solve this problem the program name is minimum speed to arrive on time and the problem number is 1870 only so first of all we are going to clearly understand the problem statement after understanding the problem statement then we will move to the logic part and in the logic part we are going to see how we can solve this problem what is the logic we are going to use to solve this problem so after understanding the logic part then we will move to the implementation part and in the implementation part we are going to implement over logic in Python C plus Java and JavaScript programming language fine guys now let's see what this problem is right and guys if you want to have a look on the solution which I'm going to write in this video I will share the link in the description you can go through that particular link and you can find all the solution right so now let's see what this problem say right so problem says you are given a floating Point number or representing the amount of time you have to reach to the office so yes we are given first of all one input that is nothing but hour right it is a flow depend that means the data type is going to be double right or slowed now we need to take n train to reach to our office simple thing right so we need to take n Trail for office right fine you are also given an integer and a distance dist of length n where if I describe the distancing kilometer of i3 so now guys we are given one area right so two thing is clear right first thing is nothing but we are given one hour our input which is going to double flow and secondly we can say uh this particular test array this is nothing but an array in off we can say integer right or it could be anything but uh this is going to be array of size length n right n is nothing but we can say the number of trains right so this is distance will tell us that for each train what is the distance that train is going to cover simple right so let's say uh this set is looking like one two four and again one so this zero index is telling us depth of zero train means first train is going to take uh one distance it's gonna cover up one distance only distance and fourth train is also going to cover one distance I hope it makes sense right so this is the simple thing now each train can only depart at an integer or R so you may need to wait in between each till night now guys let's say you have completed the first team and you complete it at the time of 30 minutes oh no 30 I will say let's say 45 minutes right fine so you have completed uh first change only in 45 minutes but the second train will depart at the fixed hour if you have completed the 40 uh Janine forty family you have to wait for 15 minutes it can only start in the next hour right so let's say you have completed in one hour 45 minutes so next train will departed at two hour only right at two o'clock not at three o'clock no 2 15 to 10 it can only departure a fix overclock right one o'clock two o'clock any Outlook right fine and so we have to wait for some time for example if first train takes 1.5 hours example if first train takes 1.5 hours example if first train takes 1.5 hours you must wait for an additional 0.5 so you must wait for an additional 0.5 so you must wait for an additional 0.5 so we can't start second train at one five hours we have to wait because that is going to start at two hours two o'clock right fine return the minimum positive integer speed in kilometer per hour that all train must travel at for you to reach the office on time right so nothing but we can say we are clear with our distance we are killed with our time what time we want at minimum time maximum time we can take to reach our office so that means one hour this is the maximum time we can take to reach our office second thing about how many train we need to take n train that is sure third time in a demon we can say um we cannot take a second train if we reach to that particular position uh or we expect that we can say not fix overclock right if you have completed our first journey and we want to take a second in but we are at a time of 130 150 130 145 150 anything we can't take a second we have to wait for the fix our light file so we are clear with this thing now let's see we need to return the minimum positive integer means minimum speed which should take up let me tell you here we need to Now find a minimum speed rate we need to find now minimum speed so that we can reach to our office in the given hour right and speed should be speed but speed of train right we need to find the minimum speed what should be the minimum or we can say speed of a train in our case for the given input so that we can reach to our office we can say in the given our right in the in this given hour so simple thing guys we have to just find out the speed of trade what should be the speed of trade right simple thing if we want to reach our office if you want to reach our offices at the given time or before this given six o'clock right if we are consider the first example right so let's understand the example then you will have a better understanding I know it's quite complex so here guys we are given a distance array one three two so this next one we can say one three two nothing but three ten uh three trainer there now guys we have to reach to office in between um at Max 6 hour after taking at much six all right so in before six we can say right before six right we have to reach to our office before six right so we should this train should not take more than six hours so we have to find the speed but speed should be the should be of train right so we have to find the minimum speed right so let's see that how we can do this so what we are going to do we are going to save if we take a speed of one so it's gonna take a one unit of time right so one distance is going to cover in one let's say one hour we can start it because it is a fixed hour ride so we can start secondary this is going to take a three distance right so as we have assuming that we are taking a one kilometer per hour speed so we can see one kilometer that means it's gonna take it's gonna cover three kilometer so it's gonna take three kilo uh three hour so total hour we are getting a six hour so you can see guys we can reach to our office to our six hour I hope it makes sense we can restore office because it's all the trains combined taking a six hour of Journey right and we can say that we if our journey is less than or equal to given hours so we can reach to our office simple condition right so find that make sense so this means nothing but we can see over one kilometer per hour speed is the minimum speed which a trace should have right if we increase a little bit so you know that guys it will want to be more than six hour right and that should not be the possible that means it's not acceptable to each our office right we will not get our attendance right fine that makes sense so now that's still here so we can see here we can write an answer one you can see uh output as well we happen right now let's move to the second example here we have one three two same time but the condition is hour should be not six now it should be 2.7 should be not six now it should be 2.7 should be not six now it should be 2.7 right I hope it makes sense so we can say hours should be 2.7 say hours should be 2.7 say hours should be 2.7 so that means that's what we want to reach to office before 2.7 reach to office before 2.7 reach to office before 2.7 or we can say two hours seven minutes if we are starting at zero then we want to read before two hour and uh you can assume it's seven in a minute so whatever you will get you can write over there between of that right so if we convert into minutes so if we say ah what we can do we can multiply with my 60 so we can say 160 162 minutes right so we want to reach to our uh What uh our office in 162 minutes that means 91 uh two hour 42 minutes right now let's see whether it's possible or not so what we are going to do we are going to say we are going to take us we know that if we take a speed of one kilometer per hour it's not possible right it's gonna take six hours to reach to our place but if we reduce it by some power not reduce it will increase our speed by two then let's see whether it's possible no so first thing is you want to take two definitely for more than one hour and we can't take uh we have to wait for that everyone so we can say if we are doing that particular part so we are to wait for next date right completely we can't use 1.3 or something else we have to use 1.3 or something else we have to use 1.3 or something else we have to complete and take two R because next 10 can only start at the fix o'clock fine the next train is gonna be take uh only one hour right because we can say always going to consume over here is four but it still is not matching our condition we want to reach before 2.7 fix our glow right the second end started at the first workflow so now we can see it's gonna take only one so it's become two now just that train is going to take now something in between of uh we can say it's sticking at three kilometer per hour speed and we want to cover two distance so you can use a distance formula distance your speed of time so you will get 91 0.66 speed of time so you will get 91 0.66 speed of time so you will get 91 0.66 right I hope it makes sense fine so its total combine is taking 2.66 here we total combine is taking 2.66 here we total combine is taking 2.66 here we haven't make it one why because there is no next in uh we can say present so we don't need to wait for anyone right we can say oh late this is the save our final result so we can see 2.667 result final result so we can see 2.667 result final result so we can see 2.667 result so now let's see whether it's matching over condition or not you can see hour is 2.7 and we are getting we are is 2.7 and we are getting we are is 2.7 and we are getting we are reaching to our office in 2.6 is reaching to our office in 2.6 is reaching to our office in 2.6 is slightly less than 2.7 right so that slightly less than 2.7 right so that slightly less than 2.7 right so that means we can get our attendance right so it is possible so we can return nothing but our new speed of 10 should be three kilometer per hour I hope it makes sense now guys we are getting a distance one three two and average it's directly minus one right you can see it's output it is not possible even so as we strain at least they are going to take at least one unit one hour right because if we take it taking even 0.1 first 20 take 0.1 we taking even 0.1 first 20 take 0.1 we taking even 0.1 first 20 take 0.1 we have to wait for the next end complete hour right so it's gonna take complete one hour that second is going to take complete R but let's say that we need to reach before two right in 1.9 however we reach before two right in 1.9 however we reach before two right in 1.9 however we have to reach to our office but it's slightly old because it's completely impossible like so we have to return minus one I hope now you understood the problem statement right so we have seen three examples and three were really interesting and we have seen the problem State under statement so but basically it says that we are given two things first is our that the maximum time we can take to reach our office second is negative distance array distance arrays have a distance of each day that each day in how much distance they are going to cover and third is nothing but we need to find that speed and that is that should also be minimum speed so that we can reach to our office if it is not possible so we have to return minus one now let's move to the logic part just because guys you can watch in a 0.75 X if you are finding this video is 0.75 X if you are finding this video is 0.75 X if you are finding this video is really fast right but believe me guys it's I find it's uh cool right fine so now how we can solve this particular problem what is the logic we should use so the interesting thing they have already told in our question that's why I haven't read this slide in a study so see instead of understand this particular we can say like tests are generated such that answer will not achieve more than 10 is per 7. that means the strain speed will not be exceed more than 10 is for 7. right an hour will have at most two digits after the decimal point so this hour like here we have 1.9 so it could be 1.92 right we have 1.9 so it could be 1.92 right we have 1.9 so it could be 1.92 right but it will not be that 1.94 uh six let but it will not be that 1.94 uh six let but it will not be that 1.94 uh six let me show you it will not be like this it will be at Max 2 digit right a second thing is Method test uh we can say speed should not be exceed more than 10 years for seven they have already there fine so we can use a simple thing simple algorithm which is going to work why first of all tell me you tell me which algorithm you can use here I know you have seen in the problem statement uh we can say on the liquid platform that whatever I'm getting used in this problem but let me tell you here this is going to be binary search and why it is a binition that already I have told you that its answer is not gonna have seen more than 10 raised to power 7 right and second thing at minimum speed what could be it could be one so we have this range now right isn't it if our we can say our answer is coming we can say our answer is satisfied our we can reach to our office in 10 days for four unit of speed right when the training speed is 10.4 then we can simply say speed is 10.4 then we can simply say speed is 10.4 then we can simply say guys the next numbers which are coming till 10 is for seven we can easily these over there right if credit speed is 1000 or 10K right 10 speed is 10K then what we can say anything more than this speed will always allow us to reach to office within the time but less than this speed will not guarantee right okay so this is the condition like if you are able to reach to office in this particular position but so we have seen this case yes we can reach to our office if the train is specific can rest before but if train speed is not 10 if 10 speed is transfer 4 but we still not able to reach to the office then what we can see then that is sure that on the left side till 1 we are not able to reach to the office right this is guaranteed but right side we may reach to office so we will move to the right side so just let me tell you simple example here so if we reach to office with this particular speed then we want to move to the right side because then we're going to move to the left side because right side will definitely guarantee that yeah you can easily reach to the office because it's over more than that right but if we're not able to reach to the office with the speeds so left side guaranteed that we could not able to reach to the office because it's going to be less than that so visualization is really important over here so if you are reaching to the office that's your this is office and if you're reaching at tennis but let's say two kilometer per hour speed if you're running at two kilometer per hour speed and you are reaching to the office fine that makes sense right if you're running two kilometer speed and you reach through the office that means but this is yes condition and here if you increase your speed you say now I'm running a three kilometer per hour can you reach to the office yes you can reach to the office because it's already increased there you know greater than that if you're running at four kilometer per hour then you reach to the office yes we can reach to the office right but there is no guarantee that although if you are decreasing your speed facing now I'm running at one kilometer per hour can I reach to the office there is no guaranteed there right you mainly to the office you may not reach to the office right so we can see we will move to the left side if we are able to reach to the office but if we are not able to reach to the office that means nothing but let's say I am not able to reach to the office when I'm running at 2 km so that means if our speed is one kilometer per hour can we release definitely directly no because even if you are running at two kilometer speed you are not receiving office how you can reach to the office when you are decreasing your speed right so miss left side is directly not possible but if I increase it can I reach the office when I'm running at four kilometer per hour speed yes you can you node yes maybe right so in if the answer is no then there is a possibility on the right side but if uh but there is no possibility on the left side there is directly no and in the case of yes there is a possibility on the left side that you may uh there is also some speed exit where you can use to the office but on the right side there is completely yes right so this was the simple scenario so we are going to see only this condition we are going to say if our if we can reach to the office with the speed so move to the left side and try to check the less speed which can allow us if we are not able to reach to the office then move to the right side and try to find the speed where we can reach to the simple two condition only so now let us move to the implementation part and let's see how we can implement this one right so I'm gonna be a browser so here guys I'm first of all with the python so what I'm going to do I'm going to say fine first of all take a length and length of distance and here we have seen the third example and let me show you here as well so this third example directly giving Smiles why because here if you focus here N Miss length of distance is but we can say greater than our this hour line and hour could be in floating number so we can use a c right so if it is greater than that so we can get that determ as like I hope it makes sense right so if our number of things or we can say distance is greater than our um because the Seal of hour then we can calculate it as minus one fine now what we are going to we're going to use a minister we are going to say low initially going to be nothing but we can say one and high is 10 is to a seven so how we can write actually like this then we are going to say while let me write while low is less than or equal to I and we can say find a made we need is one right one low plus let me use it low plus and high divided by 2 and we can say fine check now if possible with this meter meeting next whatever speed right minus but right yes if else if it is not possible so we are going to move to the right side so we can say lowest one that then we can simply return Loop simple thing right now this possible function let's define that function right so I'm going to set the file okay I have given much space find possible so what this function is going to do this function will take a speed right fine and we're gonna say fine if it is taking a speed code now we are going to Traverse all the distance setting all the page and try to fit this particular speed over there right so we can check whether with the speed we are able to reach to office or not right so what I'm going to do I'm going to say 4 I first of all let me show you a shortcut way better sold return sum and here we're going to say fine what is going to be you're going to see and we can see the distance of I divided by s p I will show you what I am doing uh if our we can say I is not equal to if I is not equal to because n minus 1. now say distance of IE divided by speed and it's gonna work for I comma and you can say what we can do we could say okay um for I in there and like foreign of distance of I not if I'm gonna say first of all take a total value which is zero so I'm going to say total plus equal to distance you have to use a c value you see and here we can say distance of I divided by that speed and at the end we can say fine after that we are going to say total plus equal to distance of I divided by speed Behavior not using a cly just because we know the last plane we have to we don't have to wait for the next train right and then we can simply returning a total should be now equal to less than hour right now let's see where the circuit final note so simple thing guys this was line this one double line which I have committed and this whole thing are same right so we got an error Mission as well also we can't use this thing here so we have to say nothing like this fine now let's see so you can see all the disc is not passed why is it so we are getting also 2 over initial node okay fine all right so we are saying total zero and foreign now let's see but still it's not faster and all right so what is I here I mean something else right I is not there let's see now hopefully you should pass right you can see guys all the desk passed the reason is guys here now let me tell you this two line so here are some doing the same thing here are assembly the same I'm just saying that for this speed first of all take all the tests accept the last eight why because last of the day I'm gonna take the complete hour right even I'm completing that journey in 0.5 hour but I have to that journey in 0.5 hour but I have to that journey in 0.5 hour but I have to take a one hour right so I'm doing a seal matt.c is going to take the Top seal matt.c is going to take the Top seal matt.c is going to take the Top Value 0.5 it's going to consider one Value 0.5 it's going to consider one Value 0.5 it's going to consider one point three you go to the serial two right but at the last eight for last in N minus 1 Train I'm not gonna do that part because I don't have to wait for the next scene I can directly reach to the office from that particular position right so I'm not doing a seal operation over here seal method and after that was done I'm just checking whether my total speed this total input is the speed which took in that particular is total is in the hour which took when all the train were running at this repeat right so if it is less than our hour means the given hour then we can say directly we can reach to this so return true but if it is not less than that particular hour so written fast so the same thing we are doing here so I hope it makes sense so let's try to submit this one and it's working fine or not let's see that part right so I hope it should work right so let's see that so you can see guys it's successfully got submitted so we have successfully submitted with this one now let's move to the next program language and then C plus now let's quickly do this right we have this uh we have invested a lot of time here so what I'm going to do I'm going to say into n is nothing but let me just do the distance of length exercise and here we are going to say fine if uh low is going to make number zero one is seven plus High divide by 1 and here we can see if possible for this mean so we have to pass here distance as well r as well N A has been made as well y before using a not a national function here so please so you have to move to the left side but if it's not the case we have to move to the right side and then you have to return a good load now let's define this function which is another possible function so I'm going to say boot possible and the name uh argument is going to take first of all battery let me use a vector right so let's take it as fine now we are going to say nothing but first of all one thing that is what we can see if not if we can use it directly uh double total as well so both make sense right so double total is going to be initially 0.0 anything you can give be initially 0.0 anything you can give be initially 0.0 anything you can give okay after that we can say 4 into is equal to zero I less than n minus one why I want to I don't want to take the last name here so I'm going to say total Plus plus we can say equal to beautiful user method not math you can be using type BC so we have used directly seal here and there we are going to distance of I divided by X right and after that what we are going to say fine but it's not going to verify we have user that number is not in flowed so we have to use multiply 1.0 right now at the end to use multiply 1.0 right now at the end to use multiply 1.0 right now at the end for lasting we are going to say total plus equal to so Omega 1.0 multiplies distance of 5 so Omega 1.0 multiplies distance of 5 so Omega 1.0 multiplies distance of 5 divided node i n minus 1 and here we can see slashes for now let's see whether I don't know and I hope as you show up we haven't used a base condition yet that's also we need to use right so let's make it a user base condition so we can see if our distance of I right so if our distance of that particular I already use the N only right if n is greater than our C of our R so we can activate them minus one now let's see you can see all the risk is postulated to submit this code as well and I hope guys it will also gonna work Java fine here let's first of all Define a function and take a lot of five right Boolean and possible and we can say the name is going to be distance we have to use a double hour and we have to use inter speed rate and before that we have to take n as well and then speed finally we are going to say double total initial is going to be 0.0 or int is initial is going to be 0.0 or int is initial is going to be 0.0 or int is equal to zero I less than n minus 1 and I plus here we can see total C and here we're going to use uh one button zero into distance of I divided by S right and then we are going to say find Total plus equal to no we don't need to use a c here we can just say 1.0 into use a c here we can just say 1.0 into use a c here we can just say 1.0 into distance of 5 divided by node i n minus 1 divided by S if I and then we can simply return quota should be less than equal to uh if it is the case then you have to return to otherwise pass fine and here now in this function mean function first of all we have to calculate the length the distance length we have to check if n is greater than right and here we're going to say y low is less than equal to high so what you are going to do there we are going to say finite we have to find me no plus I we can use high and here we can divide by one point once we found a mid then what we are going to do we are going to say find you 100 check whether it is possible or not with the speed so if possible for this we can see distance because after distance in the past hour then we have to pass n then we'll cross mid and you have to see what you have to move to the left side you should be equal to Mid minus one otherwise you have to move to the right side so you can say a low should be equal to Mid plus one add then you have to Simply return we can say no light and we have to use a return node Newton now let's see whether it's going to find a node or we have done any mistake so let's check that part and you can see we haven't definitely a mistake right so what we have done we have to use in here now let's see you can see guys all the desk is passed so let's submit this quote right so I hope it will also want to submit so you can see guys successfully about accepted function now let's see with I'm with a JavaScript now and in the JavaScript what we are going to do we are going to say first of all let's define a function or before that let's calculate the length of distance and let's say the base condition if our n is greater than math node C our then we are written -1 then we are written -1 then we are written -1 and if we can say while not while we have to use first one function post functioning what we can put a possible only so it's going to take one argument speed as we are using an asset function here we don't need to pass distance over and anything else okay so we are going to say fine uh let total is going to be 0.0 going to be 0.0 going to be 0.0 let fine n minus 1 and I plus fine and here what we can do why I am using this here what we can do is a total plus equal to and we can see uh when we can say total plus equal to math root C and here you can pass distance of Y divided by S fine at the end what we are going to do because the total plus equal to C look at that I don't need to use this here we just use distance over I uh n minus 1 divided by S right and we can return total should be less than equal to our here we could use another method as well filter but it's fine like I divided first this is done what we are going to do now we're gonna say find you found a mid now check if it is possible or not so possible with this made make High should be equal to Mid minus 1 move to the left side otherwise else flow should be equal to Mid to the right side and then you can simply create an Loop now let's see I hope it should work right let's see okay it's taking a Time and do we have some something else should not take this much time right so I think it's time complexity error no I got a long answer why is it the case so one thousand oh correct so we have to give up this one so we are using n minus 1 distance and divided by as file so possible with this me then what we are going to do we are going to say the speed totally this much total should be less than equal to our r so we can say for 0 I less than n minus 1 like this plus order should be where do c so we are adding this one and we are seeing that okay low plus I divided by 2 1 is plus seven as well if it is possible then you have to do this I should be equal to minus one if it is not possible then you have to do this it's cool fine life uh let's see what we are getting for the next one okay so it's not running even there right flow is less than high so what we are doing nothing with this much part so let's see what's the issue we are getting over here one is for seven right so it's completely this one right so I think we are doing a little mistake over here okay so let's try to divide this one right so what I can do I can simply say console.low console.low console.low let's say no and we can say hi something can you try to figure out this one what we have Miss over here we have done something long over it let's run and foreign 5000 right so it's incremented this one fine but it should not Implement with this now right so I think some issue in this particular part we have total which is 0.0 now we are incrementing with math 0.0 now we are incrementing with math 0.0 now we are incrementing with math root same distance of ie and divide by speed right so we are dividing with this one must be and the speed is called this mean fine so it should be greater than that right total should be less than this much parts so I think some issues over here the sold out low our life I don't know why we got this error in JavaScript so what we got here is I got six we got six hours it's fine it's not our what I am doing here to apply so I don't think it should be this much like so what I go I got 2.04 and Which is less than our hour right so if this is the case then this is less than what I should return to right so if it is returning a true then we are moving to the left side so high should be equal to now but it's not doing that particular part so you can see if possible of mid is written through so what we can do just give me a second guys let's equal function whether this function is normal node all right so we have taken this much so I think everything is working fine right total plus equal to distance of n minus 1 is less s the issue is here guys so we have to return it really sorry for this let's see though I don't know why I'm the animal city right another tattoo Summit so I hope guys you understood this one so what about the issue we are not returning that one and we are assuming it should be done but like two meters so now you can see guys it's actually got submitted so we have done with empty medicine python zip display Javan JavaScript I hope you understood all the implementation if you have any kind of problem understanding part logic part implementation part you can write in the comment section I'm always there to help you and if you learned something new in this video don't forget to hit the like button and subscribe my channel meet in the next video
Minimum Speed to Arrive on Time
minimum-speed-to-arrive-on-time
You are given a floating-point number `hour`, representing the amount of time you have to reach the office. To commute to the office, you must take `n` trains in sequential order. You are also given an integer array `dist` of length `n`, where `dist[i]` describes the distance (in kilometers) of the `ith` train ride. Each train can only depart at an integer hour, so you may need to wait in between each train ride. * For example, if the `1st` train ride takes `1.5` hours, you must wait for an additional `0.5` hours before you can depart on the `2nd` train ride at the 2 hour mark. Return _the **minimum positive integer** speed **(in kilometers per hour)** that all the trains must travel at for you to reach the office on time, or_ `-1` _if it is impossible to be on time_. Tests are generated such that the answer will not exceed `107` and `hour` will have **at most two digits after the decimal point**. **Example 1:** **Input:** dist = \[1,3,2\], hour = 6 **Output:** 1 **Explanation:** At speed 1: - The first train ride takes 1/1 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. - Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. - You will arrive at exactly the 6 hour mark. **Example 2:** **Input:** dist = \[1,3,2\], hour = 2.7 **Output:** 3 **Explanation:** At speed 3: - The first train ride takes 1/3 = 0.33333 hours. - Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. - Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. - You will arrive at the 2.66667 hour mark. **Example 3:** **Input:** dist = \[1,3,2\], hour = 1.9 **Output:** -1 **Explanation:** It is impossible because the earliest the third train can depart is at the 2 hour mark. **Constraints:** * `n == dist.length` * `1 <= n <= 105` * `1 <= dist[i] <= 105` * `1 <= hour <= 109` * There will be at most two digits after the decimal point in `hour`.
null
null
Medium
null
104
hi welcome back to another ease of leaker question today we're going to solve the max depth of binary tree this question is quite similar to the diameter of binary tree question that i just sold a few days ago so if you could go watch that video after watching this that'll be amazing so to solve this question we're going to iterate through the tree and for every node we're going to find the length of its right child path and then it's left child path and we're going to take the maximum of those two plus one and then return that number so that's going to help us find the depth the maximum depth of the binary tree so how do we solve this question what exactly is a binary tree depth so for example this branch right here all the way to the null nodes is a depth and then this branch right here all the way to the null nodes is also depth so we should find the maximum depth well it would be either this or this both of those branches have a depth of three and that we should return any one of those so um we're going to use dfs let's go through that so we're at this node and then whenever we get to a null node we return zero so for here we call the dfs algorithm on the left child path so it goes here we also call the dfs algorithm on the left child path we come here oh wait we're at a null node so we return zero and then we go to the right child path where the null node so we also return zero and then we take the maximum of those two zero while it's zero plus one it's one so this node of value nine returns one and then we go to the um right child path of three and it also goes to the left which also goes to the left and then returns zero this also goes to the right returns zero and then we take the maximum of those two plus one so that's one and then we go to the right child path of 20 although it goes to the left returns zero out in agree to the left return zero so we also go to the right null node returns zero and then we move back up to seven and then take the maximum of that's left and right children paths although that's zero plus one that's one two seven returns one and then we get back up to the recursive tree up to twenty and now at twenty we have the length of its right child path and its left child path and then we should find the maximum of those for this they're both the same length so we take one of them plus one uh considering 20 is one node above them say one plus one that's two so twenty returns two and then we get up to the recursive call all the way to three and then for three we have the length of its left child path and then it's right child path and then we take the maximum of those two which is two plus one considering three is one node above so two plus one that's three so three returns three so this is the maximum depth of the battery tree and then we return this so that's it that's how you solve this question that's quite similar to the binary true diameter question and uh yeah go check it out so what's the time and space complexity of this algorithm well for time complexity well we're going through all the nodes in the binary tree so that's an o of n time so your time complexity is of n where n is the number of nodes in the tree and then for space complexity we're going as deep we're using depth first search figure as deep as the deepest node so it's an o of d space of d for depth we're going to have it most d calls on the call stack d frames on the call stack so space complexity is overdue so that's it for this question let's dive right into the code okay so first let's take care of a base case that's if the root node is null so if root is equal to null and then we just return zero and then we find the length of the left child path and then the right child path so i'm going to say and left we call the recursive max depth function and then we passing root down left do the same thing for the right and right is equal to max depth of root right and then for this node we just have to return well the maximum of its left child path and then its right shallow path plus one so that's pretty much it let's run this let's see what happens knuckle i'll submit oh cool it's successful and it's really fast so that's how you solve this question i'm going to put a lot more comments on the code that i'll upload on github so that's it for this question that's how you solve the max depth of a binary tree if you like this type of content please consider subscribing to the channel comment down below if you have something to say i'll smash the like button for the youtube algorithm and share this video around the community and i'll see you in the next video bye
Maximum Depth of Binary Tree
maximum-depth-of-binary-tree
Given the `root` of a binary tree, return _its maximum depth_. A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 3 **Example 2:** **Input:** root = \[1,null,2\] **Output:** 2 **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
110,111,774,1492
134
hi all welcome to learn code repeat so today we'll be looking at day 23rd of the september lead code challenge the name of the problem is gas station and it has been asked in amazon facebook and google so let's look into the so the problem says that there are n gas station along a circular route where the amount of gas at station i is gas of i you have a car with an unlimited gas tank and it cost of i of gas to travel from station i to its next station i plus 1 you begin the journey with an empty tank at one of the gas stations so the cost of i is not the actual cost it is the amount of gas that you have to spend to go from ith gas station to i plus one gas station okay so return the starting gas station's index if you can travel around the circuit once in clockwise direction otherwise written minus one note if there exists a solution it is guaranteed to be unique so there can be only one solution or there can be no solution at all if there is no solution then we have to return -1 return -1 return -1 so both input arrays are non-empty and so both input arrays are non-empty and so both input arrays are non-empty and have the same length each element in the input array is a non negative integer so the array element will be non negative so let us look at the example so here we have taken the first example so what the problem statement says is that i can go from gas station 0 to gas station 1 okay and when i go from here to here this is the numbers in white are the amount of gas that is available in that gas station so you can take that full gas into your car and uh the car tank is infinite so you can fill the whole gas and this the number in yellow is basically the cost that means that is the amount of gas that you have to spend to go from the 8th gas station to i plus 1 gas station so if i'm at this gas station and from here if i need to go to here i need to spend 3 units of gas okay so currently i am at this gas station so my tank is zero and i can fill one unit and from this gas station if i have to go the next gas station in the clockwise direction i have to spend three units so there is no way that i have enough gas to go to the next station so i cannot start from here so let's go to the second one right if i start from here again the amount of gas that it has is 2 but the amount of gas that i need to spend to go to the next station is four so that is greater than the gas it has right so again i cannot start from this similarly for this gas station right it is three the amount of gas it has but i have to spend five so three minus five is negative i cannot start from this station then i'll come to this station right if i start from this station the amount of gas this station has is four unit and from this station to next station i need to spend one unit right so i can use this as a starting point now right so if i start from this station the amount of gas i need to spend is first i'll fill the four unit gas then i need to spend one so i'll have remaining three and then once i reach this particular station i can fill five more right so it will be plus five so at this point when i reach here i will have four minus one three plus five eight unit remaining right then if i go from here to here right the amount of gas that i need to spend is two unit so it will be eight minus two once i reach here the amount of guess that i have which i can fill is one so here it will be 1 so it will be 8 minus 2 is 6 plus 1 is 7 i will be left with 7 units now again from here to here if i want to go i need to spend 3 units right so it will be 7 minus 3 and once i reach this particular gas station i can fill the 2 units of gas that it has right so i can fill plus 2 so it will be 7 minus 3 4 plus 2 is 6. so at this point i'll have six unit now again from here to here if i have to go then i need to spend four minutes right so it will be six minus four and once i reach here i can fill the three units of gas that this station has right so i can fill three so six minus four is two plus three is five so the problem states that i need to find a circuit from which i can start and i can end also in that index right uh in a clockwise direction so i started from four and now i have reached still here right now if i go from this station to the fourth station right at this station currently i'm having five phi is the cost of going from this station to this station right so it will be 5 minus 5 which is 0 which is fine right it's not going in negative it is still 0. so once i reach the station i can fill that 4 amount and i'll still have four balance so this is a valid point right so this particular starting index is a valid starting index so the starting index was 3 correct so i will return 3 so the output will be 3 so let's see how did we solve this problem right we started from this index first index then we went to this okay now assuming that if this was possible right then we would have moved to the next one right and if the traveling was not possible from this index to the next index that means once i reach here the remaining gas that i have would have been in negative then i would have again started from this index second index right so this is a brute force approach right that i'll try each and every index and try to find out from which index the starting point is possible and if from none of the index i can complete the circuit then i will return minus one so the brute force algorithm for this will be so i am having two loops one is this for loop second is this for loop okay so i am starting from the zeroth index and the inner for loop check for each index if i am able to complete the loop so for checking in a circular manner right if i want to let's say if i start with one right and let's say the length of the array is fire hit so 0th index will be 0 1 2 3 4 right so if i start with 1 i should get one two three four zero right how can i get a zero how can i go in circular fashion i can use the mod of gas length of operator here right so i am starting with one and i am going up to whatever is my gas length the zeroth index gas length plus my i okay so i'm starting with i'm going up to gasoline plus i so what it will do here is gas length minus 1 right it's 5 minus 1 4 plus if i'm starting with 1 so it will be 4 plus 1 which is equal to 5 and here i am doing at the end if i reached 5 right here i will do 5 mod 5 right so 5 mod 5 will be equal to 0 so when i am at 4 it will be 4 mod 5 and 4 mod 5 equal to 4 and then when i'm at 5 it will give me answer as 0 right and if i start with 2 and 3 4 5 right after 4 i'm expecting a 0 and then i'm expecting a 1 right so what will happen in this case if i'm at 2 j is 2 so 2 mod 5 will be 2 3 mod 5 will be 3 4 mod 5 will be 5 mod phi will be zero and six mod five will be one so that's what happening so that's how we can do a circular traversing okay so that's taken care here and then i'm checking whatever is my total gas left till now plus the current gas amount minus the cost of going to the next gas station so that i'm showing in my total and i'm checking my total is negative then that is not a valid circuit and i'm breaking from that when i say i am breaking so it will break from this particular for loop so it will go to the next ith value okay so that way we'll we can check each and every index starting point whether that's a valid circuit so this particular algorithm since we are having two for loop it will be a n square algorithm okay now how can we optimize this n square so that it becomes o of n we can do this in one single pass how can we do that okay so let's analyze the problem again to see whether we can optimize this current solution so assuming that i'm starting from here and the green arrow shows that it's a successful path from this gas station let's call it gas station one two three four and five okay so from one to two it's a successful path two three it's a successful path and what i mean by successful path is that from 1 i can travel to 2 such that the remaining gas i am having isn't positive either in positive or it is equal to 0 okay because even if it is equal to 0 i can come to this particular gas station and fill the gas from this gas station okay so i can go from one to two to three to four is also fine but when i go from four to five right in that case i am having a negative value so the amount of gas is a negative which is less than zero so i cannot travel okay so in the normal brute force approach we would have now tried with starting from two okay instead of one we would have started with 2 right so let's analyze this case right should we start with 2 or can we directly start with 4 that means i can keep 4 as my starting point and i can simply ignore 2 and 3 as my starting point right so let's analyze that right so when i say that i can go from one gas station one to gas station two what does that mean that means the gas that i am having okay the remaining gas is either greater than zero or it is equal to 0 right so if it is greater than 0 that means at each point it's adding gas to my tank right and even after that when i come to this point i am not able to go from 4 to 5 right so even if i don't consider 1 or 2 i will never have enough gas to go from 4 to 5 correct now let's consider this second case right where it is equal to zero okay if i go from one to two and i just have enough gas to go from one to two such that the remaining gas is zero right similarly from two to 3 right so it's same as not considering 1 at all or not considering 2 at all right so that means that at 4 when i go from 4 to pi the amount of gas i have is very less so the main culprit is four it's not three or two right because even in both the cases whether i have more gas or whether i have just enough gas but when i come till four after that i am not able to move from four right so no matter what i choose from here whether it's 1 or 2 or 3 the starting point when i come to 4 is taking so much cost that i cannot go from 4 to 5. okay so it doesn't make sense that i try with either one two or three as a starting point or rather even with four as a starting point okay because in all the cases i will never be able to go from four to five because the amount of gas will be not enough because the cost in four will be more than the amount of gas that we have so we can safely say that the next index should be my current index which is 4 plus 1 okay so i can safely start with 5 and i can do the check again now in this case since it's only 5 station i can directly check if the amount that is left and the difference that i'm having till this point if i add those two numbers and if it is greater than 0 then pi will be a proper starting point so that way i can do this whole one single pass and i can check whether i can find a starting index such that i can complete the circuit and if that is not the case then at the end i can return minus 1 okay so let us look into the pseudo code for this so i have assigned three variables my total variable which is the total amount of gas that is remaining i'll store that diff is the difference variable because once i encounter a negative amount of total right i will reset my total from the starting point from the next starting point right so in that case i need to store my total in some variables so i am using dip as that variable index is my starting index that i'll use so initially i'll define that as 0th index and in the for loop i will go from 0 to the length minus one the length of the gas so first i'll check whatever is my gas minus the amount of uh gas that i need to spend to go to the next station and initially total will be zero so if this value itself is less then i'll say that my index that i can the best index that i can have is uh the next index so i'll do index plus one and i'll store my total in the dip so whatever is the dip value plus total and i'll uh and i'll reset the total to zero here i'll do this in the loop okay and at the end i'll check that if my total plus so whatever is my current total that is remaining plus the diff the difference of the negative values right that i had if that is greater than or equal to 0 then whatever index i selected return that index so at the end whatever index i selected written that index because every time we are resetting the index if the total is less than zero okay so if the index was not reset that means that last loop that was going on in that the total was greater than 0 okay so there was some positive total and some negative dip and together if it is greater than or equal to 0 then it is a valid circuit return that index if it is not greater than or equal to 0 then we do not have any valid circuit and written minus so let us code this in java okay so i'll define total my index equal to zero and f equal to zero so i'll do total plus equals to gas of i minus cos phi so i'm checking how much remaining gas i have and adding that in my total and if that is less than zero in that case uh i have to reset my total right now before resetting my total i need to add it to my tip so my if plus equal to total and also i need to implement the index so index will be whatever is my current index which is i plus one okay and i think that's it for this for loop at the end i'll return if my total plus diff is greater than equal to zero in that case i need to written the index else and include minus one so let's run this code this is fine let's submit it and the code is accepted let's get into details so it's 0 millisecond and 100 faster so that's it for this video if you have any questions regarding this problem please comment down in the comment section and i'll try to answer your questions and do hit the like button and subscribe to this channel for future such videos thank you
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
846
so hey guys what's up and in this video i'm going to see about another lead code problem that is handoff sheets right so let's get started and this is what the problem basically says that allies has a hand of cards that is given as an array of integers right so basically this is an integer and we need to find a group that is of size 3 that is equivalent to the group size mentioned as in the questionnaire that is the parameter here right so we need to find that whether it is actually possible to make this number of groups right of this size that is group size and all the elements in the group will be consecutive when you just return whether it is possible in this array or not right well after seeing the question like this what comes fast to a mind is suppose i found a number so before that let's examine this example here right we have a series of array that is this right we want to you know like return whether it is possible to have a group which is size equal to group size and all the numbers inside it are consecutive right so as you can see here we can usually make into three groups right this is one two three and two three four and six three seven and each group has a size that is equal to group size that is equal to three and all of the numbers inside this group are consecutive there's one two three then two three four then six seven eight right so the first thing that comes into mind sorting right why because we will get something information about the consecutive elements right suppose i have an element here let's examine this array only like this right so if i have this array so if i sort it right what i'll get that is one then we have two twos then we have threes then we have four and then we have 5 we don't have 5 i think so we have 6 then we have 7 and then we have 8 right that's pretty much it we have 4 m 4 9 we have also 9 here right so these are the elements when you sort it now why i'm talking about sorting is that it gives us an idea about like whether the elements number of elements that are consecutive to it right we get an insight of this with this right so how can we approve this type of questions right so basically what you can do is suppose there exists an element one right suppose there is existing element one and we need to find what are the number of like whether it is possible in order to get a group size right that is equivalent to group size right and having all the elements consecutive right so every element should be categorized into one of the groups right so if i'm considering suppose one right so what will be its consecutive elements it can be one it can be two it can be three as we have here a group size of three so if the starting elements one we can have say we have three elements to go right because now the group size is three as i have mentioned here right and we have to go for three elements only if the first element is one whatever the next two elements it will be two and then it will be three right so how this varies right if i am suppose having an element that is x that is the starting element right the next element will be x plus 1 and x plus 2 and if i write it in a loop right how will this work basically if i write it in a loop then suppose the group size is say y right suppose group size is y let me write like this suppose the group size is y all right then how will i you know like check for the consecutive element whether it exist or not what are the consecutive element it will have right so it will be basically from x it will initially have an element that is x right then it will have an element that is x plus 1 then x plus 2 up to what up to x plus y minus 1 right so it will be having x plus 1 then we have x plus 2 and it will go up to x plus y minus 1 so this is what we do right but how to check whether it is possible not right for this case we can use a value of map right what map will do is that we can use an ordered map because we want the element to be sorted right we want to check for one that if one exists then what are the number of groups that we can make having one as an element all right similarly we'll be checking for other things right so now it's the concept of map now why and how the map would be used so basically if i think of this approach right if i take one i'll have the frequency of one suppose i have one once in the total array if i have only one then i would expect that the consecutive elements that would have like two and three should have at least one right if it would have don't have the cons if the consecutive elements for the element i'm considering right in this case it is one right if the consecutive elements of it that is two and three will have a frequency less than this element right then will return false that's a simple idea now let's code it and see how it works so as we have already discussed that will be using the concept of sorting and mapping right so now let's implement it right how will it work for that i will initially create a map that will initially keep a value that the array has and the respective frequencies right so i'll make a map right and i will traverse through the array like x right in the array that is hand right and each time i find element x i'll be incrementing it right as you do in normal maps we'll be doing this right so up to this we find the frequency of each and every element and the element that we'll be having in the map will be in the sorted form right because we are using an audit map not an honorable map right so now what's the next case we need to think right as we have already discussed that when you think for each element that if suppose the frequency of the element suppose i am assuming that x is the first element right if the frequency of element this first element is 2 then what i will expect that the consecutive element that it will have suppose that is x plus 1 right this is the frequency let me write it below only right if x has a frequency of 2 what will be this consecutive elements it will be x plus 1 x plus 2 and it will go up to the group size minus 1 as we have discussed earlier right i will expect that the consecutive element will at least have a frequency of 2 that is where we can make a group right of the respective size right if it will not have a frequency that is you know like greater than or equal to this value that you are considering for like if it is less than that frequency then we'll simply return false right this is the simple idea so now let's implement it now i'll check i'll traverse through the map right i'll traverse to the map and for each of it i'll check if the value i am considering for is greater than 0 or not right if it is greater than 0 then what will i consider i will traverse for and i equals 1 to i less than the group size that's the simple idea that we have discussed earlier right and each time i'm traversing it i'll be subtracting the i t dot first value plus i what this means is suppose i am at x assume that i d dot first is x now i will be considering for x plus 1 right and whatever will the frequency i'll be subtracting with the number of values that i consider for x right suppose the frequency of id dot first is 2 then i'll be subtracting 2 from the i t plus i that is x plus 1 right and after subtracting it from it if we get a value that is if the frequency of the next consecutive element is less than the frequency of the current element that will simply written false right this is the simple case we need to see right so i'll check here like mp of it dot first plus i right if it is less than 0 right not here i will be inside this i if it's less than 0 then simply return false that's the simple case right and after this we'll simply return true and hopefully this works let's give it a shot and see whether it works or not so let me hit on run and see whether it works or not yeah it works let's submit it and see whether it gets submitted or not hopefully well this does right and you can see we got a success right hope you like my video see you in the next video till then if you're new to my channel do like subscribe and share my video till then stay tuned
Hand of Straights
hand-of-straights
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on the `ith` card and an integer `groupSize`, return `true` if she can rearrange the cards, or `false` otherwise. **Example 1:** **Input:** hand = \[1,2,3,6,2,3,4,7,8\], groupSize = 3 **Output:** true **Explanation:** Alice's hand can be rearranged as \[1,2,3\],\[2,3,4\],\[6,7,8\] **Example 2:** **Input:** hand = \[1,2,3,4,5\], groupSize = 4 **Output:** false **Explanation:** Alice's hand can not be rearranged into groups of 4. **Constraints:** * `1 <= hand.length <= 104` * `0 <= hand[i] <= 109` * `1 <= groupSize <= hand.length` **Note:** This question is the same as 1296: [https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/](https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/)
null
null
Medium
null
380
Hello guys welcome back to record net entries problems in the married to overseen of one India YouTube Channel Please subscribe this sequence to complete your problem love starts with the problems solve problems design latest updates of course all the following operations in every form 110 support operations Give instructions value in certain items bluetooth set it is not present remove value item value from the set a present in k trainer return surrender me limit for the current set of elements which element must have the same property of being written ok saudi decorations min to Implement and we need to use a mountain data structure and assured return in prescriptions center time complexity right including others have switched to superintendent of police 1968 in the school dragon age it is not presence will return true indian will call return remote to you has been only Have one element 301 Sudhir will return for speakers remote to is elements of is not the invented to 100 times does not present in every true Indian Will have written to president rule in the winter to subscribe button in the mid term will return to only one element In the given 100 requirements for this problem has been written in removing a random operation in constant touch with selected collection more hai cea operations can get educated in constant and unknown knowledge contained with the example of right knowledge 280 between sea data structure which have Slipped we will take the earliest years in the structure OK so let's you have that take care list OK now that Sachin's hundredth earliest comes integrative point to be 954 the walking bar delete pictures one elements present some benefit all the next elements to the current element Key editing to the one position where they have deleted so and was kept it's going to be of work and not random number Vikram Bhatt in user and function generator and media from chronic returned to take off and right now half skin here wear disadvantage with Delete show in which attracted get up from one digit operations www link list in office heart link playlist we have institute will again going to take off vansh and delete files for it's going to be off www in random witwer through the different from this zoom in novel Insulting All World Class We need to the number is present to not only interact one-to-one elements not only interact one-to-one elements not only interact one-to-one elements present to not withdraw into a that rolls and is *b option a is that rolls and is *b option a is that rolls and is *b option a is that did not present only need to add flash lights words 150 comes To You Never Mind As Every Time Minitool Loop OK Statement With Its Present To Not Show Any Beach Latest Words Not Look Very Fast Rate Will Give Results 900 Data Structure Which Supports Many Can We Use To Dates Which Can Be Set Up A Horrific And Gym Time is OK which gives a raw one lookup wild you are in setting a data selection only need to worry about delete portion that Bigg Boss delete lights tracking of nowhere near indore liquidating off but can get random stadium and interlink listen with were selected Earliest for final implementation it's ok sorry cities were good day at random is good how to delete operation in hormone because date declared yes in the list article se will have numbers in this way ki maa lakshmi writing down main mukesh right different century sath numbers hui OK, there is a separate to-do list number 2 OK, there is a separate to-do list number 2 OK, there is a separate to-do list number 2 and in the meantime of Ritz Swift, the objective is memory, nine available solutions, mixed elements, will move one location to the, yes, but the site is Swadeshi movement operation Vijay ko select sentence cost of n if you are editing the First Element Sell That Your Happy How To Avoid And How To Reduce The Cost Of Devotion Can Solve Within Two Years That Vinod Add A Number To Is What They Want To Delete But They Don't Know What Is The Position Of The Number 90 Fasting Would Like To Get This Hearts Index Of The Number That After And When Will Also Know That Inst Of Visiting And Transferring All Elements From All Right To Left One Lord Vishnu This Way Just Updates With The Last Element Only On Ka Hal Nahi Hai Under Delete Dish Number Only Free Mode Number Only Saunf With Didn't Have Anything Under And They Didn't Need To Shift The Things Should Immediately It's Going To Be F One Operation But For That We Need To Know What Is The Location Of District Ko Roti Sa Index Object Number Nine K Show One thing with hinduism year old using r and hai singh badal up ok so instead of only look up wikinews time please tell me when they can store number in key and index a matter which is the present in your earliest to fix reduce this addiction Se Awam Ap Will Look Like Ka 102 121 MP3 Do A Hand For More Than Knowledge Se If You Want To Digit Number To Ki Ho Ki 24 Good Night Deleted From Here What Will U Will Get You From The Great Way Of One Operation A Look And will give me the index where made to his present width last element 2012 sweater is in my expenses tile dues I can get lost element for OK I will move and update with a how to only have a foreign lineage I will sweep in the earliest also Like and inability to know more and them responsible will imbibe this knowledge delivery center for the map ok astrology operations allegation constant and software doing only reserve justice vipin the numbers which they want to deal with the earliest and did last number from my list Has smell itself then is doing to work towards itself for urine set weather it's present in the Hague updated means habit to elementary school at present in the and raw data structure will not want to insert into this return for that in the delete from it Means the benefit of where the number is present in the earliest OK itself sensible operation is going to be of way with using rituals and same way get random is * using rituals and same way get random is * using rituals and same way get random is * you can generate random index and you can get less here to here you will get in return The Are You Will Get Dhan Index And You Will Return The Numbers Formed A List Suraksha Vaikuntha 9 Let's Go Through The Code nh-24 Characteristics Vaikuntha 9 Let's Go Through The Code nh-24 Characteristics Vaikuntha 9 Let's Go Through The Code nh-24 Characteristics Standard Code Software Define To-Do List To Numbers And When They Have A To-Do List To Numbers And When They Have A To-Do List To Numbers And When They Have A Different Locations Which Will Give The And of the number is president karma object from youtube server 200 but will do it is in the constructor villain se treatment is very simple standard is time play list for the inch width the number different return for the number entry check return full width further in return for Pyun In The Missions Fast For Justice And Value And Will And The Position But Subscribe Position Of Elementary Setting Number To The Number Subscribe Must Subscribe In A Reader Box And Here's The Morning Value Is Given In The Input Soft Will Do Is First Will Check In Debate Weather that is the president of united not present straight away evil return from false knowledge effective presentation on window is will not take index of the twelve years will ultimately wood like to shweta last element of the earliest all rights will take ka location of the element name Lips Saffron Location of the element is not IA last elements in that case only would like to say Adhar Janu use na ki Suraksha It is not the David First and last element from Delhi in the middle element to the current location position to remove will replace with The last element value will stop the last elements to last elements bookmyshow updates aa index supreme leader index of the element is the aa number stocks rise minus point but acid move to the new and new location me to change the location of when will next face will remove dirt value from the SMS will remove the last entry for the rally will return to work for the random quote to generate random india will return the number for the to do not give 102 subscribe 2023 lene se in the Train Will Return Random Number From The Knowledge Compiled This Code Is And Compiled Near Different Submit Or A WhatsApp Text Secure Country Video You Like It If You Have Any Different Solution Please Write Down The Comment See You In Next Video Trailer Time By
Insert Delete GetRandom O(1)
insert-delete-getrandom-o1
Implement the `RandomizedSet` class: * `RandomizedSet()` Initializes the `RandomizedSet` object. * `bool insert(int val)` Inserts an item `val` into the set if not present. Returns `true` if the item was not present, `false` otherwise. * `bool remove(int val)` Removes an item `val` from the set if present. Returns `true` if the item was present, `false` otherwise. * `int getRandom()` Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the **same probability** of being returned. You must implement the functions of the class such that each function works in **average** `O(1)` time complexity. **Example 1:** **Input** \[ "RandomizedSet ", "insert ", "remove ", "insert ", "getRandom ", "remove ", "insert ", "getRandom "\] \[\[\], \[1\], \[2\], \[2\], \[\], \[1\], \[2\], \[\]\] **Output** \[null, true, false, true, 2, true, false, 2\] **Explanation** RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains \[1,2\]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains \[2\]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. **Constraints:** * `-231 <= val <= 231 - 1` * At most `2 *` `105` calls will be made to `insert`, `remove`, and `getRandom`. * There will be **at least one** element in the data structure when `getRandom` is called.
null
Array,Hash Table,Math,Design,Randomized
Medium
381
40
in this video we're going to take a look at three legal problems combination sum number one and number two and number three so these are all really popular uh backtracking problems so let's take a look at them start by combination number one so for this problem we're given a array of distinct integer values right and then we also have given a target integer value we're asked to return all the uni combinations from the candidates array and we can return them in any order so we can have this we can use the same number uh number of times so here you can see we have an example of array and then the target so we can have two three which add up to target and we can also have seven itself so there's no size limitations of how many elements we have we need to have in the array and basically in total we have two um combinations two distinct combinations of course we can have three plus two or two plus three plus two but that won't work because we want distinct we want unique combinations right and uh therefore we have to get all the distinct combinations right and it doesn't matter if we return three to two and a seven right or two three two and a seven right what it matters is we need to have all the distinct uh combinations so here you can see we have another example of two three five so we can have four twos and one two or we can have two three or we can have three five which add up to eight right so there's a couple more examples here but you get an idea right so how can we solve this problem well to solve this problem what we're going to do is we're going to draw the recursion tree else so to solve this problem i think it's very important to draw the recurrent tree out and once we draw the recurrent tree out um the idea the way how we solve this problem is more clear so in this case we're starting with an empty combination right in this case our current competition is empty then we can either then we can have three paths to take because we have total of three candidates we have three four five and we can reuse the current element as well so in this case we can add three so now we add three to our combination and now we have three decisions as well because like i said earlier we can be able to add our current element as well so we can add three we're at three we can take this path and we can also add four to take another path and we can add five so in this case we're going to do that for search so let's stick to one path now if we were to add one uh if we were to add three onto it now we have a total of six the target is eight so in this case within our debt for search method we need to define our base case right in this case our base case is pretty straightforward we know that um six is less than target so we can so we have rooms to search okay so let's continue now let's say we have three we add one more three right in this case if we were to add one more three or four or five it doesn't matter but if we were to add three we exceeded the limit right in this case we have nine so let's so in this case what it means is that if we have a sum that is bigger than the targets then we can just stop our searching from there right in this case because the sum is nine the target is eight our sum is bigger so there's no way that we're going to get this combination if we were to continue to search in this path so now we're going to go back right we backtrack to here now we try was a different combination right because if we were to backtrack to here there's no more combination because in this case three is the smallest among those elements right the first element and then we know that three in this case is already exceeded the song so we backtrack again now we're here then we can take the four path right the path four in this case we add four to the second element and we now know that this is seven is still less than eight so we thought we have room to continue to add elements in the candidate um what is it called the uh yeah the combination then we can continue to either have three if we were to add three right in this case then we will exceeded the sum right in this case we have something like 10 so it's bigger than eight so we backtrack doesn't matter which element we add we won't exceed so we backtrack again to here now we have three five we know that three five has the sum of eight is equal to target we can just add the current element uh sorry curtain combination onto the result list and then at the end when we um come compute all the path we can just return the result list right and the goal is that for next path you can see four you notice that we don't have any three anymore like we don't have three four in this case because we already have three four here right so in this case we cannot have three four here or i should say we cannot have the path three because we already took we already completed the path three so we're done with that so we don't have to do it here so that's how we um like getting no duplicate elements um sorry not duplicate combination right because i can have four three i can have three four right so in this case if we were to do it like this we are we can ensure that there is no duplicate path or i should say no duplicate combination so now you know how to do it let's try to do this in code so to do this in code what we're going to do is we're going to have a global variable so let's create this global variable called list of this integer that we're going to return at the end okay so then we're going to do is we're going to basically pass down this candidates and also make that as a global variable right so we don't have to pass them down each and every single time right it's going to be a lot easier so we're going to name it nums and i guess we just we can just declare it here so it's equal to can the dits right in this case what we're going to do is we're going to first have a combination which is a empty link list right the current combination that we have right and then we're going to do is we're going to have a current starting point which is 0. then we're going to pass in the sum right initially we have a sum that is equal to zero once we've done our definite search we're just going to return the results okay so let's try to create this our dfs method which has a combination list current combination we're going to have our current index integer as well as the current cell okay then we're going to do is we're going to filter right we're going to do our base case so if we have our sum right if our sum um uh one thing i forgot to do is we have to make our targets in this case let's create a target variable and just assign it to target here because we're not changing this target variable that much right so in this case so that we don't have to pass this target variable every single time so we're going to do is that if some right in this case if sum is actually bigger than target then we can just return right and if the sum is equal to the target is equal to target then what we're going to do is we're going to add the current combination onto the result list so result.add a new brand new uh arraylist we're gonna pass in the combination uh the reason why we do this is because when we're doing backtracking right in this case um this combination if we were to just pass in this combination like um like this right this variable will change right because in this case this list is reference type so what we need to do is we need to save the current data onto a brand new list and then add it onto the result list which is what we what i did here right then we're just going to return because our job is done now what we're going to do now is we're just going to iterate our options so in this case we're going to start at current index up to the end of the array so we're just going to add the current element onto the combination and then we're just going to um increment the sum uh when we pass down the different search we're going to get the sum plus the current element right and once we um coming back from the uh the different search one once we've done a deferred search we're just going to redo the changes that we made on the combination by removing the current element right the order i should say the last element that we added in the list um right so in this case we're just going to have combination dot add nums at current index right so we're adding the current element onto the combination and we're going to do that for search we're going to pass in the confirmation and we're going to pass in the current index right we're going to we're allowing duplicate values right so in this case we're starting at the current index when we do a different search right it could be two plus two and target is eight now we found our answer right so we can reuse duplicate values but we're not we're allowed to uh use duplicate combination right so we're going to have some plus nums at currents not current index my bad i right in this case it's going to be i all the way to nonstop length and once we've done that we're just going to redo our changes by saying remove uh nums dot length sorry com combination.length combination.length combination.length for size -1 right they're removing the last -1 right they're removing the last -1 right they're removing the last element that we added onto the list right so we're moving off the list for the last element that we added and now we're just going to continuously do that until we get the job done but we haven't changed this to high right we're not passing down the current index for the current index we're passing down the index that we're on right so that we don't have any duplicates um i should say yeah no duplicates combinations right so let's try to run the code and let's try to submit okay so here you can see we have our success so the other way we can solve this problem is we can use a hash set as well right so that's one way that i showed you the other way that i try to do is we can use exactly what we did in permutation problem or the permutation problem that i did in my channel and then what we're going to do is we're going to use a hash set that first we're just going to get the array sorry give the collection once we get the collection we sort the collection and then we add the collection onto this hash set and then in this case we guarantee that every time we add a combination it's going to be a unique combination the question says it doesn't really matter what's the ordering of the um in this case the combination so we can just add it away however we want it so in this case we can sort the array and then add on to the hash set and at the end we're just going to turn the hash set into a list and then return that right so that's the other way we can do it but the time complexity in this case for this problem is going to be exponential so i don't really think for if we were to sort the array we really make the time because log in time complexity is still faster than the exponential right so in this case um either way works in my opinion well now you know how to solve the combination sum one let's take a look at number two so we're given a integer array this time and then a target we're asked to find all the unique combinations uh that we can have that the sum is equal to the target so each number in the candidates might only have used once in the combination so the solutions uh set must not contain duplicate combinations so we have this array right here and then you can see we have target is eight so we kind of have duplicate combinations for example let's say we have one seven here we cannot have like another seven one because in this case we have a ray that is the half that contains duplicate values so we cannot have duplicate combinations right in this case we have two six two here and six here and um you can see that we could have one two five right um but we cannot have two one five right there's one there and we cannot have duplicate combination so to solve this problem is very similar to how we did in combination someone right one way we can do this is we can use a hash set that i talked about right we every time when we found a combination we uh put the uh we put the um we have a hash set that keeps track of the combinations that we have right all the combinations that we have for each time when we find a combination we're just going to sort the array which is going to sort the list sort the combination then we're just going to add it onto the hash set and by the end of all the combinations that we've done we guarantee that all the combinations that we have in our hash set are unique and we can just convert a hash set into a list and return that at the end that's one way i already showed you that but what we can do instead is we can first sort the array right we can sort the array once we sort the array what we're going to do then is we're just going to do this uh implement the same thing that we implement in the uh combination song number one first let's take three as the first element we're gonna um go down and say well for the second element we're gonna put three here and then we're gonna continue to explore all the options the current element right in this case the current element um now we're adding on to the list let's say this element right here we want to make sure that this element right here let's say this element right here because we cannot have duplicate right so let's say this element right here we want to make sure that this element right here is not the same as the previous element right the previous element is going to be 3 so we want to make sure that it's not the same element because in this case let's say we have 1 two five right if we were to go down the path and exhaust all the option for one we've done that we have one six for eight we have one two five for eight we have let's say one seven for eight we already exhaust those options and now if we were to have this element to exhaust all the options that we can have for this element in this case we going to have 1 2 5 again right and we also want to have 1 7 again we also gonna have uh let's see we also can have um yeah i think that's about it but you get an idea right so what we can do is that we know that the first element has more options has more path so we can just take the first element and we can just ignore the second element after we um after we do that for search for the first element right so in this case what we can do is we can say that if current element is the same as the previous element then we can just continue we can just move on to this iteration right so let's try to do this in code we're going to do the same thing that we did earlier by having a global variable then we're going to do is um we're going to make this a global variable as well so it's going to be nums and then we're also going to have a target right so in this case we're going to have a target that um in this case we're going to have a target that reached to this point reach like we're going to have a combination that has a sum that is equal to target and then we're going to add it to the result list so we're going to have the staffer search passing our initial combination which is empty list and then we're gonna pass in the current sum and the current index that we're starting at which is zero okay and then we're going to make the target as a global variable just like how we did in the previous problem okay then we're going to do is at the end after that for search after we've done that for search which is going to return result so that's our combination and then we also have our integer sum our integer current index okay so then we're going to do is we're going to first declare our base case right so let's say we have our sum so if sum is actually bigger than it's a target then we could just return right because it's bigger than there's no more there's not going to be anything that we can do and one thing that i forgot to do is we can we have to sort the array so in this case we're going to have um num so arrays dot sort and sort nums right so then we're going to do is we're going to say if sum is equal to target then we're just going to uh we're just going to say rest.add uh we're just going to say rest.add uh we're just going to say rest.add our current combination and then we can just return right our job is done if we found the element right so then we're going to do is we're going to say we're going to create a for each element right for each element in the um basically we're going to start at the current index because in this case we don't want any um duplicates combination right so you can see here like i mentioned before the reason why we have no we don't have any threes we only iterate two times here is because in this case we've done all the combination that we have three right so we cannot have like um for example three four or four three right because that's gonna we already done that so we don't have to include we don't have to traverse we don't have to include three in our um in our combination we're in our search while i is less than non-stop life what we're going to do is we're just going to um adding the current element onto the combination then we're going to um pass the concurrent combination right in this case and then we're going to pass down the current index plus one right the reason why we plus one is because we cannot reuse the current element again so in this case we're going to have combination.have current index sorry i'm gonna add the current element then we're just gonna pass down that for search passing the current combination as well to sum plus nums at i right and then the current index now in this case is going to be i plus one right where we cannot reuse the current element again so after we come back we're just going to say remove in this case that remove um combination dot size minus one index is bigger than i right so i is current bigger than the current index that we're on right so let's check to see if nums at i is equal to nums at i minus 1. if that's the case then we can just continue right because we don't want to like to do a deferred search for the same element that is equal to the previous element right so and the reason why we have current index um i is bigger than current index is that we have to have room to check the previous element and um yeah and we because like i showed you before um in this case we always want to take the first element right we always want to take the first element instead of the second element usually have less options and because the first element we already been there we already have more option we already exhaust all the options right and then we don't have to traverse this option anymore so now if we were to run the code and let's try with a few more examples all right so let's try to submit and here you can see we have our success so this is how we solve the combination sum number two let's take a look at number three so find all valid combinations of k numbers that sum up to n such that the following conditions are true so only numbers one through nine are used and each numbers is used at most once so return a list of mo all possible valid combinations uh the list must not contain the same combination twice the combination might be returned in any order so here you can see we have k is going to be the size of the combination right so in this case k numbers that sum up to n and it's going to be this target right where we want to get the combination sum to equal to right in this case 1 plus 2 plus 4 is seven so in this case we can have used numbers from one to nine only so we have one plus two plus four and uh there are no other valid combinations right we cannot have two plus one plus four um or let's say we cannot have uh three plus four because in this case we have we need to have a size of k right so let's say we have another example where case three n is nine and in this case our target is nine right so in this case this number right here these numbers add up to nine and these numbers add to nine so in this case we have three total three combinations um now let's say if we have mt oh sorry not mc let's say we have k is equal to four and n is equal to one and there's no other numbers that can add up to you know to one right in this case one plus two plus one is not equal to one right so what we can conclude based on those two examples is that if we have a situation where k is bigger than n we can just return the list okay so what i mean by that is like if k is bigger than n we can just return result right and basically return a mt list of combinations right um if we have a situation where k is bigger than or equal to n then sorry less than or equal to n then we probably have a chance that we can find a combination but if it's less than then we can guarantee that there's no combination uh if we have a situation where like something like this then what we need to do is we need to basically uh do the same thing that cut very similar to the combination some the previous combination sum problem that we did right we're going to um iterate from uh 1 to 9 right or the current element current um yeah the current element to nine because in this case we cannot have duplicate values right we cannot have we cannot use one plus one so in this case the current value the current element to nine and then in this case we're just going to try all the combinations that we can have right we're going to have a data search method right we're going to pass in the current um the current combination that we have so far as well as the uh the current sum right in this case the current sum zero and the starting point is going to be um it's also going to be uh sorry in this case the starting point is one right so at the end we're just going to return result because after we've done that for search that's what we're going to return right we have all the combinations we have right so we're gonna have that for search method that takes a list of integer and we're gonna have some and the current uh let's say current element or current number and we're going to do is we're just going to have k and n going to be the um a global variable right so in this case what we're going to do is going to rename them so k is going to be the size right and um and i should say the target right the sum right the target zone size now is going to equal k and target now is equal to n right so let's see what we're going to do then e if the current sum right so we're going to define our base case so if sum is actually bigger than the target sum right then we can just return our job is done right we cannot we don't have to continue to search anymore if the sum is bigger than targets and if the sum that we have right now is equal to the target that means we found uh we found an option right in this case we found an option then what we can do is we can just add the current combinations onto the result so in this case result that add we pass in the combination and then we can just return so if the current sum is less than the target sum that means that we can still have rooms to add our we can still have rooms to add integers onto our combination so we're going to iterate so in this case we're going to have um current which is stand for current number my current number is equal to uh is equal to none okay so while current number is less than or equal to nine okay we're gonna increment the current number for each and every single iteration and then basically what we're gonna do is we're starting at one remember we're starting at one and current sum is equal to zero so what we're going to do is we're just going to create sorry now create we're going to add the current element onto the combination so combination.add combination so combination.add combination so combination.add the current num right we're adding the current number onto the combination we're going to do with that for search uh we're going to pass in the current combination as well as the current sum which is plus current num right and then we're just going to pass in the number um in this case it's going to be current num plus 1 right we're moving on to the next element because we cannot have duplicate elements so after we've done that we're just going to say dot remove com.size so combination.size -1 right the last so combination.size -1 right the last so combination.size -1 right the last element off of the combination that we have after we've done the backtracking um sorry after we've coming done the that first search we coming back uh we can just remove the element right so let's try to run the code and we can we notice that we got a um yeah another thing that i forgot to do is that we had to make sure combination.size right so combination.size right so combination.size right so combination.size combination.size combination.size is um must equal to the size right so if it's not equal to size we cannot add this element onto it and let's try with few more examples okay i think this is an easy question so you can see here we have our success
Combination Sum II
combination-sum-ii
Given a collection of candidate numbers (`candidates`) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sum to `target`. Each number in `candidates` may only be used **once** in the combination. **Note:** The solution set must not contain duplicate combinations. **Example 1:** **Input:** candidates = \[10,1,2,7,6,1,5\], target = 8 **Output:** \[ \[1,1,6\], \[1,2,5\], \[1,7\], \[2,6\] \] **Example 2:** **Input:** candidates = \[2,5,2,1,2\], target = 5 **Output:** \[ \[1,2,2\], \[5\] \] **Constraints:** * `1 <= candidates.length <= 100` * `1 <= candidates[i] <= 50` * `1 <= target <= 30`
null
Array,Backtracking
Medium
39
315
hey guys today we are going to talk about binary index 3 application we will look at this with the help of a google interview question now a big disclaimer here this video assumes that the viewer is already familiar with the concept of binary index tree now this tutorial is not an introduction of binary index tree but rather how to apply it in hard problems in case you are not familiar with binary index tree i would recommend you to watch those roy's video on it you can also consult other resources as there are a lot of amazing content available on bit so let's look at the problem statement so the problem statement is that given an integer array nums return a new counts array where count size the number of elements smaller than numpsi and present on the right hand side of numsai and the input constraints are that the length of num's array is less than equal to 10 raised to the power 5 and num psi is greater than equal to minus 10 000 and less than equal to 10 000. now let's look at the test cases so test case one is that numser is 5261 and counts array is 2 1 0 so for 5 there are two elements on the right hand side of 5 which are less than 5 that is 2 and 1 so therefore counts for 5 is 2. similarly for 2 there is only one element on the right hand side of 2 which is less than 2 that is 1 okay and similarly for 6 there is only one element on the right hand side of 6 which is less than 6 that is 1 hence the count for 6 is 1 and for 1 there is no element on right hand side so the count for uh one is zero so the test case two is that uh num says like minus one comma minus one and the counter is zero because for this minus one there is no element on the right hand side of it which is less than minus 1 and 0 and similarly for this minus 1 there is no element on the right hand side so before jumping into the solution let's recap binary index tree for a moment now the whole concept of binary index tree is based on two apis uh the first one is so this is basically written uh in c plus programming language syntax so in some int index okay and similarly the second api is the update api which takes two arguments index and the delta so i am assuming here that you guys are already familiar with bind index three and these sum and update apis and what they actually how they basically solve the range query problems how they basically work and all that okay so this and like i already mentioned in the discriminated this is not an introduction of bit but rather how to apply binary index tree so back to our original problem so let's look at the intuition behind the solution okay now i'm denoting n uh as the length of the nums array which was our input and so when we are at the ith element in nums and if as let's assume that we had the frequency of each element on the right hand side of the ith element stored in the binary index tree then it would be very easy for us to get the count of smaller elements on the right hand side of num psi and uh now the right hand side of the ith index is basically indices from i plus 1 to n minus 1 right and uh so we can get the count of smaller elements on right hand side of num psi by using the sum api of bit and the argument which we would pass it to it would be num psi minus 1 why we are passing this minus 1 so basically this sum api gives are used to solve the range query problems and they will get give you basically the sum of all the frequencies from 0 to this particular index this particular argument which you pass now we want the count of elements which are smaller than num psi hence we are passing num psi minus 1 now if you didn't understand it that's okay let's look at it with the help of an example the example here is that our num's array is 5 3 10 11 8 7 8 12 okay and we are looking at the element 10 here which is also highlighted so let's assume that we have frequency counts of each element on the right hand side of 10 stored in binary index tree okay so basically on the right hand side of 10 the frequency count of elements would be like 11 is occurring only one time here and eight is occurring two times that is here and seven is acting only once and twelve is also occurring only once okay now in binary index this information will be stored in a different format but yeah uh i'm just denoting it here for you guys to understand the intuition okay now i want to get the basically this count of elements on the right hand side of 10 which are less than 10 okay so all i got to do is use the sum api and pass the argument as num psi minus 1. now here num size 10 hence the argument will be 9 so when we will do it so the sum will return us the count is 3 and uh which is also correct because there are only three elements on the right hand side of 10 which are less than 10 that is these 2 8 and this 7 so i hope you understood it uh this example in case you didn't understand it i would uh recommend you to watch this particular section again okay now the question now is that how do we store this information in binder industry basically how do we store the frequency of elements on the right hand side of numsa in the binary index field okay so let's look at the algorithm and we'll understand it uh via that so the algorithm is simple we start traversing array from right to left that is from n minus one index to the zeroth index where and here n is basically the length of the nums array now why are we are traversing from right to left because we are concerned about the elements present on the right hand side of the ith element okay that was given in the question so that's why we are traversing it from right to left to ease to basically is the construction of the solution now for each element num psi we get the count of smaller elements on the right hand side of it by using the sum api of bit binary index tree and as i told you earlier that we will pass the argument as num psi minus 1 by num psi minus 1 we ask because we are interested in the elements which are less than num psi now uh using this we will get the uh basically the count of smaller elements okay now before proceeding to the uh that is the i minus 1 element i need to store the count of this ith element basically i need to update the frequency of this ith element that is num psi in my binary index tree so we will use the update api for it and uh and the update api accepts two arguments that is the index and the index here would be num psi because we are updating the frequency of numsai in binary index three and the delta basically by how much we are incrementing uh the value so we are only incrementing it by one because uh we are updating the frequency by one only because the at ith element there is one occurrence of the num psi okay and when we have done this then we decrement our i to go to the preceding index and we will go on similarly until the zeroth index okay now uh in case you didn't understand this algorithm that's okay we'll understand it with the help of an example so the example here is that num series 10 997 okay now the n is 4 that is the length of the uh array and i is 3 because we are traversing from right to left so we are at the last index right now and the frequency in the binary index 3 is nothing right now because uh like on the right side of seven there's nothing so we'll get counts three uh by using the same api and we'll pass it nums i minus one that is seven minus one six and we'll get zero for this particular index right now before going to the 2 9 i need to update the frequency of 7 in my binary index tree so i do this bit update num psi comma 1 okay so i updated it and now i decrement i now my i has become 3 so we are here now our i has become 3 we are looking at this 9 which is highlighted now this 7 arrow 1 is basically denoting that in bind index 3 we are storing that 7 has a frequency of 1. again this information would be stored in a different format in binary industry but for ease of explanation i am denoting it via this here now i here is 2 now counts 2 would be bit sum and the sum will basically accept the argument num psi minus 1 that is 9 minus 1 8 and we get the answer as one here because uh we'll sum all the elements from zero to eight and uh like all the elements are zero in binary index except this seven which whose frequency was one hence we received one here now similarly before proceeding uh to the next previous i minus 1 is index that is this i minus 1 we will update the frequency of 9 here so hence i am doing this bit update 9 1 9 and by the amount with which we are incrementing the frequency is 1 now we decrement i now we are at i is equal to one which is highlighted here and in bin industry the frequency will be stored as seven is has occurred once and nine has occurred once now for getting counts one basically the element number of elements smaller than 9 and on the right hand side of 9 we will do bit sum and the sum will accept argument as num psi minus 1 that is 9 minus 1 8 and we'll get the answer as 1 here again because there is only one element which is smaller than uh and on the right hand side of it and that is seven now we update the frequency of this nine in our binary index tree so we do it by update api bit update nine comma one okay and we'll now decrement i now we are looking at i is equal to 0 that is this highlighted 10. in binary index 3 the frequency is stored as 7 has occurred once and 9 has occurred twice now count 0 would be bit sum num psi minus 1 and num psi minus 1 is here is 10 minus 1 that is 9 hence the answer which we will get is three that is this two plus one three because we will sum all in binary index tree this sum api will basically sum all the uh elements from zero to nine and that would be one plus two three and similarly we update the frequency of ten in binary index industry and we finally decrement i now i has become minus 1 so our basically we have completed this great so i hope you understood this particular example and in case you didn't understand it i would recommend you to watch this section again now there are some gachas in the problem the thing is that uh right now we have like only considered positive numbers and but our input constraint is that num psi can be uh basically greater than equal to minus ten thousand and less than equal to ten thousand and this is a bit problematic for us because binary index tree is represented in cost code usually as an array and hence can and hence arrays can only handle non negative numbers as array indices are greater than or equal to zero i am sorry here uh basically bind index we can also only handle non-negative numbers uh during range non-negative numbers uh during range non-negative numbers uh during range queries because and the reason behind that is that array indices are either greater than or equal to zero and bit is represented as an array okay now the question is that how do we account for negative numbers so it's pretty simple meet this new uh basically technique called translation all we got to do is that somehow make all these negative elements as positive and the way we do it is using translation and we will basically what we will do is that we will translate each element of num's array by some amount to make it positive and now since the minimum number possible is minus 10 000 so we can add 10 000 1 to each element in nums array to make sure that it becomes positive okay why i have chosen this the value of delta is 1001 because the minimum element in the input is minus 10 000 so adding this will basically make sure that every element will become positive so this way the range which was in our equation minus 10 000 to 10 000 has actually translated to 1 to 2 20 01 right because we have we are adding this delta in every thing make sure that you understand this uh because it is very crucial to understand the code which will follow up next okay so here i am actually i have written this c plus code in case you are not familiar with c plus so uh i mean it is still simple to understand if you are familiar with object oriented programming syntax so i usually represent my bit as a class and provide two apis in it this some api and updated api and if you guys are already familiar with bit so you guys are also familiar with these two apis okay and this is just the constructor of bit and all the data which i am storing in binary index is actually stored in array and that array i'm representing it using this vector end okay so this bit vector will actually basically this bit array will actually store all the data okay now here are the definition of this uh sum and update apis it's pretty simple and pretty standard which you guys also would have done a lot of times uh basically written this definition a lot of times so i'm not going into this now the actual code that is this function count smaller on right hand side so we are actually uh receiving this num's array as the input so we first check if the numser is empty then we can simply return the empty array as answer okay now we have this delta and the delta is same which we were using to translate so that every negative number becomes positive and that was 10 000 1 okay this is written in scientific notation now this answer area is representing the actual answer that is the counts array which will contain the uh where answer i will actually contain the number of elements which are smaller than num psi and on the right hand side of it so we construct the answer error to be of the same size of the num's array and now this here i have con basically instantiated my the object of bit class and i passed this size as the argument okay and as you can see that my constructor is accepting the size of this array bit and uh it's just that and why i'm using the value as 2002 because we already saw that the maximum number our range minus 10 000 to 10000 was translated to 1 to 20 01 okay and i am keeping this as 2002 because uh basically this size can actually store the index 2001 okay now we start traversing the array from right to left that is from num size minus 1 to 0 and i update answer i it's simple using the sum api of bit and the argument it would accept it num psi minus 1 by we are adding this additional data here because we have translated our range so that's my only otherwise it's the same which we i highlighted in the algorithm num psi minus 1. similarly before going to the next ie i8 index that is i minus 1 index we update the frequency of num psi in the bit and that i am doing via update api and passing it the argument num psi plus delta again delta because we need to make it positive and the amount by which we are updating incrementing the frequency is one here and eventually we return this answer array so uh this question is actually also known as has also a very standard name called counting inversions and there is another approach to solve it which is using merge sort but using bind index to it becomes pretty easy to implement it and it would be actually very advantageous to you during an interview scenario because the pressure there is huge and there is a time limit constraint as well and you and bind index using binary index 3 make sure that you minimize the bugs in your code as well using merge sort the code is a bit longer so there are more possibilities of bugs as well so again guys i want to react to this that this was a google interview question and it's a hard problem and i will provide you the problem statement uh link in the description section of this video okay this was taken from lead code so thank you guys for watching please don't forget to like subscribe and comment on this video and i will see you all next time
Count of Smaller Numbers After Self
count-of-smaller-numbers-after-self
Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`. **Example 1:** **Input:** nums = \[5,2,6,1\] **Output:** \[2,1,1,0\] **Explanation:** To the right of 5 there are **2** smaller elements (2 and 1). To the right of 2 there is only **1** smaller element (1). To the right of 6 there is **1** smaller element (1). To the right of 1 there is **0** smaller element. **Example 2:** **Input:** nums = \[-1\] **Output:** \[0\] **Example 3:** **Input:** nums = \[-1,-1\] **Output:** \[0,0\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set
Hard
327,406,493,1482,2280
36
hey what's up you guys new idea ready tech encoding stuff on twitch and YouTube check the description for all my information join the discord I got a bunch of few stuffs going on in there dude to get some interesting perks of joining so we're doing valid sukkot Sudoku today as problem number thirty six medium problem determine if a nine by nine Sudoku board is valid only the filled cells need to be validated according to the following rules each row must contain the digits one to nine without repetition each column must contain the digits one and out without repetition each of the nine three by three sub boxes of the grid must contain the digits one two nine without repetition pretty easy rules basically what we're gonna be given is a Sudoku board we want to return if it's valid and it's valid based on these rules if these rules are met if these conditions are met then it is valid and we return true the method is a boolean value is valid Sudoku board so if it's good if everything's good we return true if everything's bad we return false okay great and the rules are pretty simple to each row just has to contain so each row of the nine by nine board like this is a row one has to contain the numbers 1 to 9 with no repetition meaning all the numbers have to be unique 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 there's nine spots 9 8 per row and there has to be the numbers 1 to 9 and no duplicates right it's pretty straightforward same with the columns there's nine spots 1 2 9 no repeating numbers and then there's these little sub boxes you can see them it's kind of like highlighted bold outline right here you could see it right here there's 1 2 3 4 5 6 7 8 9 and these little sub boxes have 9 squares and they have to contain 1 through 9 without repeating numbers also so you can see this is the representation of the grid above as a 2d array of chars characters so you know you see it's 5 3 are the first 2 5 3 of the first 2 here but empty spaces there's a bunch of empty spaces those are denoted by periods so it says the Sudoku board is partially filled where empty cells are filled with character period okay so empties are periods and then we have all these numbers so all we have to do to make sure that this is a valid Sudoku board is to make sure that each row has no duplicates each column has no duplicates and each of these little sub 3x3 squares has no duplicates in this case you can see we have the 2d chart grid but we return false it's not valid because you can look at this 3x3 upper square right here and there's two eights so that's our repeating character that would be as if this five was an eight that's two eights you cannot have two of the same number it has to be one through nine all those characters no uniques I think we get how it works now all right it's pretty specific pretty basic so since it's a nine by nine grid traversing it isn't really a time complexity issue right it's not like this is scaling so if we were to just traverse it regularly looping through rows is the outer for loop and through columns is the inner for loop you just use J for the columns so really the this isn't gonna take any time right this isn't a lot of data to traverse right nine times nine you know that's not that's nothing that's gonna take a few like that's gonna take no time at all and when you're coding so all we'd want to do in off intuition but we can solve this problem as if like let's say it's n by n boards that would make it like they might ask that as a follow-up so we want might ask that as a follow-up so we want might ask that as a follow-up so we want to implement this in the best time complexity let's say if we were looping up to n like M rows or n columns like then it would becomes a little bit different so if it's a million by a million then we have to you know actually be concerned about time and space complexity right so the intuition that I have is like first of all we're dealing with unique values I always tell you guys if we're dealing with unique values hash is the way to go hash sets are a perfect data structure because you can put things into them easily constant time lookup s' so you easily constant time lookup s' so you easily constant time lookup s' so you can put things in you constant time lookup what's in the hash set in the only store unique values so there's never gonna be any duplicates so the perfect thing here whenever you're dealing with unique have values think of hash sets so my first intuition is to make hache set yeah each loop through the rows you can make it of integers or whatever you want to call it so you could say row Val's is equal to new hash that sorry you can make column values and then you can make the board value so I have three hash sets and as I loop through I would put the values in and make sure there's no duplicates and that's it for each of the rows for the columns but there's actually a brilliant little trick solution that I don't really come up with very often like something as clever as this but really you can do this sometimes it's you can use strings to your advantage and that's what I'll show you who wrote the solution earlier but I'm gonna code it out really quick so they understand basically what we're doing we're gonna do is we're gonna take a hash set of strings and of type string and we're just gonna call it seen or whatever you want to call it and we're just gonna do this casual loop through and we're going to get the current character so the current character we're looping through will just be you know current value or whatever is gonna just be bored of i of j we're eyes rows j's columns if the current value is not empty if it's empty then we're not even going to worry about it then we're gonna look at these numbers and we're gonna put them into the seat we're gonna put numbers that we've seen in the hash set in the way we're going to do that is we're gonna add them in the hasha and we're going to say the current Val we're gonna add it as a string so that we don't leave three separate hash sets coming in on this inner loop here we just need one outer hash set and we can just use strings to make this a little more simple we could just say current Val found in row and then you could just say the row number and this will make it so that all of the rows values are separate because it's gonna say found in row it's not gonna it's gonna put found in row and then it's gonna put the specific row number so as the rows increase it'll only it'll just go you know 0 1 2 3 4 5 6 7 8 9 or 7 8 and yeah it just keeps them separate so that you don't need extra hash sets let me know if you have questions about that feel like I explaining that but it just makes it because you have these strings separating so it's not going to like a column value that's found in a different row isn't going we're not going to find values in different rows and come run into an error because we're going to have these distinct row numbers we're gonna have these distinct strings for you to know that it's a row value and we're not dealing with like boxes or columns so yeah it's just a way to use strings to your advantage to separate things and decrease the number of data structures in this case so you could say found in like sub box or whatever and we could just say I divided by 3 and then we'll add - you divided by 3 and then we'll add - you divided by 3 and then we'll add - you know whatever J divided by 3 this is just 2 you divide by 3 on the row and column to get the current sub box right because it's the sub boxes are three rows and three columns with in length so you just have to divide the current row number by three because if you're in the third row then you're gonna do nine divided by three to get the they are in the first sub box or whatever you know what I mean and then that fear in the third column 9 to 5 over 3 to get the first etc so you're just gonna divide by 3 in the row and column to get the current sub box that you're at so it'll be the first sub box - the first yeah 1 be the first sub box - the first yeah 1 be the first sub box - the first yeah 1 - 1 or whatever you know what I mean so - 1 or whatever you know what I mean so - 1 or whatever you know what I mean so that's pretty much it and you're gonna be adding the values as you see them we start we reduce the amount of data structures using strings and also what we're gonna do is you can actually use the add method to check for duplicates because when you're adding you there is a return value when you're adding to a hash set and it says it returns true if the element is not present so if the element is not present that's what we want that's good so we're gonna say not if it's not true that's bad so we're gonna say if it's this isn't good or this isn't good I'm gonna put the not symbol or this isn't good then we're gonna say that it's false cuz there we go that should be fine then we just return false and if we make it through everything we just return true and that's the whole problem not too difficult there you can you the thing that this method this question I think teaches the most is that there are a little tricks like using strings to reduce data structures and there's also little tricks like using this add method as instead of checking ok does this hash that already contained the value we can use the add method because the add method all checks if it's contained because it says it returns false if the allman elements already present so if it returns if the elements already present we're gonna get false so we just negate that with all these knots check for ORS so this will basically just check if any of these if we found a duplicate in the row that duplicate in the column or the duplicate in the sub box then this will check for that and we can return that it's invalid based on that condition so that's pretty much it for this problem shout out to this dude I would know I would have never come up with this thing it would have taken me forever to think of this is really clever by this dude right here sooo shout out to you bro for this little string trick right here very smart very intelligent the regular way is you can also see in the discussion it's just something like this right you're looping through and then you make the just a regular hash set for the rows columns and cube the individual cubes you could check for the characters make sure they're not empty and then just get the current row and column to find the right box and you know just add to the specific hash Maps and yeah this one uses the add method to do that check it's basically the same thing the string one just reduces the data structures but that's pretty much it I think this is a really easy problem and you probably won't get it in an interview because especially with the 9 by 9 you're not like you're gonna I think more commonly I've never gotten this in like ton of interviews I've done more commonly you're gonna get questions that scale this one seems it's a little bit of a weird question too but then again it's also somewhat popular so you could get it good to know about this ad method in Java and good to know about thinking outside of the box of the strengths other than that it wasn't too bad so thank you guys for watching I appreciate you guys and I will see you in the next video goodbye oh also like and subscribe alright see ya
Valid Sudoku
valid-sudoku
Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: 1. Each row must contain the digits `1-9` without repetition. 2. Each column must contain the digits `1-9` without repetition. 3. Each of the nine `3 x 3` sub-boxes of the grid must contain the digits `1-9` without repetition. **Note:** * A Sudoku board (partially filled) could be valid but is not necessarily solvable. * Only the filled cells need to be validated according to the mentioned rules. **Example 1:** **Input:** board = \[\[ "5 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** true **Example 2:** **Input:** board = \[\[ "8 ", "3 ", ". ", ". ", "7 ", ". ", ". ", ". ", ". "\] ,\[ "6 ", ". ", ". ", "1 ", "9 ", "5 ", ". ", ". ", ". "\] ,\[ ". ", "9 ", "8 ", ". ", ". ", ". ", ". ", "6 ", ". "\] ,\[ "8 ", ". ", ". ", ". ", "6 ", ". ", ". ", ". ", "3 "\] ,\[ "4 ", ". ", ". ", "8 ", ". ", "3 ", ". ", ". ", "1 "\] ,\[ "7 ", ". ", ". ", ". ", "2 ", ". ", ". ", ". ", "6 "\] ,\[ ". ", "6 ", ". ", ". ", ". ", ". ", "2 ", "8 ", ". "\] ,\[ ". ", ". ", ". ", "4 ", "1 ", "9 ", ". ", ". ", "5 "\] ,\[ ". ", ". ", ". ", ". ", "8 ", ". ", ". ", "7 ", "9 "\]\] **Output:** false **Explanation:** Same as Example 1, except with the **5** in the top left corner being modified to **8**. Since there are two 8's in the top left 3x3 sub-box, it is invalid. **Constraints:** * `board.length == 9` * `board[i].length == 9` * `board[i][j]` is a digit `1-9` or `'.'`.
null
Array,Hash Table,Matrix
Medium
37,2254
4
hey everyone welcome back to the channel i hope you guys are doing extremely well so today we will be discussing the problem find the median of two sorted arrays now this is elite code hard problem yes so you need to understand it really well in order to solve this so what is the question stating the question is stating that you'll be given a couple of arrays yes you'll be given a couple of arrays and those arrays will be sorted in itself like array one is sorted array to assorted and you need to figure out the median if you don't know median it's a very simple thing these are a couple of errors right sorted so you merge them and you get uh the other sorted array so the other sorted array will look something like this so once you've merged it into a sorted array if you count the length will be n1 plus n2 that's 10 which is an even length so if it's an evil length you simply take two middles because a even length will have two middles so this is four and six so if you add them up and you divide them by two you get something like five so that's your median basically take the couple of middles and take the average of them if the length is an even length what if you have something like let's say one three and over here you have something like four five six so these are the couple of arrays so what you'll do is you'll again merge them into a single array so that's that gives you one three four five six so if you have this the length over here is a odd length which is five so if there is a or length there will be only a single middle element and that will be immediate so that's the definition of media so if this question comes up in an interview which is the first solution that you will propose to the interview it should be the native solution what is the name solution very simple if you remember merge short there is a merge method that we write right where we have two sorted arrays can we not use that over here let's have a pointer standing here whichever is the smaller take it that's one then move the pointer to the next now which is smaller two or three two take it move the pointer to the next now which is smaller three or three any one you can take now which is smaller four or three move the pointer now which is smaller four or six four correct take it move the pointer which is smaller six or seven six take it now which is smaller seven or fifteen seven take it move the pointer now which is smaller 10 or 15 10 take it now which is smaller 12 or 15 12 take it move the pointer now which is you don't have anything to compare so just copy paste 15. so you can definitely put this into some data structure and whichever is the middle like over here the length is even so there will be a couple of middles so just pick them up and divide them by two and you'll get your median very simple use a two pointer approach and put them into some data structure and you get your answer time complexity it's definitely big o of n1 plus n2 where n1 is the length of the first sorted list and enters the length of the second sorted list the space complexity is again we go of n1 plus n2 because you are storing all the elements into some other data structure so this will be a naive solution can you optimize this definitely yes we can make this to be go of one how can we make that again if you have a simple observation we know one thing that we actually require the fifth guy and the sixth guy so when you are doing the comparisons and you're picking up one you're picking up two you're picking up three when you're doing the comparisons why don't you maintain a counter you simply maintain a counter and whenever the counter picks up the fifth element you store this somewhere and whenever your counter picks up the sixth element take that up and store it somewhere so once you've got your fifth and sixth elements just get an average of that and you will definitely get your median so instead of storing in data structure just use a counter and get only the desired elements because you're not concerned with all the other elements you're just concerned with four and six so why don't you do that right so if the length is odd then you're just concerned with one element so let's pick it up so this will be the better version of the naive solution that is bigo of one so this video is sponsored by reliable which is backed up by an academy now let me give you a short introduction about them they're basically the first hiring tournament platform now what they've done is they've tied up with a lot of startups who are hiring freshers and people who are at the early stages of their career now they have around 500 plus positions across 50 companies and now these companies are not google but at least these companies are like a razor pay upgrade urban company and many more like all the trending startups they have tied up with so basically you won't be requiring a college degree with a high grade school or not a b-tech degree or an mba degree or not a b-tech degree or an mba degree or not a b-tech degree or an mba degree if you have skills you can definitely apply and participate in this given tournaments now these tournaments will be specifically having a couple of rounds the prelims and the mains and i'll be uh leaving the entire detail about these rounds in a brochure below you can check out the description so basically if you uh clear the mains you will get mentoring sessions from the team which will help you to clear the interviews on the basis of the score that you get when you participate in the tournament you can apply to the companies on their portal now i think you should not miss this chance because jobs are very hard to come in this covered era and a lot of you uh do not have a good network which often leads you to miss out on a lot of opportunities you must be thinking uh it will be costing a huge chunk of money or it might be an iso model no it will just cost you one triple nine and if you use the coupon code take you forward it's gonna cost you one seven nine i think it's very cheap and you should give it a try because even if you get an interview and who knows you might be able to crack a job so if you are looking for an opportunity i think you should give it a try the last uh date for registration will be 22nd june and the first tournament starts on 26 june and if you want any other further details i'll be leaving all the links up in the description go check it out and yeah look at it right will the interviewer be happy with this obviously not and he'll ask you to optimize it so when you think of an optimized solution you should uh take a notice that the arrows are sorted and whenever these are sorted arrays the first algorithm that should come to your mind should be binary search definitely so let's see if we can actually implicate binary search so if i club these into a single sorted array the elements will be something like this now the length is 10 correct so can i say if i draw a partition i know one thing for sure the left half will contain five elements i know one thing for sure the right half will contain five elements why don't i take this advantage and try to solve this problem how that's the question now just imagine for a simple stuff if i say that i'm going to pick three elements or let's say i'm gonna pick four elements from the first array so will i have one three four seven for the first having i have picked four elements from the first heavy now how many elements does this left require can i say it requires five elements so what should i pick up from array two a single element so just pick it up now so in this way you can actually form your left half okay now what will be the right half the remaining elements are 10 12 and over here 3 6 15 so i can actually pick up elements in this way now can i also say what if i decide to pick up something like one three four that has three elements from the first array so how many elements can you pick from the second array definitely two so those two elements will be two three so the remaining elements will be forming the right half so the right half will be 7 10 12 and over here it will be something like 6 and 15. i can also pick five elements in this way now can i also say what if i decide to just pick couple of elements from array one hence i will be picking up two three six from the array two because i picked just couple of elements from array one so three elements have to be picked from array two and from here i'll be picking like 4 7 10 12 and a 15 from here so i can also do this so that will be my thought process i'll try to pick up certain number of elements from the arrow one and i will try to pick up the remaining from marito in order to from the left half now i just need to check if my picked left half is a valid one valid in the sense is it the left half that i'm looking for okay so how do i check that now you can observe something whatever elements are over here are actually lesser than whatever elements are on the right half i repeat all the elements over here are lesser than all the elements that are on the right half so in order to actually check if i've picked the correct one i just need to check if all the elements here are lesser than all the elements on the right how do you do that can i say one thing this these guys are smaller than these guys because it's the same array one three four seven ten twelve rcc married can i also say 2 is smaller than 3 6 15 again same array sorted i just need to check if this guy is smaller than this guy and this guy is smaller than this guy i just need to check this can i say if it is smaller if it is a valid one or if this is the left half which is actually the answer then the 7 has to be lesser than equal to 3 because all these elements are lesser than right but i cannot see that this 7 is greater than 3 i cannot see that so this is not a valid one okay let's see if this is valid over here what do you observe 1 3 is again smaller than this no doubt in that 2 3 6 is smaller than 50. no doubt in that i just need to check the cross one so let's check is three smaller than 15 yes it is okay but is this guy smaller than this 6 is not smaller than 4 no it is not hence this is also not our left half because all the elements are not smaller than the right half perfect is this our left upper right half let's see 4 smaller than 6 yes 3 smaller than 7 yes so can i say can i see that all the elements on the left half are actually smaller than all the elements of right half yes i can say hence if i pick three elements from the array one and if i pick two elements from the array two i can actually form my left half and the remaining guys will form my right half so this is how i can actually pick up elements how to do binary search i'll come to that but this is how i can actually try to think of picking up elements so once you have got this valid left half and you have got this valid right half okay how do you find the median so let's assume i call this as left one because this is the left one and i call this as left two okay and i will call this as a right one and i will call this as right two can i say the median if the length is even we will discuss about length afterwards if the length is even can i see this 4 is nothing but the maximum of the left half can i say this yes hence can i say the maximum of length the maximum of this left half is nothing but maximum of l1 comma l2 definitely yes i can say that i can definitely say that and what is the six can i say it's a minimum of write-off of write-off of write-off hence i can say it's a minimum of r1 comma r2 yes it's a minimum of r1 and r2 and if i can get these two guys and if i divide them to find their average can i say this is my median yes this is my median so i figured out how to find the immediate how to check for validity varid check is very simple this l1 has to be lesser than equal to r2 this l1 has to be less than equal to r2 and this l2 has to be lesser than equal to r1 the cross conditions have to be valid in order to these cross conditions have to be valid in order to make sure that all the elements of the left half are smaller than all the elements of the right half which will signify that the left half is the correct left half that you have picked so this is the valid condition this is the median condition for even length i'll come to earlier but how do you yes how do you think of a binary search solution okay let's understand that too now can i see can i say in order to uh take five elements from the left i can actually try a partition uh over here that means saying i'm gonna take one element i can actually try a partition over here that means i'm gonna take two elements i'm actually gonna try a partition here that means i'm gonna take three a partition here that means i'm gonna take four a partition here that means i'm gonna take five beyond this uh it's not possible because i have to take only five elements on the left array so how do you think of a binary search now you know one thing you just need to decide where to do the partition and if you can actually figure out that this is the portion where you need to do the partition your job is moreover done okay let's understand now just imagine you are doing a partition over here right that means over here you've done a partition just imagine now you know this is not a valid one how did you know that this is not a valid one because this 7 should have been lesser than 3 perfect but it was not so can i say in order to in order for the seven to be lesser than three i need to reduce three and i need to increase three can i see this if i do this i can actually form a correct partition so in order to reduce seven if this is a sorted guy because this is array one it's a sorted cut you need to move left because the moment you move left what happens see the seven will go on the right correct and if you move left you are only taking three elements so you will have to take this three on the right so you have two three now when you compare you will have a 4 so you've reduced 7 to 4 you understand you've reduced 7 to 4 and over here you have increased 3 to 6 just because you shifted the partition leftwards so i hope you have understood when to shift the partition leftwards but when do you shift it rightwards now imagine you had 3 this 3 is less than or equal to 50 but what did not over your condition this 6 should have been ideally lesser than equal to 4 but that's not the case hence it is not satisfying so in order to satisfy what do you need to reduce 6 yes and you need to increase this 4 so how will you increase this 4 can i say or how will you reduce the 6 can i say if this guy goes right hence you will take more elements and if you take more relevance this 6 will cut off which happen in this case and this 6 will reduce to something like 3 hence i have understood if a condition like this happens i need to move right or if a condition like this happens i need to move left so once you have figured out whether to move right or whether to move left can you actually place your partition according to that and you can actually try out all the partitions using a binary search method and once you've figured out your correct partition i think your answer is done yes your answer is done so let's take this example and do a dry run of binary search so what you can see is i have these couple of arrays that are sorted again 10 elements so 5 will be on the left and 5 will be on the right so i know i can pick a minimum of 0 elements from array 1 and a maximum of all the elements that is 4 from the array 1. so let's assume low to be zero high to be four saying that this is the minimum elements that i can pick and this is the maximum elements that i can pick now figure out the middle and let's call it something like cut one okay that means uh the number of elements that you're picking up from your array one so the middle is zero plus four by two which is nothing but two so i'm picking up two elements which means a cut over here cut on the first array what about cut two how many elements am i picking up from the second can i say if the total is five i'm actually picking five minus two that's the three elements from the array two i can so the cut two will go over here saying i'm picking up three elements from array two perfect the cuts are perfect now can i say 1 l 1 is what matters so i have a 12 as l1 i have a 3 as l2 our 14 as r1 i have a 4 as r2 i know there are numbers like 7 12 there are 1 comma 2 comma 3 14 comma 15 and then 4 comma 9 comma 11 but what matters to us is these guys yes these guys i just need to compare if this 12 is lesser than equal to this four i just need to compare that and i see that it is not hence this is not a valid partition now i just need to decide where to move i can see that this 12 has to be lesser than 4 in order to this be a valid partition so i need to reduce 12 and how can i reduce that definitely i have to move left definitely so if i have to move left that's a binary search and whenever i move left what do i do this in binary search right high equal to mid minus one so why don't you do that so high will go one lesser from mid which is two so that will become one so you go one lesser so currently your low is at zero high is at one so if you try to figure out which is the cut one what is the value or the middle 0 plus 1 by 2 how much is that 0 so what you're saying is this is where you're putting the cut hence you're saying you're taking no elements from array 1 perfect where will you put a cut to the cut two will obviously be five minus zero equal to five elements here's what here picking from array two so that means a cut over here is saying you're picking up five elements from array two perfect so again what matters to you is l1 so that's uh basically no elements from the array one and over here one two three four nine from added two and on the right half it's 7 12 14 15 and over here at 11. now if you're picking up no elements always make sure you assign l1 to be a minimal value because you haven't picked up anything right so just make sure you assign it to into mean this will be your l2 this will be r1 again and this will be r2 so you just need to compare if this is the valid left half and valid right half so this end mean is lesser than this 11 perfect these guys are lesser but is this 9 lesser than equal to 7 i see it is not so what you need to do is you need to decrease 9 and you need to increase 7 and how is that going to happen so how are we going to increase 7 very simple if you take the seven from the right and you have to put it on to the left which means adding up elements on the left picking more elements as of now you're picking no one so the low will move to mid plus one because you wanna pick more elements so the low moves to mid plus one what is mid zero moves to mid plus one goes to one perfect so currently lowers at one high is at one let's figure out which is cut one is one plus one by two that's one what is cut to five minus one that's a four so saying i'm gonna pick one element from the array one and four elements from array two that's the orange stick okay so let's try to pick up so that's a seven that's a one two three four on the right that's a 12 14 15 and over here it's a nine and a 11. perfect is this a valid one yes it is why 7 is lesser than 9 and 4 is lesser than 12 so i can definitely say this is a valid one and if this is a valid one can i stop over here yes i can and how do you find the median very simple you add a seven you add a four so you need to take the maximum on the left so it's a 7 on the left you added 12 you add a 9 you take the minimum so it's a 9 so the average of them is 8 and that is what your median is so in this way you can definitely find your median so just remember one thing since you just require l1 l2 r1 r2 in order to compare if they are valid or not so we always have couple of things that is the cut one and cut two so if you carefully observe if cut two this is the blue line cut two was at the second partition i was always taking the first index guy as my l1 so can i say l1 is nothing but array of one cut one minus one can i say this yes what was l 2 was always 1 before cut 2 so i can say l 2 is nothing but array 2 and cut 2 minus 1 and similarly can i say r1 is this guy 14 2 so it's a array 1 cut 1 this is array 2 cut 2 simple just make sure of one thing if there is like cut one you're not picking up any elements so there will be no l1 in that case make sure you take it as a minimal value into mean or something like that and also in l2 same thing if you're not taking anything from the array 2 make sure you assign it to intermean for r1 please make sure if there is no one on the right you need to take a maximum because r1 is always the greater guy similarly r2 these guys has to be this is what you do if there are no r1 and r2 please make sure you check this edge case because this is a very important edge case which people miss out okay so you can look at the right portion and that is what we generally do for even length right if n1 plus n2 is even so let's take this example where i've added the 16 into this array one so now the length or n1 plus n2 has actually become 11. now let's do a very simple thing try to divide this into couple of halves where you say that the left half is 6 and the right half is having 5 elements so once you know how many elements are on the left half can't you figure out the partition and if you have figured out the partition can't you check for its validity you can the only difference is you need to figure the six out how do you do that so if n one plus n two ideally this length is five ideally this length is six so six plus five would have been eleven so just do a plus one and a by two so what you'll get is six so once you have this length six of left half i think the problem becomes super simple right the only difference is in the even length you always took two guys that is the formula that you applied in order to find median over here you know the median will always be the last guy of your left half so can i say over here the formula will boil down for median to be the max of l1 and l2 whatever is your left partition you just take the last guy and that will be your median yes that will be immediate and for finding out the length of the left half this is n1 plus n2 plus 1 you can also use this over here the length of left half why because even if you take 10 which is the length and you do a plus 1 and a by 2 then also you get a 5 and if you take something like 11 plus 1 by 2 then you get a 6. so this formula is going to work for odd as well as even you just need to alter the median and everything else will stay the exact same now till now i hope you have understood the entire intuition as well as the algorithm now it's time to discuss the c plus code now the java code is exactly similar it's exactly identical so you can definitely follow this and you can write your own java code i'll also be leaving the java code link in the description so yeah you're basically given couple of arrays nums one and nums two now as i always said you try to uh figure out for the try to do binary search for the smaller size array so if nums two is smaller make it nums one so again you call the function with nums two nums one so that you have the smaller size added ready correct next figure out n1 n2 done now you know at minimum you can choose zero elements at maximum you can choose n1 elements simple just do the binary search low lesser than equal to high and try to figure out cut one that's basically the middle what is cut one low plus high by two correct that is what cut one is done next try to figure out cut two what is cut two if it was even it is n one plus n two minus cut one basically the total uh the half's length minus whatever you have taken from array one correct so this works for odd as well as even done now if you remember l one was this l2 was this r1 and r2 so this is what i've written over here simple i have taken these guys and i've just made sure if i'm not taking anything from the left or the first array i'm making it in queen similarly if i'm not taking anything from the array 2 i'm making it into mean similarly if i'm taking all the elements from array 1 so there'll be no write into max and it max so i made sure that i have covered up the edge cases now what is the condition to check if it is a valid or not you remember if this one was l1 and this was one l2 this was r2 r1 r2 you always checked l1 and r2 so this is what i've done l1 and r2 left and right and you always check left two and right two so that is what i've done so if these conditions are valid i can say whatever currently i have like whatever cut one and cut two is currently that's a valid one and i check if the length is even you remember this was the formula that you implicated simply implicate this formula and return the immediate done if the length was odd you always implicated this formula so max of left one and left two correct now what if this is not a valid one now you remember this l one has to be lesser than equal to r you know this but this is not if it is not and can i say i have to actually reduce it if it is not and if i have to reduce it can i say i have to move my high to the left that is mid minus one or else if that's not the case i'm only left with one other case that is moving the low to mid plus one i move it and once i've done this i should definitely get a valid partition okay and just in case i don't get that means the uh nums one and nums two were not sorted and you can return something like 0.0 and you can return something like 0.0 and you can return something like 0.0 but this case will not come because the question clearly stated you will be given two sorted arrays you just have to write a return statement otherwise this function will not execute because it returns a double median can be double right so if because this return statement is inside a if and a while loop so you never know will this be executed or not the program never knows so you have to write an external return uh stuff in order to execute this code so this will be the code now if i ask you the time complexity here tell me what will be the time complexity now since you're already always making sure over here that you're always doing the binary search on the minimal guy so can i say it's a log base 2 whichever is the minimal length n1 or n2 because i'm always making sure that i do the binary search on that space complexity am i using some extra space no that's a big of one so that will be the time complexity as well as the space complexity so guys i hope you have understood the entire explanation just in case you did please make sure you like this video and if you're new to our channel do check out our channel you'll feel like subscribing okay so with this let's hop up
Median of Two Sorted Arrays
median-of-two-sorted-arrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return **the median** of the two sorted arrays. The overall run time complexity should be `O(log (m+n))`. **Example 1:** **Input:** nums1 = \[1,3\], nums2 = \[2\] **Output:** 2.00000 **Explanation:** merged array = \[1,2,3\] and median is 2. **Example 2:** **Input:** nums1 = \[1,2\], nums2 = \[3,4\] **Output:** 2.50000 **Explanation:** merged array = \[1,2,3,4\] and median is (2 + 3) / 2 = 2.5. **Constraints:** * `nums1.length == m` * `nums2.length == n` * `0 <= m <= 1000` * `0 <= n <= 1000` * `1 <= m + n <= 2000` * `-106 <= nums1[i], nums2[i] <= 106`
null
Array,Binary Search,Divide and Conquer
Hard
null
200
hello welcome to my channel for 100 lego challenge today we have medium nico 200 numbers of items so this one is really classic dfs uh questions so let's take a look at it given an m time and 2d grid map of ones which is island and zeros water return numbers of islands so what is island so island here is one is a land so land can connect each other today surrounded by the water in this example he is connected it's connected all connected so this all connected island land is count as one land and here's output is numbers of land which is one and also take a look at the example two in this case he is all connected so this portion is count as one island and here is individual one is another island and here is the third island so we output three in here so how do we solve this problem as there's one way of solving it is when you need a helper function the helper function is basically loop through every element in the grid if you see is this one that means the land then we'll increment the counter we have a count at beginning star is zero so when we see one we increment one by to the counter after increment by one and then the helper function will make this one become zero so let's draw this out so now we become zero not only that after this drawing this zero the helper function will check up left and right bottom so in this case if it's outward bound which this case in this case it will do nothing so it will return nothing and here when you go to the right side it will recall this helper function so we will make this zero basically this helper function is keep drawing once to zero and in the same time check the surrounding up left right bottom until uh everything's clear so now we check this one becomes zero and we check up output is out of bound and check right left so things left is zero so also do nothing the same case of this outer bound after this we go right zero and then uh at left so outbound level zero right zero and come down to here to draw this one and in this case left upper bottom everything is zero and we go back to here because this note only go up check upper and left and we just finished the right on this side and what we need to do is go down to check it the way of we the checking works is go up left right down or you can also choose whatever way you can do but the checking is just it's going different differently eventually it would still count all the ones cancel all the ones that's what it does for the helper function and at the beginning before the helper function we already count the counter to counter right here uh one now so we will loop through um everything until we find another one so this is the logic of this uh dfs question let's clear this first and we jump to the code now we have see first we have a count equal to zero star is zero and oh yes we have to check if grid is equal to no uh actually script.link equal to no or grid first row dot link equal to no oh sorry what am i doing then we'll return zero i think yes and then we have a counter now what we need to do is have a end um we loop through n row m column actually m row and n column so it's equal to zero sub zero i less than grid dot lane this is row and i plus to make it clear we can use r 4 and column equal to 0 column less than grid first row dot lane right personal.link and then right personal.link and then right personal.link and then c plus so they will it will look through every character so now f grid row and column equal to one in this case there's our island first thing we need to do is count plus first and then we call the helper function to cancel everything every uh adjust once let's see the helper function will bring in r column and here we will write out the helper function to take in the matrix and then we have int r and c now first thing in this helper function is check if r less than zero that means it is on top of here so if you're less than zero negative one that means it's outbound also check c less than zero this l bounce on the left side so this album there's the two more out of bound condition is r bigger than equal to grid dot link at the same time c is bigger equal to grid zero dot length case is four ways of outbound that case we will return that's it we don't do anything and we missing one of the conditions is when we see the current cut place is we're checking is zero so we don't do anything because we don't need to cancel the zero to zero we're just looking for ones to cancel it out is equal to zero then we just don't do anything now after that we will make the grid current place equal to zero changing to zero then we have a call to check four directions and the direction doesn't matter in this situation uh we put the grid in here plus one oh not iso plus one c helper function one see c plus one minus one so there's four direction here and i think this is let's see if oh yes in here after all this um look through everything we just return counter hopefully pass stat overflow let's see oh this one mistake here it's change it to the character instead of an integer so we pass okay it looks good now this one's really important most of the questions based on this dfs so i hope you get it and if you have any question please comment below and i will get back to you as soon as possible and see you in the next video bye
Number of Islands
number-of-islands
Given an `m x n` 2D binary grid `grid` which represents a map of `'1'`s (land) and `'0'`s (water), return _the number of islands_. An **island** is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. **Example 1:** **Input:** grid = \[ \[ "1 ", "1 ", "1 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "1 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "0 ", "0 "\] \] **Output:** 1 **Example 2:** **Input:** grid = \[ \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "1 ", "1 ", "0 ", "0 ", "0 "\], \[ "0 ", "0 ", "1 ", "0 ", "0 "\], \[ "0 ", "0 ", "0 ", "1 ", "1 "\] \] **Output:** 3 **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 300` * `grid[i][j]` is `'0'` or `'1'`.
null
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
130,286,305,323,694,695,2035,2103
215
welcome to january's lego challenge today's problem is kth largest element in an array find the kth largest element in an unsorted array note that it is the kth largest element in sorted order not the kth distinct element so that's helpful basically we have a unsorted list and we want to return the second largest one inside of this list now the straightforward method you think is to sort it probably do it in reverse order and then select the second element inside of that temporary that's sorted in descending order and you're done right now i did not expect this to work but interestingly enough it does work what we do is just say okay make it sorted reverse equals true and then just return the kth element but we have to subtract one because it's zero indexed and this totally works it's fine but obviously in an interview this would be a little cheeky and really not really explain anything the reason why this is so fast is because the sort sorted method inside python is just very good so you might want to explain in more detail if we can do better than this would be time complexity of n log n can we do better well one method i found interesting was we could use a variation of quicksort uh what we could do is take our elements and select a pivot it would have to be some random position here just select one of those numbers what we'll do is create three arrays we're going to create um one array that's less than the pivot number which will say uh that's going to be called right because we're going descending order so whatever is bigger than our pivot put that into our right array if anything smaller put that into our left array and if it's uh the number that we select and pivot we'll put that in the mid now the reason we can do that is we'll have this left mid and right and now we can take our k and just get the lengths of these array and check to see which one will it belong in for instance if k is less than or equal to the length of left then we know that whatever case element is uh we're trying to select should be in here with that we can start recursively calling do the same algorithm and uh move on until we find the point at which the k is equal to um well it's not we want to say less than or equal to the length of left and not greater than the length of the left and mid it's not on the right side it's in the mid and once we get there we can just return whatever number is inside that mid because whatever pivot number we selected that's the number that's going to be the kth largest so let me see what um let me show you what i mean by this it's kind of a variation of quick so what we do is first select a pivot point and we're going to use random.choice going to use random.choice going to use random.choice and select any number inside of this nums now we want to have our left array and we'll use list comprehension here we'll say all right four x in nums if this value is um when you want to say greater than our pivot then it goes to our left right so if this value is greater than pivot then put it into our left now if the value is equal to our pivot then we're gonna put into our mid and otherwise put into our right so that would just mean if it's less than our pivot oops and nums if x is less than our pivot okay so now we have three temporary arrays and we'll have to initialize the length of the left and length of the middle we don't need the length of the right because if um our k is greater than l plus m we already know that's going to be on the right side so we don't actually need the length to that we'll just get the length of left and the length of mid and first thing i want to check is look if k is less than or equal to the length of l which is our left side we know it's inside this left array right so we'll just do a recursive call here and we'll put in the left array and we'll continue putting that k now otherwise if k is greater than l plus m we know it's got to be on the right side right so i should say return here if this happens what we're going to do is say okay get the k largest but search on the right side and instead of k now we're actually going to um input the k minus l plus m here because we know k is greater uh we have to take whatever length is from the length of left side and middle side and whatever values left inside here that's going to be on the right so otherwise if none of these are true that means our pivot number is or i'm sorry the mid number is equal to the k largest right so if that's the case all these values inside of mid should be the same so we can just return any value inside here we'll say mid 0. just to be safe we'll return the first one now let's see if this works it appears to be working so let's submit that and there we go accept it so this is faster technically now it doesn't look like oven time complexity but there's some mathematical reasons why it actually it does average to o of n it's not over log n and i believe it's something to do with how many recursive calls here will do on average we do a depth of two so something like that but honestly this question like if you just want to solve it you know for programming purposes probably better to do it using sorting just using the sorted built-in sorting just using the sorted built-in sorting just using the sorted built-in library but during interview if you did something like this could be pretty impressive so it's good to know this algorithm is kind of known as quick select instead of quick sort all right so thanks for watching my channel and remember do not trust me i know nothing
Kth Largest Element in an Array
kth-largest-element-in-an-array
Given an integer array `nums` and an integer `k`, return _the_ `kth` _largest element in the array_. Note that it is the `kth` largest element in the sorted order, not the `kth` distinct element. You must solve it in `O(n)` time complexity. **Example 1:** **Input:** nums = \[3,2,1,5,6,4\], k = 2 **Output:** 5 **Example 2:** **Input:** nums = \[3,2,3,1,2,4,5,5,6\], k = 4 **Output:** 4 **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Array,Divide and Conquer,Sorting,Heap (Priority Queue),Quickselect
Medium
324,347,414,789,1014,2113,2204,2250
1,332
Hello Hi Guys Welcome to make video in a series of coding Khade Bhi Hi Dard Problem If Near Challenge Problem Of Today With S Manya States On Only Good Friday Remove First Mixer Sequence Is Yagya Na Spread Consisting Only Of Letters In This Verse Line The Best Border Line Will Help to Learn Per Problems OA Give Inside Testing Consisting Only of Letters in the Years Most Important White Single Step Which Can Remove Wellington in Subsequent Romance Return Minimum Number of Steps to Make the Thing and Dick Should Strive to Consider the Possible Cases That Will Be Alright Indies How So Let Me To Take Something Water Spring Fail In This Time With Size Zero Flash Nothing Not Even Last Regarding Money Size 000 To Solitaire Game This Not Do Anything Special To Make A Solid Okay Buy Single One Baby Ye And There's Something Like Plays And You Have Something Like Chief And You Have Something Like This That BB 21 Hundred Geezer Examples And The First Rooms And The Same In All Directions To Consider All The Answer Were Question of Your Life You Will Find What You Will Leave One Time Movie K Mein Vanvaas Anti Spring OK Other K Healthy Effects Year Perfect Palan Rome K Light Fire Shot Perfect Palan Rome Banner These Two Dancers One of the Most Wanted mid-2014 Possible Veer Lead Character Servi Number To Make A Simple But You Will Remove The Egg First Remote Times Of A Good One Shoulder As You Remove At Once You're Left With Only In 2016 Remove Thumb At Your Left To Heavy Snow Fall In Love With Nothing But The Question Of Characters You Can Move Characters Her Simple Equations And Subscribe Like This Is The PT Right Down The Course From Appearance To Team To Chest Size Equal To Zero Daily In Just 120 Just MP Singh Putra Just Dhiru Otherwise What We Can Do Yes We Can Name Milk And This * Find Weather And In Milk And This * Find Weather And In Milk And This * Find Weather And In Benesova Oil Change And Where Is Equal To Zero Initially Like Equal To Taste Size Minus One And Mileage So Will Keep Creating Apps Normal Note Is Equal To After it's ok Google please give me is European simply home visit all you can simply don't want to because itself is request to adjust not through any particular is arvind sequence bread dharmidas saun is not equal to the thing is not appear in the mixing swift notification written In this no different from its strength when you can't just want to ok it 02351 Remove Screen Light Vidron And Works That 24 Working For This Case Study Sensitive Products Accept Solution Think Solution Thanks
Remove Palindromic Subsequences
count-vowels-permutation
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does **not** necessarily need to be contiguous. A string is called **palindrome** if is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "ababa " **Output:** 1 **Explanation:** s is already a palindrome, so its entirety can be removed in a single step. **Example 2:** **Input:** s = "abb " **Output:** 2 **Explanation:** "abb " -> "bb " -> " ". Remove palindromic subsequence "a " then "bb ". **Example 3:** **Input:** s = "baabb " **Output:** 2 **Explanation:** "baabb " -> "b " -> " ". Remove palindromic subsequence "baab " then "b ". **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'a'` or `'b'`.
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Dynamic Programming
Hard
null
146
alright so in this video today we are going to talk about an apparent Microsoft question I don't know if other companies ask this but implement and LRU cache so first off let's get started with terminology what is LRU and what is a cache LRU stands for at least recently used it is a cache eviction policy when we have a loose collection of items and we want to remove items in a certain order a restricted order remember how we have LIFO first at the last item to go in is the first item to come out for a queue the first item to come in is the first item to come out the least recently used if a similar policy to the FIFO policy except it's you where you can get point of cash so here's an example say we have one two three four in a cache and it is sized for say I want to add another item zero so let me add zero so when we add zero we add it to the front of the cache what this shows is the temporal order of access to items access this item most recently this height of second most recently this item third most recently and what happens is this cache is restricted to a size of four a capacity of four it is a five we need to evict an item and what we understand is that our eviction policy is using the least recently used what is the least recently used item is four so what we do is we evict four from the cap and so now this is our new cache this is our new order of items and now let's access item number two and see what happens so what happens when we access to is that abuse to the front of our cache it is the most accessed item so what you notice is when we access an item used to the front of the list when we go over in size we need to remove an item we ruined at least recently used where will the item be is going to be at the tail of our list the end of our list and the verb I'm using is starting to hints to you the kind of data structures we'll use we'll get into that soon what is it cash you probably are familiar with this if you already are watching this a cash is just something that stores computations so that look up later can be served very quickly and not just computations but also it can store redundant data so that we have quick access to it instead of reaching out to the database instantly it could be many things but the whole point is to speed up future requests for whatever resources that are being asked for what is it LRU cache now that we've covered LRU we cover in the cache so an LRU cache is a cache will often have a finite capacity and we use the LRU cache eviction policy now let's see our constraints and see how that hints to us how we're going to solve this problem so now imagine getting this problem in an interview and you don't really know what data structures you're going to use you don't really know how we're going to approach this problem let's just look at the requirements that are asked of us we need to support an API of two functions we need to support a get operation which is where we get an item from our cache and we need to support a put operation where we add an item to the front of the cache and we evict the least used item if we hit capacity if we've in capacity and we're going to use the LRU eviction policy if we go over capacity we're gonna remove the least used item keep in mind we're going to need to know where what where that item is we need facts fast access to it we need to be able to get an item in constant time and we need to put an item in constant time these are our constraints for time complexity for space complexity we can go heavy with it and you'll see that this is kind of a space heavy approach which with event space here are the two things we need fast look ups and we need backs removals and if you've taken a data structures class have you've done any study on this you might be getting a light bulb in your hand right now when we reduce it to these constraints we know we need these things from this structure we're being asked to build so fast look ups what data structure can help us with that I think great thing my brain goes to is a hash table whatever we're trying to do fast lookups hash tables will allow us to use a set of keys where we can hash them and have fast lookups based on those keys and our hash function that we define we want fast lookups hash table okay but there's another problem how are we going to know where the least recently used item is the last item and how are we going to remove items quickly how are we going to do that maybe we could use a binary search tree that has elevate search time maybe we could use some other structure like an array so just start thinking through data structures in your head another thing that comes fast to my mind when I think of fast removals I think of a doubly linked list and this is for two reasons one if we have instant access to a doubly linked list node we can remove it in constant time because I can touch my next node I can touch my previous node and I can remove myself if it were a singly linked list I won't have access to my previous and it would take all event time to find my previous okay so doubly linked list that makes sense we're going to be able to remove in constant time and another thing is we're going to be able to prevent ourselves from having to resize an array if we use the linear structure like an array for this if we remove an item we need to shift all the elements over with a linked list it's just an abstraction of pointers and we don't need to shift items so it prevents us from doing linear work during resizing because we don't need to resize a linked list it's an abstraction of pointers between objects doubly linked list looks very good for this problem and a hash table looks very good for this problem and what you'll notice is this is a Araki pattern backing up a special data structure with the properties that we want backing it up with a hash table for fast access into that special property data structure so say we use a binary search tree but we don't want to spend all of each time searching we can back it up with a hash table so always keep this in mind that a hash table is very nice for fast lookups on a special property data structure our special data structure here is our doubly linked list and our hash table is our fast lookup thing that backs us up so now look at the approach you're going to take alright so what we're going to do is we're going to use a doubly linked list backed by a hash table we're going to run through a list of actions whatever we choose a node understand that a hash table is backing that fast lookup if we didn't have the hash table we would potentially do all event operations to find an item but we're just going to act as if we have a hash table to back us up and we're gonna walk through an example and also the code is in the description it is not my code but I heavily commented and reformatted someone else's code to make it very understandable and internalized Abul so that is in the description so let's walk through this example alright so we're going to walk through this list of actions remember we have constant I'm forget and in constant time for put operation the overall space we're going to use is all of n where n is the capacity we're going to evicted item if it goes over capacity and we're going to be storing an item so this is a space happy thing but at the same time to get fast look ups and fast flip operation so let's begin our capacity is 5 if we go over capacity we have vikt the least recently used item so what we're going to do is we're going to put 1 the key of 1 the value of 1 we're going to put that in our list so before we start anything we want to initialize our list with a dummy head and a dummy tail pointer so this is our initialize list we have a dummy head and a dummy tail or capacity is 5 our size is 0 right now what we're going to do is we're going to put the key of 1 and the value of 1 so we're going to put that into the list okay so now we have inserted 1 into the list and now our nesic it next command is put to 3 so let's insert to 3 into the list ok and now we had inserted to 3 so notice when we insert an item it goes to the front of the cache it is the most recently added or accessed item which is at the front and he notice the items that haven't been touched will slowly float towards the back and they're eventually going to be evicted we have these two eye so now let's add 3/4 okay so now we just so now let's add 3/4 okay so now we just so now let's add 3/4 okay so now we just added 3/4 again 3/4 goes to the front of added 3/4 again 3/4 goes to the front of added 3/4 again 3/4 goes to the front of our cache and now we have 3 4 2 3 1 and notice that the top-left corner is and notice that the top-left corner is and notice that the top-left corner is our keys and the sting inside is our value we look up by the keys so just keep that in mind so now we're going to add the item 4 7 so let's add 4 7 now we have added the item 4 7 again we added it to a front of our cache we have 4 key the key for key 3 key to key 1 this is our list and now we need to add 6 10 okay and now we've inserted the item to the front of our list notice when we put an item if it already exists we just update the value we have it add any values keys that already existed so we just add them to the list add it to the front of our list and now we have a get operation so we're going to get the value with the key 1 so we're going to retrieve this item and our hash table will allow us to do this in constant time we're gonna have instant access into our list without having to start from the front and traverse all the way up to the key 1 we can retrieve this item and it's going to move to the front of the list because it's just then access okay so we just access one who is at a tail a borderless we move it to the front of our list we have constant time insertion and deletion from our list or constant time removal and then replacement in our list and we also are able to quickly find an item with our hash table so now we've done this and now we need to get to the item with the key 3 doesn't exist and yes it does we know it exists in constant time so we move this to the front of our list okay so we just accessed three four and now reduce to the front of our list item with the key 3 so now yeah this is this we still are at capacity five we have not needed to exercise our addiction policy so our next operation is we need to put 1 5 we notice that this is the key already in the list so since it is already in the list we're just going to update its values but every time we interact with a node whether we update its value the foot or we get it we need to move it to the front of the list because it was just interactive anytime you interact with a node it was the front of the list so let's move this to the front all right so we updated the value of the note of the key 1 and we moved it to the front of our list the thing is you see these keys but in reality the hash table would be keeping the keys the notes would just be their nodes with their values we wouldn't need to keep the keys on their nodes we could but the hash tables job is to keep the keys this is just for demonstration purposes now we need to look the item 12 7 does that exist in the list no but does not is going to move to the front but we're going to go over capacity we're going to go over the capacity of 5 so we're going to need to evicted item what item do we evict we remove the last item the least recently used item which is sitting at the end of our list so we're going to have instant access to that item so we could just remove this item and then we're going to add this to the front of our list so let's do that so now we have just added the other 12 with the key 12 with the value 7 we've added it to the front of our list we are still at capacity 5 where then we're within capacity so we're going to put 5 to does 5 already exist in our list no it does not we're going to add it to the front we're going to remove our last entry which is the least recently used item we added the item to the front of our list and now we're still within capacity and now we perform our last operation and we're going to get the item with a key of 4 but the problem is notice that we just removed the item with the key of 4 so we're going to either return null return minus 1 whatever we want to do to signify an empty state and we are basically if finish we can't get the item 4 because it just was removed so this is how the LRU cache works this is what happens whenever we interact with an item that goes to the front of the list we want to remove the least recently Center entry and this kind of a temporal order of the usage of items and is very useful for certain things and remember the code is in the description I have commented every single line of that code walk through that code look through it's very intuitive it follows the same as our example and really let that let it internalize these concepts so it's in the description go check that out basically this is the video if you like this video hit the like button subscribe to the channel I'm trying to do videos like this every day to help prepare other engineers for the interview that's what this is about so
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
203
Jai Hind is the problem now to remove Samudra Notes from a single East West which does not indicate severe mode on words which has the value of two Souls with a result a very simple but want to give a great subscribe and subscribe the Video then subscribe to the Page as given to white to return new head it also possible development will want to delete is the beginning in that case it will be modified in the cases and will remain in the sign in which were produced for so they can keep for a Few Minutes Withdrawal Return Ise Know The Weekly Current Subscribe To A Surujmal Subha Match Current With Life Spent Effects Note SIM And Which Pimple Just Increment Very Apni Speed ​​Come Hair Serum Increment Very Apni Speed ​​Come Hair Serum Increment Very Apni Speed ​​Come Hair Serum Subscribe School Again It's Not Good To 40 Advance Very And Hadith Ka Note Listen Messages Text Message What is the Best Way to Make the Next previous12next Current Subscribe and What Would You Want to Avoid Advance 12218 subscribe and like subscribe and subscribe again I did n't match or job simple current victims previous and current welcomes it Next 9 units listen to messages 10 lakhs and that towards it's next that end current weak previous year only know when current is nulli stop so let's write you later this end return in the morning head to head even it's next to its next is this five days only one neck Point Se Zulfikar Next 25625 Share On This Channel Subscribe Button It's Not Be Modified On That Sanskrit Chapter Note MB Want To Delete All The Notes With Person In To Wheat This Is The Current Previous Year And Tap List Kal To 10 Ki Suvidha Not Right Previous Next Equal to Current Mix It is not by doing that they are current request or great value will make the Next Previous Point to the Electronic Sher Patel Previous in Al Saud 10 Science Notes Near Call Next Be Nirmal Pointer or Even in Another Language Video Next person point is not valid subscribe person subscribe share video and that and they also moved here positive special case that ganpati bsnl will move ahead in the previous year just once upon the current soayenge this current is the first not avoid one also Possible That They Have Three And Rehabilitate This Avadhesh Current Affairs In This Forest Confirm Bsnl Postpaid Bills Pay Yaar Hai Add Us Point To The First Note Supreme Absolute Simple Minute Current Is The Country First Night Hai So Just Make Direct Current Navdeep Singh On Previous This Channel Head is Hair Tonic Share It's Not Good To 30 Feet Soon Weak Again Message Don't Share and Current Weak Again Message Me Previous Next Current Ko Again Serum Share It's Not Match Speed ​​Come Again Serum Share It's Not Match Speed ​​Come Again Serum Share It's Not Match Speed ​​Come Hair Serum Se Naseer Vitamins Nau Let's Do Service To Song Start with it send list of effective channels of 2015 expected result improve gravity active le next 9 quit reply a flat se bhi hai poochna everyday one is the first not want to delete a flat se middle east and want to delete to hair Fall is the first world and mother case let's not a scenario where three take to 4 the heart to map ghost how want to delete for fat in one case for is the beginning in another case for not naming you desire to have every right wick Website In To-Do List Mode right wick Website In To-Do List Mode right wick Website In To-Do List Mode Of In Such A Situation Where To Return New Head Website In Every Village Equal Two Years For Ladies Toilet Quality Of The Main Function Love You To Write In Her Will Per Next To Friend I Am Single Well Soon This Will do this bill that were passing decent not too suite will remove all values ​​from twist and turn on their way and what we will do that is as well looted hu remove all values ​​from twist and turn on their way and what we will do that is as well looted hu is equal to well dat means he will be deleted in this case will return catch 136 Deleted hundred tips past tense 35 not equal to this will set the next to that a sandalwood written on and on that opposition is hair wear simply return water this value returns a sweet valid for every time way woman long atom district itself from the main function In Her Married People Can Call Thyself Turn On This Point mid-2012 Soul Turn On This Point mid-2012 Soul Turn On This Point mid-2012 Soul Set This Child To and subscribe this Video Please subscribe and subscirbe Atithi 21 500 E Ki Adivasi Ke Returning Back Sudesh 1558 Correct FlashLight Bodhivriksha Bana Activa Price A Super State Will Right Inch Plus app ki slabs kiss hai additional ek dum fit in the head the previous se channel ki and current is the head which improved to main body website Manoj ji ki is note dekhi is din aur life is very simple the previous years and why one should Meet the new current powder current and irresponsive of weather its current is that karan next9 left side subscribe this Video [ this Video [ this Video that equal to current next and current victims on current issues and white hair irresponsive of both dj looks husband pimple or two the previous Next Is Equal To Current Next President You Can Also Write In I One Line That And Finally Will Return Held On That Hindu Solution Accepted That Andher This Entry This Incident Rule A Synthesis The Best Audition Hips Or Investment In One Form Play List Not More Than Lord A 9 Day It's Rightful Level Just Difficult For All The Three Languages ​​National Difficult For All The Three Languages ​​National Difficult For All The Three Languages ​​National Take Much Time On Welcome Back To Record Solution Kar Do Mein Andhadhundh Voice Accepted Switch Like Share Aur Mili Da Ki Nav Laadu Sunth Pathal Kar Do Hua Hai Ke Andar Digestion Solution Jo Accepted Not Withdraw Request Code So That Will You Make A Copy Of This Key And Will Comment For This Key Equity Women Tension Jai Hind Desh Ke Shrimahant Same Effect Chapter But What Will You That He Did Not 900 Developed At All Beach Function To Remove All The Note From Well 159 Till Last Node Soviet Union Minute Instituted Of Head And Vein Vitamin C Vitamin Something Is The Head Of The New List From Which Has Removed All Dunu Safed Vihar To Senior Research Is Withdrawal Who Is Equal To Well Done in that case it will be removed so when we are moving ahead and fast food and were looking for second last not and removing all the notes key value well and did not exactly this is done in this case which can simply written much but I am Not hidden modified so it's next will be that jis hai don't like this remove elements call 100 which is first will return printhead for which this I am online for second is serial less jis call and pradeep first case when he did it well and will return from The Lips of Summit 10 Day Camp Superintendent of 10 Activations Shepherd Enfield Complete the Time This Sui Servi in ​​Mid Range and This Sui Servi in ​​Mid Range and This Sui Servi in ​​Mid Range and Transformation Switzerland Three Four Lines You Can Ride Singing in the 9th
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
905
Hello hello Abhi badi welcome to my channel let's all the problem sort of my priority to Hindus problem Governor J of negative in teachers and be happy return Ajay consisting of all divine elements of a god-fearing all the elements of a god-fearing all the elements of a god-fearing all the elements of you my return answer is Not satisfied his condition which can return and there are but all the even number of elements from directly comes first day or the number of element sorry for example here is 3124 directly subscribe the channel to three do you understand this problem is 200 will solve This problem using two point approach soft pointer will start from i 10 20 start the also appointment will start from the end of the year switch length and minus one extinct these are little i labs in a tomorrow morning a i will provide you all the even Numbers of the river rafting in the starting and dj trek order from this is not give the element how will solve this problem first form 2018 simply effective way that life 2010 simply increment i y one and it is not a patient will check balances pay bills for aids Hot Vilas Elements Of Baje Simply Decrease Chyavan Ne Ki And Defeated Notes And Decide For The Condition Between Means The Like Share It Is Life I Will Increase I Will Be Have Are It's Orders Will Decrease Will Have Sunao Infidelity DJ Hard Not Even A Leaf Take Note And soupdish to elements of not satisfied with all end case will stop dam will be based on element life will go to here and for welcome to have a strong will increase very the point unit-1 enjoy decrease y1 very the point unit-1 enjoy decrease y1 very the point unit-1 enjoy decrease y1 features will solve and ball subscribe button services 64 In The Subscribe Like And Subscribe To It's Straight Forward So Let's Clement Record Monday Roadways Bus Use This Point From Zoom Android 285 Voyeur FI Model Bluetooth Settings 108 Simply Ki Zidda Last Element the video then subscribe to the amazing spider-man 2 - - to the amazing spider-man 2 - - to the amazing spider-man 2 - - Subscribe button on left side The return typing biased and names were amazing This is the festival that sister update eggs with cinnamon friends tempo value subscribe school subscribe and subscribe the amazing elements are with both elements mix elements of obscurism hai 25 test cases getting 509 Or Episode 112 180 Runs On All Elements And Displaced And Space For This Problem Sell And Turn Off Street Light To Make Water Stream From This Like President Subscribe Answer Person Sorting Method A Pan Insulting Method Bill Gets A Two In Numbers In The Villages Returning Officer Doctor Molu Tubelight Models 2012 Will You Are Using Code To A Scientist Working Shop For Easy Reading Being Can Ride It Like This Will Put Away Like Subscribe And Festive First Media Directory In The Box From Midnight Used Cars Like And Subscribe My Channel Like Flirting Notification Videos Thanks for watching see you tomorrow
Sort Array By Parity
length-of-longest-fibonacci-subsequence
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
Array,Hash Table,Dynamic Programming
Medium
1013
509
hello now let's try another lead code problem number 509 Fibonacci numbers so this is a similar to the record problem number 70 climbing stairs yeah so for the first position F0 it is zero the second population F1 is 1. so for the next value it is f and minus 1 plus F and minus two and for this n model one yeah so it is n equals to 2 the first equal to 2 it means F2 equals to f 1 plus F zero so this is what we call Fibonacci numbers let's text the value of N and is the third thing yeah but we cannot use brute force we have to use a dynamic programming so here like the climbing steps uh climbing stairs the fiber nonsense number is also the same I'm going to Define two variables to represent the first value and the second value yeah so my first value will be first and the second value will be second so the first will be zero according to the Fibonacci numbers the definition yeah and then I'm going to use a for Loop so for i e ruins for adding units I should start formal n equals to 2 yeah and then it goes to n plus one yeah because I'm going to get this n value yeah it's n equal to 2 I'm gonna return a 1 if n equals to 3 I'm going to return a 2. yeah and then I can directly use the second then the first to have update my result so the second should be equals to Second plus first and the first this would be equal to the second in this way I can get my result so I'm gonna return the result so if uh more than and equal to one I believe it is okay yeah but here this I start from two yeah but here I'm going to return this second is this in more than n equal to 1 else I'm going to return a zero because if n equals to 1 yeah because n equals to 1 you know n equals to 1 the value is one but a equals to zero the value is zero let's check the N is more than zero yeah so if the second that is still one at the same so okay now let's submit it so there is only a little bit of change to this climbing stairs yeah because the starting point is different climbing stairs of the starting point is that is started from now let me submit it yeah the climate clears the starting point is from one but for Fibonacci numbers the starting point is from zero so this means this is why we're gonna use more than equal to one yeah it's the second and else we're gonna return a zero it's the first place as you can see yeah it is a pretty fast if you think this is a helpful please like And subscribe I will upload more list called problems like that bye
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
179
A fan welcome to learn to repeat studio is exactly date 25th September light change the name of the problems largest number gas cylinder from sada problem statements given a list of negatives an arranged times a day for the largest number blind returns with results also they Release That You Need To Return Nursing Staff And Teacher Solved Examples For The Time A Given In The Are Welcome To Back To Continue At Or Repairing And Contented With In Touch With The Results From Shirdi Brian More Pati 5210 Ko Subscribe To 200 Gr Input Stree 3034 Phase Output Tax Pay Condense 95 3430 Right The Highest Largest Number That Can Be Formed In This Combination Right See Relative Very Simple Logic Award Without Water Is The Highest Number Date Number Suit Less Prospects In This Is The Highest Number 90 Less On Pet 6 Days In The Water Between More But The First Digit Nationwide Check The First Taste Between 4 And Know What Is Life Is It Is The Richest Man In Difficulties Remain Hidden 96194 Fuel And Not In Context Which Is The Highest Peak At Night Show Fear Files With Highest Digit Between Against 3433 Fixed Deposit Is All There And Objects And Share It's 500 The Next Pending Character Balbir 50 Grams Between Guest Handsfree Which Is The Highest Peak Sexual Arousal And 3838 But If It 108 Number Canteen Max 3 Middle Age 234 376 342 323 341 More Benefit A Reply That The Number Which 5334 And Share The Number 10 Getting From History For Three Fit Third Floor And Create Servi To Do It Is The Time To Do Numbers Are A Little Difficult To Be Converted Into For Returning To Refill 30318 Previous Quid You Will Work for example and machine adhi 0 previous cancel disa friend hundred illegal air tight venture per 0381 more and at least 15 number 19 2012 president witnesses who can be contacted 95 subscribe phone number and 10 number also write and mother has been cases in Village Checking Which is Better Subject Company Which One is Better and Where 272 To Edit and Descending Order to Find the Largest Number 8 In the Morning to Check What is the Descending Order and Weekend Night Sitaram Going Right Amount to Compile Numbers Like Short and Using Computer for the Day you can convert into and subscribe a plus b plus c phone par temple bhi aadhi to convert 10 interesting reuters and lu 108 replacing are history are ko khol do the best seen phone numbers main pot me map do asubject ki singh the value of that Dot So Are 200 Grams Doing Research And Converting My Name S Pin Number Into His Team And The Making Of The Indian Touring Oily Food Basically From Jason To Convert 10 Interesting Or Andher Nagari And Trying To Convert Into A Tours And Creating New Singh Avtar Singh Swarg Into the no mint are using for loop and creating new string of tact and wedding and interesting are Shabd Lootere Constitution movie Satya-2 Doordarshan line halfing to movie Satya-2 Doordarshan line halfing to movie Satya-2 Doordarshan line halfing to multiple lines in more Anand Singh ki aapke knowledge set kiya right to compare also up and Bondar Singh saffron in With Bodh Options And A Plus B And Also Plus A Soul Will Do The Same Thing Air Cleaner Set At Less To 100MB Habit To Things Will Get Ka Safar Share Interested In Descending Order Will Be Plus And Compare To A Plus B A Ki Agar A Jhal Ka Ki Is Mirchi Ek Pad Singh Sign In Descending Order Ascending Order Second One B Plus Apps And Company British Petroleum And Descending Order 159 Are Sorted In Designing Model I Can Simply Join Barsingsar And Jitendra Singh Are Okay So The Can Do the return of the day that that that that I don't want to delete username a rehearsal test result ba court double quote and dashing are the soldiers do what character type time are now 1968 and zero in it largest digit right said that case After 22806 Will Visit Website And Difficulties In The Work To Return Us Zouk I Let Set The Condition Of That Safe 10 Day Organization 0 That If Solar Underscored Inch One Platform Status Facebook Final Submit That And Accepted For This Video Please Like Button And Subscribe Our Channel Features Videos Thank You
Largest Number
largest-number
Given a list of non-negative integers `nums`, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer. **Example 1:** **Input:** nums = \[10,2\] **Output:** "210 " **Example 2:** **Input:** nums = \[3,30,34,5,9\] **Output:** "9534330 " **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 109`
null
String,Greedy,Sorting
Medium
2284
905
hey what's up guys it's Nick white here I do tech encoding stuff on twitch and YouTube I playlist with all the hacker ink and Lee code solutions and we're doing the code sword array by parody basically what we do is we're given an array of integers and we want to put all the even numbers at the front in odd numbers at the end pretty easy problem it's like the easiest problem ever so here's the brute force solution that I thought of right away and then I'll show you the optimal one after so you just make a new array you loop through this array and then you do two loops the first loop you put the even numbers in the second loop you put the odd numbers then I don't even know if I want to type it out but whatever I'll just type it out you also need a counter to account for incrementing values two loops you do a check if a of I modulus two is equal to zero that means it's even we're gonna put those ones in first with counter is equal to a of I so we put the even numbers in first and then we put the odd numbers in second odd numbers remainder two is always one and then you just have to make sure you increment the counter on both times and then you can return the new array and this is a good solution for brute-force honestly it's solution for brute-force honestly it's solution for brute-force honestly it's not even that bad it's just that you have to use space in the optimal solution doesn't use space you don't return to counter sorry in return so yeah this just uses an extra array to put them new values in there we go worked all right literally the optimal array hopefully get that you do a loop through you only put the even numbers into the new array you forget about the odd numbers and then you do and move through and you forget about the even numbers and you only put the odd numbers in the array there you go easy super easy let's do the optimal solution this guy described it as a quicksort kind of thing I don't really see it as that you just have a two it's more of a two-pointer solution you have a pointer two-pointer solution you have a pointer two-pointer solution you have a pointer at the beginning and you have a pointer at the end it does do swapping so that I could see where it's coming from with that you just do while I is less than J if a of I modulus to so if it if am by modules to is greater than a of J modulus to well that means that this is gonna be this would be one and then this would be zero meaning an element at the beginning is odd in an element at the end is even if this condition occurs and if that's the case then we want to swap because we want all the odd elements at the end and all the even elements at the beginning so we just do a swap I mean hopefully you understand that it's not that hard temp is a of I AJ is equal to a of I know a of I is equal to a of J sorry and then a of J is equal to temp there we go that's the swap once again because mod an element a number modulus two if it's zero then that means it's even if it's one it's odd so if it's one greater than zero that means we found an odd because the I is at the beginning we have a beginning boundary and an end boundary and we're moving towards each other we're moving inwards and when we see an odd number at the beginning and an even number at the end we just want to swap because we want the evens at the beginning in the odds at the end and how do we handle we do the swaps here if we see that and then how do we keep moving our boundaries well we keep moving our boundaries if we know for a fact that a of I modulus two is equal to zero because we know that this element at the very beginning index is four in fact even because we do this check so that means the element at that is even and we can just move our boundary forward because we're good on that even element if it's at the beginning we're good we can just move it forward check more elements make sure those are even same thing at the end if we see an odd we're good dude we just can keep moving that boundary inward so I just want to do a check not a of ia of J percent of two because J is the ending boundary then we just decrement J that's it this is a more optimal so and you have to return the array it's in place here's returning the same array and this is it this is the optimal one you attempted to do submit too soon but that's fine we'll just do a run thing and then we'll submit again but this is the optimal solution because you're not using space and we're still doing it's the same runtime as the other one not using space so there you go this one's better just remember two pointers I guess I always keep those in the back your mind and thank you guys for watching please check out my other videos and yeah thanks I'll see you guys next time
Sort Array By Parity
length-of-longest-fibonacci-subsequence
Given an integer array `nums`, move all the even integers at the beginning of the array followed by all the odd integers. Return _**any array** that satisfies this condition_. **Example 1:** **Input:** nums = \[3,1,2,4\] **Output:** \[2,4,3,1\] **Explanation:** The outputs \[4,2,3,1\], \[2,4,1,3\], and \[4,2,1,3\] would also be accepted. **Example 2:** **Input:** nums = \[0\] **Output:** \[0\] **Constraints:** * `1 <= nums.length <= 5000` * `0 <= nums[i] <= 5000`
null
Array,Hash Table,Dynamic Programming
Medium
1013
1,041
Solution of welcome to line ko dp today will be looking at the 17th september 4 inch dignity problems robert appointed in circle that electric power member problem statement and internet play arrow button she stands at 0 and a not-for-profit can deceive stands at 0 and a not-for-profit can deceive stands at 0 and a not-for-profit can deceive 93 equipped and Juice For Growing State Government Has Power To Individual Left Hotspot Turn In A Bid To Right And Robert Form From Instructions Given In Order And Feed Them For On The Return To In The Juicer Pulanda Prince Incomplete But Never Leaves Government OK Plastic Deposit Jampur Pure For Example Benefits LG TV and Skimming Go Straight One Important Part in the Google App Hotspot on Instagram Tubelight Initially Dev Mention The Robot Will Be Facing Towards North It's Not the Best Dressed of Units 8090 Position Shri Akal So Let's Complete a Plate Segment First CNG and Suresh Zee First Indian Manmauji How To Take Two Years Not Moving The Less Par Tannin Tears Left A Reporter Ne Yaad Left One Time Andar Naagin1 Morals of Citizens in This Regard to the Left to Promote and Not Present Address Outside in the Rain of Terror Activities and Again but sweet full move is one unit then it is to mobile in the south again 10 minutes till sahu deficiency of vitamin e came back to the journey to develop camera and subscribe the robot is not specified time can go in any direction should be north to south And West Side Subscribe Now To Right In This Luthra See The Same Condition Is Repeated Multiple Time Right That Is Going Students Appear Again Exhausted And Light On Rights Sexual Ride In The Night When Ur Right In The Right And Left Side Su Agnikul This End Its Rear Address Center Private Do Holi Condition Where Its Boundaries Pizza From Going From Ujjain To Words North Fuel Action Against Him Going To Month And Right Banayenge Singh Aka Sintu Not Only And Condition No Matter How Many Times Repeat The Same Step I Will Never Go Back To the original vs goku in direction welcome to cigarette surya robs north soeb shaikh you and in opposition and direction as a majority in the juridiction of 101 after 10 top before singh to the north direction din i will never return to my recharge no matter How Many Times By Repeat Distance Id That And Define The Singing Time Direction Writer Day Opposite 10 Top 100 Times Will Come Back 2014 Times For Example Night Agro Tech Left For Developing Is Revolutionary Feeder Separation Magan Member First Step Naagin And Ko Straight Typical Of Drug Abuse Shetty's Left in the Guys and Techniques of Free Storage Nagari Swimming Phone Number of Seats Available to Reach Two Regions Back Side Slurry If You Sir Item Take Any Other Condition If the First Day of the Giver Number of Instructions from Any Direction Which Knocked the Right Direction Subscribe To 200 Gr What We Have To Is Back To Go To The Input 101 And Visited Key From What Is The Direction And What Will Be The Direction Of His Family Is In Noida And Right Yes Verma End Points 08 Channel Subs Possible Lights Of Example Subscribe 280 facing the north and west sudhir water from the same direction middle aged person condition jobs notification president dhaneshwari control and darkness starting direction witch gives you not slow serpent every temple run alarm set the logic siya initially in 10 given and direction smart dip they Provide the instructions from sleeping and instruction soft each character of checking the character juice for going for rent in your stride in correction is the meaning of the name of side access will increase corruption shyma direction from moving the best direction is decree that similarly a great Dan Shambo Mintu Left Side In This Current Limit Direction North Right Sleep From North The Left Side Us West And Right Side Effects Of Medicines For Benefits Left The Journey To Go To The Best Practices And Similarly There In The Laptop If you are not subscribed then friends Please subscribe to the RSS feeds and links with me to the channel to subscribe to the video so let's give the code and notices stand that Android details or 68 per cent from nh20 made servant this sample Udham Singh it's medium Radhe-Radhe this sample Udham Singh it's medium Radhe-Radhe this sample Udham Singh it's medium Radhe-Radhe Brazil Walnut Number 90 Stand And Direction Us Ashraf-ul-Haq Selection Please Direction Us Ashraf-ul-Haq Selection Please Direction Us Ashraf-ul-Haq Selection Please Friends Like Button And This Video Channel And Have Any Questions Please Like And Comment Section Thank You Jhal
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
35
Hi everyone my name is Rahul and today the lead code problem we are going to solve is to search the insert position of the element in an array. We are given an array and we have to find out if a target element is present in that array. Does it exist or not? If it exists then its position has to be returned. If it does not exist then we have to tell at which position we can insert it and the one note in this is that our array is sorted. In the form let's see the problem statement st OK so here we can see true insert position given serd are of distinct entered serd is di target value returned the index i target found is not returned the index r it would be if it were inserted In these orders, we have to tell its position. If the agent does then also the position has to be told. If the agent does not do then we have to tell the position. We can fit it in which order. If the target is five right then its position is to return. If the target is two then its position should be one because after one, if the target is seven then its position should be right from the last one. The number which will be one is in the array, so we want to tell it the position index, so this array is always from zero. When it starts, the logic involved in it is because the array is sorted and we have to find that element, so how much will it take to achieve it in A. B is sorted and linear search will be done but we will apply binary search in it. If we want to find it out, then let's start, we will take a start index that will be zero, b and end index, which will be our w, whatever is the length of our array, starting from minus g. And we will run a loop - start is not And we will run a loop - start is not And we will run a loop - start is not equal to end and the loop will run until start is not equal to end. In this we will take out the mid index. What we do in the search is take out the mid index and then check that the target is in your mid. If it is not equal to the index, then it is not equal to the middle element. If it is not equal, if the target is greater, then we search for it in the right column. If it is smaller, then we search for it in the left column. What will happen? We start with this. t and minus t and this we divided by u so we get mid index. Okay, now we check the condition if target is equal to mms made index. If it is equal then simply return that. Return mid index. Will do TL Safe Target is greater than mid index Sorry, what will you do if the target is greater than your element, if it is greater then you will search for it in the right sub array and its start index will change and the end will remain the same. The right one is st, what will become of it, we will make a 'd' in the mid index, ' make a 'd' in the mid index, ' make a 'd' in the mid index, ' t' plus and similarly, if the target is smaller than the given number, if it is small, then the end will change, the start will remain the same, and what will become of the mid index, it will be minus, and it will be fine ] ] ] And if nothing is found in it, then the condition that will be created in the last and start will be smaller than our end and whatever is our index of start, we will return it. Okay, in this we will see by running draw. Okay, first make it acute. Let's see how the right three are accepted, so let's do one thing, let's do a dry run of it, okay, we take the value four in it, let's target is our four, which does not exist in it, and K should come and should come here, okay. So in starting the start key value is zero and the key value is four array so it will be one mid key value will be 0 plus and 3 minus 0 divide by 1.5 so one comes floor value 1.5 so one comes floor value 1.5 so one comes floor value is ok so what will be the number of one One will become your street number, it is yours. If tr is not equal to ff then he will not go in it but what is your target. If 4 is greater than the number rat then you will see him in the tree on the right side. If you look in Sabre, then here If we go to the right side, what will happen if we go to the right side? Start will change. What will happen in the middle? What was the beginning? What will happen? What will become of the end? What will happen? Will remain again we will count right to mid ho jaaye hamara start is two plus 3 might is 1 divide batu if to whatever is the value of start the same will remain number hamara kya ho [ number hamara kya ho [ number hamara kya ho will go number hamara ho gaya two hai na to two What is the value of f? So what has happened now? The target was four, so now the target has become smaller, so now it will come inside the target. If our target is small, then the start will remain the same. Start and end will be the same. What will be the mid index minus then my? Now how much is the middle? Well, the middle will not go there because now the value of the start is no longer less than and equal to the end. The start became bigger than us, so what did we do in that case. Return the start, so we return the start's value to. So now where will it come to exist four tooth fo four should come here you at two position so this is zero position or one position is two position p our that will come four element will come okay tut target if there is four which does not exist then its We have run the draw and we have to return the value of start but in that case only this condition will fail and last and we will be left with the value of st in its inner position lerrat so let's submit it is accepted ok so I hope you like the Video If It Is Helpful For You Then Please Like Share And Subscribe The Channel Thank You
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
1,332
hello guys welcome to algorithms made easy today we will be discussing the question remove palindroming subsequences in this question we are given a string s consisting only of letters a and b in a single step we can remove one palindromic subsequence from s we need to return the minimum number of steps to make the given string empty a string is a subsequence of a given string if it is generated by deleting some characters of the given string without changing its order a string is called palindrome if it is one that reads the same backward as well as forward in the first example we can see that the string is already a palindromic string so we can just directly delete that and the output will be one as we needed one step to make the string into an empty string now in the second example we need two steps to convert this string into an empty string now first we can delete the 2b which creates a palindromic string and then only remaining thing is a and we delete that we can do the two steps in any particular order in the third example we see that the string is not a palindromic string so we find the palindromic string that we find is baa then this b and we delete that and the remaining is only one letter b so we delete that two and the output is two because we need two steps now if the string is already an empty string we directly return zero the constraints given with the problem state that the length of the string can be between zero to one thousand and it can only contain the letter a and b now this constraint is pretty important to solve this particular problem and we will see why before jumping to the coding part let's see how we can solve this problem so suppose this is the string given to us and we need to find how many steps will it take in order to convert this string into an empty string so we see that this string is a palindromic string so if the original string is a palindromic string we will need just one step to convert that into a empty string so let's keep that aside and now we have another example with us in this case the original string is not a palindromic string so there can be two cases if we see those two cases we see that a is a palindromic string or bbb is also a palindromic string and we can perform the two operations in any particular order in order to convert this particular original string into an empty string so we took two steps to convert this string into an empty string so the answer is two now what about the string which contains only one character so all the strings which contains only one character are already a palindromic string and will fall into the category where the result is one when we see this problem as a whole we find out as there are only two characters that are allowed in the string there are only three values that are possible in this case that is 0 1 and 2 0 in the case when the string is empty one when the string is a palindromic string otherwise all that is left is the answer will always be 2. so now let's see how we can code this so as discussed we will check if the string is blank if it is a blank string then we can directly return 0 now we need to check if the string is palindrome or not if it is a palindrome then we know that the answer would be 1 otherwise the answer will be 2. now we will implement this s palindrome method you can always use the reverse function of the string and compare the two string to find it is a palindrome or not but that requires an extra space so we won't be doing that here we will implement this s palindrome method which will return true or false so in this we have a left pointer and a right pointer and now we loop till the left is less than the right pointer we check if the character at the left is equals to the character at right if this characters are not equal then we are sure that it is not a palindromic string we can directly return false from here we will increment the left pointer and decrement the right pointer and at the end we are sure that the string is a palindromic string so we'll return true so that's all that we need to code in this particular problem when we run the code for all the test cases we get the right result let's submit this so it got submitted successfully the time complexity is of n while the space complexity is of one thanks for watching the video see you in the next one
Remove Palindromic Subsequences
count-vowels-permutation
You are given a string `s` consisting **only** of letters `'a'` and `'b'`. In a single step you can remove one **palindromic subsequence** from `s`. Return _the **minimum** number of steps to make the given string empty_. A string is a **subsequence** of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does **not** necessarily need to be contiguous. A string is called **palindrome** if is one that reads the same backward as well as forward. **Example 1:** **Input:** s = "ababa " **Output:** 1 **Explanation:** s is already a palindrome, so its entirety can be removed in a single step. **Example 2:** **Input:** s = "abb " **Output:** 2 **Explanation:** "abb " -> "bb " -> " ". Remove palindromic subsequence "a " then "bb ". **Example 3:** **Input:** s = "baabb " **Output:** 2 **Explanation:** "baabb " -> "b " -> " ". Remove palindromic subsequence "baab " then "b ". **Constraints:** * `1 <= s.length <= 1000` * `s[i]` is either `'a'` or `'b'`.
Use dynamic programming. Let dp[i][j] be the number of strings of length i that ends with the j-th vowel. Deduce the recurrence from the given relations between vowels.
Dynamic Programming
Hard
null
134
hello everyone let's look at gas station the problem statement is there are un-gas stations un-gas stations un-gas stations along a circular route where the amount of gas at station i is guess i we have a car with an unlimited gas tank and it used cost i of gas travel from station i to its next station i plus one we start the journey with an empty tank at one of the gas stations we need to determine if we can travel around the circuit once in clockwise direction if we can we return the starting gas station index otherwise we return active one let's look at example one for the input the gas array is one two three four five the cost array is three four five one two the output is three starting at station three as index three and we fill up with four units of gas in the tank we have four then travel to station four our tank has four minus one plus five that's eight then travel to station zero our tank has a minus two plus one that's seven then travel to station one our tank has seven minus three plus two that's six and then travel to station two our tank has six minus four plus three that's five and then travel to station five the cost is five and we just have enough gas to move back to station three so we just return three as the starting index one straightforward solution is to simulate the drawing process index by index and see if starting at this individual index will make the circular travel basically we need two layers of loop outer layer loop is our start index an inner layer loop simulate the driving process and see if the inner loop index can reach back to outer loop index however this is pretty much a proof solution having two layers of loop will make the time complexity o n squared can we do it better i think we can first let's look at our guess array and clustering again i think we can check if the sum of the gas array is less than the sum of the cost array that means the total gas is less than the total cost if that's the case we can confirm there is no solution we can simply return negative one let's look at the code you and then we compare total gas and total cost if total gas is less than total cost we simply return negative one because we won't be able to make it happen when we loop through the array if we use guess i minus cost i then the value we get is the leftover guess and then we can get a new array let's call it leftover array this array represents its journey what is the leftover gas in the tank and we won't make the corresponding journey if the value is negative let's look at example one what would be the leftover array it will be negative two three and then we can simply loop through this left over array to simulate the driving process by adding them one by one and we get the current gas value in the tank let's look at the code by adding individual left over i together we get this current gas this represents the current gas in our tank if this value is less than zero it means it cannot make it to the next gas station it means we can certainly not start from here and we need to start all over by reset this current guess value to 0 and reset our start value let me say this again for a start index the leftover start must greater or equal than zero we must have this condition because we cannot start from a negative value in the leftover array because we won't be able to make it to the next station and every time we add a new leftover value i to our current gas we are actually stimulating this driving process we keep accumulating this current gas value for current gas value turning from non-negative non-negative non-negative to negative the index i in the left over this value must be an active value because adding this value to our current gas it makes all previous accumulated positive value useless so we need to reset our current gas by starting over so basically we need to redo the accumulation and make sure this current gas should be a non-negative value and also should be a non-negative value and also should be a non-negative value and also our start index should be i plus 1 because at any point be between the previous start and i it won't make the current gas value positive again because of this big negative left over i and in the end we can simply return our start let's try to submit in past before we look at the complexity i think we can optimize the code a bit by consolidating these two for loops you to look at the whole code again this total gas will be used to determine there is a solution or not and this current gas represents the current leftover gas in our tank as soon as the value is less than zero we need to start over and move our start index let's look at the complexity here it's constant o of one for time it's also o n because we only have this loop once if you have any question please leave a comment below thank you for watching
Gas Station
gas-station
There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`. You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations. Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique** **Example 1:** **Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\] **Output:** 3 **Explanation:** Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 4. Your tank = 4 - 1 + 5 = 8 Travel to station 0. Your tank = 8 - 2 + 1 = 7 Travel to station 1. Your tank = 7 - 3 + 2 = 6 Travel to station 2. Your tank = 6 - 4 + 3 = 5 Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3. Therefore, return 3 as the starting index. **Example 2:** **Input:** gas = \[2,3,4\], cost = \[3,4,3\] **Output:** -1 **Explanation:** You can't start at station 0 or 1, as there is not enough gas to travel to the next station. Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4 Travel to station 0. Your tank = 4 - 3 + 2 = 3 Travel to station 1. Your tank = 3 - 3 + 3 = 3 You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3. Therefore, you can't travel around the circuit once no matter where you start. **Constraints:** * `n == gas.length == cost.length` * `1 <= n <= 105` * `0 <= gas[i], cost[i] <= 104`
null
Array,Greedy
Medium
1346
133
Jhaal Hello Guys Welcome To Your Sons Delhi Today Financing Village Problem Statement Seervi Appointed Tax Return Adheen Kar Do Note Hai Day Give To Write Note Withdraw In Vwe Raw Ko Adjust End For Everyone He Binttu Again Call The Key Cloning Write Method Over Two years old at particular value hai loot day graph a large increase new note Uttar Pradesh will work paragraph with her no like button code and subscribe to and hear loot hai settle ke per time limit exceeded extraction to vote beam does not take into consideration subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe to main to itna take this house map of MP3 hua hai to definitely the value of a node and used to all the best not to let you know relation with a well None s for half an hour to call the winner of a gift contest subscribe I have invented directly previous liquid and created nor will be the date of birthday to you in novel in this code on this video do the proper result December 10 and Nor Apna Taken Into Consideration for MP K co-ordinated and subscribed the loot liya it successfully related Thanks for watching c ne student ki a
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
279
in this problem we have to find what is the minimum number of perfect squares who whose sum is equal to a given number for example if we have a value of 20 this is our input then we can break it into 16 and 4. 16 is the square of 4 and 4 is the square of 2 so both of these are perfect squares so here the answer should be 2 what is the maximum number of perfect squares that can add up to this it can be the number itself since 1 is a perfect square 1 square is 1 so you take 20 times 1 plus 1 20 times so it will be 20 so maximum is this value what is the minimum the best case is when the number itself is a perfect square for example it's 25 then we know that it's 5 square so best case would be 1 and the maximum value will be the number itself n so in most cases our answer will lie between this range but both of these are inclusive so our answer will be one of these values so how can we find this minimum value so let's uh take an example here so let's say we have a number 13 so we know that we can break it into a 9 and 4 9 is a square of 3 and 4 is the square of 2. so how did we arrive at this so if we are given a number we will see that it will break into squares which are strictly less than this or if it's a perfect square then we will return one so we have to keep track of what are the perfect squares below this value and how many such values can be there it can be root n so uh 1 square would be 1 2 square would be 4 3 square would be 9 and if we see 4 square it overshoots this value and what is the square root of 13 it will be three point something so you take the integral part of this so there can be at max root n perfect squares below this given value so what we will do uh we will see that how can we break 13 so we know that the perfect squares below 13 are 1 4 and 9 so there are three possibilities whether one is in the solution or not so if one is in the solution then this will denote that we have added taken one so we our count becomes one and then the remaining value will be 13 minus 1 that is 12 and if 4 is part of the solution there can be multiple occurrences as well so if 4 is part of the final solution then the remaining will be 9 we have taken 4 so remaining is 13 minus 4 or 9. next whether 9 is part of solution or not so if we take 9 the remaining will be 4. now we have to solve what is the minimum number of perfect squares which add up to this so again uh below 12 these are 1 4 and 9 so if we take 1 it becomes 11 if we take 4 it becomes 8 if we take 9 it becomes 3 and here it will be 8 then 5 if we take 4 it will be 5 and if we take 9 then it becomes 0 for 0 means that we have reached a value so this denotes termination next for 4 the values less than this are 1 and 4 itself so if we take 1 it will be 3 if we take 4 again it's 0 so we it's a termination condition and here we will see that we are starting to find some repetitions 8 is here it is here also 3 so we will solve this multiple times here again the values less than 8 will be 1 and 4 so it will have 2 branches seven and four here also it will be the same thing similarly for three so you can naturally see that we have broken the problem into smaller problems and we are having repeated uh overlapping solutions so we will use dynamic programming here and we will solve the problem bottom up so for solving any value we need a value less than this all these are less than this since we are subtracting some perfect squares and these will be some positive values so if we subtract some positive value from this these numbers resulting numbers will be less than this so uh if we solve smaller values before reaching a larger value then we can get it in get it done in how many times we need root n comparisons so if we are trying to find for how many perfect squares we need to make it n then uh the perfect squares less than l will be root in perfect squares like this uh perfect squares less than 13 are three because root of thirteen is three point something so if we take square root of four it will be more than this so for nth number we need root n comparisons because smaller parts we would have already solved so for one it will be one for two it will be two for three it will be three for four it will be again one its force 2 square then similarly lets solve for 5 can be broken into 1 and 4. so if we take 1 it will become 4 if we take 4 it will become 1 we will see which is minimum 1 we have added so the value for 4 is 1 so the solution for this is 1 and this is also 1 so both minimum of these will be one plus one for this branch two so solution for five is two next we have six again two branches two squares are less than 6 so 5 and 2 so for 2 it's 2 for 5 it's 2 so for 6 it will be minimum of 2 and 2 which is 2 and then 1 for this value so for 6 it will be 3 then let's solve for 7 again 1 and 4 which is 6 and 3 it's 3 here for 3 and for 6 it's 3 so for seven it will be four then for eight one and four which is seven and four for four its one so naturally we will take this so we take one of four and another for four it's one so for eight the solution will be two next for nine it's a perfect square we will get one of the values as 0 so we will end here so for 9 it will be 1 for 10 it will be 1 4 and 9 we will subtract these so it breaks into 9 six and one so for ten it will become two minimum of these plus one for eleven one four and nine ten six and two so it will come out to be three for six uh for two it was two and then one so three similarly for 12 and finally for 13 we have broken in into three branches so we take the minimum of these we will not expand this since we have already solved it before reaching 30 so for 12 it's 3 so 12 twelve will return three nine will return one and four will return one so we take minimum are these two any of these so we know that we have to take 1 4 and 1 9 we don't need the exact values we just need the count so minimum of these three will be one and one for this branch which is two now let's take another example let's take 12. so less than 12 what are the squares one four and nine so there will be three branches corresponding to each and here it will be 11 remaining here it will be 8 remaining here it will be 3 remaining for 3 let me write the solution for 3 the solution is 3 for 8 the solution is 2 and 11 the solution is 3 so we will pick this branch we will not pick these branches so here the solution is 2 and 1 for this four so total it will be three so for twelve it will be three and the answer would be one is this four and eight will be broken into four and four so this is the sol solution for 12 but we just need to return 3 so what will be the time complexity here so we will be solving for each number from 1 to n or rather 0 to n and for solving kth number k we need root k comparisons for n we will need root n comparisons similarly for 1 root 1 that is 1 comparison and constant also here so it's the sum of root 1 plus root 2 plus root 3 plus all the way up to root n so what is this time complexity as some simple estimate would be to uh this is n numbers so take the highest one so whatever is the time it should be less than n times root n we have taken the maximum value other values are in fact less than root n so time is strictly less than n times root n that is n raised to the power 3 by 2 or n raised to the power 1.5 or n raised to the power 1.5 or n raised to the power 1.5 so it is better than n square but its more than order n and another way would be to think of integration so take integration from 0 to n and root x dx so x varies from 0 to n this is in continuous domain but just for approximation we can get some bound so this we are adding all the square roots from 0 to n so it will be integration of this will be x raised to the power 3 by 2 since it's x raised to the power half so we will add plus 1 and then multiply by this divide by this so dividing by 3 by 2 means multiplying by 2 by 3 plus some constant so take 0 n so roughly or 2 by 3 times n raised to the power 3 by 2 and minus some constant will be there so you uh again it's a rough estimate uh not exact you can solve it what should be the exact a more tighter bond but roughly it will be less than of n raised to the power 3 by 2 which is better than n square but worse than order n so let us write the code for this so we are using dynamic programming so we will keep the solutions from 0 to n minus 1 before solving n so we are using one more since some of the branches may terminate on if the number is perfect square then you see here 0 coming in so for 0 we will return 0. then we will start solving from one x less than equal to n plus x so we will solve for all values from one to n then we have to see which is the minimum so we will finally be putting this min val in the solution corresponding to x so worst case would be x itself take all ones so this is the upper bound it will gradually improve so let's check the all the squares perfect squares less than x so let's take y equal to 1 and its square is again 1 square of 1 is 1 so while square is less than or equal to x we will do min val equal to min of minwell and one plus if we include this square term then remaining value will be x minus square and we have added one since we have included this square so whichever is minimum and then we need to increment this y and nu square will be the square of y so square is always the square of y and finally this min val will contain the minimum for which branch we got the minimum value finally we return the last value that is another value which we are solving solution is accepted and let's look at this we are around 73 better than 73 of the accepted submissions now let's do this in java and not much change will be required here and here the time complexity is even better it's around 86 percent of the accepted submissions and finally we will do it in python 3. and the python solution is also accepted
Perfect Squares
perfect-squares
Given an integer `n`, return _the least number of perfect square numbers that sum to_ `n`. A **perfect square** is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, `1`, `4`, `9`, and `16` are perfect squares while `3` and `11` are not. **Example 1:** **Input:** n = 12 **Output:** 3 **Explanation:** 12 = 4 + 4 + 4. **Example 2:** **Input:** n = 13 **Output:** 2 **Explanation:** 13 = 4 + 9. **Constraints:** * `1 <= n <= 104`
null
Math,Dynamic Programming,Breadth-First Search
Medium
204,264
835
Jhaal Hello Hi Guys Welcome To Code Virus Today's Question Is Image Overlap In This Question B312 Images And Being Replaced The Same Size Translate The Images Left Right Up And Down Is Number Of Time And Placid On The Top Of The Tree Of Life Is Translation Number Opposition In bodhi images to return to find mention in which can be possible for example a giver is that health maximum overlap impossible feminine hand 30 slide in village side where to right one position and when will slide2 that they slide one down by one position the result Matric Result Will Be Formed When Will Place That Matric N Be Matrix In Three Lines Then One Will Co On Side Subject He Answer Is 3 Ka Nash Extinct But This Translation Means Like This Is Position Fat Matrix Don't Means The Reader Pro Is 5250 Download One Position And They Do Not Have Laid Down There Last Not Stop When Every One Roof Top Most Of The Worst Position Is Not The Original Position Welcome To Third Position Subscribe To That Similarly Waste Everyone Will Be Shifted About One Position And The Lowest Problems 0 Simran Rights After every problem will be shifted to right one position and right most column and left most column Vikram ji phone like this aur sunao let's look at this app which now let's look at you approach will be using BJP will win combination approach them approach music dot matrix Is Not Supposed To Be Given To Make A And B Depend Only Butter Matrix Will Be Given Notice Dot Means Multiply This Element With This Element Which Element With This Element That A This Element With This Element And Combining Dependent 10 Results No Buddhi Was Not Built Between Two stations will give the day that number of research number of overlap ingredients means department of this to make this gives one which means to make this only one religion is well over lapping is taking place which is reduced due to the daughters and different translations for help In Riching Nobody Will Be Transformed Into Abeer Which Will Have Bhi Nawab Hai Continue Matric Aur Badhar Size Big Boss Details Which Will Be Formed Ise Blend 3 Minus One Hand 800 Management Where Is The Length Of The Matrix 9 In This Module Activities From Which Attach it in IT 331 Free Pathri Represents The Represents Of Transition Like This Channel top-left Top Left Corner Represents top-left Top Left Corner Represents top-left Top Left Corner Represents Video Which To-Do Translates Video Which To-Do Translates Video Which To-Do Translates Into A Me Apply For Mehndi Tattoo Removal Don't Be Matrix D Result Metric Will Be This Matrix Ninth Will Develop This Matrix This Colonel Vidyalaya General Will Get The Region Where Overlapping Swindon Similarly E District Up Is This Matrix Can Be Formed When Arabic Matrix Andar Ghosh2 Don Electronics And Similarly Now This Matrix Will Also Be Your Life With The Matrix Nak Pre-Matric G Hall Matrix Nak Pre-Matric G Hall Matrix Nak Pre-Matric G Hall Matrix Which Contains Every Point Acid Contains All The Missions Idea Possible To Give Transmission Oil Transmission System Combination Of Combination Conditions Will Stop This A Life Of Computer Result Subscribe To The Hunt For Its Clients Will Start The Results And Will Return The Maximum Result Swift And Fertilizers in this case Jai Hind in this case and maximum slice will be from maximum answer will win from this is a so I will keep there approach will it will have converted you also matrix in to difficult matrix and original BP matrix is ​​false In the middle of this new matrix is ​​false In the middle of this new matrix is ​​false In the middle of this new matrix A noble straight through this matrix hand will take slices Outfits will be equal to the length and width of a matrix $50 length and width of a matrix $50 length and width of a matrix $50 destroys all the middle east and written in the middle of nowhere first will start the size of variable to No from the ho that this length will be three to one minus one as discussed earlier and it will also be equal to three to one minus one to a hundred in systematic zero no person film original bhi matrix however when we met *discharge matrix with distic These met *discharge matrix with distic These met *discharge matrix with distic These are matrix and listen also put form beginning also matrix and this is also matrix MP3 that diesel that will take off but trick for putting a sweet is LMB on matrix V that i plus and minus one to z plus that and minus one is equal to two Ki Bewafai Dj S Mere Mobile Fan I Plus And Minus One J O Ki Bigg Boss In And In Been Pad Matrix Bhi Original Bhi Artist 15160 Plus And Minus Under-20 Plus To Start Plus And Minus Under-20 Plus To Start Plus And Minus Under-20 Plus To Start With J Plus 2 And Row Point Of View And Kollam To Avoid Start From Zero Plus And Minus Under-20 Plus Two Cigarette Swift And Minus Under-20 Plus Two Cigarette Swift And Minus Under-20 Plus Two Cigarette Swift 10 Plus And Minus One Nine Light Bill Is Truly That Migrant Layer Here And They Will Tree Was Still Here And No Veer Who After 10 Loop Haze Arabic Middle This Point Matric- Metric Nobody To We Are We Will Matric- Metric Nobody To We Are We Will Try To Website Metrics And Will Take Every Combination Of Three To Three For This Christmas Into Consideration And Will Overlap Average Life 323 Are From This Corner And Unleash Your Metrics And Will Be Good Thought Word And Defeat Maximum Value Update Product With Its Price Will Be Don't Like You Have Got From This Like 0 Got From This Life As One Sports Activity In This Will Be Maximum Ki Suno Vo Till When Will Have To Cigarette Oven Matrix So Suppose You Have Equal To Two The life will be formed will be from this index childish next 9 import 123 slices 100 index is but on like 125 slices which will be formed will be from this end Back To Rate Na Main 222 - 102 - Dr - 148 Last Updated On That Now Desh Dimension And Honor Slice Will Increase From To In The Past Lives Will Go Out Of Bounds And Will Give One Time If Chutchi Pin A Bond Will It Rain Donor Bhi Pet Matrix Still In IPL 2018 Sexual * * And Minus In IPL 2018 Sexual * * And Minus In IPL 2018 Sexual * * And Minus One Plus This Point Which 10 To * And Minus One Z This Point Which 10 To * And Minus One Z This Point Which 10 To * And Minus One Z Plus That Nor Will E Will Always Love This Light Bill With R That He Matrix For Overlapping Evils E Will Define Annual Function And Will Give As guddu overlapping updates lies with matric inter result that he loot e will pass the matrix deposit matrix yes bhi palat mam deposit that in tie print like a this which hair in g island st starting office light setting 120 nice and what we have got From This Overlap Wife Complains From Her Previous Maths Answer Has The Messes And Will Return Are Maths Answer A New Will Live In Torment MP With Phone A Novel Writer Overlap Function Vitamin E Don't Know That It's The Matrix With His Life In The Matrix The Function Of Romance Kardiye matrix depend matrix and action virus in the representation stop this is not wilson loop ipl 2018 matrix new delhi ma siddhidatri matrix will have to use to addison ki i plus size yeh plate hai main nachu show ki hegi everyone will declare x20 2014 flat intake That access is equal to I only baje ki into being pad ki alto ki express i hand bike plus sanjay ko nominate half return a special content hotspot off but by western express highway on my plate hai jhal ki supos rs 10 action was represented s mandsaur starting Point of fertilizers in bed matrix notched maximum lap to-day is length panel above is running between them lap to-day is length panel above is running between them lap to-day is length panel above is running between them equal to 0512 that they are in the loop share 150 for this position will be considered a matrix and this position will be considered for the matrix b id 2nd Id Tricks And Displaced 248 Initially Disposition Wave 1080 Rain is in its complaints from Maxim's previous Max and Max's answer after service to the Maximum will not listen Aadhe A Hua Tha Yes Yaar Ki Intex Sharir Zinc Dot Yes Dot Ab Aadhe Dot Com A Valid Spot Setting On Custom Taste Is Not Summit On The Festival Accepted I Hope You Liked Video Thank You
Image Overlap
linked-list-components
You are given two images, `img1` and `img2`, represented as binary, square matrices of size `n x n`. A binary matrix has only `0`s and `1`s as values. We **translate** one image however we choose by sliding all the `1` bits left, right, up, and/or down any number of units. We then place it on top of the other image. We can then calculate the **overlap** by counting the number of positions that have a `1` in **both** images. Note also that a translation does **not** include any kind of rotation. Any `1` bits that are translated outside of the matrix borders are erased. Return _the largest possible overlap_. **Example 1:** **Input:** img1 = \[\[1,1,0\],\[0,1,0\],\[0,1,0\]\], img2 = \[\[0,0,0\],\[0,1,1\],\[0,0,1\]\] **Output:** 3 **Explanation:** We translate img1 to right by 1 unit and down by 1 unit. The number of positions that have a 1 in both images is 3 (shown in red). **Example 2:** **Input:** img1 = \[\[1\]\], img2 = \[\[1\]\] **Output:** 1 **Example 3:** **Input:** img1 = \[\[0\]\], img2 = \[\[0\]\] **Output:** 0 **Constraints:** * `n == img1.length == img1[i].length` * `n == img2.length == img2[i].length` * `1 <= n <= 30` * `img1[i][j]` is either `0` or `1`. * `img2[i][j]` is either `0` or `1`.
null
Hash Table,Linked List
Medium
2299
1,046
give us a collection of rocks each Rock contains and positive integer value as its weight each time we take the two heaviest the rocks and smash them and only the remaining weight stays returned the last value in this array after we smashing all of the possible rocks how would you do that's about today's video last I mean Silicon Valley this is where my dream started hi everyone this is Steve here today we're going through a legal problem one found for 46 last stone wait let's take a look at the problem this description first we have a collection of rocks each one has a positive integer weight each turn we choose the two heaviest rocks and smash them together suppose the stones have weights x and y with ax smaller than or equal to Y the result of this smashes if ax equals 2y both stones are totally destroyed meaning there is no weight remaining if X is not equal to Y but still have weight ax is totally destroyed and the stone of weight Y has new weight Y minus X basically the difference between the two weights at the end there is at most and most there is at most one stone left just all of the other stocks and all of the other rocks have been smashed into make that's nothing there's no weight anymore return the weight of this stone or zero if there are no stones left let's just quickly go through this give an example then we'll have a better understanding and 2 7 4 1 8 1 output is 1 as the problem says we always choose the two hammers two rocks that you have astrak-- hammers two rocks that you have astrak-- hammers two rocks that you have astrak-- see in this case is seven and eight right now so we smash 7 and 8 together it so this array and that the difference is only one so we add one more one into this array so this area becomes this and then we'll continue to do this two and four will be the next two biggest one then two and four and the difference is two so there is one more two here then we'll continue to do this the next two different will be two and one and the remaining difference is one so there's one here then we'll keep doing this and there are three twos we'll pick two of the three ones here then they are just completely equally destroyed and there's only one remaining and that's the result and we're going to return a very simple problem I would say the very natural idea that comes in your mind is basically use a priority queue which is going to always in this case is going to be a max-heap going to be a max-heap going to be a max-heap or which meaning every time we pull from the heap is going to give the max admin in this current heap and then we'll just keep honing well keep well pull twice because we'll smash the two biggest animates and then we'll just add the difference if there is any difference if there is no difference it's just zero well just add the difference back into the heap well keep doing this until there is no more to Hanuman's no more than 1 elements in this max heap then we'll just return that's it that's the idea let's just start running code then use a priority queue and we just keep putting we'll put all of them constructing the max heap in the first step and the second after that away just to keep Pony twice and before we keep honing twice but check whether this array has two elements at least if doesn't we'll just return the final element that's it in integer yeah and here we need to implement a customized comparator which is going to reverse the audience because by default is in ascending order but we want in descending order so we'll just a quickly implement their customized comparator for this and priority queue and then we just put every stone into the weight of every single stone into this max keep max offering number that's it after this step we have beaut and this max keep and then what we'll do is while max heap is not empty we'll just keep pulling we have a check we have a while loop here as long as the max camp is not empty and then we'll also check if the max heap size is at least two right otherwise we cannot pull two rocks to smash them max key size is greater than or equal to two then what just pull it we can just put them together very straight for there's nothing to you fancy no tricky max-heap nothing to you fancy no tricky max-heap nothing to you fancy no tricky max-heap first pole we're going to get the current biggest annamund and then this one is bigger than then so after we pulled the big the biggest one out and the next biggest one is becoming is sitting at the root of the max key then we just keep pulling max-heap pull it we just keep pulling max-heap pull it we just keep pulling max-heap pull it again so this is basically the biggest island - the second biggest animate then island - the second biggest animate then island - the second biggest animate then we'll just to added that and the difference back into the max key that's it else we'll just written alice means max heap so first we have max key is not empty and then we have max cube size is greater than or equal to two and the only ass condition is there's only one element in this max key so in that case we're just going to return max heap oh that's it to make it compile when you straight to minus 1 I mean every time - straight to minus 1 I mean every time - straight to minus 1 I mean every time - anything because this one it's guaranteed you have a solution that's the beauty of leith oh yeah that's it well we just hit submit and see all right accepted that's the algorithm first we view the primary queue by iterating through every single element to put them into the max keep and after we constructed the max key we'll just keep pony every time we component two elements if there are more than two elements in this math key max cape and then we add the difference of these two max value back into the heap so now let's talk about the time complexity and space complexity of this algorithm remember we're taking advantage of priority queue this is going to give us lock in an operation time remember we went through this priority queue Javadoc maybe a few weeks ago it's just actually a priority look it up a game priority accused Javadoc what see that's got the latest implementation I hope you guys can see my screen let's let me zoom in so here this is the priority queue Javadoc let's go through this again well the only thing that we care about right now is this implementation of this implementation provides old log n time for the Inc Ewing and dqe methods offer and pull these are the jus API is that we used right these are the two main guys offer and pull so these operations are going to cost log n time that's why I said the time complexity is o and that's where this lock and is coming from and where does this n come from this n comes from n is the number of integers in this given array why because we have to traverse through say there is a follow here we have to go through we have to visit every single element in this array to you for every single element we need to do this operation so it's a multiplication so it's n log n time that's the time complexity I hope well on the same page that make sense to you and space complexity is going to be o n because after this for loop we have added all of the elements into this max heap which contains the entire size of this array right that's why the space come back today is going to be oh I hope this everything makes sense to you and that's about the time and space complexity for this problem and it's priority queue is pretty efficient which gives us a lock login for a lot of its operations after we go through the time complexity I just would like to quickly mention IC discussable there is some confusion about whether we need to add if these two rocks the two biggest that the two rocks that we take out with the current biggest in weights what if the waits until the two weights are equal seen and two rocks with values both of them with value two on with value three after this match there's going to be none and the zero man is going to be added into this heap right see here if 2 minus T is going to be zero and we add a 0 into this max-heap is that going to 0 into this max-heap is that going to 0 into this max-heap is that going to make a difference or is this algorithm correct or wrong in that case what just used a simple example to go through that say we have 1 &amp; 2 &amp; 3 so we have we say we have 1 &amp; 2 &amp; 3 so we have we say we have 1 &amp; 2 &amp; 3 so we have given 5 a collection of five rocks and so every time we take out two biggest animals and smash them so the first time we're going to result in 3 1 2 0 right that we take out the first in the first algorithm with our current implementation we're going to add the zero back into the max scheme and this is how it's going to work let's take a look so first time when you take out two threes and they smashed they got smashed and we add a zero back into the max cube and then next time we take out one and two right these two are the next biggest elements it's becoming and the remaining one is 1 so it's becoming something like this and then we'll continue to take the next two biggest diamonds which is 1 and 1 which they smashed equally together so we add a 1 into this and finally we were just any with 0 it's still 2 elements so we take the these two elements out and its result is just a 1 so there is always we are ending up with and most and one element in this mac flavor in this case we're just written 0 here right so this walkthrough is what's going to happen if we are passing in this test case for the current image for the current environment attention which is we are adding the 0 into the Q but it just in case if you don't want to add a 0 into the max cube which is also going to work that's fine too so say here what given the same collection of rocks first we take out the two biggest elements 3 and 3 1 2 these two 3s are smashed they just got destroyed totally destroyed so we don't add the zero back into the max scheme so we'll start the next iteration from this max scheme and then from here we'll take out the max to two biggest elements which is one and two then the difference is 1 so we get a 1 and 1 this one comes from the difference of the last two biggest animals right so this is the camerawoman that we're going to go through for the next generation then we take out that max to two biggest animals which is 1 and 1 smash them together which is ending in 0 so we just pop out and return this zero and the code just needs to be slightly modified so here we check if the difference after subtracting in the slashing the two biggest the rocks if it's zero we're not going to add that back into the max key and also we'll check whether the max Cape is empty already if it's empty which is to break out and return the difference that's whether it's a zero or any other number that's good that's going to be the last value but one master stone that's left that's it so either add or don't add zero back into the max keep we just need to take the code a little bit either way works that's about it for this problem I hope you guys learned something from this and if there's any comments feedback questions just leave me down in the comment section below I'd really appreciate it and do me a favor and then tap the like button and subscribe to my channel please that's going to mean a lot to me and help my channel to grow I would really appreciate it and tap the bounded vacation so that every time I publish a new video you're not going to miss out on anything
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
520
um hello so today we are going to continue on January daily challenge so this problem detects Capital um so what the problem says is we get a string word um here and what we want is we have a definition of um a usage of capitals being right and it's right when all the letters in the words are capital for example USA or when all of them are lowercase so there is no capital letter or when the first word is capital so these are only the three valid uh usages and what we want to return is to we want to return if um if the word that we get in the input is uh is valid in terms of this definition right so for example the first one would assume true because it's all uh uppercase the second one it's not because we have an uppercase at the end but the rest is here is lowercase so it is not false so that's the idea um word can have either a lowercase or uppercase English letters right um so this should be easy to do right we can just apply these conditions and that should give us what we are asking here so what we can do is basically just check that if all of the letters are uppercase in Python we can check uppercase using just this upper check so we can just check if all of them are uppercase then here we want to return true right or if all of them are lowercase if all the characters are lowercase then we want to return true right so these two cases will cover for us the um the first condition this one and the second condition right now there is this last condition so the last condition is the first letter is uppercase and the rest are lowercase so how do we do that well we can just check if um the first letter is uppercase so I'm using S here so let me just rename this to s so if the first letter is uppercase and the rest is lowercase so to get the rest we can just start from one and we just check if the rest is lowercase then this is valid okay so now we have all three conditions right so we can if all three conditions are not valid these three are not valid and we're return false right so we're going to false here okay um so let's run this I'll submit and this we have one failure here with this G yeah sorry I meant here lower case if all of them are lowercase yeah submit okay so that passes that's that gets accepted now in Python instead of checking this here um that only the first letter is uppercase index the rest is lowercase this is actually there is a function that does that for us called its title that we can just use and so here instead of doing this we could just return and if it's title or not right because if it's title want to return true otherwise we want to return false um okay so it looks like so this is s not just the first character right okay so that passes still now we can just move this over here to be we can do it same way we are doing is title check here on the entire string python allows us to do the is upper on the entire string and that would be the same as checking for every character right so two or two true if the entire string is uppercase or lowercase right and so we could just bring all of these together and simplify this function so that would be S and we can just return this these will check all the three conditions that we have right and we can run this and submit if that passes test cases as well right um yeah so that's pretty much it that's the idea here now in terms of time complexity you are just doing these checks each of them takes at most oven um so in terms of time complexity this would be over in terms of space we are not really using any extra space so it's all one space um yeah so that's pretty much it for today's problem please like And subscribe and see you on the next one bye
Detect Capital
detect-capital
We define the usage of capitals in a word to be right when one of the following cases holds: * All letters in this word are capitals, like `"USA "`. * All letters in this word are not capitals, like `"leetcode "`. * Only the first letter in this word is capital, like `"Google "`. Given a string `word`, return `true` if the usage of capitals in it is right. **Example 1:** **Input:** word = "USA" **Output:** true **Example 2:** **Input:** word = "FlaG" **Output:** false **Constraints:** * `1 <= word.length <= 100` * `word` consists of lowercase and uppercase English letters.
null
String
Easy
2235
393
all right so hello and welcome howdy i had an issue just a moment ago where uh oh no can't forget i'm so annoyed i don't know i'm kind of distracted right now but my mind is all over the place but uh i'm already irritated i have to get irritated uh that's all right um okay so it's a great way to start i had already had to restart so i don't restart again it's a pain in the neck i have to like end the stream delete the video start over again or i could do that we're just going to keep going uh yeah i wouldn't say it's laziness it's just it's not worth the frustration just keep trying over and over again here i wanted to the reason is i wanted to listen so okay so the beginning of the video would be here um uh we want to i want to revisit utf-8 uh we want to i want to revisit utf-8 uh we want to i want to revisit utf-8 validation on the codes i had solved this maybe six months ago um and let's just say i had a stroke of ins we'll just say stroke of inspiration i don't want to say where it came from but a stroke of inspiration to um go ahead and uh revisit this question there's another way to solve this problem that i think is very clean and i like it a lot the first time i had approached this problem it was not very clean and uh it wasn't great so yeah it was kind of it was really messy it took me almost an hour and like i said it was pretty messy so i want to revisit this problem uh we'll get that in just a moment i wanted to before we get into that though i wanted to say oh yeah i want to listen to music um that was actually why i was so frustrated because i wanted to listen to music but an ad started playing and i forgot to put the audio down so i had like a few seconds of just very loud ads at the beginning of the video but yeah put that for the background all right so it's interesting so we'll go over this in a second i'll explain it hopefully this won't take too long um okay give interest array data representing the data return whether it is a valid utf-8 encoding character in utf-8 could utf-8 encoding character in utf-8 could utf-8 encoding character in utf-8 could be from one to four bytes long subjected to the following rules one byte character the first bit is a zero followed by its unicode character n bytes character the first n bits are all ones the n plus one bit is zero followed by minus one bytes with the most significant two bits being one zero at eight encoding would work so like this isn't a very good explanation in my opinion um let's just say recently someone explained what utf-8 encoding explained what utf-8 encoding explained what utf-8 encoding is and it was a much better explanation this um i think it's about why there's got so many down votes uh also this is getting kind of loud um i wanted to listen to music but it's kind of distracting truthfully um here's the deal utf-8 works like this utf-8 works like this utf-8 works like this it could be um the first bit is zero and the next bit is uh your first bit is zero and that would make that a header byte and that would be just regular ascii a regular ascii byte um the if there is a one zero those first two bits that's called a continuation byte so that means that's going to be part of another utf-8 going to be part of another utf-8 going to be part of another utf-8 encoded character and then the utf-8 encoded character and then the utf-8 encoded character and then the utf-8 encoding the header bit the header byte the number of bytes involved in that particular character is going to be equal to 1 it's gonna be equal to the number of ones that were set in that first byte so your byte might have eight you could have at most eight ones is straight across that would mean you're going to have seven more continuation bytes so that way you would have eight total bytes for that utf-8 total bytes for that utf-8 total bytes for that utf-8 um character so you can encode a lot of characters doing it this way uh with utf-8 so basically every with utf-8 so basically every with utf-8 so basically every character could have at most eight bytes for per character um and so now so if you wanted to so the deal is you can understand the header bytes there basically would be um there really are the by the bytes in utf-8 could be bytes in utf-8 could be bytes in utf-8 could be reorganized and understood as there are eight types of bytes eight categories where the i'm sorry um yeah i guess yeah that's fair actually no i wish it's that um what you would say is you would say you could say is every character has a header byte and the header and possibly zero or more continuation bytes and the header bytes are understood as uh it's the number of most significant digits most significant bits because the number of consecutive most significant bits that are set to one um tells you how many continuation bytes you expect so if you see one zero that's there's no continuation but excuse me it's that value be one more than the number of continuation bytes or that value is the number of bytes in the whole character so one zero would be just the header byte itself is the character byte um if you see i'm sorry excuse me actually this is really confusing uh i'm explaining it incorrectly actually i guess that's why it's hard to explain it i mean it's not the best explanation but even i'm not giving a particularly good explanation so at the moment so the first byte if you see it starts with a zero that's both uh the header byte that's the only byte in the character if you see a one zero that's not a header byte that's a continuation byte um followed by anything else and then if you see a sequence of ones and is an and you know it could be a zero ends with a zero or there could be no zero at the end um that represents that means that header byte is a header byte um and it's going to be um the number of ones from left to right represents the number of bytes in the whole character so if you see like eight ones that means that header byte is one and then there should be seven continuation bytes following yeah it's a little confusing um but i think that's why it's a good question to ask in this review because it's like just tricky little sort of it's challenging to kind of understand and explain it um so that you so you can write code to parse um utf-8 uh sequences and that's what we're utf-8 uh sequences and that's what we're utf-8 uh sequences and that's what we're going to do now so it took seven minutes of explaining so the deal is we want to um we want to write a routine that will validate if a sequence of we'll call them integers it could be character really should be characters but sequence of integers if they are um if that represents a valid ucf eight encoding um which means that so if you see like if you see um so each header byte that you see um if it's itself if it's one byte so if it starts the zero bit the most significant bit on the left um then that's valid right and you can move to the next one but if you see a continuation byte when you're expecting a header byte that's invalid right but if you excuse me but if you see and then if you see a header byte with um two or more first bits uh most significant bits in consecutive most significant consecutive bits two or more that means that you're expecting to see one less than whatever that number was number of continuation bytes which we said before continuation bytes starts with one zero um so that's what we want to write our routine is to make sure that we each time that occurs we see exactly that many number of continuation bites um and there's a way to do this that's like pretty concise and i like it and i realized it uh at one point i was like oh hey like this is a pretty this is a really good question to ask but like there's a very concise way of doing this so we're gonna do um we're gonna say uh count significant bits lambda expression we're going to start with that because it's very useful i think for this what we're doing would be very useful to count the number of bits and we're going to say const number bits in um an integer so i'll call it x and we're going to say we're going to start with int mask it's going to start off with so we're going to bit shift one seven positions to the left right so it'll be so it starts off in the first position we want to add seven positions over so it's in the eighth position on the left side right and then we want to do the following um we're gonna say int we say i equals zero i is less than eight so eight times we want to perform our check increment i and we're going to decrement the mass we're going to bit shift it to the right and we're going to do this is going to be kind of a subtle thing so mask and x if it's true there's a return value that we want we'll start with zero we're going to increment the return value um and here now this is another kind of a subtlety we terminate early so count the bits count the most significant bits from left to right starting in the eighth position and terminating early when a zero is found terminating with a zero set to one yeah so um that's what's gonna happen here so we're gonna if we don't have a one value in that position then um we don't have a one value in that position then we term it early then we're done and once we as soon as we see a zero that's it so we're counting the consecutive sequence of one bits from left to right until we see a zero right and then now we want to say check each header byte and if that header byte implies more than one byte for a given utf-8 for a given utf-8 for a given utf-8 character then ensure that there are exactly the desired number of following continuation bytes to satisfy the format or to satisfy the header byte the number is specified with a header byte something like this it's kind of a lot of words but something like that so we're going to do i equals 0 i is less than data.size data.size data.size we're going to say and you actually want to use size t um for a vector and we're going to say uh constant b it's going to be for byte state of i and then we're going to say now we want to use so if we're going to say count um we do constant count that's fine it's going to be count significant bits of b right so we count the number of significant bits and now we're going to say if the count of bits is zero right this is a single header byte format is correct so we just continue if the count is one return false continuation byte when a header byte is expected the format is incorrect and then finally in all the other cases it's greater than one ensure exactly the correct number continuation bytes follow header byte now this is a subtle thing we want to so we're going to say so if goes like this if then return false and then otherwise so we're gonna do two checks right the first check is if there aren't enough bytes to process so there could be um it would be something like if there aren't enough bytes to process that means that if i plus count is greater than data.size or and this is going to be an interesting check um yeah so if there aren't enough bytes if there aren't enough continuation bytes so how do we get the number of i guess we could say um the total number of bytes has to be so the total number of bytes can you do it this way it's easier way to think about it total number of bytes which is dated that size minus the number of bytes that you've considered so far which is and you say would be less than count so it's actually it's not possible to have enough bytes and you would say data.size data.size data.size minus i um so it's data dot size minus i is less than the count uh yeah i think that's right so if you had like five and three five minus three would give you two but i guess you would you'd have to add one to include um you could do it this way yeah it's a little confusing but uh if you're if you have five minus i is all of the bytes you've already considered um plus one includes the header byte if that's less than the count which the count is includes the header byte then um then you return false right it's not possible you don't have enough continuation bytes right that's one thing and then the other thing is you can do um algorithm make things a little bit easier oops oh no uh how do i keep doing that i don't know this there's some like hot key buttons that i just randomly press from time to time and end up on a window that i wasn't expecting to be on it's kind of annoying um but um yeah so now if now what you want to check is all of um should the following should be true and if it's not all of these then you have an issue and the all of let's just double check that all right so i have to have an all of routine yeah find if not so olive right so if it's not all of we're going to say data dot begin plus i to data dot begin of i plus the count and the routine is going to be very simple return um it's gonna be const x return count sig bits of x equals one right so there should be so something like this and then hold on one second i is then gonna update to the count right we're gonna add it's actually count minus one um and we're actually we're not going to include i in the for the header bit so this is kind of interesting thing too we want to say that we have enough bytes to check that's the first thing and if you do have enough bytes to check you need to make sure that all of the bytes are um continuation bytes which means that the number of significant bits is one um so all the bytes are continuation bytes and if they're not all continuation bytes return false if they are all continuation bytes and you have enough then that means you're going to move um i to count a forward count number of indices something you have to be it's subtle here you have to be careful about is um excuse me something to be subtle something subtle here something to be careful about is that you don't want to move it too far because this plus i is going to account every time for the header byte uh you only want to increment for the continuation bytes so yeah very slight thing i'm sure that there are enough bytes to check enough continuation bytes in the array sure that there are enough bytes in the array to check sure also that there are that all of the following bytes are continuation bytes if either of these cases fail then the format is incorrect and we terminate early i can check right there is exactly one consecutive most significant digit that the sequence of consecutive muslim digits set to one is exactly one size one something like that um increment the index into the data to the array past the um count continuation oh no buy the outer loop yeah so something like this oh i didn't and if we finish here okay how are we doing on time 22 minutes 23 minutes okay fair enough um oh i'm going to capture this let's see any of the mistakes that i made hey all right i think this might be correct just as it is like it's pretty it's like a very straightforward solution i guess but it's also like it's not the easiest thing to come up with on the spot i suppose if you had to um yeah i thought about this a little bit i had a few days to kind of ponder this i'll just say i mean obviously i saw it six months ago but this is like a much cleaner solution than the one that i had originally for this problem the one i had originally if this problem was pretty ugly it's pretty gross solution um let's see uh let's try some test cases i guess um yeah oops too many hotkeys man too many things to let's try some random integers here uh i think eight bits actually no they'll have to be in between i was gonna say that'll be 255. yeah this is too big okay the last one almost certainly is false um what are some other okay so what i want to do is try that one you don't have enough bits try this one where you showed twice and then um can we do one that what is that three bytes if we could do three um three bytes would be 197 okay let's do one what is it i think it's 128 is a continuation byte and then 197 is like 128 plus what's that 64. gives you 188 192 and then you want to add another 32 which gives you 192 plus 32 is um like 292 plus 20 no yeah no 190 202 plus 22 which is 224 right something like this what does this give us does that give us true at the bottom it does i think it's correct i think it's i don't know we'll go for it let's see if it goes no oh of course really i should have tested more things i thought about it thinking i was thinking to test more things but oh brutal i haven't i had that i had the opportunity to had the opportunity um what did we just do i had the opportunity for redemption you know i think it is it's kind of a pain in the neck coming up with these test cases with the uh all the bits and you got to like figure out how you're going to get a string of ones and do all the calculations just prone to laziness in that case what happened really um all right fair enough i'm disappointed now i thought i had this too but i had it i thought i was so smart how do we get a runtime error here 248 130. so 130 is what um that's what i did on our head uh so 128 yeah so these are continuation bytes these are three continuation bytes um 248 is uh he's doing right so it's um yeah it's a pain in the neck to actually convert that in your head because you have to do eight divisions by two and then reverse the remainder so you get zero gives you um 124 zero gives you um 162. zero 62 zero so zero you get 62. i don't know 0 62. 0 again gives you 31. 1 gives you um this is four i zero four minus one this should have just returned false no what happened here did this not enter this loop also no i was trying to be clever not use a raw loop and try to do this in a way that's very um like concise no so do we even we should get to this point right hmm check yeah why not this is actually exactly the case that oh i think i probably just did the math wrong here how about that i guess this is true that must be the problem sorry zero false oh yeah this should be true actually wait what that's that is the problem but what data total bytes i'm disappointed um current index count okay let's try this oh that's disappointing yeah that math is tricky man um how do we get five that doesn't seem right that's not true um or b excuse me oh it is five okay excuse me one two three four five yeah all right um if the data dot size which is four minus i which is zero plus oh are we not supposed to add one there um hmm or if it's not equal if it's too many well actually wait it's really both um actually in this case it is equal but it should i think it's supposed to be this i think that's the problem but also well being less than should be fine um like i think i'm so confused no what is going i don't know i'm so confused now my brain is spinning so oh no i'm sorry i did that wrong um yeah i'm disappointed that's such a tricky thing it's such a tricky thing um the issue is the following right the issue is the following you want i to whatever you want first you want to make sure there are enough bytes to do this um and the way to ensure that there are enough bytes is you want to take the total number of bytes subtract the index now the tricky thing about that is the number of bytes up to the point where you have the in where the index this is one of those things that's like really subtle but really tricky is that you take the total number minus an index it's not quite the math on that is not quite what you think it'll be it's because the total number of bytes including that index is actually the index plus one so it's the total number of bytes minus i minus one right it'll be minus i plus 1 which would then be minus i minus 1 right which is very subtle but then if you want to include that byte in the section that you're looking at uh like the total number of bytes that you want to count if you actually you don't want to remove the header byte but you want to include the header byte you have to add one that's why you get data minus i less than count not data minus i plus one less than cat which is the thing part that i got confused is that the in order to count numbers you would take you had enough numbers b and a you want to count the number of numbers between b and a including b and a you do b minus a plus one because when you subtract a you wouldn't subtract everything to left including a itself however the tricky thing with when you have an index versus which is zero index versus a total count which is one index you have to account for the one index versus zero index which is something that always trips me up i always forget it i always struggle with that but you have to be careful of something that's zero index versus something that's one index a total count is one index is a an index is zero index you have to subtract one from the total count or add one to the zero index in order to get them lined up in the right um sort of yeah in the right kind of uh universe i guess if you want to call it that with the right world the right alignment i suppose so that's why it's data size minus i rather than um data size minus i plus one yeah i always mess that up man that's really tricky thing but it should be correct now i think we should be correct now but yeah this is a very like concise way of doing this um if it works i hope it works hopefully we got all the test cases no oh come on oh that's disappointing ah this is you'd see why i want to revisit this too it's just like come on now why what happened we got true expected false now i want to say this is supposed to be equal to um it really i mean it should be not this one should be not equal to i have this very uncomfortable feeling that this is what i should have used and not just less than but it's not equal to i was assuming that if it's oh no nope that's not it so what it could be what could it be um well um we expect false so let's take the bit set of on each bit let's print that on each byte yeah i guess this is not a very good way of doing this because this is very um a lot of prone to error it's really prone to error which makes it a good question to ask but very challenging i suppose i don't think when i can see why i want to revisit this that's annoying i had salt yeah i did this right the first time or not the first time but way back when six months ago yeah six months ago um okay so one two three four five we got that and then what happened we should entered here we did and then we didn't return false we made it through here um now the question is why did we had one two three four five right so this should return true or yeah it should be this i think is false if we check this um and then we have to check here yeah but this all of wasn't true um begin plus i is the first is the so this the first continuation bytes this is not going to be the um this is going to be the byte after the header byte right the header byte would be the begin plus i um yeah because i is an index so it's going to just begin plus index add 1 to go to the next index so it's got to be 1 2 3 4. now when you add the count um what's interesting is oh wait this is false wait one wait what two three four five i'm really confused now um what's 145 what i actually would expect this to be true uh oh you know what this is why i got so many downloads um i think uh i think the way that this problem is set up they only want four bytes rather than eight bytes long or utf-8 i think this must be eight long or utf-8 i think this must be eight long or utf-8 i think this must be eight bytes um and i think that's the problem is that there's five bytes here or five values here this actually the way that they had set this question up um this actually should be true oh man that's a doozy how about that for like frustrating and upsetting oh no this actually is doing what it's supposed to do 145 it has yeah if you oh no really yeah 145 is probably a continuation bite oh no yeah it is so this actually is correct this actually is the correct utf string oh i see oh no i see oh hmm i said to make a small change for this particular question man then but this is pretty concise this is yeah you gotta be really careful here this part you have to be careful in this part but this is all you need for the logic um pretty good but the problem is this particular problem they're saying that uh interesting uh oh uh if the count is greater than five or so okay what do we do um so this one this is false one byte character the first byte is a zero followed by unicode character and n bytes character the first n bits are all ones n plus one bit is zero followed by n minus one bytes the most significant bits being 1 0 followed by minus 1 bytes how the utv8 encoding would work etf eight octet one two three four so i think part of the issue is that if it's if we don't if we have five if we have a count greater than four i guess we just return false that's what we can do um note that for this particular question if the encoding the account is greater than four we must return tf8 he does so how many bytes in etf eight one to four oh that's interesting but you can only use four at most oh interesting i didn't realize that uh whoops so i'm not wrong actually oopsies i'm what is it i'm wrong i'm not wrong what was i saying excuse me i over the wrong impression that actually no this was correct the something else is wrong let's say something else is wrong uh whoopsies we missed something utf-8 is only supposed to be something utf-8 is only supposed to be something utf-8 is only supposed to be one to four why did this get so many down votes it's such a good question uh oh uh oh it's one to four one bite okay oh that's awkward count is greater than four dtf encoding is invalid that's a slight detail that's an important subtle and slight detail and i actually missed that detail um in the past there we go there actually i kind of like the first solution i wrote to this then the first how long does this take 40 45 minutes no this is pretty it was pretty quick it was pretty concise i like this you know i think this is okay the first time i solved this problem way back when six months ago we actually looked at that video it was pretty messy it did take me like an hour i don't know man this is kind of hard like this approach is good but it's pretty challenging um to uh to get it right in my opinion like it's pretty challenging get all these pieces in the right spots um 50 milliseconds oh really oh wow when i first wrote this these were like pretty fast i think it's like 97 or something like that what was the uh where is um let's go to my videos let's do that this is interesting man um huh let me see something here browsing the web while streaming is like especially as i'm streaming from a laptop um especially straight from a laptop i'm looking for yeah somewhere here let's just look at this the other day here we go all right interesting actually this is wrong what i had done so yeah so this is really this is super messy previously when i did this the first time um i solved it relatively quickly but it was ugly he's recursion i use recursion and i used a an unordered map i memorized the recursive routine because i think i just wanted to solve it like really quickly i don't know it was just i don't know what i was thinking the time but um yeah this is what i ended up with this code like but it was actually this is actually correct this problem this is correct also the solution was fast when i did it solved it way back then way back when um i ran into some issues though oh no i'm sorry it wasn't that fast i take it back never mind um interesting so my solution now seems to be a little bit faster but no it's kind of slow um but yeah i did solve it way back when and i guess i was wrong um it's uh i was wrong the number of bits um you can change this routine to be a lot faster i think you could use masks for the significant bits so you could say um do this really quickly you can say like well no i guess not no it's that's probably as fast it goes actually i don't know i don't believe it that's okay we don't need to get too crazy but yeah the logic is really straightforward if you do it this way i think i did it really poorly the first time around and then i missed this part though i missed there's like two actually two cases i missed and let's just say there was yeah okay you could change this as well how about that add one less branch hey that's pretty quick that's relatively quick i think um apparently there's a way to do this even faster i like this is okay this is like pretty clean code it's pretty efficient um don't actually need this here you can make it faster as well here just think of ways to make this faster one two three no okay all right i think we ended here uh yeah 50 minutes okay last time it was like an hour so yeah a few things to it's good that i rewrote this because i thought about it i was like you could probably do it this way but um part of the problem is like you need to get the indices correct which i did i didn't get them the first time when i wrote this it's a good thing we actually wrote it because that's a very subtle thing that throws me off often and then this part i did right though that was fine yeah okay and then also with utf-8 encoding you and then also with utf-8 encoding you and then also with utf-8 encoding you got to be careful it's not eight digits it's four bytes it's only four bytes if you go more for more than four bytes it's incorrect um it's good to remember that yeah so i have solved this problem before i saw this problem yep okay 12 seconds okay 12 milliseconds is only it's not the fastest so apparently you can make this even faster um so these two cases just return false immediately and then in this case um do you need a branch for this though um i guess you'd say if it's less than or equal to one no well you wouldn't return you would continue yeah okay i get it that's fair um can you put el no else if it's not equal to one and it's not greater than four right um then uh you can go to this branch as long as it's greater than one less than four it's probably a way to logically handle this where you don't need two branches that probably is how you speed it up to get like 100 um maybe you can say i don't know how would you do this um yeah that's pretty much it i don't know it's probably good enough for all intense tense and purposes see it was nice to revisit this problem though i think there's a much cleaner way of doing it um i'm kind of disappointed myself though for the times that i've tried to solve this problem and it wasn't very clean wasn't very good um all right i'm gonna go so thank you for watching talk to you soon i'm gonna go ahead and uh i think i'm gonna take a break for a while um i kind of was uh was i saying i was kind of um take a break for a while i was kind of um i don't know mine's been kind of a little place like i feel kind of bad like not spending enough time like practicing you know um i don't know i suppose okay all right i'm gonna go thank you for watching talk to you soon
UTF-8 Validation
utf-8-validation
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters). A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules: 1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code. 2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`. This is how the UTF-8 encoding would work: Number of Bytes | UTF-8 Octet Sequence | (binary) --------------------+----------------------------------------- 1 | 0xxxxxxx 2 | 110xxxxx 10xxxxxx 3 | 1110xxxx 10xxxxxx 10xxxxxx 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx `x` denotes a bit in the binary form of a byte that may be either `0` or `1`. **Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data. **Example 1:** **Input:** data = \[197,130,1\] **Output:** true **Explanation:** data represents the octet sequence: 11000101 10000010 00000001. It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character. **Example 2:** **Input:** data = \[235,140,4\] **Output:** false **Explanation:** data represented the octet sequence: 11101011 10001100 00000100. The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character. The next byte is a continuation byte which starts with 10 and that's correct. But the second continuation byte does not start with 10, so it is invalid. **Constraints:** * `1 <= data.length <= 2 * 104` * `0 <= data[i] <= 255`
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character. Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem. mask = 1 << 7 while mask & num: n_bytes += 1 mask = mask >> 1 Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks. mask1 = 1 << 7 mask2 = 1 << 6 if not (num & mask1 and not (num & mask2)): return False
Array,Bit Manipulation
Medium
null
100
hi everybody this is Fisher Koda here as I have a lot of queries from YouTube people asking me to go through questions about trees especially binary trees or binary search trees or different sorts of trees so today I'm going through the code problem 100 very basic question but it's good to brush up on the very basics before we dive deep into more advanced techniques before we start looking at the problem just do me a favor and smash the like button and don't forget to subscribe to our Channel and turn on the bounded vacation so that every time when I publish a new video you'll get a notification instantly alright with that said let's take a look at this problem is called same tree the problem goes like this given two binary trees write a function to check if they are the same or not to binary field these two binary trees are considered the same if they are structurally identical and the nodes have the same value for example let's take a look at example one these two binary trees on plain sight we know they are identical so they are the same tree so the result is going to be true one root node is one ruin there is one laughter on the left side it has only a one showed a one child and with value to the same is also the case for the second tree and there is only one right child on the UM on the first binary tree with a value 3 which is also the same case for the second let's take a look at a second example the second example goes like there's the structure of the two trees on plain sight it's different right and this one has a left child with value two but this one doesn't have any left child but it has a right child with the value two so why don't you return false because structurally they are different remember here they are structurally identical and the nodes have the same value so the second example violates the first rule which is they are not structurally identical the third one is also false why it violates both rules ivalice the second rule which means that the notes don't have the same value although structurally they are identical it's a four binary tree - with two it's a four binary tree - with two it's a four binary tree - with two levels but in the first tree the left child has one the left side has one child with the value two but the second tree has a left child with vanning one and so does the right side so we're going to return false when looking at this problem is very easy and plain sight but how do we put the solution into code that's going to involve there multiple ways to do this you can do it either iteratively all recursively I think it's going to be the most intuitive way just think say how a binary tree is represented see there is common here so this is the clanton of the tree node on the right side I hope you guys can see my cursor tree node there is a well which stands for the value and then there are two other pointers one is called left and the other is called a right so which is pointing at a say we're looking at tree node and this route it has one left child and the other is a right child so we have left and a right and then here is the constructor so we were going to what the API signature for the solution is going to be looking like P and Q these are the two root nodes which represents the two binary trees that we are going to taking first the problem is going to be well just to check constantly see first we compare whether the root node values are equal if they're not equal directly return false right that's also actually one the access conditions out of the recursion if you're going to solve it recursively and then if the root nodes value are equal we'll just continue to check whether the first trees and left child here left a child is equal to the second trees left child and the same goes on with the first trees no right child and the second trees right down to check if there you go so these two examples are these three examples are very straightforward but that these tree could be like unlevel right so these two three examples only shows trees with two levels in can go on and on see it has three levels four levels five levels so this is where the recursive or programming power comes into play so in terms of code how can we do that what we can do first is well check whether P equals now so it's definitely possible that any one of the pasta in binary tree node there could be now right for example here when we go through to the code until the tree node added with value to its left child and the right child both of them are now right this is actually also one of the accident Isha's we just break out right the same is also true for this tree node is it's the leaf node which means it doesn't have any left or right children for this binary tree node so we're going to check if P was now all Q equals now in this case we can just return while at P equals to Q if none of them is now which means this is going to return false but if both of them are now which is a good case which means this is going to return true right then how can we check whether this these two tree are the same we're gonna check if P of so if we can pass this which means both P and Q are not now so we can safely check if P is value equals to accuse Q's value right okay well check whether these two are not equal if they are not evil head just to return false right say if here P's value is 2 while Q's value is 1 so we're just going to return false in this case and then after that we're just going to use a recursive function so call it the same tree we check whether peas left we were going to pass in peace left and also Q's left right so say P we're looking at a the very beginning which is 1 and 1 P is at 1 and there's no Q is and this node 1 and then we're passing peas left which is here too and Q's laughing which is here right we're going to check here whether they are equal or not so in this case they are not equal so we're going to end up here is going to call here so what don't you get which is going to become this P the left is going to become 2 and this Q the left is going to become 1 so we call this function again so this one tends to here it's going to call here but now this time P is going to be with value 2 and this node Q is going to be at this node with value 1 and then so it comes can you repeat not equals 2 now and Q naught equal to now either so this one doesn't hold we're going to come here then we check peas value is actually 2 ok so qs value is actually a 1 here in the second tree is the left child so they are not equal so we're going to return false here it's just to break out of this recursive function right that's going to give us the correct answer see suppose this side is 1/2 and if we change this out to be 1/2 1/2 and if we change this out to be 1/2 1/2 and if we change this out to be 1/2 so suppose here is with value 2 right that means we're going to get to here again which means we're going to break out of this loop but still that's not good enough right we need to check the right side to check the rice and whether the they have what do both of them have children if they do have children do they have the same value we also need to check we need to apply the same check on the right side of the both trees so we're going to have another recursive call here going to be P right and Q right that's going to be a complete solution does that make sense I hope that does now we can that basically is the solution we can try to submit all right it's a accepted I think we can even simplify this we don't need on this one more for loop we can just cut it off and put it here do you and so then we can have a one line here so what have they check first a piece value equals two Q's value if it doesn't equal then we'll just break out we don't visit end which is basically going to shortcut it and only when this one holds it will execute this and if only both of these two conditions hold we're going to execute the third check yeah that's basically concludes the solution for this problem this is a very basic tree binary tree problem and we're guys like it and if you do you have any questions that you would like me to go through in further details just leave me comments below I'll be happy to walk you through that and also don't forget to smash the like button and subscribe to my channel turn on the notification bell so that you can get my new videos instantly let's crack that Kony interview that's all for today I'll see you guys in the next tutorial
Same Tree
same-tree
Given the roots of two binary trees `p` and `q`, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. **Example 1:** **Input:** p = \[1,2,3\], q = \[1,2,3\] **Output:** true **Example 2:** **Input:** p = \[1,2\], q = \[1,null,2\] **Output:** false **Example 3:** **Input:** p = \[1,2,1\], q = \[1,1,2\] **Output:** false **Constraints:** * The number of nodes in both trees is in the range `[0, 100]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
null
659
hello everyone welcome to coding decoded my name is sansa deja i'm working as technical architect at adobe and here i present a 19th of august liquid challenge and for your surprise after so many days i'm witnessing a question that i haven't solved in the past the problem statement is a very interesting problem and you will also feel see the same once we will go through the entire solution uh the problem is split r into consecutive subsequences and again it's a medium level question uh it's very interesting i'll be explaining you the question as well as the solution by the presentation so let's quickly hop on to it split rn to consecutive subsequences liquid 659 it's a medium level question and i totally feel the same also in case if you have any doubt understanding this question or if you want to ask anything from me in general so please feel free to join the telegram group of voting decoded we guys have a wonderful conversations about job opportunities problem solving and it's a very interactive telegram group and i promise once you will join you will enjoy the conversation strategy without further ado let's quickly move to understanding the question says you are given numbers that are in present in sorted order so remember all the numbers are there in the sorted order what do we need to create groups of sizes that have length equals 2 3 or greater than 3 so this is another important point that you should remember that the size of each group or subsequence should be greater than or equal to three and each element in the group should be consecutive in nature so there should not be case where the elements in that particular subset or group are non-consecutive in nature so keeping non-consecutive in nature so keeping non-consecutive in nature so keeping these constraints in mind let's quickly understand it by one of the examples that was also specified in the question and the example happens to be this one we have elements as one two three four double five so first of all let's run evaluate whether it's possible to divide all these elements into groups with given constraints or not so questions said that the size of each group should be greater than or equal to 3 and the second constraint was all the elements within the group should be conservative in nature so let's start so the first group that looks very intuitive happens to be this one which is 1 2 and 3 because all the numbers are consecutive in nature and we are still not sure whether this group is complete or not but the bare minimum criteria is fulfilled it has three elements the element so far is conjugative in nature let's proceed further and the next group that could be formed is of is using elements three four and five so let's create another group which is of three four and five now comes the concern do we have any remaining elements or not let's try and evaluate it we guess we have two remaining elements which is one is four and other one is five now comes an interesting concern whether these two elements can be fit in any of these two groups that have been formed so far and we haven't closed the size of these groups why because in the question it said that the minimum size should be three there can be more elements in any of these groups so if you carefully analyze if we put four and five over here as part of this particular group which is the first one then we you will see that all the five elements will be utilized one two three four five and this forms the completion of one particular group four and five can be collated together as a result of which it makes a successful permutation and hence we will return true in all those cases where we are successfully able to form groups with given constraint as per the question had there been a case there would have been 10 over here then if you carefully analyze and then you will see that 10 cannot be part of these any of these two groups as a result of which we had to return false as the answer so there are only two possibilities of answer one is whether the configuration is possible then we will say true otherwise if the configuration is not possible then we will say false now comes the concern how can we algorithmize this up so if you carefully analyze then you will see that while iterating over the input array every number can be part of an either can be part of one of the existing groups or it can start a new group in itself so what i'm trying to say you will get to know in some time but remember for each and every number there are two possibilities either it will be the starting point or it will be creating a new group or it would be getting added to an already existing group that brings in a very important concept of availability and vacancy so we will be storing all those numbers that are available for utilization in our availability map and we will store all those numbers that we are looking out for whom the vacancy has been created in the vacancy map what i'm trying to say let's try and evaluate it by and by the same test case and let's start over this map the first and the foremost thing that i'm going to do is to create the availability map so i'll name it a m and that means it's the availability map so what how many numbers are in total there one two three four five six seven eight numbers are there and let's count the frequency of each and every number that exists in our input array the first number happens to be one has a frequency one two has a frequency one three has a frequency two four has a frequency two and five has a frequency 2 again parallely will also create another map named as vacancy map and let me just named it vm so it will store all those elements for whom the vacancies has been created and those elements could be part of the groups that we have formed so far what we are trying what i'm trying to say let's walk through the same example that i have just talked and let's start the iteration from the very first element so the very first element happens to be one the first and the foremost thing that i'm gonna do is to check the availability of one in the availability map what is the frequency of one in the availability map the frequency is one that means the number is available for utilization moving ahead i check whether this one number is being looked out for to be part of any of the existing groups or not no groups have been formed so far that means this nobody is looking out for this element and it's time to create the very first group using one when we are creating the very first group using one what do we simply check whether the element one plus 1 plus 2 are also available for utilization or not because in the question it is specified that each group should have a minimum size of 3 and the number should be conjugative in nature so the first element would be one itself the second number would be one plus one which is two and the third number would be one plus two which is three in short it means that we are looking for availability of three numbers the first number is one the second number is two and the third number is three so what are the availability of one two and three whether it is greater than zero or not the availability of one is one the availability of two is one and availability of three is two that means all three numbers are available as a result of which we will be going ahead and forming the first group which is one two and three along with that what we should be doing we should be reducing the frequencies of each of these elements from the availability map so the frequency of one gets updated to zero the frequency of two also gets updated to zero and the frequency of three gets updated to one along with that another important aspect that we should be taking care of is that we will be creating a new vacancy for element four because there could be cases that this group can also accommodate four in future if needed the bare minimum criteria for forming the group has been fulfilled however there could be case that four can be become part of this group as a result of which four will be created as a new element in the vacancy map and the frequency of four would be one so far so good let's proceed ahead to the next element and let me just write dot over here because a vacancy has been created we can close it if needed or we can add 4 on to it the next element that we have happens to be 2 what do we check whether this number is available for usage in the availability map or not the number frequency happens to be 0 that means the number is unavailable let's proceed ahead the element that we have happens to be 3 so again we look out for the frequency of 3 in the availability map so what is the frequency of 3 in the availability map it is greater than 0 that means this element is available for usage now again we are going to check whether is any group asking for this three element will check whether three as a key is part of the vacancy map or not if you carefully analyze there is no entry with three as the key in the vacancy map that means no group is actually looking out for element three as a result of which there is only one option left with three is to start another new group because nobody is asking for three in the existing group the only possibility remains is to create a new group using three in order to create a new group using three what are the constraints that were specified in the equation the first constraint was the minimum size should be three and all the elements would be consecutive in nature therefore we look out for the availability of three four and 5 in the availability map so let's do that and 3 is available 4 is available so does 5 and hence we will create another group with elements 3 4 and 5 along with that we will be creating another vacancy for element 6 could be added as part of this particular group in future if needed let's go ahead and create a new group we are consuming three four and five therefore we will have to reduce their frequencies by one the frequency of three gets reduced to zero so let's update zero the frequency of four gets reduced to one the frequency of five gets reduced to 1 again and let's continue the iteration and let's keep this group open-ended as well let's keep this group open-ended as well let's keep this group open-ended as well because more elements can be accommodated in future if needed the next element that we have happens to be three what is the frequency of three in the availability map it is zero therefore we should be skipping this up this number is not available for usage let's proceed ahead next we have four so we will check whether this number is available for usage or not this number is available for usage it has the frequency one now what we will be checking the first and the foremost thing whether it can become part of an existing group or not for checking this up we should be looking out for the vacancy map do we have an entry for 4 in our vacancy map yes we have an entry for 4 as a result of which 4 will be getting added on to this particular group since 4 is getting added to this particular group we should be reducing the frequency of 4 by 1 so the frequency of 4 gets reduced to 0 and along with that we should be removing this entry from the vacancy map and a new vacancy is getting created for the element five can be accommodated as part of this particular group if needed in future therefore we should be creating a new entry with element five comma one so remember this is a very important aspect of the algorithm if you are consuming on already existing vacancy created element then you should be creating another vacancy for the next subsequent element we are consuming four we should be creating another vacancy for five because it can be accommodated as part of this group itself let's proceed ahead the next element that we see happens to be five and we check whether the 5 is available for usage or not yes 5 happens to be available for usage its frequency is one we again check whether in the vacancy map it is present or not yes it is present in the vacancy map as well therefore 5 will be getting hooked on to this particular group the vacancy will be getting reduced to 0 and new we can see for element 6 will be getting created 6 is already part of the vacancy map therefore will update the frequency to 2 and with this we have successfully iterated over all the elements and as a result of which we can put closure on these groups the first group that gets formed is 1 2 3 4 5 and the next group that gets formed is three four and five in order to conclude it up let's quickly walk through the coding section and i hope you guys understood the entire algorithm i'll be exactly doing the same steps as i have just talked here so let's get started the first thing that i have done here is to create the availability map which will basically show the frequency of each and every element passed in the input array and the next map that i have created is the vacancy map now comes the code algorithm starting from line 13 so we'll be hydrating over the input array one by one in an iterative fashion i equals to zero i is less than number length i plus and the first and the foremost thing that we are going to check is whether the number is available for consumption or not in case that in the availability map its frequency is less than or equal to zero we abort the process and we look out for the next possible element that exists in an input array if the number is available then what do we do the first and the foremost thing is to check whether somebody is looking out for that particular element to be added in the group or not so that information will be retrieved from the vacancy map and we check whether in the vacancy map corresponding to that particular element the frequency is greater than 0 or not if it is greater than 0 that means any of the group is looking out for that particular element to be added and as a result of which the first thing that i am going to do is to reduce the frequency of that particular element from the availability map and along with that i will be up creating a new vacancy for nums plus 1 in the vacancy map itself why because a new vacancy is getting created as we saw in the case of 4 and 5 and the frequency of 4 will get reduced by 1 which has been done at line 21 so we are basically reducing the frequency in the vacancy map for that particular element and creating a new vacancy for num plus 1 in the vacancy map for future consumption and in case there was no vacancy of that particular element in the vacancy map at line number 18 it retreat falls then that means it's time to create a new group for creating the new group the minimum size should be three and the number should be consecutive in nature so we look out for the availability of nums uh at the ith index and the availability map if it is greater than zero num plus one is greater than 0 num plus 2 is greater than 0 if all three are greater than 0 then we simply reduce their frequencies in the availability map and along with that we create a new vacancy in the vacancy map for the element nums plus three so this is the same case while we were creating the group starting from one two and three and a vacancy was getting created for four so this has been taken care of line number thirty three if none of the conditions are met and it's not possible to consume an element we simply abort the process and return false if we are successfully able to iterate over all the elements we simply return to so let me just submit this up accepted 42 faster i am connected to vpn but that's all right uh the time complexity of this approach is order of n because we are iterating over the nums array once twice basically and it's pretty straightforward and the space complexity is also order of n with this let's wrap up today's session i hope you thoroughly enjoyed it and understood the algo if you did then please don't forget to like share and subscribe to the channel guys it really means the world to me and i'm looking forward to having conversations with all of you in the telegram group you
Split Array into Consecutive Subsequences
split-array-into-consecutive-subsequences
You are given an integer array `nums` that is **sorted in non-decreasing order**. Determine if it is possible to split `nums` into **one or more subsequences** such that **both** of the following conditions are true: * Each subsequence is a **consecutive increasing sequence** (i.e. each integer is **exactly one** more than the previous integer). * All subsequences have a length of `3` **or more**. Return `true` _if you can split_ `nums` _according to the above conditions, or_ `false` _otherwise_. A **subsequence** of an array is a new array that is formed from the original array by deleting some (can be none) of the elements without disturbing the relative positions of the remaining elements. (i.e., `[1,3,5]` is a subsequence of `[1,2,3,4,5]` while `[1,3,2]` is not). **Example 1:** **Input:** nums = \[1,2,3,3,4,5\] **Output:** true **Explanation:** nums can be split into the following subsequences: \[**1**,**2**,**3**,3,4,5\] --> 1, 2, 3 \[1,2,3,**3**,**4**,**5**\] --> 3, 4, 5 **Example 2:** **Input:** nums = \[1,2,3,3,4,4,5,5\] **Output:** true **Explanation:** nums can be split into the following subsequences: \[**1**,**2**,**3**,3,**4**,4,**5**,5\] --> 1, 2, 3, 4, 5 \[1,2,3,**3**,4,**4**,5,**5**\] --> 3, 4, 5 **Example 3:** **Input:** nums = \[1,2,3,4,4,5\] **Output:** false **Explanation:** It is impossible to split nums into consecutive increasing subsequences of length 3 or more. **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` * `nums` is sorted in **non-decreasing** order.
null
Array,Hash Table,Greedy,Heap (Priority Queue)
Medium
347,1422
27
in this video we'll go over lead code question number 27 remove element given an array called nums and an integer called Val our goal is to remove all occurrences of Val in the nums array and we must do it in place but there's also a Twist let's say that there are K elements in the array that are not equal to Val then instead of actually removing all elements equal to Val we can just replace the first K values of nums to be the elements that are not Val then we'd return k for example let's say that this is the nums array and the value to remove is six three elements here five seven and one are not equal to six so all we have to do is replace the first three elements of the array to be five seven and one and the rest doesn't matter then we'd return 3 to indicate that the new array consists of only the first three elements now you may be wondering why would we do something like this when we could just use the pop method that's built into python lists we could just Traverse the list and if an element is equal to Val then just pop it off now this approach works but the problem is that the pop method is very inefficient because if we pop an element near the start of the list then all the other elements need to be shifted back one spot each shift runs in O of end time and in the worst case we'd have to do n shifts so this algorithm ends up running in O of N squared time so instead we'll use a two pointer approach that runs an O of end time and overwrites the first K elements let's look at the code and see how we can do this in Python first we'll create an index variable I and have it start at Index 0. this variable will keep track of which spot to overwrite in the array then we'll enter a loop using the variable X which will take on the value of each element in the array then we'll compare x with Val and see if they're equal x is 5 and Val is six so they are not equal to each other so this if condition is true since we found an element that is not equal to Val we now want to write that element X at index I right now they are both five so we just replace five with five and nothing changes then we increment I so that it's ready to write at the next slot so next X is six and Val is also six so they're equal we actually don't do anything in this case and just move on basically we keep on searching for an element that is not equal to Val so we can write it to the array next 7 is not equal to six so we'll write 7 at index I then increment I next one is also not equal to six so again we'll write one at index I increment I and move on finally the last element is six which is equal to Val so we can just skip the last iteration and we're done with the loop the last thing to do is return the total number of elements that are not equal to Val but instead of going back and Counting we can just return the value of I since it's been keeping track of the index of the last element that was written and even though I right now is actually pointing to one spot past the last element of the array since indices start at zero this is actually the correct number I equals three so we'll return three and as you can see there are in fact three elements that are not equal to Val which take up the first three spots of the array
Remove Element
remove-element
Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm). The order of the elements may be changed. Then return _the number of elements in_ `nums` _which are not equal to_ `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: * Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. The remaining elements of `nums` are not important as well as the size of `nums`. * Return `k`. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int val = ...; // Value to remove int\[\] expectedNums = \[...\]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[3,2,2,3\], val = 3 **Output:** 2, nums = \[2,2,\_,\_\] **Explanation:** Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,1,2,2,3,0,4,2\], val = 2 **Output:** 5, nums = \[0,1,4,0,3,\_,\_,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `0 <= nums.length <= 100` * `0 <= nums[i] <= 50` * `0 <= val <= 100`
The problem statement clearly asks us to modify the array in-place and it also says that the element beyond the new length of the array can be anything. Given an element, we need to remove all the occurrences of it from the array. We don't technically need to remove that element per-say, right? We can move all the occurrences of this element to the end of the array. Use two pointers! Yet another direction of thought is to consider the elements to be removed as non-existent. In a single pass, if we keep copying the visible elements in-place, that should also solve this problem for us.
Array,Two Pointers
Easy
26,203,283
528
Yo Welcome to Record History of Net YouTube Channel Please subscribe Solar Light of Computer Problems Create Problems of Random Pick with Weight Some Problems Its and Prohibition W Positivity Saver W Fight Script Belt Join Aankh Sahitya Front Function Fix Vidya Randomly Picks and Jokes in The proposed into it's best to a vision input tweet error and loving to returning officer impromptu index wet nurse understand this example common the problems loop confusing so let's do the example it's okay Shabbir 123 456 in it's okay and airplane mode ko band thing aa siddhik total Weight Of The Amazing Minister To Consider Details Separately Hundred Person Okay So Kind Of Boat Willing To Return Indicated That E Want To Return In Black [ __ ] Dick Needs To Want To Return In Black [ __ ] Dick Needs To Want To Return In Black [ __ ] Dick Needs To Be A Good Profession To The Weight Of The Tax Is So Let's Heer And Offices Se Zor Only one ok khush show what is the position of this index and that how many times index next to be retention total sum this fantastic year considering the tragedy of hundred percent 1654 plus three plus 6 days into your for sure of teenage and hundred percent How many times and how many percentages How many times before being late for office Finances How many times need to return President Shiv and divide by 40 OK * President Shiv and divide by 40 OK * President Shiv and divide by 40 OK * Hundreds of evil does that this is going to be the percentage Taat's interview The title of Adi Sahare Na Quit 110 177 Sort Of A Country Time Seven Per Cent Will Need To Register Na Index C Protein Go For The Index 1535 V0 And 210 Dars Pain Adhik Twitter Na Aa Jaye Index 1742 All Say Hain Sorry Number Is For Yes Protein In T20 Today Going To Be Almost around 800 to return dependency in force for the plastic surgery 600 these are more net we 14% visit to return these are more net we 14% visit to return these are more net we 14% visit to return of intake last intake service word problems statement from winnie to reach of inner portion coming to the waste will have in proportion to the development minister Returned At Index That Aapke Knowledge Science Tenth Solution Approach A Ajay Ko Ek Alag Saheb Returns The Amazing Wits And Actors Where Is The Percentage Indices Contributing And Other Indices Having Proposal To The Number Is The British Yes Okay Nawda The Thing Bhi Naukri Are Switch Total Samuday GPS on OK reliable hundred percent after all Now one thing which aims and they want to generate random index of which so they can do is not worth the user in them from desire to class and generate random number box between I may not have a great effort Will Generate Between December And 202 MP3 A's Swelling Red Number Random Pages Which Lies In Between Different 023 Loop's Decades Content Which Have The Number Random Number Minister Beach Center In The Proposal To The Water Which Went To Chronic To The Final Between To Generate Inverter Nutrition And 1000000 1218 A Sadhu Generate Proud Of Position Show One Thing Binoy Speed ​​Is Weight And We Have Always With Binoy Speed ​​Is Weight And We Have Always With Binoy Speed ​​Is Weight And We Have Always With Starting From One In This Point I Will Be Anything Total Time Is Equal To 410 Range Available Through Inch In Your Dream We Want Two parties in this train whom the secretary a day after seven 50 updates partition will give the inducers 000 indexes warning 90 index sensex 253 person should give the induction course number is higher and plastics how to download 12345 160 that in som and pichde phone number one we Can Do It Is Target Will Labeling A Plate Gear Solid S&amp;P Labeling A Plate Gear Solid S&amp;P Labeling A Plate Gear Solid S&amp;P 500 Index Hero From Here To The American Earth Will Take Index One From Dead Own Words Will Take In Printed To Interest Will Be Considered Jatin Birthday Will Be Able To This Partition Of This Range Is Not Uniform Distance to be the proposed in with your support to the Positive Contributing Editor in Hindi But quite best all the number date will have come and with sparing Begusarai from here.the British 1021 will be Begusarai from here.the British 1021 will be Begusarai from here.the British 1021 will be and index 40 points 6 Difference will be and index biro that after all in from one to three and Will be 420 and 120 is going to be index the one in from that such it for more saiyan response from five words [ __ ] words [ __ ] words [ __ ] se mix indices tube informed her own words for starting index 320 light a can do for examinations bihar cabinet all in one year Next 1234 And Anvi Exit In This Will Get The Sporty Look Is Tasty And Range Better Best On Hot Wheels After Having No Problem Office China Taxes In This World With King Now Profit In Two Years Now They Can Generate Random Number OK Vighn-Vighn Generator Random Number Between Vighn-Vighn Generator Random Number Between Vighn-Vighn Generator Random Number Between Range 1-2-14 OK Liquid Form Number Range 1-2-14 OK Liquid Form Number 10 - 10 - 10 - Research into Determine Number in the middle of India will start from difficulties after - 10 - 2nd year - 30 will get out post after - 10 - 2nd year - 30 will get out post after - 10 - 2nd year - 30 will get out post - 3 tats effective equal to speak what - 3 tats effective equal to speak what - 3 tats effective equal to speak what is teen sidana - sid is teen sidana - sid is teen sidana - sid ki aapke butt s par raw partisan logic it means to indore negative test match Tourist Kheer Want To Get A Tune And Here You Want To Get A Is Vansh Sage Saint's Support Will Two Years Will Naagin Aa Meet Positive And Anil Sector-21 Sadhak Will Get The Correct And Anil Sector-21 Sadhak Will Get The Correct And Anil Sector-21 Sadhak Will Get The Correct And You Say Mix Go Back To The Code And Review And Hard To Understand So Let's Go Through This Course Will Have 10 Scooters And Behavior That Bigg Boss Went There In The Country Type Women Should Be Worshiped By All Our Award Office Amazing Should We Do This Post Will Depends On Length Of But Here In This fast missions fast element with element of dahez ki meeting the song just get the range finder next index time tak 500 years of generating mere length of the india generating 10 current mili na virvar and also will win the ranji song ki aapke aansoo it will generate Range 102 Aa Protein But Years In The Input Tax Clearly It Is Definitive Generator AIIMS One To The 21212 50 Will Always Generator Aa Between The Will Always One Shift Desire Chances Of Generating More Than 100 Will Get The Correct Train Number 90 Withdrawal Number And Generated With mother fukes with return value positive-positive and in the written value positive-positive and in the written value positive-positive and in the written test and when love videos and villa 56001 will return from this to main office badr complete knowledge all media jhal main office record accept the main ka rakshak in this video please like it you ghee Add Comments You have a different approach and you are looking for solution for different problem thank you guys
Random Pick with Weight
swapping-nodes-in-a-linked-list
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. * For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). **Example 1:** **Input** \[ "Solution ", "pickIndex "\] \[\[\[1\]\],\[\]\] **Output** \[null,0\] **Explanation** Solution solution = new Solution(\[1\]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. **Example 2:** **Input** \[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\] \[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\] **Output** \[null,1,1,1,1,0\] **Explanation** Solution solution = new Solution(\[1, 3\]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: \[null,1,1,1,1,0\] \[null,1,1,1,1,1\] \[null,1,1,1,0,0\] \[null,1,1,1,0,1\] \[null,1,0,1,0,0\] ...... and so on. **Constraints:** * `1 <= w.length <= 104` * `1 <= w[i] <= 105` * `pickIndex` will be called at most `104` times.
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Linked List,Two Pointers
Medium
19,24,25
1,439
hello guys welcome back to the channel so guys in this video we will be solving lead code problem number 1439 find the kth smallest sum of a matrix with sorted rows so let's first understand the problem statement the problem is saying you are given a matrix of size m cross n and then integer k which has its row sorted in non-decreasing order so we are given non-decreasing order so we are given non-decreasing order so we are given an array of something like let's take the first example so the array matrix has all the rows in sorted order in non decreasing sorted order so let's just take the example of first so the matrix is this and we have an integer k so the integer k is 5 right so you are allowed to choose exactly one element from each row to form an array so we have to choose exactly one element from each row of the of this matrix right and we have to return the k smallest array sum among all possible arrays okay so guys if we choose exactly one element from each row so the all the possible arrays can be like we can have one comma two we can have one comma 4 we can have 1 comma 6 and then we can have 3 comma 2 similarly i will just write 3 comma 4 and then 3 comma 6 and then 11 comma 2 and then 4 11 comma 4 and at last 11 comma 6 so we will for this matrix we can have total nine possible arrays where we have at least one element from each row all right so after forming this array we can find the sum of each all arrays like first will be the sum will be three then five and seven then five then again seven 10 9 10 13 10 15 then 17 so these are the sum of these array so after that we have to return the k smallest array sum so we have to return the k smallest so from this the kth cell smallest can be like if we sort this in increasing order so 5 comma 7 comma 13 comma 15 comma 17 so the here that is k equals to five fifth smallest will be sev this seven okay so this is the problem statement all right now we have to solve this so guys the one thing that is important to see here is that we don't actually have to create these array we have to just keep the sum with ourselves because we have to written the kth smallest array sum not the actual array so it is the crux of that problem this problem so now let's see how we will solve this so let me just explain with this example so we will now move towards the board and now we will discuss this example so let me create the array so the array is 1 10 and 1 4 5 and then 2 3 6 and the value of k is 7 right so this is our example number 3 so we will be seeing how we will solve this problem by solving this example so now let's see the approach so what we will do is we will start with row first so we will create a temporary array which will contain our row first row of this matrix so it is 1 comma 10 so we will keep it as a temporary array so now what we can do is we know that we just have to keep the sum so to include the element from second row what we can do is we can uh include this one after 1 10 and 10 so for this one we can have some like 1 plus 1 so adding 1 adding 4 adding 5 and then for this 10 we can have 1 4 5 right and then for this 10 we can again add 1 4 and then 5 so what will be the sums so 1 plus 1 is 2 4 plus 1 is 5 plus 1 is 6 again 10 plus 1 is 11 ten plus four is fourteen and ten plus fifty five is fifteen n plus one is eleven ten plus four is fourteen and ten plus five is fifteen so these are all the sums that we will get if we include one element from first and second row each okay so now if we sort this so we will get something like 2 5 6 11 14 15 right so now what we can do is now these are the sum when we have exact chosen exactly one element from row one and row two now we have to include row three right so what we can do is after this two we can add two three six and again create an array something like this but we have to make a decision here we have to prune this array so what i mean by this is we have to remove some irrelevant elements that will not be included in our answer for example here the value of k is 7 so we know that we have to find the kth seventh smallest so but the size of array is one two three four five six seven eight so if the size of array is eight so we know that the last array and last element can be removed because it will not be included because all these seven elements are smaller than this and they will make the sum and some smaller than the last element so we can remove the last element and now at this stage what we can do is we can include we can add two into we can add 2 3 6 and again this tree will be created for each element and then we will create a final array and after sorting that final array we will return the kth element of that array and this will be our answer so now let's move towards the coding part so let's see how we will code this so what i will do is firstly i will initialize our size of array so this is the number of rows and this is the number of columns now what i will do is i will create a temporary array which will store the row zero zeroth row of our matrix now what i will do is i will iterate over each row starting from first till n so this is the for loop for i uh for each row now inside this what i will do is i will create a current array which will store the current uh sum till current row that is if we are at i equals to 1 so current will store the sum in which we have chosen exactly one element from the row 0 and row 1 all right so after this what i will do is i will go to each column m and j plus and inside this we will have to create one more loop what will it do is so for in i equals to zero so we have to take k we have to take some another name i t is equals to zero i t and so we have to say that i t less than temp dot size and id plus so this is the array for that submission for iterating over this array this is our temp array so we will be moving we will be seeing in our time array this loop right so what we have to do current dot push back amp of i t plus a of i j so this will do our sum something like this if we have the temp array so we will iterate over the so if this is the damp array so we will iterate over all the this row and add this right so this is what we are doing in this step now after this what we will do is we will sort the current array current dot begin comma current dot end and after that we have to clear the amp array and we have to just put we will either put k1 k plus 1 elements or the current if current size is smaller then we will just put that only for example int maximum size is equals to minimum of k plus 1 comma current dot size right now what we have to do is for end j equals to 0 j less than max size j plus we just have to push back in temp dot pushback and we have to write current of j right so after this at last we have to return the amp a minus one because uh we have the temp array has index from zero and k kth is starting from 1 so we will return temp of a minus 1 so let's just try running the code so okay no matching so we have to type pass this to end so let's see so it is running absolutely fine let's just try submitting it so yeah it is getting submitted so let me just again explain the code to you so initially i have initialized n and m with the size of matrix and then i have created a temporary vector which will which is storing the zeroth row and then i am iterating over all the rows remaining rows of the matrix and inside that i am creating a current vector which will store the which will store this the current sum right so and then we are this is for each column and inside this we are moving in this temp array so we are adding uh in temp array suppose 110 10 is temporary so we are including one four five with each element of five one four five with each element of the empire so what we are this is what we are doing in this loop and after that we are sorting that this current array and only taking the k plus one number of elements or if it is less than we are taking the old current array and pushing it inside the temp and finally we are returning k minus 1 the element which is at the index k minus 1 in the temporary array right so hopefully you are able to understand this problem and solve this problem so thanks for watching the video and do hit like if you are able to understand this and subscribe for more videos like this thanks for watching
Find the Kth Smallest Sum of a Matrix With Sorted Rows
running-total-for-different-genders
You are given an `m x n` matrix `mat` that has its rows sorted in non-decreasing order and an integer `k`. You are allowed to choose **exactly one element** from each row to form an array. Return _the_ `kth` _smallest array sum among all possible arrays_. **Example 1:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k = 5 **Output:** 7 **Explanation:** Choosing one element from each row, the first k smallest sum are: \[1,2\], \[1,4\], \[3,2\], \[3,4\], \[1,6\]. Where the 5th sum is 7. **Example 2:** **Input:** mat = \[\[1,3,11\],\[2,4,6\]\], k = 9 **Output:** 17 **Example 3:** **Input:** mat = \[\[1,10,10\],\[1,4,5\],\[2,3,6\]\], k = 7 **Output:** 9 **Explanation:** Choosing one element from each row, the first k smallest sum are: \[1,1,2\], \[1,1,3\], \[1,4,2\], \[1,4,3\], \[1,1,6\], \[1,5,2\], \[1,5,3\]. Where the 7th sum is 9. **Constraints:** * `m == mat.length` * `n == mat.length[i]` * `1 <= m, n <= 40` * `1 <= mat[i][j] <= 5000` * `1 <= k <= min(200, nm)` * `mat[i]` is a non-decreasing array.
null
Database
Medium
1327
910
hello guys so today i am going to explain lead for problem number 910 the smallest range we are given an array of integers and we can do either of the two operations that is decrease the analysis of the array by k or increase the element by k we cannot do anything other than this and we can do this operation only once to each element so what we have to do now is that we have to return the smallest possible difference between maximum and minimum value of our new array which will be getting after applying these operations so how do we approve this problem we can like this is very clear that it is a greedy problem so in 3d problem most of the approaches are that we fix a particular element and we check our answer corresponding to that element so what is what we can let's say that this is uh so we let's say that we have a number line this okay okay so now there must exist a particular partition so the partition does what is that below all the elements which are existing below that partition must be increased with k okay must so this is a kind of intuition which we get from all the greedy approaches so how do you approach up to here is that you solve a lot of greedy problems and you will be able to get the inclusion that we have to somehow make a partition here after that things are very easy so what you do is that if you keep an array you subtract all the other elements you sort your array given array you subtract all the elements of the particular partition and you just find the minimum and maximum of this array you update your answer correspondingly so the partition we don't have to make partition between in between we can make partition here and here so we just traverse our array and we subtract all the elements above our current position and we had all the elements below i will explain that we are uh yes uh if we add k to this element element will be this one and this one because we are separating will so if you have any doubts please ask in comments thank you
Smallest Range II
nth-magical-number
You are given an integer array `nums` and an integer `k`. For each index `i` where `0 <= i < nums.length`, change `nums[i]` to be either `nums[i] + k` or `nums[i] - k`. The **score** of `nums` is the difference between the maximum and minimum elements in `nums`. Return _the minimum **score** of_ `nums` _after changing the values at each index_. **Example 1:** **Input:** nums = \[1\], k = 0 **Output:** 0 **Explanation:** The score is max(nums) - min(nums) = 1 - 1 = 0. **Example 2:** **Input:** nums = \[0,10\], k = 2 **Output:** 6 **Explanation:** Change nums to be \[2, 8\]. The score is max(nums) - min(nums) = 8 - 2 = 6. **Example 3:** **Input:** nums = \[1,3,6\], k = 3 **Output:** 3 **Explanation:** Change nums to be \[4, 6, 3\]. The score is max(nums) - min(nums) = 6 - 3 = 3. **Constraints:** * `1 <= nums.length <= 104` * `0 <= nums[i] <= 104` * `0 <= k <= 104`
null
Math,Binary Search
Hard
null
435
Hello hello guys welcome back to take division in this video you will see the noble shopping intervals problem which is established as dog is challenge and this will be dongri algorithm so let's read problem solve this problem we have collection of rare to find the number of units which are in Order to make the no veer 1023 loot 68000 666666 se withdrawal values ​​but no problem ki se withdrawal values ​​but no problem ki se withdrawal values ​​but no problem ki vihar-3 overlapping intervals nine to vihar-3 overlapping intervals nine to vihar-3 overlapping intervals nine to remove the minimum number of interviews in order to make the sentence was not known what we can do you can simply remove This 023 Land Can Remove This Point To 6 To Make The Subscribe Button Just 231 Will Remove All Subscribe Now To Three Loot 689 Subscribe Interview What Is The Meaning Of Do CBSE Inter List Of Intervals Indian Overlapping Intervals Absolutely To Minimum Of What Ever Removal Surgery Possible Soayenge Utvan Possibilities to Remove 062 Possibility to Remove 60406 Nodal Center List in To-Do Remove 60406 Nodal Center List in To-Do Remove 60406 Nodal Center List in To-Do List of Noble Descent Example Similarly in Travels and Tours 2006 Subscribe Saugandh Possible Points 216 6069 If that is the vision of this science well and they can right to remove the 023 Lad To 60 12152 6 Others Subscribe And Will See What Does Not All Possibilities In To-Do List * Does Not All Possibilities In To-Do List * Does Not All Possibilities In To-Do List * * * * * * * * * * * * * * * * * * * No Internet Problem Neither 10 Minutes Ago Diy Aa Photo Send 628 Basically In Overlapping No Latest COD Romantic Representation In Order To Get The Concept Of Remove With Minimum Number Of 100 This Is The Figure Winters Bcd Na Dhir With Values ​​From Left To Bcd Na Dhir With Values ​​From Left To Bcd Na Dhir With Values ​​From Left To Right What Will Be The Number To Remove The Evening Intervals 999 9999 First option will be B C D A We removing girls and women in the world will only be known as well reddy shri removals no the question is that will keep all the best option is that we can remove the see and observe Mode Switch Board The Story In Order To Get A Good Job Skills Develop Noble You Subscribe Minimum Number Remove Which Were Making In Order To Make The Meaning Of These Travels From Central To Make No Love You To The Number Remove Which Can Be Possible For First Number To Make The Meaning Of Typing In The Morning That Universe To The Problem Statement Complete Ki Nao So Let's Not Look At The Cases In Order To Solve This Problem Saudi Arabia Basically Three Cases In Case 180 Nobel Prize In The First Period You Can Straight Completely Normal Behave Like Subscribe And Problems Will Be Considered Do n't Forget To Subscribe To His Novella Subscribe The Video then subscribe to the Page Achievement And Bare Basically The Same Okay Saudi Two Figure Falls Under K To Overlapping K Not Remember To Remove The First One Should Also Keep In Mind Which No One In This World Can Be Completely In This Is Not The Beach Inside A Bird Subscribe This Channel And Subscribe This Channel Like Subscribe And Scientist NC Bread This Remove This A Pattern That Will Be Better Choice And Free Mode Of Bandhai Kabir Person Also Overlapping Time Interview With To The Journey To The Subscribe The Amazing Veer The Latest Seervi That All The Interval Seen Ascending Order By First Value Date Will Be Equal To Id's CD 110 Will Be The Order Canceled To The List Of But Will Not Be Able To Which Will Be The Left Front * * * * * * Avoid To Remove The Left Front * * * * * * Avoid To Remove The Left Front * * * * * * Avoid To Remove The Center Of The In the will be quite late daily waste to best interval of this is ok so this mix it well in PS2 this is two overlapping case one Sudhir which were falling saw in the case of pm swimming this is not be removed his son will Be A Born Nor Will Get Updated With 22122 Operation In This Is The Subscribe to the Video then subscribe to the Page Men Will Be Removed Nagaur Road Will Be Appointed To CNC Now Remote Control And Account Will Be Intimated 512 MB 299 This point to see the subscribe The Video then subscribe to the Page if you liked The Video then subscribe to the Page that and also for the end interval of this defect there right hand side off This and interval of this is directly overlapping this is the role of this point to overlapping citizen widow and will be totally free mode on this is not only so you can directly NC noble and e will give the number of which will be moving restaurant nov12 hu is This examples are basically not covering all the cases but you can try from different example a well known latest look at the code for this algorithm Saudi is the code veer 1999 will run through all The individuals and so will be making competition will always be with the subscribe is like this left side se difficult to values ​​in this right in difficult to values ​​in this right in difficult to values ​​in this right in travel and is loop control values ​​and travel and is loop control values ​​and travel and is loop control values ​​and animals will win over lapping in that case will simply update these elements of Obscuritism Overlapping subscribe And subscribe The Amazing Removing This And They Will Update You Will Know Like This Is The And The Left Will Get Updated To Right And Right Will Move One Position K 100 Welcome To Be Removed And You Will Imbibe All Cases In Order To Solve This Problem If You Are Able To Understand Problem Comment Subscribe Like Share And Subscribe
Non-overlapping Intervals
non-overlapping-intervals
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\] **Output:** 1 **Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping. **Example 2:** **Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\] **Output:** 2 **Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\]\] **Output:** 0 **Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. **Constraints:** * `1 <= intervals.length <= 105` * `intervals[i].length == 2` * `-5 * 104 <= starti < endi <= 5 * 104`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
452
1,048
hey everyone today we are going to serve the editable question longest string chain so you are given array of words where each word consists of lowest case English letters so what a is a predecessor of word b if and only if we can insert exactly one letter anywhere in word way without changing the order of the other characters to make it equal to wall B so for example ABC is a predecessor of a b a c while CBA is not and the wall chain is a sequence of what one two and a 1K and where what one is a predecessor of one two and one two is a predecessor of was three and so on a single one is trivially a word chain with k equal one so return the length of the longest possible words chain with the words choosing from the given list of one okay so let me explain how we think about the solution so according to the description so we can create another word B from what a by adding one letter anywhere in word a so seems like it's easy for us to solve the question with sorting because the difference between word a and what B is just one liter so I thought sorting uh sorting might make the question easy to compare words and but the question is that what do you sort or input data by so each character in all words So my answer is to sort by length of input Wars so I have a three reason so first reason is that so increased potential for efficient of solution so sorting the award by their links allows us to process the walls starting from the shortest potentially leading to more efficient algorithm as we can prioritize shorter was fast so this is a fast reason and the second reason is that enables pre-processing so since we are enables pre-processing so since we are enables pre-processing so since we are sure that what B is plus one longer than one a and the world B has one different letter from word a so if we take off one letter from one B one by one we can create all predecessor of world B which are all possible one a so for example so what b is now ABC so if we take of a from one B so we can create like a BC right this is a one possible predecessor right and so if we remove B so we can create AC and the same thing if we remove C so we can create AV right so we have like a three possible predecessor candidates one more important thing why we should sort by Links is that now we check ABC which is length of 3 so that means we already finished checking the max chain length until length of 2 because we sorted by length of input words so in other words we should have the result for all possible walls until length of 2. so all possible was means all was coming from input list was so this is a sad reason to sort by length of walls so in this case we need to keep all the previous results so what strategy do you use to keep the results my answer is dynamic programming so more precisely to use hashmap so we can only use was from input list words so the keys of hashmap should be was from input list words and each value stands for like a Max chain links for each word okay so let's see what I said with this example so current world B is ABC and we have three possible predecessor candidates like a PC AC and AV and let's say we have the result until length of 2 like this BC is 1 and AV and 2. and before we check in so every time so we uh plus one is current one because this is a one positive change right at least we have a one chain for ABC so that's why ABC is now one and the first of all take the BC so we have result of VC which is one so compare like this so this is a um like a formula Max um current what passes so BC plus one so Now ABC is one right and uh BC is one chain and this time we uh some character right into anywhere in BC right so that's why we need to plus one so that's why one plus one total two so which is a longer chain definitely this one right so that's why update ABC um with two easy right and then so we repeated this process and that so look at the AC check result of AC but we don't have the result for AC in hashmap so which means AC is not listed in the input list words so just ignore AC and then address check a b and then we have a result of a b which is 2 in this case so now um ABC long exchange for ABC is 2. so that's why so C ABC so change ABC hashmap ABC is 2. and so in this case this key should be a b so A B is 2. so 2 plus 1 so which is a 3 right so compare two versus three so three is a longer chain right so that's why update ABC um V3 in this case so we repeated this process and in the end this hashmap named negative change and change has the max chain length for each valid world so all we have to do is just take a marks of change from hash map and yeah seems like a sorting a dynamic algorithm strategy works so that is a basic idea to solve this question so with that being said let's get into the code okay so let's raise a call first of all interesting hashmap so let's say change and how smart and as I explained earlier we need to sort um all was by length so sort it was equals sorted and there was and then the key should be length so easy right and then next iterates through all words one by one so for what in sorted was and first of all um so current one itself is at least one chain right so that's why I change and the word equal one and then we use another for loop I in range and the length of what and uh so first of all we should create a predecessor so let's say equal what so current what in the column index Plus what in the I plus 1 and until last so yeah this is a little bit complicated so let me explain with this and so let's say what is ABC and then I equals zero in the case the first part this part so in Python and this number is like uh excluded so that means currently I equals zero so what i is like empty and then second part so I plus 1 is 1 right so from index 1 to rust we include everything so that means BC right so empty plus BC is BC and that when index number is 1. so exclude one or later so just uh in this case array index zero and uh I plus one is two so we should add 2 or under later so in this case so skip index one and add from index 2 and that means C right so that's why a plus c is C AC and then yeah same thing I equal to in that case so exclude the 2 or later so that means index 0 and 1 so that means a b and uh I plus 1 is 3 so there's no uh character I think X3 so that's why M3 so we can get a B so in the end we can create three predecessor candidates like a PC AC a b yeah so uh and I hope you can understand now and then so if predecessor in chains so that means current predecessor is like a valid word in the case um chains and current what so in this case ABC equal Max and the chains and the word buses change and parenthesis plus one and then after that just return some Max of values in hashmap so change dot values yeah that's it so let me submitted yeah looks good very center algorithm bid 96 percent so time complexity of this option should be order of analog n plus length of walls multiply 16 so overall time complexity should be order of energy so n log n comes from sorting plus length of was and multiply 16 so 16 comes from one of constraints I didn't mention that but each length Max of each length is 16. so and then we remove each character one by one so at most we execute 16 times and this is the number of words so actually which is n so 16 n and we remove the constant number so that's why n log n plus n so and in this case analog n dominates the time so that's why overall complexity should be order of n log n and the space complexity is I think o n so N is a number of words so we use a change so at most um the number of data in hashmap is equal to um Links of input was so that's why yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
Longest String Chain
clumsy-factorial
You are given an array of `words` where each word consists of lowercase English letters. `wordA` is a **predecessor** of `wordB` if and only if we can insert **exactly one** letter anywhere in `wordA` **without changing the order of the other characters** to make it equal to `wordB`. * For example, `"abc "` is a **predecessor** of `"abac "`, while `"cba "` is not a **predecessor** of `"bcad "`. A **word chain** is a sequence of words `[word1, word2, ..., wordk]` with `k >= 1`, where `word1` is a **predecessor** of `word2`, `word2` is a **predecessor** of `word3`, and so on. A single word is trivially a **word chain** with `k == 1`. Return _the **length** of the **longest possible word chain** with words chosen from the given list of_ `words`. **Example 1:** **Input:** words = \[ "a ", "b ", "ba ", "bca ", "bda ", "bdca "\] **Output:** 4 **Explanation**: One of the longest word chains is \[ "a ", "ba ", "bda ", "bdca "\]. **Example 2:** **Input:** words = \[ "xbc ", "pcxbcf ", "xb ", "cxbc ", "pcxbc "\] **Output:** 5 **Explanation:** All the words can be put in a word chain \[ "xb ", "xbc ", "cxbc ", "pcxbc ", "pcxbcf "\]. **Example 3:** **Input:** words = \[ "abcd ", "dbqca "\] **Output:** 1 **Explanation:** The trivial word chain \[ "abcd "\] is one of the longest word chains. \[ "abcd ", "dbqca "\] is not a valid word chain because the ordering of the letters is changed. **Constraints:** * `1 <= words.length <= 1000` * `1 <= words[i].length <= 16` * `words[i]` only consists of lowercase English letters.
null
Math,Stack,Simulation
Medium
null
1,614
hi welcome guys so that song is very simple question called maximum listing that's or the parenthesis so string is valid uh parenthesis string of vps if the mid following uh empty so empty is uh string or single uh character not equals to this or this and you can be written as a b so basically it's the valid parenthesis so i believe that everyone knows what is what it means and this state means that the listing test for example is that's zero and this is that's one because we have most uh fixed city inside one and then this is two because in this part is two okay and ask so somebody give you a string and then you read to return the nesting death okay so basically uh for this one uh i think you can use your eye right so this is three because this one and for this guy this is all those three and for this one uh it's one right enough for this one zero okay so a very simple uh very trivial idea is that uh you're just using the standard results the standard idea so for example uh so each time you see this you map into one and you'll see this you map into minus one okay so for this problem you only you can see one minus one 3 is 1 minus 1 okay and then you compute the prefix sum right so this is 1 this is 0. prefix sum means that uh just some over from left to right so this is one and one plus minus one zero plus one is one plus one is two minus one is one minus one zero plus one is one two three to one zero okay so this means it's the correct right and you can take the maximum okay so this is the depth okay so uh you just initialize the answer to zero so this answer is just one count and the result is our answer and then you go through the string if it's left then you plus one write your minus one and then you update what is the maximum number that you have stated right so this is just a single pass in the linear time finally return the results right this is a very simple idea that you could just go through okay so uh see you guys uh next videos
Maximum Nesting Depth of the Parentheses
maximum-nesting-depth-of-the-parentheses
A string is a **valid parentheses string** (denoted **VPS**) if it meets one of the following: * It is an empty string `" "`, or a single character not equal to `"( "` or `") "`, * It can be written as `AB` (`A` concatenated with `B`), where `A` and `B` are **VPS**'s, or * It can be written as `(A)`, where `A` is a **VPS**. We can similarly define the **nesting depth** `depth(S)` of any VPS `S` as follows: * `depth( " ") = 0` * `depth(C) = 0`, where `C` is a string with a single character not equal to `"( "` or `") "`. * `depth(A + B) = max(depth(A), depth(B))`, where `A` and `B` are **VPS**'s. * `depth( "( " + A + ") ") = 1 + depth(A)`, where `A` is a **VPS**. For example, `" "`, `"()() "`, and `"()(()()) "` are **VPS**'s (with nesting depths 0, 1, and 2), and `")( "` and `"(() "` are not **VPS**'s. Given a **VPS** represented as string `s`, return _the **nesting depth** of_ `s`. **Example 1:** **Input:** s = "(1+(2\*3)+((8)/4))+1 " **Output:** 3 **Explanation:** Digit 8 is inside of 3 nested parentheses in the string. **Example 2:** **Input:** s = "(1)+((2))+(((3))) " **Output:** 3 **Constraints:** * `1 <= s.length <= 100` * `s` consists of digits `0-9` and characters `'+'`, `'-'`, `'*'`, `'/'`, `'('`, and `')'`. * It is guaranteed that parentheses expression `s` is a **VPS**.
null
null
Easy
null
357
welcome guys welcome to my little song in section 357 uh so uh right so this problem is basically it looks like a high school i mean high school mathematics right it should not be on should not be only code right but we can still solve it uh just for fun so given integer n return the count of all numbers with the unit digi x where x is greater equals 0 less than 10 to the n so uh yeah so the same so on this if one is two right so you usually start from a zero one and two dot go to ninety nine right and uh but uh you only count uh countland if there's a no repeated digit right so basically you have uh right total you have what you have 100 minus uh nine of them right because uh one two uh 33 44 right so total you have 91. and uh if only zero then you only have zero okay so let's maybe make a table to make you guys understand so let's say only zero the answer is zero so this is answer okay i mean i apologize for my bad writing but you guys understand so we also only 2 is 91 right so that's right yeah it's a nine plus that's right yes okay so if one is one then you are going to zero one two three up to like nine right so total you have what you have ten of them how about i write ten as one plus nine and i want to write this 1991 as a one plus nine plus uh ninety sorry nah this is ten so eighty one okay so what i want to say is that uh if one is the two uh it consists of the element with the one digits and the two digits and then for the one digits you have ten of them right for the two digits you have nine times nine why nine times nine because the however the first one there are nine ninth uh there are one to nine you can choose right but for the second digits you can choose zero to nine but uh the but the uh but uh for uh but uh you are not allowed to choose any number which is the same as this okay so there are nine plus so this there's nine plus nine okay so now you understand the trick right you're honest intrigue so let's maybe write a trick so you know uh how about an equals three that let's just write down answer and we see so only goes three contains the number with the uh one digits two digits and three digits and we know the one digits will give us nine of length and the two digits will give us nine times nine of length right how about three digits so three digits right suppose you have three the first one can choose one to nine right because the first one can't be zero so they are knifelength and the second one can choose one can still have nitrous because the second one can choose additional zero to nine but any number which but you cannot choose the same number as the previous one so there are nine of them how about this guy so the third digits originally has 0 to 10 but you are not allowed to choose anything which you are not allowed to choose the least two right and at least two are different so you are nine times eight so the answer for n equals three must be uh must be like uh also you also need to count it consider the zero right so the answer must be one plus nine plus 99 plus 9 times not 99 times 9 times minus okay so this is an equal to 3 right so obviously y is an equals to 4 when n equals to 4 you have one plus nine times nine plus nine times eight plus nine times a times seven right this is the four digits contribution so zero first digits second digit third digit first digit okay so uh very easy right so let's let me define s to be one nine times nine is so it is n equal to four so this is only sorry this is n equals to two and equal to three four five six seven eight right and for anything you just return some uh from mod to m plus one let's just submit right so that's it and uh i mean yeah sorry so if you want to solve directly then you can check you can briefly say that oh insert zero and you check that for all but if you just prove also solve it then i think you will not solve it because i think only goes to a is too fast i'm sorry it's too large okay so uh this problem should not uh happen in the league code but we are just solving for fun right but because my video account is mathematics fun okay i'll see you guys in the next video
Count Numbers with Unique Digits
count-numbers-with-unique-digits
Given an integer `n`, return the count of all numbers with unique digits, `x`, where `0 <= x < 10n`. **Example 1:** **Input:** n = 2 **Output:** 91 **Explanation:** The answer should be the total numbers in the range of 0 <= x < 100, excluding 11,22,33,44,55,66,77,88,99 **Example 2:** **Input:** n = 0 **Output:** 1 **Constraints:** * `0 <= n <= 8`
A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
Math,Dynamic Programming,Backtracking
Medium
null
825
hey guys how's everything going this is chaser in this video I'm going to take a look at a two five friends of appropriate ages some people will make friends request the list of the ages is given that ages array and the HSI is the age of Earth person a will not make friends request way the person B okay B is not equal to a if any other following conditions are true so eight B is too small or A to B is bigger than a so people will not make friends request to people I will have a larger age which B is bigger than ten and H I is 1 and 100 bigger than 100 and ace more than 100 so this one actually is contained in this condition right so it's meaningless I think otherwise a will friend request be okay know that if a request be B does not necessarily request a so people will not friendly request themselves also how many total friends request may well just so we can just calculate whether it each pair would send friend requests or not right so the brute force I think we could do about the input an input is a maximal was twenty thousand people and the ages will be one from one to one hundred twenty so it's finite well this is a very huge hint we could start put force also how many pairs are there well it's 10 and minus one pair right so we can this pair but its direction its with the direction so something like this because he's direction we need to compare the twice right for each pair I known this note not to because it is already direction and this is not direction business without direction this direction for the photo of start will be in possibilities for the annual and minus 1 yeah so this is the near so this is the time complexity actually let's just track ok the first we will define should send should request okay a helper function which is from into I suppose this is already done I create account initialize to 0 before I find all the pairs if itself we need to skip if not we can pair it right so if should request energies I can use J we count finally we return the count so which issue should request just figure out these invalid cases yeah - palm plus out these invalid cases yeah - palm plus out these invalid cases yeah - palm plus time 7 turn boost up to speaking a tiny pulse and finally we try and shoot so this I think we're done this boost for solution yeah I try some it so it's technically logic there's no problem right we're just doing what were asked to of course tre okay it's too slow so how can we improve mm-hmm one night one we improve mm-hmm one night one we improve mm-hmm one night one we condition here is that people will not send requests to people who have a bigger age so that's given us him that we could sort the array first right if we sort we don't need to filter we don't need to calculate for the other pairs like sort first we do it a sense descending like a sword so now how many pairs are there also from the start it will be ten right for the B and though it should be n minus one if we start from the first thing that connects plus n max to plus two one so should be and n minus 1 times 2 divided by 2 so this will be cap down half of the comparison here right well so we start we surf from to here's the problem if that originally if they are two edges are the same we would send two requests but now we just compare them only once right yeah this actually we need to do some change here so I from zero to two previous one and J will start from I plus one and to the end okay if it is saying it's not there is no K select here so we just compare two edges if they should request then if ages and I if they are the same which we passed two because they were to request right if not there wouldn't be only one so this should also work and slightly faster cool we're accepted and so it's twice as fast as the previous one weighs brute force with first and their time complexly actually doesn't change but slightly better it's like this okay so it's actually still into the squared well how could improve more mmm let's try to analyze our result our example a little better will give me the hand actually the ages are two and two hundred one and twenty right so rather that we compare each pair of ages we can actually find the ranges like if the edge will find the appropriate range for specific age like 14 16 the range will be like say for 16 so this will be 8 if so for 16 it should be bigger than 50/50 smaller than 16 bigger than 50/50 smaller than 16 bigger than 50/50 smaller than 16 something like this right yeah so he's actually 16 itself it's 15 is too small a 70s to be able to beg so actually 44 so for each age the range is limited and age is finite right you said we got the edges from 1 to 200 so we could just do the counting right for the ranch of each egg right this is what we get cool so let's do it so it should be better than this so let's say how what the time complexity will change so now we travel through all the ages so it's in your time and for each age we will calculate it from we will sum up the count from the minimum is oh it's just to try find the smallest one okay so for one it should be what a bigger than seven bigger dance for one it should be bigger than seven point five so it should be from eight inclusive to one so this 0 right so to still is - you should be bigger than still is - you should be bigger than still is - you should be bigger than eight you should be 9 &amp; 2 so 0 right so eight you should be 9 &amp; 2 so 0 right so eight you should be 9 &amp; 2 so 0 right so what's the age that 0.5 times X plus 7 what's the age that 0.5 times X plus 7 what's the age that 0.5 times X plus 7 this one should be smaller than X so X should be 15 right it is this right it should be bigger than this one uh-huh and the smaller than this yeah X uh-huh and the smaller than this yeah X uh-huh and the smaller than this yeah X should be a bigger than 14 let's see what happens to 14 Wow 14 would be 14 so bigger than 14 it should be 15 and 14 no so it's not still zero so the age should start from 15 is a seven point five 14 - is a seven point five 14 - is a seven point five 14 - 15 - 15 this is finally the first one 15 - 15 this is finally the first one 15 - 15 this is finally the first one yeah the agent must be at least 15 to have appropriate a friend request okay let's go to 100 to see what happened 100 it is 50/50 57 so we bigger than 57 so it is 50/50 57 so we bigger than 57 so it is 50/50 57 so we bigger than 57 so 58 to 100 right oh the maximum should be 120 let's see 120 it should be 67 68 - to 120 right - so yeah so we'll just do wait a minute we don't even to calculate for all the people you could just account how many 15 for age 15 how many people's are there how many people are there and for each of them they are they're actually the same right so 15 they count and to find their range count mm-hmm so find their range count mm-hmm so find their range count mm-hmm so actually yeah we first we okay the time first we will use linear time to count all the ages and then count the ranch should be will shoot what it should be well it's constant right it's maximum is 100 420 we just count yeah so actually it's this should be Nene in linear time okay Wow cool let's start so the first step is count the ages to you each age and then count the ranch cool okay now let's create the page count new array because he's from one to one hundred twenty so 101 two to one I feel 0 for that age both ages age count age plus one so we got the count now we look through each age and check the checked edge right here we let's see the result set the result to 0 and then for that for not let the age but for the minimum is from 15 so fortunate I equals 15 sweater then 221 plus this is the age so every actually every Renji will contain itself right so now let pro apropriate age count equal zero for let J it was math is should be ceiling right singing but sitting I divide by Z to 0.5 and I was seven this is the lower in lower boundary J smaller than or equal to I plus so we just sum them up right appropriate count plus what do you would do so age count J right it's like for 15 2015 so we count 1520 we will start from 68 mm-hmm no we have a problem mass 4 plus 1 actually what's here plus 1 right if it's 15 it's uh it's 14 it's 1/4 14 here plus my 15 its fifth it's 15 1/4 14 here plus my 15 its fifth it's 15 1/4 14 here plus my 15 its fifth it's 15 it's still it's 14 15 cool so this is right okay plus them for 120 we will start from 68 to 120 and we can that we can all of them and so for these age there will be like these kind of this amount of appropriate ages in the list right so the total will would be but these will this actually have this I counted right the I is in the ranch we need to remove that so I think we should start with minus 1 this could have removed itself and we sum them up cause propria count account time well because the request is to demon to 2 is to 2 way right like we got to wait know how many for i there will be multiple i in it right there are 3 people with the same with this image 15 and the 3 will be counted in here so we sum them up like a 15 be 50 itself so we three so it's 2 so for one die in 12b to friend request sometimes age count hi yeah so that's we how we get the result and finally we return result I'm not sure this work let's review our code before we try okay we're free to 0 that age of we can them up mmm-hmm see like 16 got to okay now mmm-hmm see like 16 got to okay now mmm-hmm see like 16 got to okay now we start zero we do from fifteen to 120 cool perfect age minus one we start from 16 so 16 this is a 15 so it's still 16 to 16 so it's 16 stuff here 15 16 21 16 so 3 so 4 1 its last three but okay a 2 so this is actually 2 to plus minus 1 so 4 1 it will be only one friend request so two of them - awesome oh this request so two of them - awesome oh this request so two of them - awesome oh this should work and this should be returning 3 yeah ok cool now we're accepted and a little faster than previous one still we're not doing so great hmmmm so okay for this one it's actually I think he should be dinner time why we're so slow and we use a lot of memory that's because we were checking the age of 120 we are definitely want to collect the calculus some to write so this should be no problem mmm probably maybe because you see we start use a lot of memory let's try to improve it we here we use a Ray to do that maybe we could use a map because map is better for sparse as far as things if the like say 220,000 people doesn't if the like say 220,000 people doesn't if the like say 220,000 people doesn't cover all the age range so you using this full array will be a waste of time okay if we say it's a new man huh if we if has it we set a get a 1 no we set it to 1 cool so now we actually we could just to do through the keys of the map right so the possible ages it's not like got 15 right okay so for let H count of a count uh-huh the count should be like this uh-huh the count should be like this uh-huh the count should be like this hey J maps for H well he's more than that age 30 count plus was to age count yeah Jay hmm right we have to reading the code from array 2 map let's try to see it helps mmm not a number what okay we use a map we had a past my age we set it to that's why not we set it to 1 now we do shoe the 8 and account you're pretty work by this one we start from 8 plus 7 Swann just women chic and they would pass forget J mmm-hmm this actually it pass forget J mmm-hmm this actually it pass forget J mmm-hmm this actually it looks good to me ah God I don't need to be sorted sorry first I'm so stupid I don't need to sort cost us a lot of time let's continue our using map okay this looks good za 0 edge count J start from the range okay what's the problem 16 to 16 it's good for these we got problem one okay sorry I've got me to lock the agent and so - I've got me to lock the agent and so - I've got me to lock the agent and so - yeah this is right ah man why I'm so stupid they might not be the matter exists if you're using the array we can initialize for all the count to zero but now yeah we need to set the default value got lon mmm-hmm does this make a difference thank you God here's one-on-one so thank you God here's one-on-one so thank you God here's one-on-one so 100 from insane if this will return undefined and if it's undefined we set to 0 so it's shaping the problem ah I think that because each code doesn't support the double question mark which is the what is cleanse nourish cleansing right new foolish cleansing mark this right women oh no it's not about that so why this problem it can teach a undefined okay try say if I was to so mark appear which is age and Jack get it okay so wandering 488 we get one and then sell one mm-hmm sell one mm-hmm sell one mm-hmm and one dream to 15 one so this actually is zero this one is 1 this one is 2 this one itself so really should be 3 so - one huh - one huh - one huh I see what happened until four five there's nothing so you said it - one there's nothing so you said it - one there's nothing so you said it - one just actually will be plus all right yeah I know what happens here god I'm so stupid okay we plus it mmm okay we better set to zero and count so we found something but why 5 is minus one but what five should have itself as the five minus one ah yeah because before we use the array we set the minimum to 15 right but with a new map there is no minimum of 15 something so I'll say if age is what a 9:15 so I'll say if age is what a 9:15 so I'll say if age is what a 9:15 continue ah I'm so stupid this cool not let's submit hmm great we are accepted and still we're not that fast what's the problem maybe it's because of this black is not a fast let's go back to the array approach which is like this but the we do is remove the sword it's cool still we're not that fast ah this now time is fast all right so that's all for this one the actually the H is finite give us a hint that we could actually count to the count something like a pocket sword just count the amount of each egg and do the direct access right without doing the comparison they tried to see other people is doing Wow approach one is counting cool oh it's done yeah we're doing actually the same uh actually we're running better than then it because it's a start from zero and to the check but actually we could do the minimum it's like this and ignore this nor these checks right yeah I think we're doing great cool that's all for this one hope you help see you next time bye
Friends Of Appropriate Ages
max-increase-to-keep-city-skyline
There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person. A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true: * `age[y] <= 0.5 * age[x] + 7` * `age[y] > age[x]` * `age[y] > 100 && age[x] < 100` Otherwise, `x` will send a friend request to `y`. Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself. Return _the total number of friend requests made_. **Example 1:** **Input:** ages = \[16,16\] **Output:** 2 **Explanation:** 2 people friend request each other. **Example 2:** **Input:** ages = \[16,17,18\] **Output:** 2 **Explanation:** Friend requests are made 17 -> 16, 18 -> 17. **Example 3:** **Input:** ages = \[20,30,100,110,120\] **Output:** 3 **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100. **Constraints:** * `n == ages.length` * `1 <= n <= 2 * 104` * `1 <= ages[i] <= 120`
null
Array,Greedy,Matrix
Medium
null
80
hello everyone in this video we will be solving problem 80. remove duplicates from a sorted array level 2. the problem statement is we are given an integer error in nums which is sorted in a bond decreasing order which means increasing or ascending we need to remove the duplicates in place such that each unique element appears at most twice the relative order of the element should be kept the same another part to that challenge is we should not allocate extra space for any other array we need to solve this by modifying the input array in place with o of one extra memory so example number one we are given an array nums with having three ones two twos and one three and based on the problem statement we need to modify the nums to this format having two ones then two twos then one three and whatever is there after this three stays the same and because there are five valid numbers that we identified we are returning five even though we had three ones in the original input but we are only allowed to have at max two duplicate numbers so we took only two in the output if we look at example number two with this input we have four ones these four ones are translated to only two ones in the output and then we shift all the remaining characters at this point our array would look something like this zero then two ones one two three so these are all seven characters and then whatever we have after seven in the original input stays the same so we would have another two threes over here from the last two indexes i hope that you understood this problem let's switch to the whiteboard and talk about how this can be solved without using any extra space if you were to solve this problem without considering the space complexity it would be a very simple solution all we need to do is build a new array and start moving all of these elements into it and every time we find a certain count of duplicate values going beyond two we would just skip that and move forward and then once we are at the end just match the index from the input and copy the value as is but because of the constraint that is given to us in the problem statement to solve it with constant space we won't be able to apply this logic so now let's think about how to improve the solution so let's write down the constraints that are given to us duplicate values should be less than or equal to 2 no extra space should be used to build the output one approach is to have two pointers the first pointer will iterate through all of the elements in the input array without caring if the values are being duplicated or not the second pointer will be pointing at the index which needs to be updated j is actually going to be the pointer which will be incremented in certain conditions only let's go through a couple of example and identify where how these two pointers will be useful so here i have four columns i and j pointer this previous value column will hold the value of the previous iteration that we completed with i pointer so before we can start the iteration i will set the previous value as 0 because that's the first value in my array and the count will be 1. the idea is that we already have a value 0 and my iteration will begin with i is equal to 1 and at that same time my j is also going to be pointing at 1 so with i pointing at 1 the value is 0 does it match to the previous value yes if it matches then my count will be incremented to two and my previous value will still be zero i will increment my pointers so at this point i am incrementing i and j both so my i will become 2 j will become 2 my count stays 2 i'll just record the current value over here as well for simplicity my current value is one it does not match to the previous value so in that point i will update my previous value to one reset my count so my count will be reset to one because the count did not go beyond two i do not need to make any changes i will continue with the iteration my i is incremented and so is j now with i is equal to 3 the current value is 1 it matches the previous value so my count will be incremented again it is not greater than 2 so i will continue the flow i is incremented to 4 j is incremented as well now with i is equal to 4 my current value is 1 it matches to the previous value so my count is now incremented to 3 so here's where we have to change our logic a little bit with count greater than 2 we should not be incrementing j we need to save the value of j so that we can override that index with a certain value my previous value will still be 1 for the next iteration i is incremented by j stays the same the current value is 1 it matches the previous value so my count is going to be again incremented so now it is 4 because the count is greater than 2 we should not be updating j so now the next iteration i is 6 i is equal to 6 gives me the value 2 is not equal to 1 so my counter will be updated 2 is not equal to 1 so my count should be reset and because this is lower i need to take this value 2 and save it to j plus 1 so this j is going to be incremented and then 2 is going to be saved at this position at index 4 which is this i will be taking the current value and replacing it so this will become 2 and i will increment my j so my new value of j is 5 because count is less than 2 and my previous value will become 2 in that case incrementing i to 7 so my j will be incremented to 6 at 7 the value is 3 so i will have to take this 3 update it to the value 5 and i will continue the iteration so at index 7 the value is 3 does not match to the previous value so count will be 1 i will take this 3 and append it to 5 which i already did now and my previous value will now be 3 incrementing i it is now 8 j will also be incremented new value of j is 7 at i is equal to 8 the value is 3 this value will needs to be updated at index 6 so i will move it here 3 matching to the previous value yes so count needs to be incremented and previous value will become 3 talking about the output whatever j is pointing at is the number of elements that were updated since our output is going to be seven if we rewrite this output array it would look something like this these are seven characters which are valid after that we will have three and three but we did not touch that and because we did not use any extra space our space complexity is o of one and time complexity is o of n let me show you how this can be implemented using c sharp here is my c sharp solution i start by having some validation to make sure that nums is not null and the length is greater than 0 then i have saved this current index which is j and the count variable then i start this for loop from i is equal to 1 all the way to the end if the value at i is not equal to value at current index or the previous iterated index then it means that we need to restart our count hence we am just taking the current value and updating it at the previous index at this point the current index may be or maybe not equal to i and then i am resetting this count over here and then later on incrementing it to 1. if the count is less than 2 then i'm just moving or rotating the value at index i to index current index plus 1 and then after this if and else if conditions are done i am incrementing my count after the iteration is done this current index will be pointing at the index that was last updated because we have to return the number of values i'm just adding one to it and returning it thank you for watching this video this source code is available on my github repository the link is there in the description below feel free to check that out and i will see you in the next video thank you
Remove Duplicates from Sorted Array II
remove-duplicates-from-sorted-array-ii
Given an integer array `nums` sorted in **non-decreasing order**, remove some duplicates [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm) such that each unique element appears **at most twice**. The **relative order** of the elements should be kept the **same**. Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the **first part** of the array `nums`. More formally, if there are `k` elements after removing the duplicates, then the first `k` elements of `nums` should hold the final result. It does not matter what you leave beyond the first `k` elements. Return `k` _after placing the final result in the first_ `k` _slots of_ `nums`. Do **not** allocate extra space for another array. You must do this by **modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** with O(1) extra memory. **Custom Judge:** The judge will test your solution with the following code: int\[\] nums = \[...\]; // Input array int\[\] expectedNums = \[...\]; // The expected answer with correct length int k = removeDuplicates(nums); // Calls your implementation assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums\[i\] == expectedNums\[i\]; } If all assertions pass, then your solution will be **accepted**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\] **Output:** 5, nums = \[1,1,2,2,3,\_\] **Explanation:** Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Example 2:** **Input:** nums = \[0,0,1,1,1,1,2,3,3\] **Output:** 7, nums = \[0,0,1,1,2,3,3,\_,\_\] **Explanation:** Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. It does not matter what you leave beyond the returned k (hence they are underscores). **Constraints:** * `1 <= nums.length <= 3 * 104` * `-104 <= nums[i] <= 104` * `nums` is sorted in **non-decreasing** order.
null
Array,Two Pointers
Medium
26
1,573
hey what's up guys john here again so today let's take a look at uh this week's uh bi-weekly contest problem this week's uh bi-weekly contest problem this week's uh bi-weekly contest problem one of the problem here number 1573 oh my god it's over 1500 okay number of ways to split a string okay and okay so you're given like a binary string as here uh a string consisting only of zeros and ones and you need to split the string into three substrings okay s1 s2 and s3 where the uh each of this the substring here right the number of ones are equal okay and it asks you to return how many ways you can split the string such that uh can satisfy this condition where each substring has the same number of ones okay so for example i mean this one right 1 0 one zero basically there are three ones in total which means uh in each of the substring you need to have one okay and there are like uh four ways like four ways of doing this right you can split here and here okay and for example two here since the you only have two ones which means you cannot there's not enough ones right to be allocated into us three substrings that's why we returned zero and the three the example three here that's the this is a special case basically if there's no ones at all basically zero one still counts as like a and the same number of the ones which is zero right so in this case you can split any of the substring right uh as long as they're like a valid uh substring there basically you can do split whatever you want and the same the last one is this one basically they are like uh i think there are six words in total so which means you need to have uh two ones in one string right okay so i mean so this problem you know it's one of the math combination problems word yes i think you can think about that way because uh let's forget let's take a look at this normal case and we'll deal with this special case later on so for example this one okay let's say we have about zero one okay and zero okay one zero okay so there are like two ones so basically you know the key idea for this problem is that uh you know let's say we uh our cutting point right so the cutting point for the first string and second string will can be some starting from here range here to here right because we that's the base case right we can either cut from here or we can cut from here we cannot go uh go to left more any further or go to right any further right that's the boundaries of the first two cards right and how many ways right how many ways we can make a cut right that's the basically we have a number let's say the distance between these two ones is three here right h3 so basically we have four options three plus one equals four we have four possible places that we can cut uh between the first substring and second substring right so because one two three and four okay same thing for the second one right same thing for the second one here for the second cut basically this for the second card is same thing we have a two which means that's a 2 plus 1 equals to 3. so in total basically that's a combination we have four options here and three options here in total it's going to be a three four times 3 equals to 12. okay so now the problem converts to we just need to find the distance basically the gap right the gap between the first three and then second string and the second string to the last to the third string so that we can just use the gap plus one to calculate our final answer cool pretty yeah so this one right so how about this one okay you know so for all zero cases this is like a pure combination case right so what does this one it means that let's say we have a uh let's see we have five zeros right and then it just it means that we just need to find two places out of six because they're like one two three four five and six those are the so the total number is the length plus one that's the total candidate and out of those total candidates we need to choose two so basically that's a combination of what n of two right so what's the value of this so it's like n times n minus 1 divided by 2 times 1 right so i think that's pretty much it so basically this problem is basically we have two cases right the first one is the normal case where we need to find the gap between the first the basically the zeros right between the first strings and the second string and then the also the second also the between the seconds string and to the third string okay and to be able to find the gap here right between the like the th this one and this one they're like a few different ways so you can do it right i mean you can just simply like get since we know each group will have two ones you can record the last index for this right and then the next time when you find a new index you can just do a like a range right you can you know the range of this or another way is that you know uh since we know the first group will have two ones and the second group will have two uh four ones basically so every time so while the uh okay while the character is zero and the ones counts is still two then we know okay we are in the range between the first group and second group okay and then same thing for this so while the counting is equal to four and the string is the character is zero and then we know okay we are in the range of the second gap that's how we can another way of counting the length of the gap here cool uh sure so let's try to code these things up here okay and so first we need have like a count of ones right one once equals string dot count one okay i thought okay fine and so we just need to check a few things basically if the ones divided by 3 it's not equal to zero right so we know we simply we can simply return zero here okay and if uh if one's equal to zero okay then we know okay it's uh it's all zero case and we just need to do a combination of that basically we just return what the uh okay and we also need the n here n equals the length of s right and um yeah so since the uh the total number is n right and we have a n plus one case so here's going to be m plus 1 times n divided by 2 okay also okay yeah we also have neither mod here 10 to the power of 9 plus 7 okay and then we would use mod by uh do a mod here okay and then else right else uh let's find the uh gap one equals to zero and the gap two equals to zero okay so now we just need to do a character in us and if current ones equals to zero okay basically if uh if the c is equal to one okay then we just do a current ones plus one okay and then like i said now the second one the next one is basically if it's c equal to zero player and if the current ones equals to the what the ones divided by three right then we know okay we're now we're at the gap this first gap okay we just increased by one and if the current ones to the two times right once divided by three okay then we know we are right you know in the range of the second gap okay and once this is done we have the length of the gap one and gap two okay now we just need to simply return what gap one plus one right since the length is three but we have four ways to cut this from here basically the options right for the gap one is the gap one plus one times gap 2 class 1 and we also need to do a mod okay yep i think that's that should work let's try to run the code here yeah so the first one works uh submit uh length four 10 oh did i do it uh five oh one two oh sorry my mistake for the zeros okay sorry it's uh the options we have is like uh the places where we can make the cut it's like it's n minus one it's not unplugged i'm sorry so yeah let's see we have five zeroes here so the places we can make the car it's only four places here and here there's no point of cutting uh like on the left and on the right side right because it doesn't make sense right it's this we're not cutting anything here that's why the uh sorry the return is gonna be n minus one times uh my a minus two right and then divided by that yeah because the total uh possible ways of cutting it is a minus one and then let's do a combination here so submit cool all right so it works i mean this one is like a little bit tricky problem but it's a it's not nothing more than like a math combinations i mean so the first thing you guys need to know is that how can you calculate the combinations right the combinations of the uh of this all zero case and the other case is like you just need to know like find out the uh it's actually the combinations between the number of zeros the number of the first gap between the second gap because you are freely you can do any cut within this range the gap one and the gap two and in the end you just simply uh multiply those two gaps together and then you got your answer cool i think that's pretty much it is for this problem yeah okay thank you so much uh for watching the videos guys uh stay tuned see you guys soon bye
Number of Ways to Split a String
find-two-non-overlapping-sub-arrays-each-with-target-sum
Given a binary string `s`, you can split `s` into 3 **non-empty** strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** s = "10101 " **Output:** 4 **Explanation:** There are four ways to split s in 3 parts where each part contain the same number of letters '1'. "1|010|1 " "1|01|01 " "10|10|1 " "10|1|01 " **Example 2:** **Input:** s = "1001 " **Output:** 0 **Example 3:** **Input:** s = "0000 " **Output:** 3 **Explanation:** There are three ways to split s in 3 parts. "0|0|00 " "0|00|0 " "00|0|0 " **Constraints:** * `3 <= s.length <= 105` * `s[i]` is either `'0'` or `'1'`.
Let's create two arrays prefix and suffix where prefix[i] is the minimum length of sub-array ends before i and has sum = k, suffix[i] is the minimum length of sub-array starting at or after i and has sum = k. The answer we are searching for is min(prefix[i] + suffix[i]) for all values of i from 0 to n-1 where n == arr.length. If you are still stuck with how to build prefix and suffix, you can store for each index i the length of the sub-array starts at i and has sum = k or infinity otherwise, and you can use it to build both prefix and suffix.
Array,Hash Table,Binary Search,Dynamic Programming,Sliding Window
Medium
null
1,751
Hello friends welcome to code Sutra let's all lead code problem number 1751 maximum number of events that can be attended and this is the second version of the problem in this problem we are given an events array and what does this indicate this indicates that one of the event starts on day one and on day two it will end on day two inclusive of day two it will having two days that is day one and day two and if you attend this event you will be getting four credits so that is what it indicates similarly what does this indicate this indicates that the event will be from day 3 to day 4 inclusive and it will give you a credit of three if you are in this event and we are given one more variable that is K which indicates this is the maximum number of you can attend events that you can attend and where what you have to do you have to maximize your credits or the profits that you are getting from here so how do you do this the first thing is if you attend this saver you won't be able to attend this event right why you won't be able because this event is still going on the second day and this event is already starting on the second day so if you attend this event cannot be you cannot go to this cement so what are all the options that you have to choose two events or you can just choose one limit one option is you'll choose this event and this event what will be the profits will be seven the next option is you can just choose this which will give you a profit of just three or you can just choose this which will again give a profit of just one or the first event we will which will just give a profit of four but which is the best among this is seven so seven will be our answer let me give you another example so this is the event what does this mean this means for example the events start on day four and it will continue on day four five six in closing of this day and you utter if you attend this what is the credits or the profits that you are getting five similarly if you look here the best choice that will be able to make here is for this plus this save it right why because attending any other event will lead us some lesser than this for example if you choose to attend just this event why because you cannot attend any event other event if you choose to attend this but if you attend these two events you will have a profit of name so that will be our answer so now once you have understood the answer let's dive a quick observations and we will draw the intuition what is the quick observation that we can draw from here once you decide to attend an event all the events that have a start time less than or equal to this event's end time will be Vanishing for example you decided to attend this event what is the end time that the end time is 2 so you can't attend this event and this event that is the first Intuition or if you decided to attend this event then you won't be able to attend this it that is the first and the quick observation that we can draw from this what is the second once you have selected K events for example in this it is given that K is equal to 1 that is you can just attend one event so if you have selected this event can you select any other event no right so if you have selected K events then it is the time to stop that is you cannot further accumulate anything what is the third observation that we have every event has only two options either we choose to attend it or we choose not to attend it these are the only two options that is therefore any two M so with all this observation let's divide the problem into two things first let's first solve this part of the problem that is once you have selected a event what happens you have to reject all the other events right for example you selected this event you should be in a position to reject all that what is that we can do can we sort this array first of all in ascending order of the starting time yes let's first start this sort this will be first then we will be going to 2 3 1 2 4 8 3 4 3 and finally we will be having four six five but why did we sort this is because once I have attended this event you can just directly go to this index and Skip these two elements because these two events you will never be able to attend if you decided to attend this so the first thing that will be doing is we will be sorting this particular given array based on their start once they have sorted this it will be very easy to pick up the next index say you decided to choose attend this event now you can directly pick an element whose start date is from three so how do you do this we will be using binary search because we can do linear search also that is after this index we will search an element which is greater than two that can also be done for example but if this was one and nine so how long you have to go right so linear search won't be an optimized way of doing this so we will be using sorting plus binary search what happens in binary search suppose it will come to this element and it will say it is still two so can we eliminate all the values prior to that so that is the idea of binary search and we will be using binary search to eliminate all the values and choose this particular index so let me share the pseudo code for binary search we'll be just initiating the left and right and will be going on until we find the best possible index that is the event that has a start date just greater than the end date of today's event so now we are done with the first part of the problem we have solved how we can find the next event if we choose to attend this event now what is the element of choice we have at every given event one is you decide to attend the event or you decide not to attend the event this is you decided to attend the event and the right side is you decided not to attend the way now let's look at what happens if you decide to attend the event if you decide to attend this event what happens the first thing that happens is you'll be given a credits of food right what is the second thing that happens is your index that was at zero will go to this point why because these two events cannot be attended right so that is we are changing the index here that is the second thing that happens and what is one more implication of attending the event it means that you have already attended an even so the number of events that you can attend from now on is just one say suppose K is equal to 2 we will pass 2 here if you have decided to attend this event it will be subtracted so this is the first uh if you decide to attend the event there are very simple things credit will be added the index will be changed and the number of events that you can attend further will be reduced what if you decide not to attend this event if you decided not to attend this event the problem Remains the Same but the only change that is going to happen is index is going to increase every other Thing Remains the Same now let's look at further so what happens say you decided to attend the first payment now your index got increased to three our problem reduced to this you just have to choose one event from these two which is the best event how will you choose that again you will make a call along the same lines whether to include this event or not include this event but if you look here most of the things are recalculated that is 4 comma 1 is recalculated so how do you avoid this you can avoid this by memorizing this or storing this value somewhere for example you already found 2 comma 2 is there a need for us to find two comma 2 again no right so what we can do is we can store this in Array and we will call this array as DP array and what will be the length of this array will be in this case it will be 3 cross 5 why 3 cross 5 this will store 0 1 2 that means you have a option of availa attending two events this indicates you have option of returning one event this indicates you have attended all the event and this indicates the first second third fourth and the fifth so once you are done with this let me share how this particular thing is getting fit I would choose a top down approach in this particular problem why because we don't want to unnecessarily fill all the values here so I will be choosing the top down approach only in this particular case so what is the first case that we have applied the first case is if we have just this so we wanted to choose out of these two elements right so once we decided we won't attend this event what is the only event that we have this event if we choose to attend this event then what is the value that will be changing is here that means we decided to attend the fifth event and we got a profit of 5. yes we got to up profit of Phi but now the number of events that we can attend has reduced to just one okay now similarly other values will be filled similarly this value will be filled finally whatever is at this place will be our answer so every stage one of these values will be filled with this so if you have both of this answer you finally have this answer also and finally you will be having the entire answer which will be stored at this point which is which will be written so let me dive to the pseudo code of this problem we are doing two simple things if count is equal to zero this means you have attended all the possible event so you will not be containing further or if the indexer is greater than the event's length in that case also you will not be doing anything but returning 0 because you cannot attend any event further now there is one more choice that is if the value is already present in the DP array it means that we have already computed that value for example 4 comma 2 or 4 comma 0 we already computed this value so is there a need to compute this value again no right so that is what we are doing here that is we have just returning the value and we are not recomputing next thing is we have to find the next index why are we even finding this out we are assuming that if we include this event what is the next index that will be able for example if we attended the event one we have to skip event two and three right so that is what we are calculating here using the binary search algorithm next is the two options that we have got what are the two options one is you decide to attend the event that is this option you will be getting the profit of this event or the credit of this event and you will be doing the same algorithm but with an increased index not an increased index but with the next index and the count will be reduced by one or you have one more option that you don't decide you decide not to attend this event when you decide not taught in this event the choice is straightforward so you'll be picking the maximum of these two and you'll be passing it to the prayer function finally we'll be returning the answer so there are very similar problems uh this problem is actually a combination of two to three problems so if you are able to solve all this medium level problems these are very similar problems but if you are able to understand these problems this problem that we solved will become very easy and we have a dedicated telegram group where we will be discussing this problem and where we will also be conducting some free Workshop I have mentioned the list Link in the description so do consider joining the telegram group finally this is the share this is the code of this particular problem that is I would like to remove the events and make it a global variable why I am making this because the coding becomes very simple and it becomes straight forward we need not pass this again and confuse the next thing that we are doing is we are sorting the array based on the start type once I have sorted the array we are creating the DP array just to store the already calculated values all right and we are initiating all of them to minus one what does minus 1 indicates it indicates that we have not yet attended the this particular image finally we will be calling this particular function and the choices are very simple here the choices is if you have already made all the choices and R if you have exceeded all the events you will be stopping the second is if you have already computed you will just return that value what is this statement indicates that if you have already attended the event then you have to skip some events right so what is the next index this is what we are doing by binary search I will share the algorithm for this also but after you have done this what is the next thing is you have two options one is you will attend this event or you will not enter this event so these are the two choices finally you will be returning the value of this particular index after that this is the algorithm for binary search thank you for watching the video please do like share and subscribe
Maximum Number of Events That Can Be Attended II
slowest-key
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend. You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day. Return _the **maximum sum** of values that you can receive by attending events._ **Example 1:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2 **Output:** 7 **Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7. **Example 2:** **Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2 **Output:** 10 **Explanation:** Choose event 2 for a total value of 10. Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events. **Example 3:** **Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3 **Output:** 9 **Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three. **Constraints:** * `1 <= k <= events.length` * `1 <= k * events.length <= 106` * `1 <= startDayi <= endDayi <= 109` * `1 <= valuei <= 106`
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
Array,String
Easy
null
1,004
So hey professional maximum consecutive errors and wait k return d maximum number of consecutive advances make it 3 ok so I started from here only k time can be present means if I started from here then zero came k value was three Meaning, you can consider three times 0 as half van, which means you can convert this zero into van, then you can also convert this zero into van, that means, how much value of yours is left with us because of the two times one can convert it into van. Done it, then turned it into a figure of zero with the help of K in the van. Then you let this van remain a van. Let this van remain a van. Now once K has value and if you have a child, you will turn it into zero. But as if you have come here, now we have Zero child nearby and Sara's is over. Okay, like Sarak is over, so what is your maximum? This is your maximum test. It means one element, two elements, three elements, four element punch, element total punch. This means I understand this. Well, if my eye is on the fifth position, see how it was till now, it depends on every question, it is calculated, I will tell you in the approach, now if you have kept the code, then it can be a problem, if you do not have a gem, then there is only one method in yourself. The pattern is happening because I am going to tell all the questions of the pattern with the help of a template. We are going to do who knows how many questions because it becomes necessary to watch the old video, you will understand it very well, so let's go here and there. I had said that why do I do this minus L plus WAN to get the window size, then you will understand it if you watch the video. You can also understand that by doing the index of head and index plus WAN, I am understanding this field condition on head. If mine is standing, then what is the total number of elements? There will be one from the back of the van, if it has not taken head mines, then there can be a problem. It is good, is n't it? If you have found the pattern, then put in a little effort and everything is structured. Sub Inspector will remain the same, show a little change, my head is above there, before going to the field, put the booking there, everything is there, you will understand if you watch the video, my pattern there was something like this and people were walking, I had head and oil. Google had cleared the head, the oil will move forward only then it will work ok and I had delayed the answer, this answer is in the question of what is the video, if my A is zero then the value of K has to be decreased because all the help. It depends on what has been done, why if the van is coming then I don't have any problem, keep doing it, Hero is coming there too, no one cares about how long till it reaches, it means I have to do this, right there I am like Sam. The map was being updated. It is not so here. Here there is a check case. If A is off head of mine because my head is moving again and again. Then perform the condition if there is power and zero. With respect to mine, I have no problem, my answer will be included, when is the problem going to happen when my head becomes equal to zero, okay, the latest suggestion like here in this question, my pay was added here, when zero was on the index, then I added zero. Why did you distance the van because the cake balloon was sufficient to convert this zero into a van? Because to convert the zero into a van, you need van equal to 1, so all were equal to three, meaning here my categories for this head would have been done. You must have done it then look at this code, see it is reducing and I have also maintained the pattern like this. If you have made notes and are watching the video properly then you can solve the code of this question in a very easy way. You can do it yourself and okay, I have less to explain, so I am doing that less again, this eye is equal to my van, these people are mine, so my sorry, I go to the eye again and again, this head is equal to mine again. There will be a van, it's okay, now see, I am building the condition below, not how will you guys think, all these things do not come to my mind, after that the next condition will also spread, then there will be some strike in my mind, all. I will write some code, right now I am just struck that when I have zero, it is a balloon decoration, honor vice, keep moving forward because zero is also considered, the answer is also, when I have nothing left and zero comes, then I am going to have trouble. Then I will write something there, okay, so this much must have been understood, then when I said that what is head equal to van, you can also consider zero in van, because this is mine here, you were here, mine is here, I will keep writing. For i equal to zero, this was my 3 but this zero, when the head of zero got my zero, it must have gone to K2, then for i equal to van, my k was tu, so when this zero got converted to van, k1 must have been ok. Now when sorry, this is coming again and again, I am writing sorry, head will be head equal to one, for that and head is equal to zero because for one, it is okay, now I am head equal to tu pe aaya, I change the color, I add equal to when here. Sorry, I came here, this is my van, so I don't have to do anything, I have to move ahead and then my head came on equal three index, this is also considered and see my answer, till now I get four elements, maximum is fine. Now I went to this zero, so sorry, as soon as I went to three, see, I can convert even 33 0 to 1, but as soon as I reached head, my head reached four, now my head reached four index. The value of the cake has become -1, it has become zero, why because till now all my cake has been consumed, why one K has gone to make this hero, K has gone to this zero to make a van, so the maximum length I have got till now is 5. Okay, now what is my end, as if I came to the head equal punch, then I have become my daughter, so this answer will not be considered, it will not be the direct answer, what will I have to do, it will start from behind, if you notice the pattern. In my previous video, I had said that the rule is simple that you will create two global warriables, head oil, headphones will continue to run as long as your condition is true, this is just a loop and will run to power the entire loop and all the elements. And here you will write that the mechanism of your window sliding is doing all that, so Sam is doing it is storing the element in the map, either here the degree is doing it, when is it doing small things, now after this, then I said that Now I got a problem, when a problem came there, what did I write, problem is my problem, I mean, perform something till then, this is not a problem, it will come out automatically, okay, I said, when did the problem come here, when? If this less than of mine will be zero, then it will be simple. I had seen the condition there also, I have to do it in the same way, I used to write whatever problem I had, I used to write it, I am making it true, that when will it go out of this A loop, when it will become true. Right now, sorry, when this thing falls, right now, I mean, let's take my game, it is zero, so why do I have to make CAPS POS, only then I will be able to stand the further answer, so I will start hoping from the back, ok, start hoping, I will write wild. I would say till then there is zero, till then the elements keep coming out from behind, Sam was there, I came to all the mines and the elements were coming out from the map, I was the elements coming out from the map, now here the oil will come out and I hope Sir, when will I get benefit by doing this, my off oil will be zero only then I am going to get benefit because I have to concentrate my mind only on zero, if the van comes then I have no problem but if zero is there in my details. Meaning, as soon as I took out this zero, it means that I have worked hard that the value should increase automatically, why should I because when this zero came, it must have been contributed by one and as soon as I expected, my value will increase, why is this my recovery? It will happen because one is of one, what would have been the info contribution, to convert zero into van, similarly if I took out my zero then the value of my van A will increase but I said, brother, why did people write simple, pay attention to one thing, then I made the pattern. Said pattern is not even sweet, brother, you should understand that it was not in the pattern, that is why I did not write the letter. Suppose there was such a scene in the oil here, van zero. Okay, so how long would I have had to wait until I reached this zero. Because why will this pose of mine be able to be made with the help of this zero, because all the steps must have been taken to make it zero, so there will be no benefit for me in getting it out, I will not be able to get it out unless I get it out. I have understood. That's why I wrote mobile and it is a simple thing, if there are very many problems, watch the video again and there is even more problem or you have no interest in programming at all, it means you can also memorize the patterns, no problem. No pattern everything is this one normal two global what can be zero can be any element my element any element my value is zero and the first element is zero I got its answer my zero whose shortest answer is zero answer zero Now you can also take internet, I said, when it is the longest word then you take internet to compare the answer and when you have asked me without answer then give the answer but here it seems simple to me, I can do less than zero. Because Lance, we are all positive, zero, oil, I look at the oil, it is a small change in the pharma and there was no much rocket science in it, just oil equal to zero, 10 only A + + respect vice, you have to keep zero, 10 only A + + respect vice, you have to keep zero, 10 only A + + respect vice, you have to keep hoping, keep doing until. This was not possible. You came out and said, 'My answer will not possible. You came out and said, 'My answer will not possible. You came out and said, 'My answer will always be updated, why if I want maximum then maximum, I have no problem, first there was minimum, then I would have to think that if I have to update it inside Vice Look, then I have to update it outside, where to do it? And there is maximum, I know it is maximum then the answer will always score maximum then why did not I do minus three plus one I just told here see that on selling the price of window there was such a simple code and latest support this answer is my maximum update If it happens then I will finally when all these people are finished all these people finally what should I do return you guys tell me what to do should I retain the answer no brother return answer directly will not do this I will return maximum why so many videos I had told you Here I tell you again, I will do this only in June, why will I be safe, brother, what if the aspect of my cake is you like this and my element is zero one, it is ok, zero one three, see the answer in this, what will be this. Loop, this loop will be updated, no, this code will run here because basically I am always updating the answer, but if I had updated the answer only inside, then this problem could have happened, meaning there would have been some case like this, my head would be outside. Yes, but its condition is solved sometime, then what do I have to return? Why is the maximum answer now on head four and it is seen with you that all the answers are possible, then head becomes mine, that is why I say this shop John. To live in, you take it out and give it to me with respect like Vice. If your mind is logical then you can even think, you can take it anywhere, but let me port it and show it. You may have enjoyed the same pattern. This is also an example of shrink cable in pattern identification, so this template has been married to a portfolio with ring cable. Let me port it quickly. I said make it from the glove gate and I have made the head and oil as if I could have given you this complete course earlier. If you do n't remember the body then you will remember it because the pattern is very simple, I like the small conditions, anyone will understand the way I am telling it, this will do the whole tower, now when will we benefit, the benefit will always be there when it means we get the output. Have to perform a little less, these mines have to be mined and if these mines are mined and your A is negative then use their mobile till here it is zero, till then these people keep going, what do they keep doing, if A is off the oil will remain equal to zero, see. I should go out, but the run time is about to come, now I mean, I would like to show my mind, so tell me more for you guys, the video will be a little long, because of that, maybe it cuts me, okay, from where should the answer come to this. About people gone, see here one two three four punch six from here also one from here should be right 1234567 This one has become zero, this one is leaving, then see this is mine, now I am staying here, this is my maximum size And when you open the window on my screen, the minimum price will be there, it will remain updated, then my head will be lying here, and as soon as it comes here, the problem will come again. If k becomes negative then 9 - 1 8 but the total becomes negative then 9 - 1 8 but the total becomes negative then 9 - 1 8 but the total elements are one two three four punch six seven what I proved, I explained it to you in the way, there I said this, do n't see and if I have written the fit below whereas There I had told understandingly, see again the same thing that you people will make it run in every way by applying advance oil, why am I doing this, it is a simple thing, it depends on you can get both of them booked for oil. It is better than that and why is there an error here now, so we will have to identify it here too. For now, I have told you why this happened, when you people will also write this, then it will be understood, I am a man. Now you guys will identify this thing because look at the essentials, the approach to asking all the questions is the same, only the method may be different, I did the student in the first video also, so I have shown two methods but you cannot show it in every video. Now you also do some hard work and identify it is not wrong at all, but how far is your brain, what kind of changing do you do in the court, like it doesn't matter in the court or not, you guys, let's meet in the next video, keep coding and If you like the video, then give me a thumbs up in the comment box of this video, I will not make a video again, okay see you guys.
Max Consecutive Ones III
least-operators-to-express-number
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s. **Example 1:** **Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2 **Output:** 6 **Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Example 2:** **Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3 **Output:** 10 **Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\] Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. **Constraints:** * `1 <= nums.length <= 105` * `nums[i]` is either `0` or `1`. * `0 <= k <= nums.length`
null
Math,Dynamic Programming
Hard
null
513
hey everyone today we are going to solve theal question find bottom left three value okay so let me explain with this example so typically there are two ways to tr three right breast F such and death suchar so in this case which trasor is better from my perspective I think breast f sarch is better than death F suchar why so that's because if we use a death F suchar so definitely we can reach the leftmost value for example four but U we are not sure this four is in the last row of the tree right so in that case we have to manage like a level of three right and in fact in this case we should return seven in this case four is not answer so it's going to be tough to manage a lot of information on the other hand if we use a breast search so we can Traverse like a level by level so that means uh first of all we Traverse this level and next this level and then this level so um we can manage our level information easily right so all we have to do is we focus on like this is a left most value or not so that's why um bre for search is better than t for search okay next how can we know uh this is a leftmost value actually I have two solutions and uh I'll show you first way and after that I'll show you another way so um for two solution we is a q so more precisely d q and first of all we have root note right so that's why we put root node to Q so one and then um we iterate through level by level so we uh TR us first of all this level so that's why we pop one from q and then check this node one has child or not and if this node has child we append uh its child to Q again and in this case one has node two and node three right so that's why we append node two and node three to Q so at the time uh we first of all we append left at first so that we can know first node is left most value in the next row Next Level right so in this case so we pop one from q and then check left child and right child and we have two not two for left child so that's why first of all we append two to q and then we have right child right so that's why next we append node three to q and then we finish uh traversing at first level and uh next we have two and three right and we know that this two is um left most value in the current level so that's why this two is one of candidates for return value so we initialize that let's say result variable and then when we start traversing in the new level so next this level so first node is um leftmost value so that's why update U result variable with two so I forgot to say uh first of all result should be in this case one and then uh when we start uh traversing at second level so update result variable with two and then um check node two as child or not and uh node two has left child right four so in this case I pend node four to q and then so we finish node two and uh we have node three and then pop node three from Q and then check node three has child or not and node three has left child and right child right and then upend the left child at first and five right and then next six and then U finish our second level so next level should be five four five six right and we have four five six looks good and uh every time as I told you uh when we that new level so first node is left most value in the current level so that's why four is one of the candidates for return value so that's why update result variable with four and then uh four is four doesn't have no child right so that's why U we don't append anything and then next five and the five has left side seven right so that's why upend seven to C and then next six and the six doesn't have any child right so that's why we don't append anything and then I'll finish thir level and then we have seven right so that's why we continue this is a false level and then um pop seven from q and uh this is a like a new start so that's why this seven is leftmost value so update result variable with seven and then uh seven doesn't have um any children right so that's why we don't append anything and then uh we finish all uh we finish uh traversing all no right so that's why we should return seven in this case yeah so that is a basic idea to solve this question so let's jump into the code okay so let's write the code first of all initialize q and Q and then upend the root node and the first candidate return value should be root no so ini L equal root bar and then let's iterate through one by one and while Q so Q has node in the case we have some noes in the current level right so let's continue and as I told you we know that first node is leftmost value in the current level so that is one of the candidates for return value so that's why first of all um update less equal q and the first node is index zero dot value right and then after that let's iterate through one by one so for underscore in range and length of Q and then um first of all pop most left node so node equal Q do pop left and then if node do left so if current node has left node left child in that case Q do upend and node left and then we do the same thing for right child for node do right and Q do append and node write yeah actually that's it after that return result variable yeah so let me submit it yeah let's get and time complexity of this solution should be order of n because we visit all no one by one and the space complexity is also order of n for Q so we append all no uh to Q right so that's why okay so let me explain the second way okay so in the second solution we also use q and result variable initialized with one I mean root node in this case and then we have root node in Q so not one and then uh iterates through level by level and uh in this case so first of all we pop um leftmost value from Q one and then in the solution one we append left child at first right but uh in this case we append right child at first so um in this case we append three and two to q and uh three and two completely opposite of our solution right and then uh how can we update result variable so it's simple um every time we pop some node from Q update result variable so in this case we pop three and then first of all update result variable we three and then um we do the same thing up and right fast and left next so in this case six and five and then now pop three and then next pop two from q and then um update the result variable with two and the two has left side four so upend four to q and then finish uh Second lbel and uh we Trav third level and we have 654 so looks good and then first of all pop six from q and update result variable to a six and then six doesn't have any children so move next and pop five and update result variable with five and then uh five has left child so up and seven to q and then pop four from q and update result variable with four and then node four doesn't have any children so move next so next level is seven right and then uh pop seven from q and update result variable with seven and then finish iteration so all we have to do is return seven in this case Okay so let's modify the first solution so in the first solution we use a y Loop and four Loop right and actually we need only y Loop for second solution so that is this for Loop and uh actually we don't need this line so if Q has node just um execute pop left and then after that um as I explained earlier update result variable every time so L equal no bar and then we use this if statement but this time um as I explained earlier so we append right node first right so that's why we put if node right is pass condition and if current node has right child and append right child to q and next left child right yeah actually that's it so let me submit it yeah let get and the time complexity and the space complexity is same as solution one and time is O and the space is n okay so this is a bonus code I solve this question with is dep for sear okay so let's write a code we have to manage max depth of three we visit so max depth and initialize we zero and result variable initialize with let's say n and then call Des for search and passing the root node and the first Revel is one right and then after that return result variable okay so let's create a death f tou as an inner function and node and deps and first of all if not node in the case return just return and we want to use max deps and result variabl so um non local max depth and res variable and if current depth is greater than max depth in that case it's time to update so max depth should be current depth and uh result should be node do bar and then um so after that we go to left side at first so call dep F search again and node left and then passing the deps and the next level should be this plus one right so that's why + one and plus one right so that's why + one and plus one right so that's why + one and we do the same thing for right side for node. WR and then deps plus one so U as you can see so we go left side at first right so that's why if current depth is greater than max depth so definitely current node is leftmost value right and at the same time um we update the max depth with current depth so if we go to right side so max depth and uh current depths should be equal right so we don't update result variable in that case yeah so let me submit it yeah look good and the time complexity and the space complexity is same as solution one solution two time is o n and the space is also o n so for space complexity so in this case we don't use a q but uh we use a memory for recursive C stack and in the worst case um three is like ambalance tree like a skill tree in that case um space complexity should be order of n where N is a number of nodes in the tree yeah so that's all I have for you today so please support me with the action such as comment and hitting like button I'll see you in the next question
Find Bottom Left Tree Value
find-bottom-left-tree-value
Given the `root` of a binary tree, return the leftmost value in the last row of the tree. **Example 1:** **Input:** root = \[2,1,3\] **Output:** 1 **Example 2:** **Input:** root = \[1,2,3,4,null,5,6,null,null,7\] **Output:** 7 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-231 <= Node.val <= 231 - 1`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
220
hey what's up guys john here again so today uh let's take a look at this uh lethal problem here number 220 contains duplicate number three so this one gets a lot of like downloads i'm going to give it my own uploads okay so you're given like an array of integers okay and then you need to find out whether there are two distinct basically if there are two different distinct indices i and j in the array such that the absolute difference between the numbers i and number j is at most t and the absolute difference between the i and j is at most k okay so for example this one right so the difference between those two numbers has to be zero which means they have to be the same right and the difference between those the index the indices it has to be at most three so in this case uh this index is zero right this index is 1 0 1 2 3 so this 1 and 1 happens to be the our answer right happens to satisfy the conditions those two conditions basically i minus j okay the absolute value is smaller greater equals or equals smaller than the uh than the k and the numbers right the numbers i minus numbers j okay smaller than t basically those are the two conditions we're trying to satisfy here right and so the first one the those two ones can satisfy both of the conditions here and second one is the uh zero so it's two so basically anyone can and the difference is one means the uh actually basically any of them can satisfy this condition right and here it is false right so the difference is three but as you guys can so the minimum difference is four in this case right so we there's no way we can find the two indices right whose difference is uh less than three here that's why it's false okay so uh so i think today i'm gonna introduce a few different solutions right so the first one obviously is the root is brutal force okay so basically i mean since the index since uh the condition once here basically what we need to do is we need to maintain like a sliding window right basically we're gonna maintain like a sliding window whose size is k okay and every time uh when we have like a new starting point okay let's say when we start from one here we just we need to basically we're gonna scan right we're gonna scan the next two elements okay and we'll see if any of them right if any of them has a the difference right between the current starting point is smaller than t then we know we find the answer if we cannot find those such candidates right in the end we simply return false okay um yeah that's the brutal force but in this case if you use that one so this problem is going to be tl uh timeout because you know that problem as you guys can see depends on how big the k is right and basically the time complexity is going to be the n times uh so each time we're going to scan k elements right so we're going to be n times k if the k is the same size out of the n right so and then the time complexity is going to be n square basically that's the first brutal force way right and a second right the second uh option here is that you know let's say we have a like uh different numbers here right we have different numbers here okay i'm gonna randomly draw some numbers here let's say the sliding window is this let's say we are maintaining like a sliding window here so that's a sliding window okay um yeah so maybe i'll draw a little bit more here let's see the sliding window it's this okay that's the sliding window i mean if like if the numbers within the sliding window it's sorted okay if it's sorted and let's say we're trying to find uh say we're trying to find three here okay let's say three is our card number and we have like uh and the sliding window right let's say the k is like um the k is five right k equal to five and our car number is three area right and if these five numbers they're sorted okay then with current three here it's very easy for us to find uh to find the current condition because uh since we're maintaining like a case size of sliding windows so the condition one is always matte and we just need to find the if there's like uh a number right uh whose difference is absolute difference is smaller than t if the if this is like five numbers they're sorted right so all we need to define is if we can find the previously number let's say there's a previously number one here uh and one and two okay and three and four and n5 okay assuming all right assuming these three here the number three is red just right in the middle of this sorted five numbers here okay if that's the case right actually all we need to check is we just need to compare the difference between the previously basically the uh the previous number and the difference between the next number okay why is that because they are sorted okay they are sorted because which means n2 is bigger than n1 okay which means that if the difference between the n2 and n3 is greater than t okay then the difference between n1 and n3 is definitely even greater than t here so we don't have to worry uh compare with the rest of the numbers here same thing on the other side okay because n5 is greater than and four so we just need to check if the neighbors uh of the three if any of the neighbors are in averaging the range of the t here then we know okay we find the answer because they are sorted yeah and now the question comes to uh how can we uh maintain this sorted array here right i mean we can always every time we have this one here we can always sort but that's even slower right to sort these k numbers right if we do a sort method every time we have a new numbers here it's going to take like a k log k time right so it's even slower than the k here than the brutal force way and so one of our options is to use the uh what is that the uh the binary search tree provided in java because in python there's no built-in because in python there's no built-in because in python there's no built-in binary search tree implementations so i mean we can of course use like uh build our own like binary surgery in python but that would be too much of the code so the first solutions today i'm gonna show you guys i'm gonna switch to the java so we so i can use the built-in java so we so i can use the built-in java so we so i can use the built-in like uh tree set to maintain the uh the difference okay yeah okay cool so let's try to call the first one java version so i'm gonna switch to the java here okay so in java you know there's like a data set called tree set so and here um i'm gonna you know so i'm gonna initialize with a long type instead of integer the reason being is because you know in the test case they're like some right like a very big test case that has the biggest uh value of the integer and if we're doing that and we do a uh we do a minus t here it could be out of the range right that's why i uh we just uh just to avoid that things we're gonna uh convert all the integers to the long type so that we don't have what we don't need to worry about the uh the values out of the interior range okay so set okay uh it's going to be actually the tree set right so the tree set goes to what the new tree set okay so same thing here yeah so it's the java we have to remember those uh semicolons columns here so like i said we need to just need to for like okay sorry for i equals to zero okay and uh i is smaller than the uh nums dot length okay uh i plus okay uh so basically for each of the number right so for each of the numbers here where we're trying to find the uh you know with the three set there's like two how two functions we can use either the state ceiling or the floor okay so you know the trees are basically the balance of binary surgery right basically the ceilings will give you the uh okay let me okay let's try to find the floor okay so uh floor okay floor equals to the uh tree set dot floor so this floor will give you the biggest number that's on the left basically the neighbors of the numbers i on the left so number size okay i'm gonna do this right basically if you pass in like this card numbers here the floor will give you the left neighbor of the number here okay and basically if the floor we check if the floor uh it's not now okay basically if there's no such numbers though this flow will be now here and what and the uh since the floor is a smaller number of that right and number miners floor okay it's within the range of t okay so if that's the case right sorry i will simply return true okay same thing for the right neighbor which is going to be the ceiling okay ceiling of tree set dot sitting number so the ceiling will give you the right neighbor of the uh of the cart number so same thing here if the sailing okay uh it's not now and uh the ceiling okay mine uh subtract the number right it's within the range of t okay and then we also return true so that's the two step and the next one is we're gonna we need to insert right basically we need to insert the uh the card number into the tree stat tree set dot add number okay yeah i think i yeah and the last thing is we have to maintain the size of the case uh sliding window here right basically we're maintaining like a sorted uh k sides of the integers here so basically if the i is greater than k okay sorry uh i have been uh coding with in python for too long so i have to get kind of getting used to this i need to get used to this java style here and trees that dot remove okay we need to remove uh which element right numbers of the i minus k right so that's how we maintain the uh sorry of maintain k size of binary search tree okay yeah and then if nothing happens here we simply return false okay yeah oh and okay and i think we need to do some like uh conversion here because the uh the number it cannot explicitly convert the integer to long that's why we have to do uh some conversion here okay so yeah i think that's pretty much it let's try to run the code here ah same colon here long integer okay close all submit what okay we have a floor here floor numb ceiling oh sorry here ah maintain the size of that it's not i here it's the tree set dot uh size yeah sorry it's not the index okay and that's yeah cool so yeah it passed all right and um yeah i mean so the time complexity for this is so we have o n here right we have a o n i'm sorry we have n times uh here right so the floor so this is log n right so the floor is locked and the log n here and uh sorry it's a log k sorry not log n log k because we are maintaining a size of the k bst and here is also for log k and also here right so also log k basically the complexity time complexity will be the enough log k and the space complexity will be a o of uh basically the minimum of the k end of k right it's not a it depends on like uh who is smaller okay either and okay yeah so that's the first approach basically we're doing here we are basically we're utilizing a tree set right a tree set in java to uh to maintain like a sorted uh size assorted integers right sorted integers of size of k okay and we'll just use b since it's sorted we can simply compare the left and right neighbor with the card number to check if that is the it can satisfy with the second condition right which is this one okay cool so that's that and okay and another even better way is to use the bucket idea here okay so um you know i think it's just actually we're borrowing the idea of the bucket sorting you know for the bucket sorting if you guys don't still don't who still don't know the bucket sorting is basically we're separate we're having a range of the bucket here right range of bucket here and let's say from zero to nine okay 10 to 11 i tend to tonight 19 okay 20 to 29 and then 30 to 39 okay and within each of the bucket we have a sorted array story array is like uh one four seven right so 11 uh 13 18 so on so forth okay basically every time when we have a new number right we put it into the uh relay associated we're gonna use a key uh to a mechanism or like a function to find the bucket right this number it belongs to and then we're going to assign this number to that to its bucket so you can see everything it's sorted right in inside the bucket uh by the way we're going to use some like sorting method right to store each of the buckets okay and then in the end we simply like concatenate everything together to get our sorted list okay so that's that and we're not using everything in the bucket sorting algorithm here we're only using the bucket itself we don't care about it what's inside we don't care about sequence inside there so why is that okay so how can we use the bucket sortings right to find the uh bucket idea to solve it i mean this problem and basically here's how we do it let's see so we have a uh we have like a size of the t here right size of the uh sorry the difference we're looking for is t okay and so that means that i mean the range of the of a bucket right the range of a bucket is like uh is t plot is t plus one okay so what does it means that let's say that the range of the bucket we have okay we have a bucket and the range of that is the uh is t plus one so this is also t plus one okay and then every time when we have a numbers comes in right we just use the number the current number right uh divided by the width of the bucket so that we can have like index here right so that will have an index of the bucket that number belongs to okay and okay basically you know so the way we are checking it since the uh let's say we are let's say the range is this t plus one let's say the index is this one so this number belongs to this bucket okay we have zero one two three and four okay let's say the current number belongs to this bucket and if that's the case all we need to check is the current bucket plus the bug the bucket one and then the bucket three we don't need to worry about uh any other buckets right so it's kind of makes sense right because uh because the range of the bucket is t plus one so anything uh outside of this one two three will definitely like uh the difference right will definitely be greater than t okay right so that's why we all we need to check is the previously the bucket on the left side and the bucket on the right side if there's anything basically if there's anything in those two buckets right actually we don't even need to care highlight which element in those two buckets right as long as there's one element in that bucket then we know it had the difference right the difference between those between the card number and that number has to be equal or greater or smaller than t right so in that case actually we don't even need to keep multiple like numbers in one uh inside one bucket we just need to keep one uh we just need to keep like one uh numbers for uh per each bucket okay and still we also need to maintain like the size of the case sliding window which means every time when the when any of the numbers are all the outside of the sliding window we just need to uh move that number outside of the basically we just need to remove the number from our buckets okay cool well actually you know what i just realized that you know here uh like we were we're trying to use i right but we it failed because you know we can also use i here it's just that we just need to use i plus one here right because this is the length it's not the index i is a zero base that's right so for the so we have to make it one base to do a plus one okay so this should just also work yeah so i mean we can also use the index to remove the uh the basically to remove those like numbers that outside of the sliding window okay so back to our bucket solution here right so like i said we just need to like create different buckets and then all we need to compare is just to compare the left bucket and the right bucket if there's any numbers in it okay uh cool so let's try to code that things i'm gonna switch back to java sorry switch back to python and okay cool so let's see um with equals to t plus one okay and then we're gonna have a bucket right so the bucket is the uh i'm going to use like a hash table so each nut for number in nums right so the key right the key of the bucket it will be uh where the index right index of the bucket is the nums divided by w right so that's the index now we have the index uh we have to do a few check here basically if the index uh the key let's see the key is that bucket one is yeah so the bucket here so the key will be the index right the value is the numbers in that and let's see so yeah actually so one more thing so the reason we're doing like a t plus one not the t as the weight is which one we want to make sure uh the left and right can cover the range of t here right so we don't have to go uh one bucket beyond left beyond the neighbors okay so that's index basically and uh if the index right if the index or it already exists right in buckets okay then we can simply return true okay yeah so it which means that we already have like uh we already have like the same numbers right uh numbers within the same bucket so that we can uh we can simply uh because the reason being is that let's say the bucket size is four right let's see let's say t is equal to three okay and the bucket size is four so the s the width will be four okay and then basically uh let's say five right so for if we have five so five will go to the bucket one right because 5 divided by w will be 1. and how about the next one so that's the smallest number in bucket one so what's the biggest number is uh so eight will it will be two basically will be seven for sorry yeah actually four will be the first one okay so four will be bucket one and seven okay we'll also be bucket one right yeah so yeah right so that i mean that's why we uh that's why we are making the size of w uh the size of the bucket t plus one because the beginning and the ending right the difference will be will exactly be the t here that's why if there are two elements inside the bucket okay then we know okay they have to be uh within the range they have to the difference has to be in the range of t here okay that's why we can simply like uh return true if the if there's already like elements in the same bucket okay so else right so if uh then another exam another like the scenario is that we just need to compare with the left neighbor right or the left bucket basically if the index minus one okay in buckets okay and the numbers in that bucket is smaller than the uh than the w than the t here so since the size of the w is size of the bucket's w right so we have to also compare otherwise if they're on the under on the boundaries of each bucket right the difference will be a t plus one okay so that's why we do a uh abs of the uh of the number right minus buckets index minus one okay it's equal to smaller than t right then we return true here or same thing for the right bucket okay and abs same thing class one okay return true okay and here we just need to we just assign that right bucket dot index okay equals to num okay same thing if the i plus one right is greater than k if the length right if the length is greater than k then because again so i zero base k is one base that's why we do a high plus one right we do delete we delete the bucket delete the buckets of the nums uh i minus k divided by sorry divided by w right that's how we maintain like the buckets of the size of the k numbers every time we have a new a different one we have a number moved out of outside of the k sides of the sliding window we uh we remove it from our from the buckets and since each bucket only has one number right that's why we can simply delete the buckets and here we simply return false in the end okay run it sorry oh um yeah we don't have i here enumerate right submit huh oh index w oh yeah so um she had minus one the difference t is minus one uh which means the difference between the uh the is minus one no that's basically if the t is smaller than zero that's not valid right we can simply return false okay yeah cool so finally i know this bucket solution is not easy to understand right basically oh first time complexity right so the time complexity here as you so we are only checking the previously bucket and then the next bucket so which makes this check here constant time so basically now the time complexity will be just o of n all right space uh space same thing right space is like o of the uh maybe minimum right minimum of n k okay so whichever is smaller that's going to be our space complexity yeah so i know for this uh bucket solution is not very intuitive but i think you guys can try to understand this right basically we just allocate the size of the t plus one okay so that we can we are sure if there are two elements if they are we have two elements appears right in the same bucket and then we know okay their difference is uh at most t and then we also we can also use the left and the right buckets to check if there's any uh other numbers that can satisfy our conditions and we only we're only maintaining one numbers in inside of each bucket yeah because there is no point of maintaining all the numbers in the bucket right i think this part is a little bit tricky to think about but if you guys uh think about that i think it kind of makes sense right yeah i think i got it so why we can only maintain like only one numbers here let's say we have a bucket here we have a bucket of three uh zero to three right and then four two seven right and then the uh 8 to 11 okay so let's say the current number is 9 here right let's say there's a 9 here uh the current number is 9. and assuming we have four five six seven right b i mean b before in the before nine here right so but the issue the tricky part here is that we don't have to come uh maintain i'll do more than one uh numbers in inside one bucket because why is that because every time as long as we see more than one numbers inside the same buckets we simply return true here okay basically if we have ever seen four five six seven any two numbers be before right any of the duplicated numbers before nine here we would have already returned the true so by the time we have nine here right by the time we have nine here and we know that so the previous bucket will at most have one numbers okay that's why we can simply always uh set this number the current index with the card number so because we don't uh since we don't need to worry about more than one numbers because it will be it would have already been returned before okay cool i think that's who pretty much i can think about for this problem yeah i hope you guys uh can learn something from this and yeah cool guys i think thank you so much for watching the videos guys and uh stay tuned i'll be seeing you guys soon bye
Contains Duplicate III
contains-duplicate-iii
You are given an integer array `nums` and two integers `indexDiff` and `valueDiff`. Find a pair of indices `(i, j)` such that: * `i != j`, * `abs(i - j) <= indexDiff`. * `abs(nums[i] - nums[j]) <= valueDiff`, and Return `true` _if such pair exists or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,2,3,1\], indexDiff = 3, valueDiff = 0 **Output:** true **Explanation:** We can choose (i, j) = (0, 3). We satisfy the three conditions: i != j --> 0 != 3 abs(i - j) <= indexDiff --> abs(0 - 3) <= 3 abs(nums\[i\] - nums\[j\]) <= valueDiff --> abs(1 - 1) <= 0 **Example 2:** **Input:** nums = \[1,5,9,1,5,9\], indexDiff = 2, valueDiff = 3 **Output:** false **Explanation:** After trying all the possible pairs (i, j), we cannot satisfy the three conditions, so we return false. **Constraints:** * `2 <= nums.length <= 105` * `-109 <= nums[i] <= 109` * `1 <= indexDiff <= nums.length` * `0 <= valueDiff <= 109`
Time complexity O(n logk) - This will give an indication that sorting is involved for k elements. Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked. When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next overlapping set of k numbers again.
Array,Sliding Window,Sorting,Bucket Sort,Ordered Set
Medium
217,219
1,213
this is Widow to question number 1213 intersection of three sorry Dori this is eg question let's get into given three integer arrays or a1 or a2 and a3 sorted in strictly increasing order the Eternals or array of only the integer death of peered in all three array okay let's check the reason for one in this case one two three there is one is three twists only two threes only two for is only 2 5 is 1 2 3 6 is 1 minus 81 so up this one five okay yes this right now we can use a precursor of each numbers first we can scan all of array at once and then calculate the second sorry if frequency is to be the meanings each array has the item so three array each array if each array has one total is 3 so we just get the number frequency is 3 at the time term complex this linear and space complexities linear oh there are Perrault wrote in this time I will show you to approach one is dis approach another is warmer better way Mortimer pedis constant space it okay you mentioned as I mentioned a reduced mana is I will use collection before sticks and if I reach the zero is integer and then it will be item is not in man if we add something it automatically attach the jato so we can we be able to use very easily without any additional of additional action okay in a one map lungs num +1 it is time there are known lungs num +1 it is time there are known lungs num +1 it is time there are known knowns in where first time Terrell already met but if we access this key collection T politic generates default value zero so now get put into one or a two to three and that's what initiate our iteration or key and value in map unfortunately my plasma when iterator so we need to use cadence measured because I Adam Mossad has it iterator so if value is to be I will appear am I really cut out for less check okay looks good in this time complexity is linear sorry linear so in your time we did we used map linear space okay let's make it better how we can make it the cost and the minister we do not be gonna map use map at the time there are maybe only one way that is using planar in this case we need the three pointer and then first each pointer indicate first item of each race and then check the value if driven is same and then append to alpha and then move to next one to explore this one is the same but this always lasts a bigger tell ya we really create only this - this one is same but create only this - this one is same but create only this - this one is same but this one is bigger so it please list this one's Tesla Maslow smaller and please list now it treats the same so put the value here and then increase then there are no Malta and then we exit because we do not check this one we do this one because this one is already finished Damon is even that to either is same that is low mini be needed two or three or a did you make is this one is zero to whatever to make pointer one two three please sir index three Nationals each other index and then now why one is belonging sorry one and two is greatly if Ari wants one and or a tooth - and or a three - and or a three - and or a three please same hand out to other one that one because the same value stripper is same and then in page one as 1/2 plus same and then in page one as 1/2 plus same and then in page one as 1/2 plus 1/3 plus 1/4 next iteration and then as it recedes or 8 2 is smaller than or a 1 then time I will increase to Polly as if a three small band or a one we also create one else s mean is there a 1 case left one music says ok it's time for ok looks good ok great how memory side is 100 because we do not use any extra memory so now a pen complex this linear and constant space thank you
Intersection of Three Sorted Arrays
handshakes-that-dont-cross
Given three integer arrays `arr1`, `arr2` and `arr3` **sorted** in **strictly increasing** order, return a sorted array of **only** the integers that appeared in **all** three arrays. **Example 1:** **Input:** arr1 = \[1,2,3,4,5\], arr2 = \[1,2,5,7,9\], arr3 = \[1,3,4,5,8\] **Output:** \[1,5\] **Explanation:** Only 1 and 5 appeared in the three arrays. **Example 2:** **Input:** arr1 = \[197,418,523,876,1356\], arr2 = \[501,880,1593,1710,1870\], arr3 = \[521,682,1337,1395,1764\] **Output:** \[\] **Constraints:** * `1 <= arr1.length, arr2.length, arr3.length <= 1000` * `1 <= arr1[i], arr2[i], arr3[i] <= 2000`
Use dynamic programming. Let dp[n] be the number of ways that n people can handshake. Then fix a person as a pivot and turn for every other person who will have a handshake, the answer is the sum of the products of the new two subproblems.
Math,Dynamic Programming
Hard
null
818
hey everyone uh welcome back to such recorder uh this is Ravina and today we are gonna look at problem 8 18 which is race car this is uh the most frequently Asked Google question in 22. uh now let's start by reading the problem says your car starts at position 0 and speed plus 1 on an infinite number line you can your car can go into negative positions your car drives automatically uh according to the sequence of instructions where a is accelerate and R is reverse when you get an instruction a your card does the following position becomes position plus speed becomes speed into two when you get an instruction R your card does the following if your speed is positive then speed becomes negative one otherwise the speed becomes positive one and your position stays the same given a target with a position Target return the length of the shortest sequence of instructions to get there so let's start by understanding the problem here let me open my Notepad okay let's uh try to understand uh let's take the example number two where we have a Target as six uh now let's take into account the variables here we have a position variable the position is always starting at zero so we'll take 0 and our speed is plus 1 to start with so my S would be 1. uh let's talk about the number line here so we are at the starting position let's say uh let's uh create a tablet we have moves we have position and then we have speed to start with we are at position 0 we have made Zero moves we are at position zero and to start with my speed is one now uh we want to reach our Target 6. we are at position zero we need to reach position six for that we want to accelerate right we have two commands accelerate and reverse we need to we should accelerate so that our position is incremented by speed and we move forward so suppose uh so I'm gonna give an acceleration command once I give the acceleration command my position here becomes position is equal to position plus speed so my position becomes 0 plus 1 which is 1. and my speed becomes speed into 2 which is 2. so here I have made one move my position is one and my speed is 2. after one acceleration I am now at position one I need to reach six so yes I need to give another acceleration command I give another acceleration command uh right now what happens is my position again becomes position plus speed so position becomes 3 and my speed is doubled so my speed becomes 2 into 2 which is 4. with two moves I get to position three and my speed is 4 this is after another acceleration command uh I'm still at position three I need to reach six so I'm gonna issue another acceleration with another acceleration my position becomes position plus speed which is 7 and my speed becomes 4 into 2 which is 8. now with three moves I am at position 7 and speed 8. now if you look at it we wanted to reach Target 6 but right now we are at seven that means that we need to go back R6 was somewhere here right now this is 7. uh we need to go back for that uh we need to issue a reverse command when we see uh when we issue a reverse command what happens when we receive we our speed if it's positive becomes -1 otherwise the speed positive becomes -1 otherwise the speed positive becomes -1 otherwise the speed becomes 1 and your position stays the same so I issued a reverse command here my position well my moves becomes 4 because I uh issued one more command my position stays the same but my speed is if speed is gray or positive then it becomes minus one if otherwise it becomes one my speed is positive it's 8 so it becomes minus one so here this is my uh current condition okay I'm at this place which is the same position but with different speed and moves once I receive this reverse command I know that right now I'm pointing in the left Direction because my speed is minus one every time I uh change my position will be position plus speed which is going to go to the left hand side which is going to decrement my speed and that's what we want right now so here we need to issue another acceleration command so that we can go backwards when I do that when I issue an acceleration command my position becomes position plus P so my position becomes 7 plus minus 1 which is 7 minus 1 which is 6 and my speed becomes minus 2 speed into 2. so here at this point my moves are 5. my position is 6 and my speed is -2 position is 6 and my speed is -2 position is 6 and my speed is -2 do you see this we reached position 6 which is our Target and how many moves did it take for us to get here it took us five moves uh do you understand what the problem is now uh let's see how we can solve this so on basis of this explanation do you see a similarity between uh do you see resemblance of an algorithm uh if you look at the problem here it says find the shortest sequence uh find the shortest length um and it actually looks like a graph to me so suppose you have your we are driving a position graph now let's say this is position one two three four five six zero seven and if you look at it we go from uh it's zero we go from zero to one two three you know three to seven to six uh and somewhere Suppose there are connections here so this actually is a graph if you look at it we start from a particular source and we want to reach a Target and do you know algorithm that can help us with that would be breadth first search so we can solve this problem really using breadth first search I know that this problem is categorized into a DP which is dynamic programming but I think that during interviews you know if you see a problem this is what comes to you intuitively I mean this is the intuition behind it you should be able to solve it with dynamic programming uh what I have personally experienced is that I am not able to solve any dynamic programming problem that I have not looked at previously and this type of solution is intuitive it helps us you know it shows us how good we are with algorithms are we able to solve a problem so I'm going to solve this using breadth first search okay so uh let's start by writing some code I hope this uh explanation was helpful okay so I'm gonna start with a queue since we are doing a breadth first search I need to have a queue in place so I'm gonna write create a queue for myself Q will be collections.tq and then I'm gonna add my in my queue I'm gonna add a couple of my uh moves position and speed similar to what we did okay so I'm gonna do uh moves my moves are 0 to start with my position is 0 but my speed is one so that's what I did the next thing I want to do is suppose I go through a node again and again so let me uh tell you what that means so suppose if I am traversing through this graph and uh I'm here I go here uh here and suppose I again reach a node that is already visited so I need in that instance I want to keep track of which node did I visit which distance did I calculate so for that I'm gonna keep a visited set so I will do a visited set uh now I want to go through my queue so while my queue is not empty I will uh pop up the top element from the queue so sorry the leftmost element from the queue so my queue dot pop left that would be my moves my position and then the speed um the next thing that we do here is once we pop the element first we want to check if we have reached the position and the position is at the Target so we check if my position is equal to the Target at that point we just return the moves because we have been storing moves position and speed into our queue then we can just retrieve in a retrieve it and pass it along if it doesn't match the target the next thing that you want to do is we want to check if it's already visited if it's visited then we just want to skip it and move on to the next element so let's check if position uh comma speed is in our visited set okay visited set if that's true then I want to just continue oh my God okay if it's not in the visited set the first thing I want to do is add it so I will add my oh my God I'm doing so bad with my spelling spellings today visited Dot add uh I'm gonna add my position and my speed okay the next thing that I want to do is I want to uh add my moves my position plus b and my speed the current speed to the queue so I will do Q dot append my moves would be then moves plus one because we want to increment it with every take my position will change to position plus speed since that what we do with acceleration command and then my speed becomes speed into two now comes the tricky part how do we issue a reverse command how do we check if you know we are going in the right direction we need to reverse or we are going in the reverse direction we need to go to the right um there are really two conditions to do that let me get back to my notepad here real quick okay suppose you are on this number line okay the first condition would be that you are at your target now this is the target six okay and you are way above the target you are somewhere here where you are position plus speed is right here and your speed is going in the right direction towards the right on the number line that's when you know that you are way past your Target and then you have to go back that's what's happened that's what happened here in this scenario that we were at seven we wanted to go to Six and our speed was still positive that's when we were like oh yeah I want to go reverse now in order to reach my target so that is our condition one the second condition would be your target is six you have your position somewhere here you have position plus speed somewhere below your Target and your speed is going to the left your speed is negative that's when you know that oh my target is on the right I'm going to the left I'm moving further and further away from my target so I need to change my direction I need to make it a positive my speed positive so these are the two conditions that we have to take into account when we change the speed or get a reverse command so let's do that the first condition was if I'm way above the Target and my speed is positive so that would be my position Plus speed is greater than Target and my speed is greater than zero that means I am moving towards I'm moving in the forward Direction and I am way above the target or the second condition would be my position plus speed is less than Target and my speed is also less than zero so my speed is negative a little typo here let me connect that okay so if that is true then we want to issue a reverse command and uh what happens when we receive when we show reverse command ma if my speed is positive it becomes negative otherwise the speed becomes uh sorry if my speed is positive then it becomes minus one otherwise it becomes 1. so let's do that my speed is minus 1 if my speed is greater than zero yes it can come in the end I want to add that to my queue so after changing the direction I'm gonna add that so Q dot append my moves plus one when I show reverse command my position stays the same so my position is the same and then I already calculated my speed so this is my speed okay so that's really all the lines that you need in your program so let me try and run it to make sure that I did not make any spelling mistakes that I was making very frequently during this video okay it runs so let me try uh let me submit it okay it's submitted faster than 42 percent it's trust me guys this is uh intuitive solution and very easy to understand and would be worth going through before you go if you have any Google interviews coming up so now let's talk about uh the time and space complexity uh it's a bit uh tricky uh if you have worked with binary trees uh I think you would have an idea of how to calculate a Time complexities for something that is uh growing exponentially so in our case our speed right here is incrementing by uh I mean incrementing two times right so in this case our time complexity would be really log of uh n where n is the target so let me uh try and tell you what it is so here I speed was supposed was one it becomes 2 4 8 you see it's growing exponentially it's uh it's multiplying by two every time so in that case my time complexity instead of going through all the notes so suppose I have like the scruff and instead of going through every node in order to calculate BFS breadth first search it's going to skip some levels it's going to skip some notes and those notes are going to be you know two times it's going growing into two times so that's going to skip it so basically it's like a binary trade uh kind of scenario so my time complexity here would be o of log of n where n is really the target so we can just say log of T really and the space complexity would also be log of n that's because we are going to save uh you know whichever uh nodes that we explore we are going to save them into our queue and we are not gonna explore all the nodes it's gonna be really log of n because we are growing the speed is getting multiplied into two so our space complexity is also going to be log of t okay I hope this is helpful and this was the this video was clear and you're able to solve this problem uh please like the video and comment on it if you like this video it really helps me out and then please subscribe if you want to be notified about new videos coming up this score will be on my GitHub and I will include a link in the description also I am on Discord channel so if you have uh any questions then you can connect with me on Discord I'll include that link as well in the description below and I will see you next time in my next video Happy coding
Race Car
similar-rgb-color
Your car starts at position `0` and speed `+1` on an infinite number line. Your car can go into negative positions. Your car drives automatically according to a sequence of instructions `'A'` (accelerate) and `'R'` (reverse): * When you get an instruction `'A'`, your car does the following: * `position += speed` * `speed *= 2` * When you get an instruction `'R'`, your car does the following: * If your speed is positive then `speed = -1` * otherwise `speed = 1`Your position stays the same. For example, after commands `"AAR "`, your car goes to positions `0 --> 1 --> 3 --> 3`, and your speed goes to `1 --> 2 --> 4 --> -1`. Given a target position `target`, return _the length of the shortest sequence of instructions to get there_. **Example 1:** **Input:** target = 3 **Output:** 2 **Explanation:** The shortest instruction sequence is "AA ". Your position goes from 0 --> 1 --> 3. **Example 2:** **Input:** target = 6 **Output:** 5 **Explanation:** The shortest instruction sequence is "AAARA ". Your position goes from 0 --> 1 --> 3 --> 7 --> 7 --> 6. **Constraints:** * `1 <= target <= 104`
null
Math,String,Enumeration
Easy
null
47
let's do the thirty-seventh problem let's do the thirty-seventh problem let's do the thirty-seventh problem illegal abomination to given a collection of numbers that might contain duplicate return all possible unique combinations so and this is a bit tricky problem okay you know none of our previous work finish the ways we use to do combination and permutation they won't actually work here we'll have to come with a new and a better approach so to say so we start by in a as usually defining the return variable we will define the other we will this and sort my array lunch once it sorted I'll call my heart method get lumps and new blend of lumps of length and then this return I guess now would help take - this boy and I'm going to have this - this boy and I'm going to have this - this boy and I'm going to have this condition that if God saying is equal to 9th 11th then is not add new array list little bit all and otherwise we will go to the follow and I is equal to zero I this last 10 nouns and I plus two if used I remark this means if we use five is false and this means I has been used yet that means we can go in and check if I is greater than zero and the mouth I Liang Shuang is equal loves I and used I minus one is equal to basically values are equal then continue else our this at lungs I am I last used of I is equal to - once it comes back from the call and - once it comes back from the call and - once it comes back from the call and villages remind these two operations a lot sighs - one seems to tent okay sighs - one seems to tent okay sighs - one seems to tent okay let's see okay his walking sushi working the summoned board and accepted thank you guys
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
115
welcome to september's leeco challenge today's problem is distinct subsequences given two strings s and t return the number of distinct subsequences of s which equal t a string subsequence is a new string formed from the original string by deleting some can be none of the characters without disturbing the remaining character's relative positions ece is a subsequence of abcde while aec is not say we're given a source string of rabbit with three b's we're gonna have three ways of forming target three sub sequences rather we'll have ones using the four letters and then the it here was one using the two letters that come at the end as well as two letters and skipping that middle b as well so we already kind of know intuitively that we probably want to do this recursively and if we can do it recursively there's probably a dynamic programming solution so let's start with the recursive solution what we're going to do is pass in the i and j which is going to give us the index numbers of s and t and we want to see if we could get to the end of j or the target string right so what i'm going to do here is first write m n equaling the length of source and length of target and let's write a recursive function we'll call it cursive and we're going to pass in the i and j which is going to represent the source and the target index number so at this point we find that j is greater or equal to n that means we've hit our target right so we can turn a one otherwise if we hit our i if we decide i is greater or equal to m we're going to return a 0 here so what i'm going to do is first iterate down uh recursively uh by increasing our i and what i'll what i mean by that is it's because we call i plus one but we'll keep that j to be the same so whatever returns here uh that's going to be the count at some point we should return a zero when we start the very beginning right and then what we'll do is say if s of i is equal to t of j then we want to increase both pointers i and j right so we'll say count plus equal recursively i plus one as well as j plus one at the very end we should return our account and that means all we have to do is return our recursive and just passing zero i'm pretty sure i have to do our lru cache here as well okay so this would be our recursive approach let's see if this works and it does look like it's working submit that and there you go accepted so this would be what m times n time complexity i believe because we are caching but it's kind of hard to read it's a little bit unintuitive so let's see what we can do dynamically do a dynamic programming solution as well here so just say that we had a very simple example say that we had a target of a b and a source string of a b now we already can tell from here that this is going to be an answer of two right we can form a b or a the second b a b so that would be two but how could we do this bottom up how can we build this up well we would need a dp array first considering a blank string for both say that we had a blank string for the target well there's only going to be one way to form that regardless of how many strings or characters we have in our source string if our target's blank there's only one way to do that always right so this would all be one here now if our source is blank and we have some characters in our target these would all be zero right so the first row is going to be all zeros so those are our base cases now we want to build up somehow what's the thing that we need to consider uh well there's two things the first thing is how many were we able to form for this target with characters that came before so here with blank string from our source we had zero ways of forming a right so we're going to bring that over um and if we did have a way we want to bring that over because we're actually adding an extra character here in our source right and when we find that yes our source target our source character is equal to our target character at this point we're going to bring over however many times we're able to form it right before both of these so this would be the i minus one and j minus one so we want to add this right here so here we're gonna bring that over this would be one here at a b we first want to take the one right above which would be zero but these don't equal one other so that remains the same thing here we want to bring over that one down but a and b don't equal one other so there's nothing to do here same with here we bring over zero but we do see yes b and b equal one another so we want to take what about at this point one was just a and a we did have one match there right so we're going to bring that over here one so this point right now we were able to form a b using these two string these two characters in our string once now same thing here let's bring over one down but they don't equal one other so we don't care and here we're going to bring over one down because we're adding an extra b here but we were able to form our target at least once but b and b equal to one another right so let's add whatever we had here down here so this would be two so that would be it we can form a b using abb two times and this would work all the way down however many uh characters we have here so okay that should be a little bit easier to understand let's calculate this being the length of uh source and this would be length of target let's create our dp array now we're gonna have all zeros at first and we'll say times n plus one for blanket range of m plus one now first thing we want to do is that first column let's make mark them all as ones so we'll say 4i and range of um m dp of i zero these will all equal one so these this is like if the target string was just blank okay now for i in range of starting from one to n plus one i've got that plus one here it's my fault and for j in range of one to n plus one this is for the target string what do we want to do okay so first thing you want to do is take our add to this whatever was right above right before we were able to add this extra character from our target string let's add i'm sorry for my source string we'll say i minus 1 j and it's only when these characters are equal to one another if s of i is equal to t of j but notice that i'm going to subtract one here because i added an extra column for these two indexes right so if this is the case if these characters right now are equal to one another then we are going to also add to j whatever came right above and left so i minus one j minus one so finally we turn the dp i minus 1 i mix 1 and that should also work and there we go so this is also an m times n time complexity but my opinion it's a little bit easier to understand uh it's very hard to come up with though these are questions all right thanks for watching my channel remember do not trust me i know nothing
Distinct Subsequences
distinct-subsequences
Given two strings `s` and `t`, return _the number of distinct_ **_subsequences_** _of_ `s` _which equals_ `t`. The test cases are generated so that the answer fits on a 32-bit signed integer. **Example 1:** **Input:** s = "rabbbit ", t = "rabbit " **Output:** 3 **Explanation:** As shown below, there are 3 ways you can generate "rabbit " from s. `**rabb**b**it**` `**ra**b**bbit**` `**rab**b**bit**` **Example 2:** **Input:** s = "babgbag ", t = "bag " **Output:** 5 **Explanation:** As shown below, there are 5 ways you can generate "bag " from s. `**ba**b**g**bag` `**ba**bgba**g**` `**b**abgb**ag**` `ba**b**gb**ag**` `babg**bag**` **Constraints:** * `1 <= s.length, t.length <= 1000` * `s` and `t` consist of English letters.
null
String,Dynamic Programming
Hard
2115
7
so hey guys welcome back so in this video we are going to solve the problem named as reverse integer so basically we are given a signed 32-bit integer X so are given a signed 32-bit integer X so are given a signed 32-bit integer X so we have to return x with its digits reversed right so if reversing X causes the value to go outside of the signed 32 bit end is the range which is from minus 2 rishwa 31 to 2 risk for 31 minus 1 then we have to return 0. so basically uh if x will be you can say if uh if it will go greater than into max right n to max value if it is greater than or equal to end Max or if it is less than or equal to end mean so simply will return 0 right assume the environment does not allow you to store 64-bited user signed or you to store 64-bited user signed or you to store 64-bited user signed or unsigned so simply uh what we'll do is so we have to Simply reverse the number and we have to just check the two conditions if you if it is going out of to minus 2 raised to power 31 or you can say if it is going out of end mean or you can say out of index value then we have to return 0. otherwise we'll return the reverse Train diesel so basically we have one two three so we'll store it in let's say any temporary variable right because uh we have to reverse the numbers so we can't change our original number so we'll store it in any temporary variable so one by one we'll get this number one by one will get this number and let's say we are showing uh in the variable code reverse of integer type right so first we'll get this number how will get this so let's say we are showing each number in a in any variable let's say called D so it will store it something like so it will be tamper mode and so it will be so in this way we are going to get each number every time right so for example we'll get three and we'll add it in a reverse variable so reverse is initially initialized with zero so it will be worse multiply 10 plus this D so initially it will be 0 multiply 10 plus this T it will be 3 so we'll get three so now we have to remove this so we'll do tab is equal to temp divided by tab so now we have one two so now we'll get this number 2 and how we'll get this in D so it will be tab mode and temp mode 10. so now D will be 2 so now uh our reverse was so now reverse operator reverse will be 3 multiply 10 plus d so now D is 2. so it will be 30 plus 2 now 32 right so now again we'll do time is equal to time more 10 so now we'll remove 2 so now we are left with 1 right so we'll show this one in the D so now again we'll do reverse is equal to now reverse is 32 multiply 10. plus this D value which is 1 so it will be 320 plus 1 which will be 321 right so you can see here we have got the reverse number so let's code it side by side and we have to just check the to our two different cases right so in Reverse is equal to zero and one more variable let's say we have taken d so now first condition we have to check if x is going out of these bounds to raised for 31 minus 1 if it is going greater than or equal to index over X is less than or equal to in the mean inter mean then it's given in the problem that returns 0 in that case right as we'll reverse the number simply right so we'll show the original number in any temporary variable so now y lover while over time is not equal to zero right so D will be temp so from back we'll show each number in the variable called D and will keep showing every number in the reverse manner it will be multiplied 10 plus d right and from back whenever we are processed with the number so we'll keep removing one number right so now we'll check if reverse is greater than or equal to end mean so if it's given in the problem that uh if reversing X causes the value to go outside then we have to return 0 otherwise if it is in this range if reverse is greater than or equal to inter mean and was is less than or equal to index then only uh we'll return this reverse number right then only we will reverse else so else uh will return 0 right else will be down zero and it's given assuming the environment does not allow you to store 64-bit it is a signed over 64-bit it is a signed over 64-bit it is a signed over unsigned so and so we'll get error otherwise so we have to take it as long otherwise it will not be able to show this much reverse value so you can see here it's accepted so otherwise we'll get the runtime error if we store it in as a D in the integer variable right otherwise we'll get the runtime error it but if these variables will be of only integer type right then we'll get the signed integer overflow so I hope it is clear right simply we are reversing the number right using these steps so we're just checking these two conditions uh so if it is already out of these bounds so we'll return zero and before returning this reverse number so we have to check if it is in this range or not if it is in this range only then we'll return this reverse number otherwise will return zero right uh so it's a very easy problem so I hope it helped you so you can comment down your thoughts in the comment box so if you like the video please do share and subscribe to the channel so stay tuned for more videos
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
287
Yes, hello developer. Today's Prole problem, which has been migrated to Children's Gaebing, is how the finder tipple ended at number 287. The integer multiplier is given. Now, it is an integer array that increases sequentially from 1 to n. So there is only one duplicate number. This is a problem of implementing a function that returns a duplicate number. For example, there is 134 e, and since you are now a duplicate, it is convenient, and you will only say 3134 3 times, and it will be 1. Yes, then let's solve it. It plays the role of a chaser like the previous videos. Declare an object and share too much. If there is a lot of casting, enter the value as 4. If it does not exist, enter the value as 1. Rotate the phone like this and the cache n value will be entered. Then, I will enter the cache through the visible door. If the cache transfer key is If the value is 2 or more, it would be a duplicate number. In this case, just return 2 kills. This king is an element of the array, so you can get the correct answer. I solved it with 4 waves. I solved it once using this adjustment cache. That's it for today. See you in the next video. Thank you.
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
149
and welcome to my channel so in this video i'm going to try to solve this problem and also do some live coding work at the same time i'm going to try to follow the general steps we should follow including interview so before we start the coding question i would really appreciate that if you can help us go on this channel so let's get started first of all let's uh first resort this problem so given an array of points where point i is represented by x and y i representing a point only x y plane which is a 2d plane so return the maximum number of points that lie on the same straight line so let's take a look at this example we have the three points so we are going to return three because uh there are uh three points lying on the same uh on the same line for this example and for example two there are six uh points and the maximum number of the points laying on the same line is those four points so we are just going to return four so let's see the constraints it says the points uh we have uh between 1 to 300 points and each point is represented by x and y and the x i and y is within the range of minus 10k to positive 10k and all the points are unique so it says all the points are unique so we don't need to actually worry about the same point something like that so having said that um i think not too much to think about the ambiguous part uh and too much room to think about ash case because it says that the points is uh so we are going to have more than more or equal to one points and also all the points are unique so it's pretty clear for our question so the next part is let's think about how to solve this problem so how are we going to solve this problem i think what we are going to do is we can have a for loop with the another for loop it's like four layer of the for loop um so we iterate through the points so it's something like uh p uh let's say just a pi is equal from zero to uh to let's say that their endpoints and then we are going to have another thing which is pj from p i plus 1 to n so it's something like that so you're going to have to layer the for loop enumerate any pair of the points and then try to compute the slope of the points so in here we are going to have a map so the map is essentially keeping the slope and the corresponding count so we are going to have the slope and the corresponding cup so when you try to compute uh p when you try to do the computation on p and pj we just try to compute the slope on top of it so it's something like for each of the point pi you're going to keep a map uh the key of the map is going to be the slope and the value of the map is going to be how many uh points that connect with pi that has the same slope so in this case uh what you're going to have is we're going to have like for each of the point we are going to have the number of the points on the same line and then you're going to have like a global variable let's say the maximum count which is going to keep track of the maximum number of the points on the same line so during the computation we are going to update this value on the fly as well so in this case uh we are going to do like a two layer the for loop so essentially the runtime is something going to be o and square space wise we are going to keep a map so let's say we have an endpoints then the space wise it is going to be all open as well uh sorry it is going to be all of them but not as well uh so run time and squares space wise all event so having said that i think we are pretty sure how to solve this problem let's do some coding work on this one so let's uh let's do some coding work all right so first of all let's say if we have less than three points then we don't need to do any computation actually because like if you have two points for sure they are going to be the same line so i will say if the points the less is smaller than three then you're just going to return this lens without doing any computation otherwise it is our major logic we are going to have a max let's say max num points on same line starting from let's say starting from two then we are going to enumerate out all of the points so let's say you just define num points as a local variable so we have first the points i starting from zero until the last one or actually the one before the last is just fine so i would say yeah so it would be something like this plus i and then you're going to have the j i plus 1 j is smaller than num points yeah plus j so essentially we don't need to start j from zero that's because we have already done the computation before so we don't need to re do the recomputation so here like he said we are going to have a map so you're going to have the slope so just to represent the slope of the string because if he is double or whatever it could cause potentially cause some issue so uh i'll just use accent y representing the string using the string representation of the slope so this one this is so we i will just name it as slope counts yep so that's pretty much it for this one uh let's do the computation on the slope so let me define a helper function here so this one is going to be the slope get slope so we will have the p1 the p2 so this one you're just going to do how to do item here and currently i just leave it as something empty so i'm going to compute the slope and put it into this map um so let's see it says that all the points are unique so we don't need to worry about the same points here uh if like not all points are unique we need we still need to do some special competition special processing for that one so let's say get a slope uh so slope so the string the slope is going to be slope on top of p1 p2 sorry p uh points i and points j so if the slope is already within this one you're just going to update it otherwise you uh you're going to have put something new but instead what we are going to do is we are going to just put some conduct and put the slope count get or default the slope zero plus one then it should be the slope yep and then i think pretty much it and then in the outside of here you're going to go through all of the counts so let's say string so you're just going to go through this map and update the maximum points on the same line so this one is slope count now key set so max points is equal to maximum max between this one and slow com.gets and slow com.gets and slow com.gets so finally we are just going to return the mics num points on the same lines so that's pretty much it let's finish this to do item so for this guy slope however we're going to do the computation so let's say you're going to have the x as p1 zero minus p two zero y is going to be p one minus p two one and now so because uh the gcd the grid's greatest this divisor a common divide greatest common divisor between x and y can be non-zero so can be or can be larger than non-zero so can be or can be larger than non-zero so can be or can be larger than one so something like this so let's give you an example let's say we have the accent as 2 and y is 4 it is pretty much the equal something equal as x is s1 and ys to 2. so we definitely want to uh divide the x and y by the gcd of the both things before combining it as a string so we need to compute the gcd here so let's say we have the gcd uh define another helper function let's say it's called gcd um so i'll just give you like uh y so i think the gcd is um well i'll just leave it to i go to the item so if so here look at like um if you want like for example the p1 0 p20 it could be eco or the p11 p1 could be zero so that's big that's something like uh the two points are on the horizontal line or the vertical line so in that case the gcd is just going to return zero so uh in that case we are going to do is um x uh so first of all i need to get the gcd so the gcd is equal to gcd on top of x and y so x is equal to is gcd uh equal to zero if yes then if the gcd is equal to zero then you're just going to ha so if gcd is equal to zero well if gcd is equal to zero we're just going to divide it by okay so i think i know it we're just going to have the x uh divided by mass x and y otherwise we're going to have x divided by g c d so if gt is equal to 0 then it means it's either horizontal or vertical so what i'm going to do is i don't want to have the divisor as equal to uh the we don't want to have this divided by zero so we are going to have like change it to be a nonzero stuff otherwise we are just if gcd is not equal to zero we are just going to divide by gcd similarly we are going to do the same thing on top of y so this one is going to be yeah and finally you're just going to return uh the it could be like x and then y oh yeah i'm just gonna underscore here so that's pretty much it so the rest of the thing is to how to compute the gcd so i think the gcd uh let's see i kind of let's return i think it's something like it is y is equal to zero if yes then it is going to be just x otherwise it is going to be gcd on top of um y and x divided by y so i think it's something like this um so let's give it a shot by running this through this piece of code maybe it's wrong yeah so it's one two and three we have the output as two oh so that's because i didn't actually add a yes i didn't actually add it included the orange so for example let's say we have one as i encountered two i didn't include the one as a count so that's why i'm not doing the correct thing so let's see so finally we're just going to have the maximum it should be like i have like a plus one here all right so let's run the other task cases okay it seems like to be right let's do a submission here all right so it seems like everything works well and that's it for this coding question so if you have any questions regarding the solution or regarding the coding work feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching
Max Points on a Line
max-points-on-a-line
Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_. **Example 1:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** 3 **Example 2:** **Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\] **Output:** 4 **Constraints:** * `1 <= points.length <= 300` * `points[i].length == 2` * `-104 <= xi, yi <= 104` * All the `points` are **unique**.
null
Array,Hash Table,Math,Geometry
Hard
356,2287
1,298
hello so continuing on with code contest weekly contest 168 this is the last problem maximum candies you can get from boxes problem number one thousand two hundred ninety eight so the problem says we have n boxes and each box is given in the format status candies keys and content boxes such that status at position I contains an integer where if the value is 1 that means the box is open and when the value is 0 the box is closed and so basically we have boxes that are half candies and these boxes can be opened or closed and we have the keys for the boxes and we have because some boxes are closed we can find some keys in boxes that can open these boxes and also some boxes contain other boxes and we also get an array of initial boxes where those if they are open we can take the candies right away so you we will start with this initial boxes and we can take all the candies in any open box and if the box contains some keys we can use these keys to open new boxes and you can also use the Box you find in a box so basically if I say you have a set of boxes you can only take even if other ones are open you can only take those that are the initial boxes and then from the initial boxes you can access more boxes or access more keys to open boxes that are inside the initial maxes that you got right so it will be more clear maybe with an example so let's say here we have these the statuses of some boxes the first box is closed is open so one the second one here is closed this one is open and this one is closed and these are the number of candies in each of these bugs so the backs at index zero which is open has seven candies in it the one at position one that is closed has five so if we open it we get five candies and these are the keys in each box so the box at index zero has zero keys in it at index one has zero keys in it but the box at index two has the key for the box at index one alright so the content of kids represents the box a position right and contained boxes here the Box in position zero which is open contains two other boxes which are the box at position 1 and the boxes position 2 and the box as position 3 0 1 2 3 which is the last one that is close sorry the box at position 1 which is the one here that is closed contains the last box which is closed here and initially we get only one box which is the box at position 0 that is open so we get that one and so what we can do is while we get the first box this box at position 0 we will find 7 candies in it so we won't keep that we'll keep that here and then we will find in it the boxes at position 1 and 2 the box at position 1 is closed so we can't use it but the box at position 2 is open so we can and so we take for the four candies in it so now we have 7 and 4 and then the bats at position 0 has no keys but then since we open box at position since we got the box at position - because it was in bags at position 1 - because it was in bags at position 1 - because it was in bags at position 1 and it is open it is opened then we from there we get so 0 1 2 we get the key for bugs in position 1 right and since we already obtained bugs in position 1 in the first box that was open we can now open it because now we have the box and we have the key so we can open it and so we open the box at position 1 here and get the 5 candies that are in it and that's it the box at position 3 we get it when we open the box at position 2 but the problem is it's closed and we didn't get the kid for it right and so we can't open it so I can't get the candies in it so the overall we get 16 candies so that's the idea you can go over the other examples to understand that but this is the main idea so how can we let's see how can we solve this problem okay so let's see how we can solve this problem so first let's take the first example that we have there which is that we have the following state for the boxes so one is that the status is the first one is open the second one is closed the one after that open and they're closed and then we have candies and for the candies the first one contains 7 after that 5 4 and 100 for the keys we have the first one contains nothing's I can one nothing that what contains the key for the first the box at position 1 after that contains no keys contained boxes so the first one contains the box is 1 &amp; 2 the first one contains the box is 1 &amp; 2 the first one contains the box is 1 &amp; 2 the second one contains box 3 the one after that is empty it doesn't contain any boxes and initially we get the bugs at position zero only and so if we can kind of draw this out just to get an intuition of what is happening here so if we have say the box at position zero right so the bugs the positions are zero one two three so if we draw out the box at position zero let's say this one is the box at position zero so that one has the following boxes so it has the box one and two right so it has the box one and has the box - in it right so these are has the box - in it right so these are has the box - in it right so these are like their position now the box at position 1 is open so this one is open that's why I left it like this the best position 1 is closed so this one is closed and the back says position 2 is open the box at position 3 which is actually in box 1 so this one contains box at position 3 and that one is closed like this so you get the idea of how this works so I'm going to put in this color here these I'll put the candies a number or count and so box 1 contains 7 candies box 0 contains 7 candies box 1 contains 5 2 contains 4 and the third one contains 100 and then in each I put the contained boxes now let's put the keys so I'll put in let's say this here I'll put the keys so in position 0 1 to position 2 so the boxes position 2 has key for box 1 so that here has key for position for this box here right and so now we need to have backs to be able to open box one and once we open box one we have box three now we need a key for box three to be able to open it but unfortunately we don't have the key for box three so we can't get the counties in there so you could see here that there is a dependency between the boxes right so for example in order to be able to get the candies impacts to we need to have box zero which fortunately we have that in the initial boxes so that means we can get it in order to be able to also get the candies and puts in box one we need to get back zero right and get the key to box one and to get the key to box one we need to have bugs too which fortunately we have it in box zero so you get the idea of the dependency so basically box zero gives us access to bucks - right zero gives us access to bucks - right zero gives us access to bucks - right and gives us access to so this is just access not necessarily the candy is in it because that depends on whether it's opened or not or whether we have the keys or not but zero gives us also access to box one right and backs to gives box zero gives us access to key one right so you can see here with these dependencies you need one box in order to access that bus but to access the next box then you we need to think immediately above using BFS and we could just simulate using the data we have and BFS basically adding by adding to be fsq only boxes that are available that which means we have them we have access to them and our eyes are open all we have kids we have the key right and so we just need to orchestrate our BFS in a way that we can process this here and so how can we like how can we cut this up so one thing we know is that the we need a cue so that we can put them right so once we find like a box is available and open then we add to the queue right so this is the process that we will that will do one thing we need to be careful of is not to terminate not to keep processing boxes and definitely so for that we will need to have a visited or a done set that will keep track of to keep track of boxes that have been that from which candies have been collected right so that we don't recount them and we don't process them again so boxes that have been processed I'm just going to call it process it or handled we also need to know with the available boxes we have so that we can check if a box is available so for that we need to have available which is can be just a set same thing for visited or can be an array to keep track of boxes that we have why do we do that because sometimes in some cases we might have the box but it's closed right and we might obtain the key afterwards right and so we need to keep track of the available box so that once we obtain the key we can directly open it and use the candies in it right and we need with our cue right our cue that we want to put the boxes that are ready to be priority to be hand to be process it right because they are both available and opened right and so this here this one here can be initialized to the initial boxes that we have right same thing with the available since it's available and the visited right and so that's pretty much it and every time we get a box from the queue we will check the boxes that it contains because those are now available we will add them to the available there are structures that we have and then we will check if they are opened if they are open we add them to the queue if they are not we don't add them to the queue and then we'll also check the keys in the box that we are processing if the we market so once we have the key we can mark the box as opened right away so once we get key then we mark the box as opened right away right because now we just are waiting for it to be available and we can use it and to do that we can just do something like status for the bugs we can set to one right and now if that box is in the available set of boxes that means we can start processing it and we can add it to the queue right and so that's what we will be doing so now let's just initialize those data structures and see how this would look like so first we need the available solar definition so it's max candies and I'm just going to assume that we have the input here and we need available set which gets initialized to the initial boxes that we have right so those we already have them they are available right and we have the visited set that I'm just going to initialize to the initial boxes because I consider that I already that I'm going to process them and then I need the queue that will contain all the boxes that are ready to be processed and so this one also gets initialize it with so with BFS we use DQ in order to keep track of the things to process and we add them to the end and we get them from the front right and so here we'll add the initial boxes right and now while we have something in the queue we have something to process we will continue right and so the first thing we do is we get a box out of the queue so that we can process it right so we get it from the front right and then the next step is while we need to return the final result right which is just the counties that we obtained the maximum candies that we obtained basically with this we will get as much candies as we can we won't stop until we can get any more candies and that way we'll get the max candy is possible right and so here as soon as we get a box since it's in the queue that means it's available and it's opened so I can like take these in short boxes and check if they are open but I'm supposing that the initial boxes that we have will be opened already and so I'm going to add them since I know anything in the queue is anything in I'm coding my solution here so that anything in the queue is available and opened right and so that means I can get the candies and so I can just add them by getting candies in position out of the box right after that I will go through the boxes so I have a box so I have access to the boxes in it and so I will look at the contained boxes so that I can get the boxes in there and check them and so to do that I will just say for the contained boxes see in contained boxes of the box that I'm processing and so if I get that first I will check if I already processing it because if I already did I shouldn't even worry about it right so if that is in visited I should stop so I should just continue to the next continuing to the next contained box otherwise I need to check I need to add it to the available box because now it's available I have it right so I will need to add to the available boxes right and then I will check if it's open because if it's open that means it's ready we added to the queue and so to do that I'm just going to check if the status of the contained box is one that means it's ready to be processed so I can add it to the queue and I added it to the queue that means I visited it in the in my simulation of the graph here so I added to the visited set so that I don't visit it again next time because it's already being cured to be processed it I don't want to queue it again right okay so now I handle the content boxes right now I need to handle the content keys and so for every key in the keys for the box so key at index box it gives me the keys that are in that box the one that I market here and so for key in keys of the box same thing if that box which I get by I was just called this K so if that is visited I don't need to worry about it right so I can just skip it now otherwise I need to check so otherwise I have the key now so I know it's a I can open it so I can just consider it to open and then I will just wait for it to be available if it's not yet available and so once I get a key I'm mark I mark it as open using this here and so once I get a key I'm going to mark it as open by doing status of the box equal to one right and so now that I have it opened I can check if it's already in the available set of boxes because if it is it was closed so I didn't add it to the queue but if I now have the key and I opened it and it's available that means it's ready to be processed so I added to the queue and so I do if K in available right so that means it's ready to be process it so I do the same thing that I did here which is added to the queue and add to the visitor set so that I don't three add to the queue again right and that's pretty much it now once I'm done and the queue is empty them is I process it all the available and opened boxes I can and got the candies from them right because I have all I would have pappad them off and got the candies I can just return the final result right and that's pretty much all there is to it so the overall algorithm is just get the initial boxes write those out of available boxes that I have and start off processing those and so they are opened and then I check the boxes in them if any of them is open I add it to the queue to be processed if something of these container boxes is not opened I keep track of it and then waiting for it waiting for me to have the key so that I can open it and then I process the kids that are in the box that I just got and I check if it's a market has opened since I have the kids for it I check if it's in the available boxes that I have if it is that means it's ready to process it so I add it to the queue and every time I popped from the queue I add the candies that I got and at the end I returned those and so this is pretty much it and yeah so let's type this in later code and see if it passes okay so I type it the solution that we just went over and the so it's the exact same one we have the available insurance available visited and the queue and we process the process of them in the order in which the boxes are laid out so the contained boxes if they are opened we process them and if not we keep track of them and that's pretty much it so here and I collect the candies and at the end I return the result so let's run this and see if it passes okay so it seems ok so let's submit ok so that passes now in terms of time complexity so the queue here we won't add more than the available the entire set of food boxes that we have right and if we consider that to be n then at most since we have visited here that doesn't that prevents us from processing a box multiple times that means we will do at most oven time here yeah so that's pretty much it in terms of space here we have these three ones that will go up at most two n so it's also over in space I think yeah so that's it pretty much for this problem thanks for watching and ceiling
Maximum Candies You Can Get from Boxes
reverse-substrings-between-each-pair-of-parentheses
You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where: * `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed, * `candies[i]` is the number of candies in the `ith` box, * `keys[i]` is a list of the labels of the boxes you can open after opening the `ith` box. * `containedBoxes[i]` is a list of the boxes you found inside the `ith` box. You are given an integer array `initialBoxes` that contains the labels of the boxes you initially have. You can take all the candies in **any open box** and you can use the keys in it to open new boxes and you also can use the boxes you find in it. Return _the maximum number of candies you can get following the rules above_. **Example 1:** **Input:** status = \[1,0,1,0\], candies = \[7,5,4,100\], keys = \[\[\],\[\],\[1\],\[\]\], containedBoxes = \[\[1,2\],\[3\],\[\],\[\]\], initialBoxes = \[0\] **Output:** 16 **Explanation:** You will be initially given box 0. You will find 7 candies in it and boxes 1 and 2. Box 1 is closed and you do not have a key for it so you will open box 2. You will find 4 candies and a key to box 1 in box 2. In box 1, you will find 5 candies and box 3 but you will not find a key to box 3 so box 3 will remain closed. Total number of candies collected = 7 + 4 + 5 = 16 candy. **Example 2:** **Input:** status = \[1,0,0,0,0,0\], candies = \[1,1,1,1,1,1\], keys = \[\[1,2,3,4,5\],\[\],\[\],\[\],\[\],\[\]\], containedBoxes = \[\[1,2,3,4,5\],\[\],\[\],\[\],\[\],\[\]\], initialBoxes = \[0\] **Output:** 6 **Explanation:** You have initially box 0. Opening it you can find boxes 1,2,3,4 and 5 and their keys. The total number of candies will be 6. **Constraints:** * `n == status.length == candies.length == keys.length == containedBoxes.length` * `1 <= n <= 1000` * `status[i]` is either `0` or `1`. * `1 <= candies[i] <= 1000` * `0 <= keys[i].length <= n` * `0 <= keys[i][j] < n` * All values of `keys[i]` are **unique**. * `0 <= containedBoxes[i].length <= n` * `0 <= containedBoxes[i][j] < n` * All values of `containedBoxes[i]` are unique. * Each box is contained in one box at most. * `0 <= initialBoxes.length <= n` * `0 <= initialBoxes[i] < n`
Find all brackets in the string. Does the order of the reverse matter ? The order does not matter.
String,Stack
Medium
null
260
hey everybody this is larry this is day 5 day 6 of the leco daily challenge uh day 6 of the legal daily challenge hit the like button hit the subscribe and join me on discord let me know what you think about today's prom also just want to say happy diwali to people who celebrate it uh yeah anyway today's problem is single number three okay so i would also two things one is i saw this live so it's a little bit slow let me know uh the second one is um the second one is i actually uh i feel a little bit sick today so if i'm a little bit foggy on my mind that's my excuse and i'm sticking to it um okay so let's see given a ninja num away numbers in which two uh ones and other elements appear twice find the two elements that appeared only once okay so actually i know this one to be honest um because i do remember it because it is actually interesting that's why i know it i suppose um and maybe i'll have a link below on because i've solved this on stream i don't know how long ago maybe a year maybe longer than that two years ago maybe three years ago so i'll put a link there or something like that or someone can put a link there and i'll give you props but so it's a little bit weird for this one for me to kind of like think about it but maybe like it's hard for me to demonstrate like oh i don't know this one let me stop it from scratch because this is very unique um i would say um doesn't really come up that much to be frank but i will try to do my best here to kind of explain it better than my other video because the other video maybe i was just more about exploring and solving it where now i know the answer but i'll see if i can explain it um okay so yeah so one key trick so one thing that we know uh is let's see um there is the easiest single number i don't know which one it is but this is a well documented trick um if you don't know it i don't i wouldn't feel that bad about it's almost trivial in that like it's just something that people know because people asked it on previous interviews i think back in my day um this was not a commonly known thing so it was more interesting to ask as an injury problem but i feel like these days um if you get you only get asked these kind of questions if you get someone who's way out of touch or just i don't know maybe they discovered it the week before and like oh this is a coupon let me ask on an interview or something like that because i there's really no value in it per se now that i uh for me like i would never ask it um i never asked it before but i would not ask this as an interviewer in the future um so yeah so the key thing to note is that any number x or itself is equal to zero right and one thing i would say about bitwise operations and i guess this one doesn't actually accord to it but if you think about bitwise operation the one thing that i would say is that think about all the bits independently um because basically we can separate all the bits by themselves so then it mix and if you're able to think about it that way um it makes these kind of problems easier because no matter what or like doing operations on these things do not change the other digits right so that's one thing that i would say um and now so maybe through this idea we think okay what do we get right well the two numbers that appear twice oh sorry two numbers that appear once and one number that appear twice right so that means that we uh or if we put xor everything in their way what do we get um so we have i don't know a sub zero uh a sub one a sub two dot a sub n right equal to some number z c z um and a lot of these cancels out because it appears twice and you know we have this identity which maybe you just have to know or play around with um so then now you come up with two numbers that um only appear once so you have x um x or y is equal to z right so this is what we get when we exit the entire thing um and then the question is well we know something right we know that z cannot be zero because if z is zero that means that x is equal to y which um i guess would not it's guaranteed that's not the case because otherwise i don't know that's just a very funky problem and obviously it has infinite solution as well um or maybe not infinite solutions but i don't know maybe no solutions to power you want to phrase it i think that's that more accurate actually i misspoke but in any case so we know that z is not equal to zero right so then what does that mean that means that set can be represented by a binary number uh that is the result of all these xors right um and that means that as we said um all these numbers or all these bits you can think about it independently of each other and that means that for every well that means that if z is not equal to zero that means that this will contain at least one right um that means that they differ in one place so otherwise that's a zero right so then now let's just kind of remove all these things and then now let's just focus on one of them let's just say we look at this digit and only this digit you know there might be other ones well that means that x to the y at least in this digit in the fifth digit i think of dividing one count but in the fifth digit is equal to one right that means that now um now you can think about it as okay that means either x is one so this is one of these two cases right um yeah obviously so that means that here if we xor everything and yeah huh how did i want to go with this sorry give me a second i am solving the or even trying to figure out how to explain this live so um so i'm trying to um find a way to kind of be clear about it and it is a skill as well obviously because if it's not then well i would not be good or bad about it would just be right but in any case um yeah so that means that now if you go back to this formula um now we look at every number right and how do i want to think about this well there are a couple of ways you can think about this actually i guess but the way that i'm thinking about it now and to be honest i did not remember or do not remember the solution as much as i thought i do actually i suppose um but the way i would think about it is okay there couple ways to do this right one is that if you look at order let's say we focus on i don't know one of these things ones and zeros it doesn't matter right this is commutative so for all effects is the same so that means that if we take all the numbers in the nums list that is one by definition well i mean okay maybe let me step one second back which is that okay let's say now we have you know uh we only look at this digit um on the fifth digit say just as an example and you have something like this um something like this right dot whatever um so it's just like you know you have n digits or n numbers and each of them this is the digit and then um this is the value in that num uh digit right and in this case we always said that this is going to be one and this is just because this is just by definition because um we looked for it right so we find a case where this is true and then now let's say we do um you could call it a bucket sword or just regular sword it doesn't matter now you can sort it by something like this dot uh and then at some point obviously there'll be one right so you have something like this and of course now you can see that all these zeros cancel out right um for at least for this digit all these zeros cancel out um or not cancel out they just don't have any impact it doesn't matter where they get canceled out where everything on the right side here um everything cancels out except for one right so that now um and this point may be a little bit tricky in that okay now that means that we could get rid of these numbers with no impact on the values so that now we only look at the numbers where there's a one in that value and then now that there's a one in that value we think okay um now you bring it back in and if you only look at and also wait sorry let me step back just a second um so now that we have here right we one thing to note is that um in this case let's say y is one and x is zero uh just for whatever uh this part so x is here right and then on this part uh y is here oops so that means that this is x is here and y is here um that's so that means that by getting rid of this half we know that y is in here and here by itself right and then now um now we kind of bring all the digits back together again which is that if we kind of you know make this uh a multi-digit number uh the make this uh a multi-digit number uh the make this uh a multi-digit number uh the for every subset because now x is in the other half this just reduces to the single number the easiest single number problem of okay every number here has a double except for one number and that is y so that now we can just figure out do this to figure out why um oops right we can figure out y from here and here now that we've configured y from here we can just take it yeah like we have this formula and therefore and yeah i mean i'm not gonna prove this too much but this is now you can figure out x is my point um and that's pretty much the idea behind this problem um let me know what you think i spent some time on this because i think it's a cool problem but just not it doesn't come up that much to be honest so depending on how you want to figure it out but i did i think i figured this out by myself and to be honest i thought i remember this more than i did um so i did kind of um kind of figure out how to explain it even right like for this part so i think hopefully that's cool so yeah so now let's implement this uh so xor sum let's say let's just do this one zero so then now for x and nums xor sum we xor x right and then now we know that xor sum cannot be zero so then now we find a digit where that is the case so digit is equal to zero while um xor sum and once the digit is equal to zero we increment so this is going to be true for some digit um and if you have doubts about that and you worry about things then you can just do something like this um oops greater not your zero i suppose uh and assert that i guess there's no store here you just want an infinite loop if your assertion is false um but so here you may just have a mental note of okay there's time to make seeds it's probably this perfect um and i was wrong about something um but yeah and then now we do for the loop again uh if x uh you may notice that i love adding a lot of prevent on my bitwise operations um the reason is because if i don't um i don't i'm always really bad at order of operations for these things well i'm like i know how it is but i don't want to think about it right like i mean it's not hard to know it but i feel like i mess it up enough times that i you know just have one consistent way of coding and even if it's a little bit weird and in this case it's not even that we're both it's just more clarifying if you ask me um you know it makes your life a lot easier um yeah so here we have y to the x uh maybe using x and here is not it uh okay let me change this up a little bit just so that it's slightly less confusing with respect to the things that we talked about right and then now we have so x is equal to xor sum to y and then now we can return x y um and that's pretty much it i hope this is right because if it's not then there'll be a little set oh there could be negative numbers actually i didn't know that let me think that might be wrong actually or i don't know if it could be wrong but i also have a typo but i have to think about that a little bit because the bitwise operations of negan number is a little bit weird maybe um or like in python i always feel like i there are always random surprises that i'm like ah this is not how any other language just does it but uh but yeah uh but it seems like it handles it okay i don't know how to feel about that let's actually add this but except for make this negative um because now the xor thing is a little bit awkward maybe i guess it still works um i mean without getting too much about two's complements and stuff like that um and xo some would still be positive in this case well in this case but not always right so if we had written this we would be wrong because technically i guess this would be negative right um because this would fail i think oops negative numbers is actually interesting i didn't think about it that much try and see this would give you an error and you'll be like oh now my assumption is wrong i have to figure out what to do um and then the other one that i want to do was um yeah okay this i suppose because now they only differ from this side oh no because of two's complement so that's why i guess i was wrong in i mean i do understand it if i think about it but i think i was too hastily to kind of prove to yourself that something is in because it is easy to prove yourself like oh it should be obvious but sometimes it's not or like you may be right for the wrong reasons and it leads you to trouble down the line so sometimes it's worth bringing the time but if you have questions about this just think about two's or not think about but google up uh two's compliment and that should kind of give you an idea um okay let's give it a go let's give it a spin uh yeah apparently i did it two wow this time flies this is two years ago in c um when i first started doing this channel i did a lot of random things in c because that was always my most familiar thing but i've kind of you know obviously do uh did different things over time but uh but yeah anyway uh that's all i have oh wait let me go over the time first of course this is linear time um kind of uh but yeah because uh because this depends on the number of digits and stuff like that so it's a little bit awkward to say linear um in that there are actually two variables this is there is um oops there is oh this is n where the number of elements and maybe something like d where is the number of digits and in this case this would be o of um n times d i guess um because in this case you can say that this is of nd um this is o of d uh this is o of also i should have cached this um if you want to think about this as d this would be an optimization but anyway this is also of nd because for every com uh xor it's all of d right because this is all d because i mean i know that there are computers or um cpus that does this as an operation but um and especially given that it's a primitive but if you want to generalize it so yeah uh and in terms of spaces this is o of d where d is of course again the number of digits because we that's the um space needed to store d x or sum this digit number and y right so yeah so this is so in place and of course um given that d is a fixed uh cut you know it's a fixed with uh primitive um for int i think yeah um so therefore this d is i guess thirty two or something like that um so that's why it is quote unquote n and of one but depends on how strict you want to get anyway that's all i have for this one um stay good stay healthy to good mental health i'll see you later and have a great weekend bye oops didn't pass the bun bye
Single Number III
single-number-iii
Given an integer array `nums`, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in **any order**. You must write an algorithm that runs in linear runtime complexity and uses only constant extra space. **Example 1:** **Input:** nums = \[1,2,1,3,2,5\] **Output:** \[3,5\] **Explanation: ** \[5, 3\] is also a valid answer. **Example 2:** **Input:** nums = \[-1,0\] **Output:** \[-1,0\] **Example 3:** **Input:** nums = \[0,1\] **Output:** \[1,0\] **Constraints:** * `2 <= nums.length <= 3 * 104` * `-231 <= nums[i] <= 231 - 1` * Each integer in `nums` will appear twice, only two integers will appear once.
null
Array,Bit Manipulation
Medium
136,137
49
all right let's do Lee code 49 group anagrams uh in JavaScript this is a medium problem uh they want you to group all of uh the words in here that are anagrams together so for the output example um Nat and Tanner anagrams of each other so group those together put them in Array and do the same thing for any other words in there and then return those as a sub arrays of an array this is a uh I solved this with the hash map um so let's do this so we're going to first we're going to create an object and then we're going to Loop through every item and what we need here is we need a key so we're gonna do a key equals I oh I dot split so first thing we're going to do here is we're going to sort all of every item as we're going through it and the reason we're doing that is we need to see our things anagrams of each other so what we're going to do when we build up our hash map is we'll build up a hash map with a key of the anagram version of a word and then the value will be all the words that match that as they were sorted so let's get a little deeper in this so we're going to do uh if the key doesn't exist the object T doesn't exist we'll create it and we will set it to I and we're setting it to the word in here otherwise if it does exist what we should do is we should get that object key and push in I to it see it's an array here so push into I so let's uh make sure I type this out correctly and we can console.log our object run that yes this is what we got so it's building this up what we're doing is we're building up like I was talking about we have this right here this is the key that we're creating the key of all of these values these are all anagrams of each other this is just a sorted version we have to have a way to sort all these items and compare them against so that's what we're doing here so every time we grab one of these words here we go all right we're going to reorganize it using split sort join then we're going to check to see is this key anywhere inside of our map if it is not we will create it and we will create it as this is a good example of that of one that was just created but hasn't anything pushed into it we'll create it as an array and we will put in the word otherwise we will push in a word into our existing object key such as here this has had Nat and tan when it was created uh it had one of these and then the other one it uh it had it pushed in as well okay so now that we have that what we need to do is we need to just return the output in the correct format right here so what we're going to do is because this is an object we can just return all the values from it and we will need to pass in our object to that to do so and that's it so let's give this a say let's give us a run save okay passes test cases I'll hit submit great that's accepted and I'll leave this on the screen see you next time
Group Anagrams
group-anagrams
Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** strs = \["eat","tea","tan","ate","nat","bat"\] **Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\] **Example 2:** **Input:** strs = \[""\] **Output:** \[\[""\]\] **Example 3:** **Input:** strs = \["a"\] **Output:** \[\["a"\]\] **Constraints:** * `1 <= strs.length <= 104` * `0 <= strs[i].length <= 100` * `strs[i]` consists of lowercase English letters.
null
Hash Table,String,Sorting
Medium
242,249
823
hey what's up guys uh this is juan here so this time let's take a look at today's daily challenge problem uh number 823 binary trees which factors so you're given like an array of unique integers right and where each integers is strictly greater than one and we need to make uh you can make a binary tree uh using these numbers these integers and each integer each number can be used at for any number of times and the requirements is that you know each leaf node sorry each non-leaf node value should be sorry each non-leaf node value should be sorry each non-leaf node value should be equal to the product of the values of its true of its children right and they and you need to we need to return the number of binary trees we can make and then since the answers will be too large we need to do a modular by this one right and here's the example so if we have two numbers we have two and four right so for this one uh we can make basically three trees so i mean the first observation is that you know the number itself can always make a tree right because two by itself is a tree because two to a two as it's as itself it's like you can think it's the eyes of both non-leaf node and the leaf node right non-leaf node and the leaf node right non-leaf node and the leaf node right that's why you know the node itself is always the number itself can always satisfy this condition and this is one and this is another one which is four and the third one is this one two four basically we have four we have two then we have two all right since no any integer can be used as many times as possible that's why you know it's four we can make two and two okay and here so if we have two four five ten right i mean so first obviously we have four trees at the beginning right and then we will have like two four ten two five and ten five two all right cool so this one okay so here are the constraints right so we have like uh the array length is like one thousand and the number range is a ten to the power of nine okay so this problem you know it's to me you know i was like you know how can i was basically i was trying to write a few uh examples or not you know with some numbers but so because here in the examples it only gives you some like very simple examples right so let's say if we have 10 and 10 right so we have 10 uh 2 and 5. all right but if we have more numbers let's say we if we have more numbers above 10 right so here we could build like another numbers here right so it's going to be a maybe 20 somewhere here right and on the other side we have two somewhere here basically we can build the numbers build the trees uh in this way and another observation is that you know since we need to uh obser make us our of uh the non-leaf nodes right should be the non-leaf nodes right should be the non-leaf nodes right should be the equal to the product of the values so which means that you know when we build the tree right so on the basically the if we think this tree in the bottom up way right so basically the number is increasing which means that you know the parent node will always be greater than the thenx child node that's because that's only that's the only con only then we can satisfy this condition here right and another observation is that you know whenever we choose like a if we have a number 10 here right basically any factors right can be uh can be its child right oh let's see let's say 20 right let's say 20 is the numbers basically we could have like what we could have like 2 times 10 equals 20 but we also have like what 4 times 5 right equals 20. all right so which means that you know any of those numbers as long as it says in the array here you know they can be uh they can be the child right of 20 right and since any we can use those number any number of times so which means that you know uh so it's better for us to sort this array first right and this is so now we have like a some like a dynamic programming concept here basically you know let's say uh if we sort the array from smallest to the biggest right and then whenever we have a we have an i here we have a dp dpi here right so which means this dpi means that you know the total number of trees right we can build uh by using i as a root note so in this case 20 right so which means that you know we're gonna loop through sorry this is like the ice number right so base which means that we're gonna loop through from dpj right times dpk here right so this is going to be a plus equal here okay so which means that let's say if we have 20 here you know we uh we can loop through the previously uh numbers because only because that's the only possible way we can uh find the child node for this current one right so first we have the d we have the j here right and then we need to use the j to find the other numbers 10. let's say we are at two here right and then we need to know okay do we have a 10 in this array i mean if we do then okay obviously you know the total uh combinations or the total different ways to do the to form a binary tree with these two numbers is a dpi times dpk right because let's say for this uh for this js number if we have like four different ways to uh to form a sub a subtree right by using this js number as the root and then if we have like three ways of forming the subtree business case number as a root then the total combination for the current like what the ice number will be 4 times 3 it's going to be 12. right so now i think the uh the dp transition functions is kind of clear basically no with each dpi here you know we loop through uh we look through the numbers from zero to j right where the j is smaller than i okay and then with each j uh j index here you know and we know the number of the j index and then we can uh calculate the other numbers of the uh the other number of the three of the uh of the child here right so and if the other number doesn't exist right so if the rnm doesn't exist which means that you know the child is the same as 20 right sorry so okay what i mean that so if the other number that doesn't exist of course you know it's the uh it we won't need to accumulate that number and if there's a special case let's say if there's a 20 another 20 after 20 let's say we have uh 220 here right so 20 can also be a 20 like this right so this is also a valid tree okay but this one actually it's a this is a special case and i we can simply ignore this one because this one will not increase any of the ways we can build the tree you know because this one is the same because we couldn't we cannot have another like note on the other side because each node each number is strictly greater than one right so which so they're the only possible way we can have is the one here but there's no node uh there's no node one here that's why for this one we can simply ignore it because it's a special case that uh we won't consider in this case cool so i think that's pretty much it is right basically you know since we are we store the array first and we process from the smallest number to the biggest number right and whenever we're at i here so basically both the number of j and the number of k will be the dp i and j and the k will be smaller will be has i mean had already been processed before so that's how this basically the dp works right and yeah i think let's let me try to start coding so i mean like i said first we want to sort and we have an length of array right and then we need to define a dp here so i started this one with one because you know the reason being is because the number itself can also form a binary tree that's why for each of the numbers the column will be one the initial column will be one and another one is that you know we have to somehow uh let me see i think i will i'll create like a set here you know so that we can easily check if the other number is exist in this array or not that's why i'm doing this kind of set array right and then for i in range of 1 to n right we do a for j in range i right basically if the r array i right so if that's the number uh can be divide can be divided by uh it's divisible by this uh array of j right then i got this number two right so assuming we have this number two here then we have an array i do a modular array j right and then i check if this number two in this array right in this array set now i do dp i uh plus dpj right times a dp of this number two we need to find the index of that right because we use index to represent this the dp here so which means uh you know we can do this one i mean the num index right we can always so this array dot index of num2 right then we can just use this one index too yeah so this is one way of doing it and then okay let me finish that maybe we can improve that a little bit later on so and then next we just simply do the output right so first let's define smart mod here right plus seven and then we just need to return the sum right sum of dp to a modular of mod right so i think this should work okay yeah so yeah this one works right i mean but time com the time complexity for this one i think we have four two we have four loops here so it's gonna be n square i believe this one uh this index you know race this is also like a off n right but i mean we can improve this one a little bit so which means we can build like a num index uh a dictionary for at the beginning right so where the key is the number and the index will be i right for i dot number in enumerate array right and here we can simply use the number to find the index yeah i think that's some yeah this is the way we should do it right yeah this one should also work cool so now the time complexity for this one obviously it's o often of n squared right and the space is o of n right yeah cool i think that's the way right that's the logic for to solve this problem it's like you know so the idea behind this one is like the things we can so first one is we have to sort this array because that's the only way we can use uh apply the dp idea to this problem so which means that no every time we have a number here the dp ice number if we can find like about as a child right the both child both the left channel and right child exist in the uh in this array here you know basically we'll do a dp i times dp the other one right and this five two and two five has already been handled by this one because when we loop through the j here you know if we'll basically the j will be both two and five right so which means we'll we're accounting for all the scenarios here and right and the key idea is that you know we have to be able to realize that you know so every time after uh calculating uh a value for the current ice number like let's say for example 20 those pre those uh stored number can be used you know for the further uh calculation that's why basically that's how this dp idea comes from right yeah as long as you can figure out this one is a dp problem and the rest will be just do a sword and then do some like a regular like dp uh traverse right basically for e for each of the number here we try all the previously possible child candidates right if we can find a match right if we kind of find a matched pair of the child we do this applies uh multi multiply right and we accumulate it to the current dpi here in the end we do this uh sum dp right because things you know basically we're accumulating all the possible numbers right basically this one's some dp means that you know we accumulate all the possible binary trees you know uh for any number right for the for all the possible numbers as the root and we do divide it by mod cool i think that's everything i want to talk about for this problem yeah and thank you for watching this video guys and stay tuned see you guys soon bye
Binary Trees With Factors
split-array-with-same-average
Given an array of unique integers, `arr`, where each integer `arr[i]` is strictly greater than `1`. We make a binary tree using these integers, and each number may be used for any number of times. Each non-leaf node's value should be equal to the product of the values of its children. Return _the number of binary trees we can make_. The answer may be too large so return the answer **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[2,4\] **Output:** 3 **Explanation:** We can make these trees: `[2], [4], [4, 2, 2]` **Example 2:** **Input:** arr = \[2,4,5,10\] **Output:** 7 **Explanation:** We can make these trees: `[2], [4], [5], [10], [4, 2, 2], [10, 2, 5], [10, 5, 2]`. **Constraints:** * `1 <= arr.length <= 1000` * `2 <= arr[i] <= 109` * All the values of `arr` are **unique**.
null
Array,Math,Dynamic Programming,Bit Manipulation,Bitmask
Hard
2162
191
hey everybody let's Sol today's lead Cod Challenge which is number of one bits so in this problem we are given an integer number and what we have to return is the number of set bit in its binary representation so let's say for n = to representation so let's say for n = to representation so let's say for n = to 11 what is it bation 1 right so in this we have three ones so three is going to be our answer okay so how do we calculate that the straightforward approach could be checking for each bit from right to left whether it is one or not okay so how do we calculate that for that we can for the rightmost position if we take it its add with the mask if the mask is one and if I take end of N and M it is going to give us the value one if the right most beate is set otherwise it would be zero so let's say for this example if I taking and with one so it is going to give me zero now let's uh now in my in our main example let's shift The Mask by one mask left shift one now this is our n this is our mask 0 1 0 now it is going to give us 1 which is not equal to Z it means there is one at that position it is going to give us 1 and zero okay which is not zero so what we will do is we'll check for every position and we'll see whether the number is non Zer or zero so in that case like let's also write a pseudo code for that for all the positions so for i = 0 to I all the positions so for i = 0 to I all the positions so for i = 0 to I less than 32 for each 32 positions we will see whether and mask not equal to0 in that case we will increment our answer and after each position we will left shift for mask by one okay so in this case what would be our time complexity 32 because we are checking for each bit which is equivalent to constant time but we can further enhance this problem solution by uh no checking every single bit in this in its binary X the second approach to solve this problem would be no checking for each bits instead checking the rightmost set bit let's say for the same example 1 the rightmost set bit is one and then this one so in this way we can reduce some operations like uh and how do we do that if we take and of n and n minus one what it is going to do is it is going to flip all the deserts from in all the desert right to the right most significant bit so in this case we don't have any bit as a z in the right rightmost the right significant bit so in this case uh it would be like 1 0 is the n minus 1 this is n and if we take and it is going to be0 1 Z it means we have removed right most significant bit from this n so what we'll do we'll keep on repeating this operation we'll keep on removing the right most significant bit next right most significant bit which is zero so let's say this is n if we take n minus one 1 0 1 so from right most significant bit to the right rightmost side all the bits are flipped they will get give us zero result okay in the further iteration we will remove this sign WR more significant bit 0 let's say if it is n what would be the N minus one 0 1 okay if we take n it will give us zero so it took three operations instead of 32 in the previous example so at each step we will take and of n with n minus 1 so this operation is going to remove rightmost set withd okay and we will keep on doing this while n is greater than zero okay so the time complexity would be constant one because 32 can be the maximum answer for us but we have reduced our operation to the set bit only instead of checking for every bit let's score this the code to this problem is going to be pretty simple like we will just remove the rightmost significant bit until this n is not equal to zero so let's take a variable to store our answer and in the last we just going to return that variable so while n is greater than Z maybe while n is not equal to zero okay it means that we have at least one set bit present in the N if there is no set bit it means it's all zero so we don't need to check further n is equal to n and n minus 1 so this expression is going to remove right most significant bit we have removed one bit so we are going to store one to our answer so in the last the answer will store the number of one in binary representation of and check over some the test cases okay submitted successfully okay thank you guys
Number of 1 Bits
number-of-1-bits
Write a function that takes the binary representation of an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 3**, the input represents the signed integer. `-3`. **Example 1:** **Input:** n = 00000000000000000000000000001011 **Output:** 3 **Explanation:** The input binary string **00000000000000000000000000001011** has a total of three '1' bits. **Example 2:** **Input:** n = 00000000000000000000000010000000 **Output:** 1 **Explanation:** The input binary string **00000000000000000000000010000000** has a total of one '1' bit. **Example 3:** **Input:** n = 11111111111111111111111111111101 **Output:** 31 **Explanation:** The input binary string **11111111111111111111111111111101** has a total of thirty one '1' bits. **Constraints:** * The input must be a **binary string** of length `32`. **Follow up:** If this function is called many times, how would you optimize it?
null
Bit Manipulation
Easy
190,231,338,401,461,693,767
1,041
hi everyone today we are going to discuss about the problem of robot bounded in circle this is little bit tricky problem but it's very easy try i'll try my best to explain this in a very easy manner so let's start it so this is the problem statement what it was written that on a infinite plane a robot initially stand at zero uh coordinate right let's suppose visualize there's an uh infinite plane and the robot stands at zero and zero which faces towards north suppose i am trying to draw a coordinate here so this is not this is sour this is east and this is west right so my point is robot is now stands here cool robot it's now stands here as per the question now uh the second point is um if the robot can uh the robot can receive one of three instruction if it is g on that case robot will move uh straight by one unit if this is l so on that case it will turn uh 90 degrees to the left okay matlab uh it will not move in this case okay it will just change its direction to the left okay visualize yourself in the place of robot it will be very easy for you on that case and suppose for r it will uh turn to a 90 degree right okay uh concentrate on this line the robot performs the instruction given in order and repeats them forever means suppose any instruction is given like g l r on that case it will be repeated on an infinite pattern okay so on that we have to return true if and only if there exists a circle in the plane such that the robot never leaves the circle it means suppose in a plane we have a circle so the robot will never leave this circle but look the robot can move like this in this circle in a loop but it can't leave this circle on a in finite plane okay so this is our problem so now let's discuss about the test cases instruction that is given to us is gg l lg okay but uh the suppose the robot is at zero coordinate g means for the first time we are going to face the instruction uh phase this character g so the robot will move to the first one unit then again it's d so robot again will move to this another one unit now what is written that uh it's l means suppose this is the head of the robot so now it turns 90 degree to the uh left that means robot is now pointing towards way uh west okay and again turns uh left right so again i'm going to turn left to 90 degree now it points towards out okay again gg so for that first robot again we'll move to the uh first one unit again next one unit okay uh and it is now the difference between is that in this point the robot face towards not direction now it face towards south direction right again it's gonna repeat g l and g so suppose i'm gonna repeat this so again g one unit again it turns to uh ninety degree left again it turns to ninety degree left so means this is the my pointer right now again if g and g so what you guys can see from here is robot is in a circle right is it is in a circle so sorry for my bad drawing it is in a circle of 2 unit y see it first moves towards a 1 plus 1 2 so it is in a circle of 2 unit where it moves in an infinite manner this is a loop right it is it moves in an infinite manner in a particular loop and it never leaves this circle so on in this case we are going to return true okay let's take another example when i am going to return false now let's understand the another example of gg so for the case of gz uh suppose robot is at zero coordinate again we'll move to straight again we'll move to one unit uh in a north direction right so in this case we are going to return false why it moves infinitely in one direction and we are never moving back to the origin or there's no possibilities to move back to that point as well right so what we can conclude that we have by observing the test cases the very first thing that we have concluded that to get the uh our value as boolean value as true we must the robot must return at origin means if the robot after travelling a certain part it returns at origin it means it will never ever leave that circular path right so uh the first condition that we need to satisfy is x equal to zero and y equal to zero after traveling a certain amount of car and suppose our robot is pointing towards north only so on that case we will going to return false means suppose my direction is a variable and my direction at the end of the entire code is equal to north only on that case we are going to return false right so for true condition we have to just check if this is not equal to n on that case we will return true okay so now we are going to implement this two thing in our code once then we will code it in java so first uh let's suppose we already take one variable as n that is direction we consider our direction uh is n and the coordinate as x equal to zero y equal to zero okay suppose uh this is our instruction let's suppose that instruction is what g l and r okay let's suppose this is a given instruction g l and r and we have to return some boolean value right so suppose our robot is pointing out in this point so on that case and we face from this string a character g so if my given character is equal to g on that case we will return we will increase the x value by 1 isn't it we will increase the x value by 1 because we have already uh have the direction as n but look when we have g we are going to increase the y value depend upon their direction suppose we suppose my direction is overwritten by e or w or s we will increase the y a x value based upon that sorry this is y plus okay this is y plus very sorry now uh now let's understand if suppose we fetch the value l okay suppose a given string is equal to l on that case suppose my raw robot is now not direction okay the head is now towards north and suppose i have uh the order l so on that case i will return to west so suppose direction is equal to n on that case it will return us w matlab we are facing towards north and l and the order given to us is l on that case with our direction will be over our direction will be equal to west on that case and that is similar to s and e you can draw the coordinate and you will understand this better and for right the same thing will happen we will change the direction uh manually now what we are going to return at the end we are going to return uh return x is equal to zero and y equal to zero this is our condition again if the robot returns back to the origin on that case it will it must return true or this is all okay or if direction is not equal to n on that k it will return the boolean value of this expression if this or this is true we will return true otherwise we will return false okay so now let's see the code okay so this is our code as i mentioned you earlier that firstly we will check the uh we will assign one character value means the direction to not then we will uh assign x and y value next what i have done i have um find out the length of this particular instruction string and i iterate through that complete instruction and i am facing one uh data means the character one by using care at i so if the direction equal to n means towards uh n so upper jar so in that case i am increasing the y value if this is towards south i am decreasing the y value looking at right now this is east so i'm increasing the x value that is positive axis and otherwise i am decreasing the x value because of waste okay now suppose the direction is equal to l on that case i am uh if this is uh direction equal to north on that case i am returning direction as west i'm telling you the above i am explaining you already with the help of the robot hit and the same thing happened in south east north and south right uh you can draw you will understand this better and same for right if this is not imagine if you are facing towards north and the right instruction is given to you obviously you will turn towards east right so i have done the same thing one by one and next i have written the case that i have told you so this is all about the code i hope it uh you understand all of the or you understand the code and problem totally so thank you
Robot Bounded In Circle
available-captures-for-rook
On an infinite plane, a robot initially stands at `(0, 0)` and faces north. Note that: * The **north direction** is the positive direction of the y-axis. * The **south direction** is the negative direction of the y-axis. * The **east direction** is the positive direction of the x-axis. * The **west direction** is the negative direction of the x-axis. The robot can receive one of three instructions: * `"G "`: go straight 1 unit. * `"L "`: turn 90 degrees to the left (i.e., anti-clockwise direction). * `"R "`: turn 90 degrees to the right (i.e., clockwise direction). The robot performs the `instructions` given in order, and repeats them forever. Return `true` if and only if there exists a circle in the plane such that the robot never leaves the circle. **Example 1:** **Input:** instructions = "GGLLGG " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (0, 2). Direction: South. "G ": move one step. Position: (0, 1). Direction: South. "G ": move one step. Position: (0, 0). Direction: South. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (0, 2) --> (0, 1) --> (0, 0). Based on that, we return true. **Example 2:** **Input:** instructions = "GG " **Output:** false **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "G ": move one step. Position: (0, 2). Direction: North. Repeating the instructions, keeps advancing in the north direction and does not go into cycles. Based on that, we return false. **Example 3:** **Input:** instructions = "GL " **Output:** true **Explanation:** The robot is initially at (0, 0) facing the north direction. "G ": move one step. Position: (0, 1). Direction: North. "L ": turn 90 degrees anti-clockwise. Position: (0, 1). Direction: West. "G ": move one step. Position: (-1, 1). Direction: West. "L ": turn 90 degrees anti-clockwise. Position: (-1, 1). Direction: South. "G ": move one step. Position: (-1, 0). Direction: South. "L ": turn 90 degrees anti-clockwise. Position: (-1, 0). Direction: East. "G ": move one step. Position: (0, 0). Direction: East. "L ": turn 90 degrees anti-clockwise. Position: (0, 0). Direction: North. Repeating the instructions, the robot goes into the cycle: (0, 0) --> (0, 1) --> (-1, 1) --> (-1, 0) --> (0, 0). Based on that, we return true. **Constraints:** * `1 <= instructions.length <= 100` * `instructions[i]` is `'G'`, `'L'` or, `'R'`.
null
Array,Matrix,Simulation
Easy
null
1
let's all leak code one to some the most popular leak code question so we're given an input array and some target in this case 9 and we want to find the two values in this input array that sum to 9 so in this case it's 2 &amp; 7 now we want so in this case it's 2 &amp; 7 now we want so in this case it's 2 &amp; 7 now we want to return the indices of these two values so the index of zero of the index of two is zero the index of 7 is 1 so we return 0 &amp; 1 return 0 &amp; 1 return 0 &amp; 1 we're guaranteed that there's exactly one solution so we don't have to worry about not finding a solution and we don't have to worry about multiple solutions now the most intuitive way to solve this problem is basically just check every combination of two values and see if they can sum up to our target so we start at 2 we check every combination we can make that includes 2 so we scan through the remainder of the array 1 5 3 and check if any of those numbers added to 2 some store target for in this case none of them do so next we can repeat the process let's check every combination including one that sums up the target for so we scan through every element that comes after at 5 &amp; 3 and we find that one after at 5 &amp; 3 and we find that one after at 5 &amp; 3 and we find that one added with 3 sums up to our target 4 notice that we didn't have to check the values that came before 1 because we already checked the combination 2 &amp; 1 already checked the combination 2 &amp; 1 already checked the combination 2 &amp; 1 when we were up over here remember when we checked every combination with 2 so we didn't have to repeat that work down here we only had to check the numbers that came after 1 so the runtime of this algorithm isn't super efficient this is basically brute force we're going through the entire array of length and we're gonna do that worst case n times for each number this means that over all worst case time complexity will be O of N squared so can we do better now the thing to notice is that for each number for example 1 the value we're looking for is the difference between the target and this value 1 so we're looking for 4 minus 1 which is equal to 3 so that means this is the only value we can add to one that'll equal the target so we don't have to check every number we just want to know if resist s-- now the easiest way we can do resist s-- now the easiest way we can do resist s-- now the easiest way we can do this the most efficient is by making a hash map of every value in our input array so we can instantly check if the value 3 exists now let's try the same problem except let's use a hash map this time now in our hash map we're going to be mapping each value to the index of each value so the index of 2 is 0 the index of 1 is 1 the index of 5 is 2 the index of 3 is 3 so let's so in our hash map we're going to be mapping the value to the index now we could add every value in this array into the hash map before we start iterating through it but there's actually an easier way to do it if we added the entire array into the hash map initially then we would get to the value 2 first right we would want to checked as the difference between target 4 minus this value 2 which is equal to 2 exists in our hash map and we would find that 2 does exist in our hash map but we're not allowed to reuse the same one right because they're both at the same index we can't use the same value twice so we would have to compare the index of our current 2 with the index of the 2 that's in our hash map there's actually an easier way to do this though and it's a little clever and let me show you how to do it that way so doing it this clever way initially we say our hash map is empty so we get to the value 2 first of all right and we want to look for the difference 4 minus 2 in our hash map is empty so we don't find 2 so then after we visited this element then we can add it to our hash map so now that I'm done visiting it I'm gonna move to the second element 1 and before I do that I'm gonna add this value 2 to our hash map and the index of this value is gonna be 0 now I'm at 1 I'm looking for 4 minus 1 which is 3 I see 3 isn't in our hash map but it actually is in our array so what's the problem well for now we're going to say we don't find our find three so we add one to our hash map the index of this one is one and now we move to the next element five we check does four minus five it's four minus five exists in our hash map that's negative one so no it does not then we add this five to our hash map and it's index which is two and we move to the last value in the array three we checked this four minus three e exists in our hash map now that's one so we see it does exist right over here it exists the value exists and it's index is one so now we found our two values that sum to the target and we want to return their indexes their indices which are going to be one and three so with this algorithm we don't have to initialize our hash map it can be initially empty and then we can just iterate through this array in one pass now the reason the algorithm can work in that way with just one pass is this so let's say we had a giant array right we know for sure that there are two elements in this array that sum to our target right we don't know where they are they're at some arbitrary location when we visit the first one of those elements our hash map is only going to be this portion of the array it's only going to have the values that came before the first value so we're gonna notice that the second value that can sum to the target is no is not going to be in our hash map yet but once we get to the second value our hash map is going to be this portion so every value that comes before this right so we're gonna be guaranteed that once we visit the second element that sums up to the target we're gonna be guaranteed that the first one is already in our hash map so we're guaranteed to find the solution now since we only have to iterate through the array once and we're adding each value to our hash map which is a constant time operation and we're checking if a value exists in our hash which is also a constant time operation the time complexity is going to be Big O of n we are using extra memory right that hash map isn't free so the memory complexity is also going to be O of n because we could potentially add every value to the hash map so now let's code the solution so remember we need a hash map right I'm going to call this previous map because it's basically every element that comes before the current home that every previous element is going to be stored in this map where it can be mapping the value to the index of that value so now let's iterate through every value in this array we need the index as well as the actual number so let's do it like this and Python before we add this to our map let's check if the difference which is equal to target minus n now let's check if this difference is already in the hash map if it is then we can return the solution which is going to be a pair of the indices so I can get the first index like this and the second index is just AI now if we don't find the solution then we have to update our hash map so for this value n I'm gonna say the index is I and then we're going to continue since we're guaranteed that a solution exists we don't have to return anything out here right but I'll just put a return for no reason now let's see if it works and it works perfectly so with this kind of neat little trick but just doing it in one pass you can reduce the amount of code you have to write and not have to worry about like edge cases and comparisons and things like that
Two Sum
two-sum
Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. You can return the answer in any order. **Example 1:** **Input:** nums = \[2,7,11,15\], target = 9 **Output:** \[0,1\] **Explanation:** Because nums\[0\] + nums\[1\] == 9, we return \[0, 1\]. **Example 2:** **Input:** nums = \[3,2,4\], target = 6 **Output:** \[1,2\] **Example 3:** **Input:** nums = \[3,3\], target = 6 **Output:** \[0,1\] **Constraints:** * `2 <= nums.length <= 104` * `-109 <= nums[i] <= 109` * `-109 <= target <= 109` * **Only one valid answer exists.** **Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
A really brute force way would be to search for all possible pairs of numbers but that would be too slow. Again, it's best to try out brute force solutions for just for completeness. It is from these brute force solutions that you can come up with optimizations. So, if we fix one of the numbers, say x, we have to scan the entire array to find the next number y which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
Array,Hash Table
Easy
15,18,167,170,560,653,1083,1798,1830,2116,2133,2320
1,765
hey there everyone i'm your host faraz we are solving the contest by weekly contest 46 and this is the problem number three so let us go through the problem statement once we are given a matrix m cross n and each cell is either zero or one zero represent land and one represents water now we have to return a matrix of size m cross n as the answer and how do we have to create this answer so the cell which is water that should be marked with zero and all the other cells should be marked with something positive and these are the rules the height of each cell must be non-negative height of each cell must be non-negative height of each cell must be non-negative so the value which we assigned to each of the cell must be non-negative of the cell must be non-negative of the cell must be non-negative the water cell is zero and any two adjacent cells must have absolute difference not more than one so we can see the adjacent cells are uh the difference of adjacent cells are not more than one also find the assignment of the height such that the maximum height is maximized so what is the adjacent cell here so for this particular cell this is adjacent this one is adjacent and this is adjacent actually they share a boundary right so that is why they are adjacent so we have to assign in such a way that the maximum height is maximized okay the first thing that we know is some cells are marked with one in the given matrix and they represent water so in the second example here this is what given to us and we know that the cells which are marked with one represents water so this represents water and this represents water so we can mark them with zero in the final answer according to the given rules now we need to assign height to the other cells how can we do that so basically we can start with this as a reference we can start from this point and we know that the adjacent cell to this one is this and this what values can you think what values you do you think can come here so we need to assign in such a way that the absolute difference that doesn't exceed one so we can either go to minus one or we can go to one these are the only two options right because the absolute difference between the zero and something that we put here should not be greater than one so obviously um we cannot assign minus 1 because we are not allowed to use negative here so we can just mark them with one okay all right so we are done putting the adjacent values of the zero so we are done processing this now let's move on to the next zero which is available to us so the next zero is over here this is so similarly this is the neighbor these are the two adjacent again we can assign them with one and one the absolute difference is maintained here and absolute difference between these two is also maintained and these two is also maintained the absolute difference between these two is a zero so it doesn't exceed one anyhow all right so after this we can go to any of these ones so let's say we go to this one now all these indices all these um adjacent cells to this are this one and this one these are already filled so we don't need to proceed with this one now let's go to this one okay so here the adjacents are this and this now this is empty so what value can uh do you think can we put here we can either put zero here the absolute difference will be maintained we can even put one here then also the absolute difference will be maintained and we can even put a 2 here why because still the absolute difference is maintained and as in the question it is given that we want to maximize the um yeah we want to maximize the maximum height so that is why we will put two here now again we will go to this particular one this is also unprocessed so we will look at the neighbors of this these are the neighbors these two are already filled this one is not filled so what value can we fill here we can either put 0 1 or 2 so we will putting 2 here so this is how we do this first of all we start with 0 we start processing with the zeros and once we are done filling all the neighbors of 0 then we will move on to the next one so either this or this we can start with any of these ones and then we can fill the neighbor of these ones so what do you think can we use here which structure do you think can we use here we can simply use a bfs right a multi-sourced bfs multi-sourced bfs multi-sourced bfs breadth first search the sources are going to be the zeros okay so the zeros are going to be the sources to start this breadth first search all right so this is what i came up during the contest so i'm just going to quote down this particular algorithm this particular approach if you know some other approach please let me know in the comments so how to do this multi-source this multi-source this multi-source bfs so for that i will create a queue will be of type pair of end comma int so as to store the what you call the injs the location of each particular cell right so this is the queue now i will go to each of the indices i is equal to 0 i smaller than n i plus and i'm traversing the given matrix this is water j is equal to 0 and j is smaller than m and j plus n is the length w dot size and m is w zero dot size okay let me also create an answer here answer should be a vector again a vector of int this is the answer this should be of size m cross n cross m so n and a vector of int so it should be of size n cross m and let me initialize this with a maximum value into max okay so this value into max or maybe minus one i can initialize it with minus one so this value will represent that i haven't filled that cell yet okay now let us go to each of the indices if w of i comma j this is equal to 1 if this is equal to 1 it represents that it contains water so at that position in the answer i should fill 0 and this is one of the source so this is one of the source of the bfs to start the bfs this is one of the source so i can push it into the queue so q dot push i comma j done all right now i can start the bfs from here while not q dot empty so i will be looking at the topmost element or to a is equal to q dot front and q dot pop okay so this is the top most element uh this is the i will find out the one of the source now int v is the value so the answer of i comma j or a dot first and 8 or seconds so i will make x is equal to a dot first and y is a dot second so these are my i's and j's okay so this is x and phi this will give me uh what is the value at this particular cell okay now i will explore the neighbors of this cell x comma y i will i am going to explore the neighbors and how do we go to all the four neighbors so for that we use this trick we create a vector of int v um are we using v here so we can use a temp vector of temp and i can initialize this with minus 1 0 then minus 1 then 0 and then 1 minus 1 0 minus 1 i think here we should use one here so minus 1 0 and 0 -1 so for in i is equal to 0 i smaller than temp dot size i plus just hold on i will just explain why i'm taking this temp you can explore the four neighbors by simply taking let's say if this is your x and y you can simply explore the four neighbors by taking x plus one y x y plus one x y minus one and x minus one and y so these are the four neighbors right so um i don't want to write them separately that's why i'm using this trick over here so if x plus temp of i if uh this is going to be one of the neighbor okay and if this is greater than equal to zero and x plus temp of i is smaller than n and y plus temp of i plus 1 if this is smaller than m and y plus temp of i plus one is greater than equal to zero so i'm well within the boundaries okay if answer of this cell this neighbor x plus temp of i and uh y plus temp of i plus 1 if this is not equal to minus 1 it means that it is not processed yet then only i will proceed further so answer of x plus temp of i and y plus temp of i plus 1 this will be equal to v plus 1 also i am going to push this particular cell into the queue so q dot push x plus temp of i comma y plus temp of j this is just the normal bfs that we are doing here and in the bfs we usually require to maintain a set of visited set so instead of visiting set i am just using the answer because i will see if the answer is not computed for this particular cell then only i will proceed with it otherwise i will continue okay and finally i can return the answer from here let me just try to run this if there are any compilation errors hmm so temp of g where did the temp of j here yes i plug i plus 1 here so it is not giving me correct answer for i don't know what reason let me just try to figure this out once i think i am inserting everything into this q then x is this y is this v is this um this is the temp i square squares more than ten plus i plus temp of and this is smaller than n and y plus temp of i plus 1 is smaller than m and y plus is greater than okay so if this is not okay if this is equal to minus 1 then only we are going to proceed right so it is giving me some error because i am accessing the index which i shouldn't access so where can i okay let me just try to debug this a little bit so i'm just printing answer here okay the answer is being printed so we are correct till this particular line now i will try to print over here okay so it is also printing correct okay so basically the error is at this place so temp dot size minus 1 because i am accessing the index 10 plus 1 as well so let me just try to run this now it is giving me correct answer let me just try to submit this and it got accepted so this is nothing but a simple bfs but with multiple sources okay so we should start the bfs from the cells which are marked with zeros and then proceed further okay so this is it for the solution if you like the video make sure to hit the like button and make sure to leave your comments and do subscribe to the channel if you want more such content in future as well thank you
Map of Highest Peak
merge-in-between-linked-lists
You are given an integer matrix `isWater` of size `m x n` that represents a map of **land** and **water** cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a **land** cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a **water** cell. You must assign each cell a height in a way that follows these rules: * The height of each cell must be non-negative. * If the cell is a **water** cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of **at most** `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is **maximized**. Return _an integer matrix_ `height` _of size_ `m x n` _where_ `height[i][j]` _is cell_ `(i, j)`_'s height. If there are multiple solutions, return **any** of them_. **Example 1:** **Input:** isWater = \[\[0,1\],\[0,0\]\] **Output:** \[\[1,0\],\[2,1\]\] **Explanation:** The image shows the assigned heights of each cell. The blue cell is the water cell, and the green cells are the land cells. **Example 2:** **Input:** isWater = \[\[0,0,1\],\[1,0,0\],\[0,0,0\]\] **Output:** \[\[1,1,0\],\[0,1,1\],\[1,2,2\]\] **Explanation:** A height of 2 is the maximum possible height of any assignment. Any height assignment that has a maximum height of 2 while still meeting the rules will also be accepted. **Constraints:** * `m == isWater.length` * `n == isWater[i].length` * `1 <= m, n <= 1000` * `isWater[i][j]` is `0` or `1`. * There is at least **one** water cell.
Check which edges need to be changed. Let the next node of the (a-1)th node of list1 be the 0-th node in list 2. Let the next node of the last node of list2 be the (b+1)-th node in list 1.
Linked List
Medium
null
1,008
Scientist A I Video I Hop Alia Doing Good Welcome to the Land Co DEA and Today Khavan Equations Construct Binary Search Tree From Preorder Traversal Edit This October Challenge October Liquid Challenge Questions and Cities Given in This You Have a Preorder Traversal Are Like This One and you have constructed last from this traversal show what is this what is inverter is left root left node root this is clear values ​​ value is loot and third values ​​ value is loot and third values ​​ value is loot and third values ​​like this poster left fruit and nut sid values ​​like this poster left fruit and nut sid values ​​like this poster left fruit and nut sid not left and right a So it is that this software in node din also can simply say in 8517 This is Stomach and Ulcer Handsfree Mode Access Definition of Values ​​Notes87 The 80 Roots Vacancy Root Values ​​Notes87 The 80 Roots Vacancy Root Values ​​Notes87 The 80 Roots Vacancy Root That Now You Have to Find the Left Value in Array Value Under Person 125 But What Is the what is the value of is physiological value is greater than 800 hind meanwhile they seth is the value which gives vacancy this is your node this is your left nd right equipped it is and right din from here to here deficit and if component withdrawal Developed by Dr. Subscribe to Right Side Must Subscribe to Avoid Yo-Yo-Yo-Yo Starting from a Point in Your Life When Will Take Its Root Will Take You Will See 825 Validated This Note Lipids Day Will Again Call Preparation for This Point ND Share Dis my nift objective left were sole supply that one so js units page 102 that what is start e0 is what is in india s length of use table sir a minus b cosmetic in this also 200 what time singh samsung note off soft end Creating And Using New Node JS A Start Because Started 0098 Vacancy Addison Notes For 1818 Meeting And No If You Find The Value Which Giveth 200 Gram Singh Index Is Equal To That Star Plus One So If You Traveled From Fear Because It Dropped From Here To here I will find who is the value which should be on the right side To find your support and the first rally of this party Stand swipe to find a way which will give marriage to boil Saw this will go that in you slept water Can say against a cliff hands free mode on traversal of start S8 is the great day dutiable clean intake is the point at which visit from here to hair soft this 2015 S8 youth 98 all of this grand 531 to back each other wise this is to Give a good so Dixit was wrong index citizen five eight is lesson 5 98100 all of you reverse entry 1000 will break tomorrow morning is powder next 50.84 right side against 50.84 right side against 50.84 right side against 200 what is nod a boat lift is free a decoration for star plus one Key Wife Because They Lift Your Left Parties 517 And How Can Find Vinod This Is Not Aware Fus Validating From Meets Delegation From Here Swadeshi Start Plus One End Decisions The Index - Decisions The Index - Decisions The Index - Man Indexes Dushman Independence 1000 Starting From Five End Indicators 7 220 Patti Index - Bank End Indicators 7 220 Patti Index - Bank End Indicators 7 220 Patti Index - Bank And what is rights What is right is pre-EMI index a prominent will go is pre-EMI index a prominent will go is pre-EMI index a prominent will go to Italian a view to return road a that and if you're in this day start that I just returned here a nun a pan is start is equal to Note of liter of these vegetables is just a minute so I return to India which is hair as well that their shoe vacancy vitamin run so let's take time when labeled was software and point collect daily behind gear shifting from date with were Starting Point for the Right Value of a Guru Can See I'm Going to Tell Me This Lesson 5 Years Ingredients You 98100 Is an Affair Interview for Right Side Surdas Index This is the Four Things from Years 525 Decide This is My Right Down What is That Point Star Plus One Is Vansh 542 And Expansion In Taxes For Defense Ministry Start Phase Me Lift And Claim A Right From Falling Asleep Again For This Is One And For This In This Case Ad Submit And Servi Worker Note That His Vacancy Vitamins Submit Perfectly in single and in a single strike I hope you have one teargas this is not very tough this project take care of points vacancy this point to point 20% faster and point to point 20% faster and point to point 20% faster and events gas I will meet Ansh video dance video til daan bye-bye take care video til daan bye-bye take care video til daan bye-bye take care do it
Construct Binary Search Tree from Preorder Traversal
binary-tree-cameras
Given an array of integers preorder, which represents the **preorder traversal** of a BST (i.e., **binary search tree**), construct the tree and return _its root_. It is **guaranteed** that there is always possible to find a binary search tree with the given requirements for the given test cases. A **binary search tree** is a binary tree where for every node, any descendant of `Node.left` has a value **strictly less than** `Node.val`, and any descendant of `Node.right` has a value **strictly greater than** `Node.val`. A **preorder traversal** of a binary tree displays the value of the node first, then traverses `Node.left`, then traverses `Node.right`. **Example 1:** **Input:** preorder = \[8,5,1,7,10,12\] **Output:** \[8,5,10,1,7,null,12\] **Example 2:** **Input:** preorder = \[1,3\] **Output:** \[1,null,3\] **Constraints:** * `1 <= preorder.length <= 100` * `1 <= preorder[i] <= 1000` * All the values of `preorder` are **unique**.
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Hard
1021
811
hi this is ike so today we're just on lead code i think i'll just pick a random easy problem and try to solve it so let's there's a whole bunch of problems here i'm just going to click pick one uh we might get a problem that's not easy but we can always just keep trying again all right so we finally got an easy problem uh let's switch the language to python three okay says a website domain like disqus. disqus. disqus. consists of various subdomains at the top level we have com at the next level we have and at the lowest level and at the lowest level and at the lowest level discuss. discuss. discuss. when we visit a domain like discuss. discuss. discuss. we will also visit the parent domains and and and com implicitly now call a count paired domain to be a count representing the number of visits this domain received followed by a space followed by the address an example of a count pair domain by might be 9001 disqus.li we are given a list cp domains of count paired domains we would like a list of count paired domains in the same format as the input and in any order that explicitly counts the number of visits to each subdomain uh so i don't completely understand it just reading that so i'm going to look at some examples so the input is this 901 discussed this 901 discussed this 901 discussed and the output is so we just have what's the 9001 hold up now call a count pair domain so it's account representing the number of visits this domain received followed by a space followed by the address oh okay so they paired the count with the domain okay and all right so they give us the count and the domain and so we have to give a new list with the count then the full domain and then i guess we slowly chop uh things off so it's like nine zero one then disqus. one then disqus. one then disqus. nine zero one then nine zero one then nine zero one then then just 9001 and com so yeah we only have one website domain discussed at the the the .com will also be .com will also be .com will also be visited so they will all be visited nine zero one times oh okay um and this one oh but this one we have counts and different addresses so here we have 900 google. google. google. okay so this one wants not oh okay 901 901 901 50 so why is that nine oh okay i see so gets 900 from google. gets 900 from google. gets 900 from google. and then it also gets one from intel. intel. intel. um because technically is being um because technically is being um because technically is being visited 900 plus one times from like the google.mail then the intel google.mail then the intel google.mail then the intel mail okay so yeah we will visit google. so yeah we will visit google. so yeah we will visit google. nine hundred times fifty times intel dot fifty times intel dot fifty times intel dot once and five times once and five times once and five times for the subdomains we will visit yeah 900 plus one equals 901 times uh com we'll get 900 plus 50 plus one times okay so let's think of how we can solve this it almost in my mind i'm already thinking of like uh so in my mind i'm already thinking of a hash table because we need to store the first i guess we need to like break this up into its components and then we need to count each uh we need to break it up into its components to find the subdomains like after each dot and then we just need to have counters for each uh sub domain okay so yeah i think the first thing we should do is like break up these strings so we know we're going to get a count and then an address so let's see let's have a function let me just call it like split uh split oh not split uh like split address and that'll just take in the domains uh put a pass there for now okay uh and so then the first thing we'll do is we'll just say let's just say return the list and we'll call this here so we'll say what do we how do we want to represent this though so we can say for let's see for d and cp domains we'll say c we'll say count domain is equal to d dot split and we'll do it on the space and let's just print these things just to make sure it like actually works so we'll just say self dot split address and just type in cp domains take this out and we should see a few print statements okay we got the wrong answer which was expected but we got some nice standard output uh so i'm just gonna say i'm gonna split these up though so they're not on the same line let's run this okay cool so we get the count and we get the domain but for the count actually we want to make that a number because i'm pretty sure that's still a string right there so i'll just say like count equals int count okay and run code i guess we won't see any visible there should be no visible changes in the output uh but still wanted to do that so let's then go up here and so we've successfully like split the uh the count and the domain but now we actually want to process this so basically the next thing i'm thinking that we need to do is probably uh process these sub domains because we need to have a we need to keep account for the full domain here then like say if we're looking at google. we need to process google. we need to process google. we need to process we need to keep account for the full one then we need to keep account for uh mail dot com and then like dot com alone all right so then let us go to here let's say let's just say like process domain and it's just going to take a domain put a pass on there let me space this out and i'll delete these print statements since we don't need them anymore hopefully uh let's go here and so what do we want to do so first we know actually let's take in that count too uh so we have account and a domain so we'll say self dot we've got to put in self so we'll say self dot process domain and we'll just put in we'll put in the count and the domain okay and so what do we want to do here so we need to keep track of the count and i think it'll probably be best to use a dictionary for that so i'm just gonna call this i guess i can't call it map uh i'll just call it the yeah i guess yeah whatever i'll just call it d equals dictionary and then now we need to process the sub domains and how do we get those so we know for sure that there's dots between all of these domains so then let's try we'll say that split domain equals domain dot split on a period and let's actually let's just print out split domain just to see how it looks like uh so run it we should see like disqus then leak code yeah we should see discuss leak code com there so that's good and so the map needs to basically take in all of these uh with the same count so then here we can say i'm trying to think do we even need to no yeah we probably do want to keep track of the dots so how should we what's a good way of putting these in i guess i'll just kind of go the brute force way i'm thinking that if we do uh hmm because we want the entire thing for one and then we basically want to go we want one less each time so i'm going to say for i in range let's do the length of split domain so yeah it seems kind of expensive but i think this is uh one way of doing it so let's try to do uh let's see yeah so we'll say the domain or no we don't want to touch well we've already used domain up here but let's just say like uh we don't yeah we don't need domain again at this point so i'll just overwrite it uh but we'll say domain dot so split yeah split domain is a list at this point it's a list that looks like this so let's do let's try to join these so we get the full thing and then and then com so and then and then com so and then and then com so i'm going to say uh split domain dot join and here we'll just do uh oh whoops we'll do dot join and split domain and let's just print it out and see what happens we should be able to see the different uh addresses and we'll take out this print statement here let's run code oh whoops i didn't even change anything in the uh for loop so we want we basically want a different range each time so let's think about this how can we splice this so we get what we want so the first time around we want everything uh and all that is doing should be let's see yeah i mean i think we can just pass in i right here it'll just put like it'll just get i to the end uh yes just get i to the end so say like discuss would be at position zero leak code would be at one com will be at two so when i is zero we wanna get everything when i is one we just wanna get is one we just wanna get is one we just wanna get and then when i is two we just get the com so yeah let's just let's run it and see cool yeah so we get discussed cool yeah so we get discussed cool yeah so we get discussed and and and com all right so then now we actually need to put it in the dictionary along with its count so we'll say if let's take out the print statement and store this in a uh let's say like let's say i'm struggling with the names today so say like domain string so if domain string is not in d yeah if domain string is not in d then we will say if domain string is not in d then we will let's see it's not in d then we'll say d at domain string is just going to be equal to the count and then if it isn't there though then we're adding to something so we're going to say the domain string plus equals the count okay and then after that we should just be able to return the dictionary that we just created so i'm just going to say return d all right okay so what's next uh we have the dictionary with the counts there so let us then go back down to here so process domain should return a dictionary so say like uh let's see let's say like domain dictionary equals process domain account so then we actually have uh yeah so we actually are just creating a dictionary for um so this is actually this is creating a dictionary for each uh domain like each count and domain so let's try to do maybe we shouldn't create the dictionary here actually we should probably be using one dictionary and passing it into the function by reference uh so let's say like domain dictionary and we'll change these names and so we actually don't need to return anything okay so pass in the dictionary so we'll say domain dictionary is equal to empty dictionary and so process domain with the domain dictionary because now uh so if we have something like this we want to get from every we want to get from every we want to get from every single domain like and we want to aggregate the counts so we should uh we're going to need like a dictionary that is added to by every single domain and count all right so then let's see we have domain dictionary it's equal to dick then we say for d in cp domains we split it get the count and domain process domain with the count the domain and the dictionary and so let's actually let's print out so after we do this let's just print out the domain dictionary and see how it looks at this point we should just see yeah we should just see like nine zero one with leach with leak code dot com discuss leak code dot com and nine zero one com uh so let's see how it goes uh so that should be changed to that and let's run it again okay wrong answer but oh that's kind of uh that's kind of a large count it's getting two times that so why is it getting was it getting that two times uh oh whoops yeah that's probably not the way to do it so if it's not in the domain dictionary uh we want to initialize it with zero with a count of zero okay and so we have discuss. okay and so we have discuss. okay and so we have discuss. with count9001 with the same count and com with the same count and com with the same count and com with the same count so now we need to work on outputting it and i was kind of glancing at the output it says the answer output can be returned in any order so let's actually uh work on doing that so we'll say for key value and this will be for count domain in uh that should be in domain dict dot items we'll say like result equals nothing for now and then how do we need to return this we just need to say we just need to put the count and then the address so we'll say result dot append and we use an f string here because we need the account space the address so we'll say the count and the domain and we can return result and i noticed we did not have a return down here because we call subdomain visits then we return split address calls process domain and let us run it okay wrong answer uh oh whoops yeah the so the domain was the key and the count was the value all right let's run that again okay cool so let's submit and see how it goes all right well looks like it succeeded uh got 97 so the speed was pretty good the uh memory not so good so i'll probably take a look at the solution or the discussions to see other ways of doing the problem because there's most likely much cleaner ways to get this done so yeah if there's any other leak code problems hackering problems or coding projects you want to see done on this channel please let me know in the comments down below and i hope this was helpful to you so thank you
Subdomain Visit Count
number-of-subarrays-with-bounded-maximum
A website domain `"discuss.leetcode.com "` consists of various subdomains. At the top level, we have `"com "`, at the next level, we have `"leetcode.com "` and at the lowest level, `"discuss.leetcode.com "`. When we visit a domain like `"discuss.leetcode.com "`, we will also visit the parent domains `"leetcode.com "` and `"com "` implicitly. A **count-paired domain** is a domain that has one of the two formats `"rep d1.d2.d3 "` or `"rep d1.d2 "` where `rep` is the number of visits to the domain and `d1.d2.d3` is the domain itself. * For example, `"9001 discuss.leetcode.com "` is a **count-paired domain** that indicates that `discuss.leetcode.com` was visited `9001` times. Given an array of **count-paired domains** `cpdomains`, return _an array of the **count-paired domains** of each subdomain in the input_. You may return the answer in **any order**. **Example 1:** **Input:** cpdomains = \[ "9001 discuss.leetcode.com "\] **Output:** \[ "9001 leetcode.com ", "9001 discuss.leetcode.com ", "9001 com "\] **Explanation:** We only have one website domain: "discuss.leetcode.com ". As discussed above, the subdomain "leetcode.com " and "com " will also be visited. So they will all be visited 9001 times. **Example 2:** **Input:** cpdomains = \[ "900 google.mail.com ", "50 yahoo.com ", "1 intel.mail.com ", "5 wiki.org "\] **Output:** \[ "901 mail.com ", "50 yahoo.com ", "900 google.mail.com ", "5 wiki.org ", "5 org ", "1 intel.mail.com ", "951 com "\] **Explanation:** We will visit "google.mail.com " 900 times, "yahoo.com " 50 times, "intel.mail.com " once and "wiki.org " 5 times. For the subdomains, we will visit "mail.com " 900 + 1 = 901 times, "com " 900 + 50 + 1 = 951 times, and "org " 5 times. **Constraints:** * `1 <= cpdomain.length <= 100` * `1 <= cpdomain[i].length <= 100` * `cpdomain[i]` follows either the `"repi d1i.d2i.d3i "` format or the `"repi d1i.d2i "` format. * `repi` is an integer in the range `[1, 104]`. * `d1i`, `d2i`, and `d3i` consist of lowercase English letters.
null
Array,Two Pointers
Medium
null
1,704
hey YouTube welcome back today we have this problem it's called determine if string helvis are alike uh halves are alike you are given a string s of even length uh split this string into two halves of equal lengths and let a be the first and half and B be the first half two strings are alike if they have the same number of vowels we these are the vowels notice that s contains Upper Keys and lowercase letters return true if a and b are alike otherwise return false okay so let's just go to the sketch first I want to copy this one let's copy this example okay and I wanna copy files okay let's put the vault in okay um so let's just take the example with a book and it's returned true because if we put this string into two strings two identical strings we have a b o and okay and both of them are has one vowel and therefore they are alike if we look to the other example we have textbook for text we have a for book we have two vowels o and this one we have only e so this is uh one vowel and the other one is two vowels so it's it is false so from there we can just build our um something so let's just see how we can build this so let's just take this book and let's just editing okay ish and Okay so first we wanna split this one in half and compare each vowels of like split this one and a half and compel compare the valves of the left side oh and the valves of the right side so what we should do first we split them the second thing that we could we should create a variable that has all of the vowels and we will create a counter for each um for each string because this is string and this string we're going to counter for this string of the vowels and if the counters equals to each other we return true otherwise will return false so let's uh let's just see how this will look in the code so let's just first start with const it's called vowels equals um now just put all the vowels copy okay we have all the vowels right now and not just create const I will create a variable call in and this will be s.lint because I don't wanna type is the s.lint because I don't wanna type is the s.lint because I don't wanna type is the length each time okay it's the length and I'll say um I'll first I'll get the string e and string B so able equals the first half of s so it will be yes dot sub string substring from zero to math dot flow is I guess in divided by 2. and I guess B will equals sorry lit a lit B will equal and not floor I just met the seal for this one and we have a and b right now and let's just we have the first half and the other one has the second half and we will see let's a vowels down count equals zero and let B vowel count equals zero okay and we will uh make uh let's just make a loop here four equals zero um I less than uh a dot length and oi plus and this Loop will count the vowels of the character a so I will say if vowels dot includes um a of oil a vowels Plus increase it by one and for I will do the same for B and b no just make sure that we are separating and I guess right now because we counted the vowels in E and the count vowels are B we just have the last step which is like return if B the allowed equals data valves and I guess that's it yeah voila but it's 22 it's not good it's not a good solution but there is something new that I want to do with you right now when we discover our solution is not that good let's just check for the bitter Solutions and see how they can do it how did they'll do it actually so first the created um uh count one and count two okay and they have is the lens the length is divided by two okay so the making one Loop hmm that's interesting so we have two counts and we're just making one Loop I'm saying let I equals uh r a i is the length okay if I less than Lin oh this is brilliant okay so let's just describe What's Happening Here our problem that we did two Loops so uh our example was um we had two Loops for this one but they have only one Loop and when they have only one Loop if you can see it right now or just I'm checking that if it's valid or not but I can just create that includes I guess it doesn't need to have all of that if statements maybe like this is overkill but they have one Loop and maybe I'm saying that if I is less than Lin that means I'll encounter one so if otherwise I'm encounter two okay this is brilliant okay this is nice but maybe my thing that I could be against it that I guess this is overkill doesn't need to have all of that because I'm repeating myself a lot of time but although it's a brilliant choice oh it's really cool Choice it's a really cool solution I like that I really like that so um yeah so okay we say we you see two solutions right now maybe this one is better than mine so yeah that's it for today's video hope that my description was quite good if you like my description make sure to subscribe hit the notification Bell so you will never miss a video and give me a thumbed up otherwise feel free to give me a comment and I will tell you something about the comments because it's quite important yesterday um one of the uh one of the subscribers gave me a comment about that I put a wrong address of the of us of a problem and here give me a comment about that and this is actually this helped me to improve my content and actually what I did from now on and just double check each title problem to make sure that if um to make sure that I'm not doing putting the wrong title so if you find something that I'm doing wrong just feel free to comment this helped me to improve my content and this help you also to get a better uh quality or better content in terms of quality so that's it for today's video and see you soon
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
190
in this problem we have to reverse the bits of an unsigned integer and it's very clear from this title that we have to reverse the bits so let's say our integer is represented in just 3 bits i cannot draw 32 bits here so what we have to do this least significant bit should become most significant bit so this comes here the second one comes here and this one comes here so these are reversed so how we will do it we will look at a few ideas we will implement one of the ideas or two of them and we will also see some more ideas which can be used to reverse it so let's start with a trivial solution that would be good enough that would be over time and constant time not dependent on the input size so here let's say this is the input integer so here we have 32 bits i have divided in bytes each in different color so what we will do we will start with our result which will be all zeros so let's say all of these zeros so this is our result we will be modifying it and what we will do we will pick the last element or the least significant digit we will check if it's zero or one so what is the way to do that let's this number is n so if we take n and 1 so what is this one is 31 0's followed by last bit as one so if we take the end of these two if this last width is zero the and will be zero if this last bit is one the and will be one so this can be either one or zero depending on whether the last bit was set or unset you can also use modulo in modulo 2 is equal to 0 or 1 so this again can be 0 1 so we will take n and 1 if it's positive that is if it's 1 then we will add 1 to it and then left shift it and right shift this one so that way we will pick the first bit set it here and then move it left move it right so let's run through this so first bit is zero so we make it zero it's already zero we will not add anything just left shift it so left shifting it will not change it so it will remain as it is let me construct it from beginning uh so left shifting it still remains zero then we right shift it so what will happen this left uh this will be gone this will be the listen can bit now and one zero will be added here in this side then uh we see that again it's zero so we will just left shift it then this is gone then we have one so we add one here and left shifted so first we need to left shift the result this is result and then add one to it if the last bit is one so it's one so we left shifted the earlier two zeros and added one here then this is gone then again it's one so we left shift it and add one so this is the state now and this one is also gone next again it's one so we add one and left shift it then this is also gone then zero so zero and we left shift it so first we left chip then add so either we add zero or one again this zero is gone now this is again zero so one more zero then one so one left shift and one that when we left shift another zero comes here automatically but if it's one we also add one here so this zero turns into one then we have left shifted so this becomes zero then it's 0 so we do not add then next is 1 so we left shift this so another 0 comes then it is a 1 so we add 1 here so this becomes 1 similarly for this it will be one we will left shift four times and add one each time then for these five we will just left shift but we will not add anything since these are not one so till here we are done let me redraw it shift it left side 0 1 0 then 1 0 and 1 more 0 next we have 1 so we left shift so 0 comes here then we add 1 to it so it becomes 1 so this is gone then 0 so you get the idea this will build this in the reverse order so 1 0 1 then 0 1 0 and so on all zeroes so now if you compare this you see that we have 0 1 and here it's in 0 1 so zero one then zero then four ones zero four ones and you can see that if you read it in this direction and the result in this direction it will be same so this is one idea so how we can do it we can run a loop initialize result equal to 0 then run it 32 times so i equal to 0 to 32 first left shift result and then if n and 1 is more than 0 that is its 1 then result plus and also n right shift by 1 and finally return the result so this will work now let's see another idea so here we ran this loop and it ran for 32 times irrespective of what is the number it will always run 32 times here we will use bit masking so what is the idea this is again n and the bit bytes are drawn in separate color so first we uh divide it into two parts take the first 16 bits and next 16 bits and flip them using mask so what will be the mask so take uh if we take uh end with first 16 bits as one so these are all ones and then next 16 are zero so what will be the end of these two it will be these 16 bits followed by all zeros because and with anything and of anything with zero so this will be all zeros and this bit will be preserved now do it again next time take the left part all zeroes in this mask this is mask we apply the mask two different mask on the same number first time left 16 bits are 1 right 16 bit are 0 in the other mask left 16 bits are 0 and write 16 bits are 1. so if you take the or of these two after shifting so take the end of these two what will happen so let me explain this masking thing for one example for one step then the same logic will follow so let's say this is the input and our first mask is all once or you can also write it as f so this is in hexadecimal so this denotes four bits so this is one byte fff 0 so this means 16 bits are 1 16 bits are 0. 5 6 7 8 9 10 11 12 13 14 15 16 then zero so this is mask one call it m1 take the end of these two what will happen it will be this blue region so whatever is this blue followed by this yellow and then all zeros so this will be all zero so this is coming from this is result one let's call it r1 we will not do it separately but we will do it in one step but just for illustration now let's write the mask to is this one zero x zero f so this is m one m two zero then one so result will be result is the end with n so r1 is n and m1 r2 is n and m2 so what will happen these things will become zero so i am writing in blue this time this left half becomes entirely zero and in the right half we have this white region so whatever is this white bits and then the green bits now what we need to do make r1 right shift by 16 so what will happen it will be all zeros here so i'm writing r one a bunch of zeros sixteen zeros followed by this blue rectangle followed by this yellow rectangle so whatever was this region this has come in the right part and left part is all zeros similarly r2 will be this white region followed by green region followed by all zeros so whatever was in the right 16 bit comes here now take the r of these two so what will happen r1 or r2 that will be uh this white bits eight bits are there then eight green bits then uh eight yellow bits and finally eight blue bits and in the input we had blue yellow white green so here we have white green blue yellow so 16 bits have flipped so this is how we can flip uh reverse uh bits not flip but reverse bit in groups so here we have first reverse this half take this half as it is move it here so this is the result after one iteration so we have reversed in batches of 16 and here mask was 0x ff 0 and second mask was 0x 0 f ff next what we will do uh we will take this half and reverse these eight bits so this eight comes here similarly this comes here this goes here and you can see the result so here the mask was 16 ones followed by 16 zeros and then we needed to shift left shift and right shift in terms of 16 and took the or here we will have eight ones five six seven eight zeros then eight ones eight zeros so here this 16 is further divided into one and zero so if we take the end with this and this what will happen these bits will become zero next time we take the opposite mask that is eight zeros followed by eight ones then eight zeros eight ones just like this these are these masks are reverse of each other so this time if we take the and with second mask then these will go away and these will remain these will go away these will remain again right shift one of them by eight bits so this it this white will come here this blue will come here and in the second result uh we do opposite left shift by eight so this yellow goes here this green goes here and then we take the r so these will be flipped and the result will be this so now you see this eight bits right most eight bits are now left most eight bits then followed by white yellow blue so we are making progress first 16 then eight and next you can guess we will reverse these four so this one zero and this will be one zero one similarly for this so what should be the mask here sixteen one sixteen zero then sixteen zero sixteen one here it's in terms of batches of eight ones eight zero eight ones 8 0 and here it is the reverse zero followed by one so in this step we will the mask will be four ones four zeros again four ones again four zeros again four ones and so on so what is this is a again f this is zero f zero so you get the idea and again f zero 4 times and what will be the reverse will be 0 1 and so on so 0 f and so on 8 times so this will reverse in this four bits will be reversed next we will reverse in two batches so we need 1 0 and so on and the other mask will be 0 1 and in hexadecimal we you represent 4 bits by 1 letter so what is this is 0 plus 4 plus 8 that is this is 12 this is again 12. so 12 is represented by c so it will be c all c's and what is this is your one plus uh two that is three so it will be three so the reverse mass will be three so this will uh flip in terms of two bits then finally we will do it in one bit so it should be all alternate bits one zero so this one zero is uh two plus eight that is 10 that is all a's are there and in the other mask it will be 0 1 and this is 1 plus 4 that is 5 so it will be 5 so let's write the code for these approaches we will mainly first write for this approach which is simpler so first we left shift result then we added to it if the last bit was 1 then we right shifted n and finally return result so let's try and expected matches so let's submit and the solution is accepted and it's 4 millisecond you can run it a few times it can become 0 also now let's write this same thing in java first let me try this second approach which is n equal to so this here we will calculate r1 and that will be n and zero x f zero and we right shift it by sixteen and here what we will do n and zero x zero f and this time we left shift it by 16 so this is m1 this is m2 this is r2 this is r1 and we are right shifting one left selecting other taking the or next what we do so this will be for eight this will be for four to one now let's fill these here it will be f 0 and 0 f 4 2 two one and here it will be uh c so we need uh 1 0 so 1 0 8 plus 4 that is 2 8 plus 4 that is 12 which is c and here it's 0 1 so that is zero one that is five so it's zero one so it should be three and again this works so let's submit and uh for those uh who are using c plus they can also try that bit set thing so bit set will uh if you write bit set dot two string it will return the string representation of this bits then you can always reverse the string using a reverse function you need to pass string.begin and you need to pass string.begin and you need to pass string.begin and string.end string.end string.end and once that is reversed uh you can create a new bit set passing a string representation of a bits so that will be the reverse bit set and in bit set we also have dot 2u long or functions like this you can explore it and then print the number so you can try that thing also so for java i will continue with this method and the solution is accepted in java finally we will do it in python 3 and in java i think there is a ready-made function ready-made function ready-made function let us try that reverse integer and it works you can see let's submit so it is accepted also but we generally don't use ready-made functions in these use ready-made functions in these use ready-made functions in these problems and the solution is accepted in python as well and we are around 87 percent
Reverse Bits
reverse-bits
Reverse bits of a given 32 bits unsigned integer. **Note:** * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned. * In Java, the compiler represents the signed integers using [2's complement notation](https://en.wikipedia.org/wiki/Two%27s_complement). Therefore, in **Example 2** above, the input represents the signed integer `-3` and the output represents the signed integer `-1073741825`. **Example 1:** **Input:** n = 00000010100101000001111010011100 **Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 **Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. **Constraints:** * The input must be a **binary string** of length `32` **Follow up:** If this function is called many times, how would you optimize it?
null
Divide and Conquer,Bit Manipulation
Easy
7,191,2238
289
welcome to december's lee code challenge this problem is called game of life according to the wikipedia's article the game of life also known simply as life is a cellular automation device by the british mathematician john horton conway in 1970. now the board is made up of m times n grid of cells where each cell has an initial state alive represented by a one or dead represented by a zero each cell interacts with its eight neighbors horizontal vertical and diagonal and use these following rules here are the rules any life cell with fewer than two life cell neighbors dies so it turns from one to zero any life cell with two or three life neighbors lives on so that just stays as a one and any live cell with more than three live neighbors dies as if by overproduction so that also becomes a one two zero now any dead cell with exactly three live neighbors becomes a life cell as if by reproduction all right so we have these four rules here i think that's going to be important and what we'll do is traverse through our grid and simply check its neighbors if we don't care about memory we can just create a temporary 2d array and store the next state in that array after we finish we could just replace the original board with all the values inside that temporary array now there is a monkey wrench here to do it in place without using extra memory but let's start with try and solve this uh without caring about extra marines okay so the path that i'm going to go here is what we'll do is uh first initialize some variables uh like you know the call number of rows and columns and stuff as well as our temporary array we're gonna write a helper function here and this helper function is going to check all its neighbors and return the next state into the temporary array so into the temporary and finally we're going to go iterate through our 2d array using our helper function and then replace the board with our temporary values okay so let's start with initializing some variables here we'll start with our n let's say m and n and this will just be the length of board oops as well as the length of the first array inside the board so this will be your length board zero okay we also need to have our temporary array here and this will just start with a bunch of values of none so we'll say none multiply that by the number of columns which is n and we'll do this inside of uh um let's see here side of a does this work inside of a list comprehension so for whatever in range of m is that right i believe that's right yeah so this would be number of columns and the number of rows so cool all right so now we should write our helper function and we need to make sure that we have all our rules in place so let's copy paste this here and it's going to help us write our uh our helper function here so what do we need to pass into a helper function well we're going to make it a function within the function so we'll have all these sort of as global variables so all we need to really pass in is the row and column that we want to check okay so now so for every position all eight positions which is going to be up down left right and the diagonals we need to check the counts right all right so let's start with creating a list of tuples that are going to have all the directions in here so this might take a little time let's see the first item is going to be the x coordinate and second value is going to be the y coordinate so we want to go up it's going to be 0 1 right now if we want to go down it's going to be what zero minus one okay so let's also have coordinates for left and right which is going to be one zero and negative one zero and finally we need all the diagonals uh let's see so if we go northeast we're gonna go one northwest is gonna be one negative one and it's gonna be one negative one all right so these are all eight directions that we need to check all right so first we'll initialize our count number of live cells around our neighbors and start with zero i'm going to say four let's say x y and p we're going to first make sure that it's in bounds and we have our length of the columns and rows and then we also want to check to see if it's alive and if it is then we'll increase our counter by one so if let's make sure i get this right here so let's start with the row r plus y is less than m and c plus x is less than n less this and board r plus y and c plus x if this is equal to one then we will increase our counter by one and finally we're going to have our number of counts and it depends on these four situations here right so if the board let's first say if it's alive then we have our couple conditions if the count is less than 2 then we can return a0 because it goes from 1 to 0. now else if count is 2 or 3. then it continues to live otherwise it's greater than that it also dies now if the cell is dead we want to check to see if the county is equal to three right so if count is equal to three then it's going to turn back alive otherwise it dies okay so now we have our helper method that's great and we have all four cases taken care of so all we need to do now is iterate down our board so we'll say 4 r in range of m for c in range of n we'll take our temporary array and we'll make that equal to the whatever value we return from our helper methods rc okay so now that we have our next state in our temporary array we need to replace everything in our original board with the values inside our temporary array so this would be like this and we take our board here and replace that with our temp alright so let's see if this works all right does look like it's working so let's submit that and there we go accepted so time complexity wise this would be m times n times 8 which becomes m times n but the trick the problem here is we use extra memory right with our temporary array here we also use m times that extra memory so the follow-up here if we want to solve the follow-up here if we want to solve the follow-up here if we want to solve it in place how could we do that well we want to solve it in place we can't have this temporary right here so normally with these sorts of questions there's three approaches one there's either some sort of pattern you can take where you could not really have to care about the next state but here because we're going eight directions that's really not realistic so we'll abandon that uh second approach might be to use multiple pointers but again i can't really do that with eight directions it's just too complicated and the final way we might be able to do it is to actually add the next value inside of the array board itself so instead of using this temporary array we're going to store that information inside the original board and then update it afterwards so let's do that let's see if we can do that and because we only have two states here alive or dead one and zero what we can say is all right if it's alive and we know that we're going to turn it to dead we'll increase that to 2 so if it's a 1 but we know it's going to die the next time we'll make it a 2 so that way we can know that hey this originally is was a was alive same wave this was a 0 and we know that it's going to turn back alive we'll make it a negative 1. and that way we can say all right then we can track later we know this is dead but we can update it later to say i make it alive again let's say to do that we can get rid of our temporary and we will say instead of equaling to one we'll say if it's greater than zero then we're going to increase our count because we know that the original state was alive even though we're going to turn it to a dead later okay so let's see here if same way here we have to say if this is greater than zero we know it's alive all these remain the same well actually no they don't this does this remains the same but if we know it's gonna go from one to two or one to dead we will make it a two now otherwise if we know it's less or equal to 0 we if we know that it's going to come back alive we'll make it a negative one otherwise we'll keep it at dead so let me see here if this works yeah so what we do is instead passing this original board and we'll have to go through it again but this time we'll say all right if board c is equal to two that means we have to make it dead so it was alive but now it's going to be dead else if board rc is equal to negative one then we know we're going to make it back alive all right so i hope that makes sense it looks like it's working so submit that all right accepted so that concludes the problem like i said usually with these in place problems like you want to be able to store that state information inside the original board itself it's easier when it's binary like this sometimes you could keep track you know use the positive or negative sign to keep track of that um but hopefully that helps and yeah i think we'll end it here all right thanks for watching my channel and remember do not trust me i know nothing
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
94
Hello Hi Guys Welcome Back To My Channel Short Wave And Discuss About The Amazing That They Are Here I Am Linking In The Eye Button For You First Go Watch The Video Of Free Mode On Opposite Reversal And Come After Watching Migratory Key And Henry Kiwi. That if you have seen that then it is for you it's not given a guys 2 minutes ever in front is okay for you 2009 transfer given auto minutes very easily you can do it very quickly can do it okay and a little bit I demand I am sure that you are watching my previous video because if you are not ready to watch it then I will have to explain a lot and it will become a very long video, we can make it so long, okay if we don't have time, okay so let's not waste the time for. Stop and I will tell you here what is this, why am I doing the matching in the inverter and after that I will write to you and give a dry run in a way so that I have done a lot of experiment Vikram ji, first of all at this time So what is the question, let's move on to the plate so that the question is fine, so I have already submitted it from the office. I know you know that now only after making this call, I will make a video, like Directory in all travel bags, so this is the question. You will definitely find the link in the description, go and read this post, try to understand irrigation from here, so I am trying, what are you doing, by the way, you are doing something similar to what you said in your nutrition episode, so we have to do playlist one in which Let us look at the inverter and the family, like this I will show you the inverter, what will happen in this particular, its inverter is 400, you guys will be surprised. Okay, so if I send you guys that post a video and answer the questions you are thinking, then this is the route. Africa is inverter and these lights are Africa inverter rock band you can try so Ayub Yuva has tried to solve this problem by himself and electrification lock what is this to you what is this, first of all I have already told the free mode on the road I am telling you what happens in the previous video, Admin and Tele Buddha, when I keep the root, then there is a change, when I am its height, then nutrition and they have understood this, then what happens to the inverter and then there is more when I am on the route when Vaidya in route day basically Anand Inverter object is fine 210 priest and the priest 12345 hair reduce location at this time by clicking here you can say with to understand you can say like this when I am in the left So in the family, post mortem will be done in the right below and to understand the nodal after getting up, they do not have any contact below, so to understand well, you can say this note here, neither I am the cream but if I take the post, then it is okay, so like Inverter and peak this post office APN 2350 decision in and leave this post 250 flash support staff details in 10th a pre 3316 in six post six inch 3372 130 posts 76 posts thirty first tag I am you guys understand inverter traversal here Yogi, what is it, okay dear, so after 10, now I will tell you as if you have understood now, otherwise you will have to wait in this time only for the bread to burst because there is a phone at the bottom of the bank, after that, if I keep walking like this, then the most First, my bottom was changed from 50k supporter, then the water table of quantity changed from when did you say leave, after this the button of 110 is visible to me, it is like a request in a reception party, while walking nearby, I got the return button, I thought you are thirty. Now let's talk to me, the bottom of terror will tell me, and now I have someone's button, when it's too much, what is the logic behind the inorder traversal of minority. Okay, now let's talk a little about what I am as an inverter, let me write here once. Gift to you again 2058 06 3878 Look carefully at this, what is there in the middle there is fruit in the play list, there is something in the laddu, there is something in the play list, what is there, tell me, then pick this up, referee and it is left sale in the factory mandal way, that is the trick in which They displayed 2014 in such a way that I do n't want to pre-order Mistry isi cup n't want to pre-order Mistry isi cup n't want to pre-order Mistry isi cup reporter kya aayega dekh hai 340 hai jab shyam episode and this is what is written here, ka is written on the right, think carefully, it is on the light. Use of Right Safari A Sorry Free Mode Caron Ne Inverter Right This Product This Africa Inverter Yes It is written Lights Africa Road While Taking Out - Lights Africa Road While Taking Out - Lights Africa Road While Taking Out - See This Thirty This Six This Entry Left Side to Front Again Nodal Message Chalunga My Child Said Vacation Will Let's Go Nearby Its bottom is visible, that tree is this 260 note, it has become Amazon, the button of thirty is the button of compulsion, when it is the richest, I wrote it for 160, then it got torn, yesterday I wrote it again, this is the use of the bell, this is Lights Africa, there is an order here. But put it as we had done in the sentences, we had to use the pre-quarter traversal of all trees we had to use the pre-quarter traversal of all trees we had to use the pre-quarter traversal of all trees in the pre-quarter, we had to use the in the pre-quarter, we had to use the in the pre-quarter, we had to use the poster version of all Please use nutrition less, here also it is the same, if you like, Yadav family used to illuminate the note. Left Right means write a note, after that Let's Africa pick up the family and ride using FD and bring it, fill in this cross and you will get the answer, post toe travel time, what did we do, we did not tear the Africa poster and were right all the way. Used to pick up posters and wash them and get themselves turn left light old war nutrition Africa nutrition and pick up and bring lights Africa nutrition and stand up write yourself and add all these things in one address your poster flour what are we here So what we are doing here, if you can understand here, what we are doing here is that you Africa in order that then you pick yourself up then lift the upright sub method inverter and you do this in this But two, your answer is okay, what we used to do in that, we also used to do our own adjusted cricket where we will not do that cricket, let's see what happens if I just think superficially and do it, on top of that, we have to think above in the information verification. That's like I have 10.32 like I have 10.32 like I have 10.32 ear in the national side what is the small problem is that if there is only carrier then its in order to attain it's a because small block second I know inverter has also Brett Lee's so told You have next 9 and light provider, not left, right poster, next flight mode, inverter, left, no dried, so you know that in left loaded sites like Twitter, inorder traversal and I know, there is a little problem, it goes, it is not doing anything, big problem. Ok do that and see how but if the function of supreme power travels will ask me on the address then it will do it ok so I accepted that I will call inverter travels from left Saptari then Africa will ask inverter then he will ask for the host in which student in which how till 5020 sure This is the inverter left atrium. Now what do I say, okay what should I do now, if I add myself in this, first t20 fever and I had time, then I have added that, now this is my request, it is WhatsApp. If the method is burnt in the inverter then he liked my 6817, is there any cure in it and look, if I add this one to it, what will become 150 0 and the six after that are 3878, this is my inverter, this is what it is. Africa is the inverter, I am this is Africa, so now you have understood from above, what was the exact procedure, after writing the book, let's see mine. You see, I will be able to write the code in so many people. If you want to tell you the real of the country, then You go and watch the previous video, you will know that if the breakage ever stops, then what remains is the empty address, we return the laptop in the freezer, make the interior in this list, physical symptoms balance, why am I doing this, if you Think logically also, if you think logically then what can I have, if you give me empty Delhi which has a root canal, then it has a root canal and removed me from the deep list in which you will fill me for the sake of inverter towards it, brother. If the tree itself is empty, then it is full, in the end that ride is empty, simple Rosemary, just what I said, I told you that what will you do with the publication of the left, everything is fine with the left, the inverter will do it for me, it is okay that we solve our small problem. If you had brought a big nectar pot, then I said to the equation, let us go and do one thing often. Bring the left list, what is this reference to me, so actress Dabir, he can write in Bengali that in order to travel, it is okay, nodal traversal is of people in Africa. N order in my list so I add this to it and after that I request to order the right sub method also if a flash lights Africa that if I want Vinod Travels mobile now what should I do I have already ordered Africa N order Africa to order inverter After that I can add myself and if I'm going to right something and kill Jasmine, look at what I do, by the way, this is a trick, so I work on this again, dry selected, this is okay see, like I have. Agri police station 1000, this is 40ft more than 1617, what can I say, get me to do it like this, don't do so much work, my request is to give me a lakh left sub method inverter, that is, after bringing me a gear list filled with 1428, I got an electric and after seeing it, he added me to the police. So, what should I do now? 1428 and 10, this is the condition in my left list, this is the current condition, all the work is pending in my reference also, so much is pending, okay, what am I doing now after this? I have also taken the required list from Bhagwan Se Vacation, so what is the rights list, rights le se 6 3078, this is my light list and this is also subject to verification, so tell me, if I add rights to this also in this list, will my songs be included in my playlist? If the complete inorder traversal comes, then try to do it there, see it, have fun, what do I mean by adding it to the light list, relax, by adding it, if all of Tytler's were there, then 14% interacts all of Tytler's were there, then 14% interacts all of Tytler's were there, then 14% interacts with long Tubelight list. A latest edit on the list of this name and if I think about it, now my complete inverter option is lying inside this loot, that is, if I do it should be accepted. Why am I taking so much time, does anyone sleep in 16 minutes of work, giving so much time? We do n't need it, till then we can work, we can even try to appoint people as dealers, till the time we correct what we have said, it is okay, I will tell you the drafting, till then maybe we will see. Give the network, ok, it's 20 minutes, so I told you to watch the video in free mode, either you used to create an empty address in it, in the pre quarter, I used to create an empty balance, add myself, then connected the laptop and then switched on the light. There was empty balance in the poster continuously but I don't add myself. If I open the app first, I will add it to my friend, then I add myself, where I don't know about your play list, I am not created for anything. Let's go and see it in the shop. I say, let's buy the color. The second one is, go from here, go on. Okay, I am saying that I will give my Africa inverter of the play list. The brother in this is his referee. Said to his referee that he has put his inverter in the country, but man, when people in the form, there is an empty initial S off here, what did I say, this is my leftist but I had to add something to it, I After that, I cut you this strip, after which I would have put a pause on Friday, then the restroom had come to the right, so whiteness for the right, what did I say after this, add all the hours of the dry list to it, this and that too. Only the datasheet remained, after this my work was over, so I moved ahead, now look when I came to Twenty Kuldeep Twist, did they take the painting reference that this fatty one, what to do, added something to it and then to this You have called your light, okay, now Africa will leave, open its app where you will get super clearance, what will it do in it, add it to it, then who will employ your writer, now call this cloth, eat it from here, Yasmin whose hours If you copy it and move ahead then come a night list near 120, come a rightist near half an hour, okay, what is filled in the brightness party that has come, everything is filled in it, okay, now I had done 20, something in the left list. It was ideal, one work left is to add right this content, so the general thing is that what is next, what will become of this will become here, 4028 4820 have given A certificate to some or added this, even after adding this, where will the list go? Is this list of mine, I am here near 110 and Tank has this in the blacklist, Tank has this reference which if he adds himself on the left then will Bandagi become a leftist reference, was it the husband or for a minute then this thread will work on your light for a minute then this thread will work on your light for a minute then this thread will work on your light and you have understood that you have also understood its trial run, once in its trial, we will see here, everything is done, if you submit it then it should also be submitted, the tablets are done. Okay, that's all, we will meet in this video in the next video where we are going to start something new, it will be interesting in traversal, till then good and bye-bye.
Binary Tree Inorder Traversal
binary-tree-inorder-traversal
Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[1,3,2\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
98,144,145,173,230,272,285,758,799
146
hey guys welcome back today we're going to solve lru cash problem number 146 on Lee code so the problem statement says to design a data structure that follows the constraints of a least recently used cache first we'll talk about what an lru cache is and then we'll jump into the code okay let's get started a great way to visualize an lru cache is to imagine visiting websites on your computer before we've visited any websites our cache is empty so first we visit website a our browser then caches website a and stores it into memory next we visit website B this time when we store B in memory we move a over to the end of the list to indicate that it was the least recently accessed website next we visit website C when we try to store C into memory we see that our cache is full so we go to the end of the list to the least recently accessed website and we remove it now we can shift B over and add C into the cache now let's say that we revisit website B so first we check is B in the cache we search the cache we find B and we return what we need to render the website quickly however in the worst case scenario that website is at the very end of the cache we have to search through every single value in the cache to find it and the problem asks us to find a solution we're adding and retrieving values from the cache happens in constant time so what we can do to achieve that is maintain the locations of each of those websites in our cache using this method we can very efficiently query our cache and ask it does B exist in the cache and it does and here's exactly where to go in this data structure to find it so this is kind of a hint as to what kinds of data structures we'll need in order to achieve that o of one time complexity we'll need a linked list where we can keep track of what's been most recently accessed and what's been least recently accessed and will maintain a hash table which will tell us exactly where to go in the linked list to find the website if you're not already familiar with how linked lists and hash tables work go check out my videos in the description box below where I explain exactly how they work and how to implement them in Python okay I think we're ready to jump in and start coding let's start by defining our lru cash class we'll initialize it with a set capacity and we'll use the dictionary class to initialize our hash map next we'll create our linked list so we'll start with the head and our tail we'll go ahead and connect the two by setting head.next to our tail head.next to our tail head.next to our tail and tail.previous to our head so we're and tail.previous to our head so we're and tail.previous to our head so we're essentially creating a doubly linked list having a doubly linked list means we can travel across the list in both directions we don't just have to start at the head we can be given a location within the list and move either towards the head or the tail I also just want to point out we're not initializing The Head and the tail To None to start we're using these dummy nodes as placeholders it gets a little complicated if you don't do it this way so I do highly recommend having a dummy node on either end of a double e-linked list all right end of a double e-linked list all right end of a double e-linked list all right so moving on to our node class it looks pretty standard it'll take in a key value pair and we'll initialize the previous and next nodes to none so first let's write a method that will retrieve a value from our cache our get method takes in a key if it doesn't exist in our cache we should go ahead and return negative one otherwise let's go into the cache at that key and retrieve the node that we've stored there so at the end of this method we know that we can return the value of the node we also need to change the position of the node within the linked list to indicate that it's now the most recently accessed node the easiest way to do that in a linked list is to First remove the node from the list and then add it back in at the head let's define some helper functions to execute this logic so we'll need a remove helper function and an add helper function let's start with defining the remove function so to remove a node from a linked list we need to set the previous node's next value equal to our current node's next value we do the same process by setting the next node's previous value equal to our current node's previous value let's define our function that will add a node to the beginning of the list we'll keep our dummy node at the head so we'll essentially insert our node between the head and the head's next value we'll start by storing the value of head.next then we'll link our current of head.next then we'll link our current of head.next then we'll link our current node by setting its previous value to the head and its next value to head next now we can rewrite head.next to our node now we can rewrite head.next to our node now we can rewrite head.next to our node and we can set head next's previous value to our node now let's define a function that will put a new value into our cache if this key is already in our cache we'll need to go ahead and remove it so that we can insert it at the most recently accessed position in our linked list next we'll create our node and we'll add it to our linked list and we'll save the location of our node in our cache we also want to account for an edge case where our cache exceeds our capacity so if that's the case we'll have to remove the last item in our linked list and we'll Define that logic in a function that we'll call remove from tail this is a pretty straightforward method we'll take the value at the end of our list so the value that's right before the dummy note at the tail and we'll call our remove helper function and then we'll delete that value from our cache the last thing I'm going to do is drop in this helper function that will print out our linked list so let's check that everything's working we'll start by initializing a cache with a size of two and just like in our example before we'll visit website a and if we go ahead and print that out we can see our linked list has those two dummy nodes on either side and website a is the only value in our cache next we visit website B and now we see that website B is at the beginning of our cache finally we visit website C and website a has been removed from our cache because it's the least recently accessed site when we visit website B now we see that B and C switch places because B is the most recently accessed site all right now that we seem to have come up with a workable solution let's go back to Lee code and see how it performs so it looks like the runtime of our solution and beats about 75 percent of other leak code users the memory could definitely be improved so that's something we can work on in a later video If you have a different solution or have ideas about how to improve our lru cache leave a comment below and if you like this video please give it a thumbs up and subscribe to the channel and I'll be back next week with another Lee code solution thanks so much for watching and I'll see you next time
LRU Cache
lru-cache
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**. Implement the `LRUCache` class: * `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`. * `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`. * `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key. The functions `get` and `put` must each run in `O(1)` average time complexity. **Example 1:** **Input** \[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\] \[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\] **Output** \[null, null, null, 1, null, -1, null, -1, 3, 4\] **Explanation** LRUCache lRUCache = new LRUCache(2); lRUCache.put(1, 1); // cache is {1=1} lRUCache.put(2, 2); // cache is {1=1, 2=2} lRUCache.get(1); // return 1 lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3} lRUCache.get(2); // returns -1 (not found) lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3} lRUCache.get(1); // return -1 (not found) lRUCache.get(3); // return 3 lRUCache.get(4); // return 4 **Constraints:** * `1 <= capacity <= 3000` * `0 <= key <= 104` * `0 <= value <= 105` * At most `2 * 105` calls will be made to `get` and `put`.
null
Hash Table,Linked List,Design,Doubly-Linked List
Medium
460,588,604,1903
165
Jhaal Hello Everyone 123 Question is compare version numbers question sir state will give one to two a view to zoom two version settings on mp and contain any digit give one different 2.5 is not two and half mitthu one different 2.5 is not two and half mitthu one different 2.5 is not two and half mitthu version is The first second level revision of the second for celebration yesterday morning means that if to is the first level division and spa is the celebration with example in example 1515 1.2's example 1515 1.2's example 1515 1.2's combination of to is great britain - 1m combination of to is great britain - 1m combination of to is great britain - 1m as we post version 1.0 512 it's only as we post version 1.0 512 it's only as we post version 1.0 512 it's only One person who has written words into it similarly in version 107.5 2012 is 1.5 similarly in version 107.5 2012 is 1.5 similarly in version 107.5 2012 is 1.5 132 Jai Hind is the first two digits same with them due to remove want to visit 300 words into its readers and visitors - words into its readers and visitors - words into its readers and visitors - 110 that Example number four version 1.0 weight So this is that Example number four version 1.0 weight So this is that Example number four version 1.0 weight So this is 1.00 130 not counted 3151 turn off that 1.00 130 not counted 3151 turn off that 1.00 130 not counted 3151 turn off that similarly in this example version 1.0 similarly in this example version 1.0 similarly in this example version 1.0 2012 this is 1.00 phone game not counted in both are 2012 this is 1.00 phone game not counted in both are 2012 this is 1.00 phone game not counted in both are equal to be written 0 so let's move to the expansion and will see the code lipstick example for also question wherever Giver is the one thing I want to tell the only thing present in this page guys it's n decimals so they can easily spread digits by using moments in python using displacid convert moments in python using displacid convert moments in python using displacid convert string into to-do list in which string into to-do list in which string into to-do list in which every digit is given separate Entities Are Nine Since I Have This Is The Pair Distribution Over Its Way Into The First And Second Patients In Both 323 Lots Of Love Oo Me Sloth Is Great 1212 Is Coalition Version Ancestry In Britain Minus One Not Only Issues The Length To Words May Not Be Scene on Jai Hind example present for in the present in button server to compare authority Jha land record dance of death note episode to the opposite palt several examples like this the world and since first I did not scene video button version to wear nothing to compare To So That They Can Do Video Friends Page 1280 Display David Christ Forrest Gump If Students And Asked His Senses 2004 Disposes Better And Have An Answer Please Take Another Example He Is From 500 600 800 2013 220 Return Sides Flat Repeated Again To Posted Through Split String based on the decimal this period list using for loop the thing edu 2012 - wwe and in 1995 2012 - wwe and in 1995 2012 - wwe and in 1995 that unsupportive one to them subject such a certification for question a list rence wwe * fitting their like this rence wwe * fitting their like this rence wwe * fitting their like this my heart related entries version tu i online uk Lallan Mishra and operation to very a mein jalan to position one for inquiry into history in next online number 10 Singh alias Lallu to the range of the length of wave 2 MP3 maximum full length 400 points 102 a little fitting over so Version is tourist but less to point wrong weight to is present length weight one sweater glass placid frill 2075 only 10 and very good smoke compare truth equipped computer 75 complete 2520 2314 smooth and digit of this vibration 2018 238 complete annual plan is incomplete 108 Number Delete This Time To It Is My One Is Not Equal To Is Too Young To Check This One Is Greater Than It What Is This Is Not Satisfied By One Is Equal To The Return Of The Day That I Code Accepted Were Nothing So Much For Watching the video please don't forget to subscribe thank you
Compare Version Numbers
compare-version-numbers
Given two version numbers, `version1` and `version2`, compare them. Version numbers consist of **one or more revisions** joined by a dot `'.'`. Each revision consists of **digits** and may contain leading **zeros**. Every revision contains **at least one character**. Revisions are **0-indexed from left to right**, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example `2.5.33` and `0.1` are valid version numbers. To compare version numbers, compare their revisions in **left-to-right order**. Revisions are compared using their **integer value ignoring any leading zeros**. This means that revisions `1` and `001` are considered **equal**. If a version number does not specify a revision at an index, then **treat the revision as `0`**. For example, version `1.0` is less than version `1.1` because their revision 0s are the same, but their revision 1s are `0` and `1` respectively, and `0 < 1`. _Return the following:_ * If `version1 < version2`, return `-1`. * If `version1 > version2`, return `1`. * Otherwise, return `0`. **Example 1:** **Input:** version1 = "1.01 ", version2 = "1.001 " **Output:** 0 **Explanation:** Ignoring leading zeroes, both "01 " and "001 " represent the same integer "1 ". **Example 2:** **Input:** version1 = "1.0 ", version2 = "1.0.0 " **Output:** 0 **Explanation:** version1 does not specify revision 2, which means it is treated as "0 ". **Example 3:** **Input:** version1 = "0.1 ", version2 = "1.1 " **Output:** -1 **Explanation:** version1's revision 0 is "0 ", while version2's revision 0 is "1 ". 0 < 1, so version1 < version2. **Constraints:** * `1 <= version1.length, version2.length <= 500` * `version1` and `version2` only contain digits and `'.'`. * `version1` and `version2` **are valid version numbers**. * All the given revisions in `version1` and `version2` can be stored in a **32-bit integer**.
null
Two Pointers,String
Medium
null
48
given an n-by-n 2d matrix representing given an n-by-n 2d matrix representing given an n-by-n 2d matrix representing an image you are asked to rotate this image 90 degrees clockwise how can you do that in place that's about today's video let's get into it hi everyone this is Steve here today we're going through a legal problem 48 rotate image oh this is very classic programming or interview on math question let's take a look and you are given an N by n 2d matrix representing an image well asked to rotate image by 90 degrees clockwise there is a note here you have to rotate the image in place that means you have to modify the input to the matrix directly without allocating another 2d matrix and do the rotation of course you can do that of course that's going to be a lot easier but you're not allowed to do that but that's the fun part that's the meat of this question let's take a look give input matrix 1 2 3 4 5 6 7 8 9 this is the given input and we are asked to rotate the matrix in place such that it becomes this seven four one eight five two nine six three how it becomes like this how it rotates like this is because we rotate this matrix 90 degrees clockwise 19 degrees clockwise so you see one becomes here two becomes here three becomes here so it keeps rotating 90 degrees clockwise now we have gone through the problem description let's think about how we can tackle this problem so first the very easy brute force solution is that we can just allocate and new matrix of course that's not allowed but I'm just going to talk about throw the idea there how we can actually implement that we can just implement a new four by four matrix right at the very beginning is going to be all for feeling with a zero so up four by four matrix is going to be filled with 16 zeros here then what we will do is that we can just a copy row by row 5 1 9 11 right where now we're going to copy those just look at here 5 1 9 0 then we're just a sine row by row to the new matrix column my column from right to left right five one nine eleven then find one nine eleven here then the second row is going to be copied to this the last second column which is two four eight ten to four eighteen right and then the third row is going to be copy over to the third last column from the right which is three six thirteen three is six seven thirteen three six seven the last row is fifteen fourteen twelve sixteen then fifteen fourteen twelve sixteen that's the very brute force we are actually allocating a completely new and by n matrix to implement this of course that's not going to meet the problem requirement that's not going to be accepted but we just talked about the brute force solution a slight variation of the total brute force solution which is to allocate the entire n by n matrix to do the rotation we can use in temporary so that way we can do it layer by layer is so here for example five one nine eleven we'll move it to this place five one nine eleven and then move this array eleven ten seven six move it from this last column to the bottom row and then we'll move this one six sixteen twelve fourteen fifteen to it's correct position which becomes the first row which becomes the first column sixteen twelve fourteen fifteen what we will move is a row by row and we'll initialize in temp array to hold this either this row on this column that's one way so this is the first layer and then the second layer will continue to do that move three four no move four eight to it's correct position which is four eight here and then continue to move eight six to its correct position which is becomes the last second row which is eighty six here what can continue to do that's one way kind of in place but still not completely in place because we i we are taking advantage of a temp array right so how can we really do this in place using constant actress pace well just and we can trick the second follow-up solution the follow-up second follow-up solution the follow-up second follow-up solution the follow-up to the total brute force solution a little bit which is instead of moving this entire layer or the entire row or column completely once what we can do is we can just remove one element at a time that's going to give us constant extra space which means we're rotating the matrix in place right so what we will do is that we just need to find every single nment from its original position to its final correct position right let's go through this for example five moved this is five moved to here right so just think about how we can swap two admins we use one tenth variable assign this is basically three lines right assign one number to ten and assign that second number to the first number and then assign temp to the first number then we finished the swap between two numbers we just use one temp variable so here instead of two numbers we have four numbers right so we always swap phone numbers that's going to implies that we're going to have five lines instead of three lines because we are swapping four numbers but still we only need one tenth variable we're good enough so here say first we'll start from the very top left row one is a row 0 column 0 so here we'll just follow the number swap logic well save this one into a temp variable and then we know who's going to take this position so say here 15 is taking this position so we move 15 to this we don't need to worry about with losing this value because we saved this one to the temp variable right and then who's going to take over this position so we saw 16 so we'll move 16 to here then which number is taking 16 s position here we see 11 so we moved 11 to this position now 11 is gone right 11 is gone now we see it happens that five should be taking the position of the then we finish in the mood so basically five move to here you let them move to here sixteen move the to here and fifteen move to here then we finished this one every number is in its correct final position then let's think about oh that actually can work out or we can how actually put that into the actual logical code let's take a look so here you see what just reuse another example still it's four by four but I'm putting all of the elements in order 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 so that we can follow the logic easier this is the initial state which is the given four by four matrix and then as I said we'll swap just two phone numbers using only one temp variable so that's in place where wrote and whatnot we're using only constant extra space so what would you will start from here right one so what well save this one into the temporal or call it top because this is in the top row right next well what we won't do is so first one i is 0 j 0 we're standing from the outer loop this is the outer loop next what we will do is we'll remove the bottom one here 13 to the top position override this that's fine because we saved at the value in the temp variable right 13 is in the final position final correct position that's the second line of the code during the full number swap remember we have five lines of swap to swap four numbers then next third step is that so I'm using the dark red color to indicate that this number is in its final correct position already and using the yellow color to indicate that this is the number that we just removed so in this run in the third step what we will do step one point three in the third step what we do is we move this number 16 to this number to this place right because it used to be 13 in this place but we move to 13 to its final correct position already so we're just override it we put 16 to this position right this is step three next step or continue to do to move that last number which is the fourth number so is the fourth step we'll move the last number in this round into its correct position it here it used to be 16 right but 16 is moved to its correct positions and we move for two here and then the last step as you can imagine last step is to move the first number which way which we saved into the temp variable in here that's it so at this moment all of these phone numbers they are all in its final correct position after if we want to rotate this four by four matrix 90 degrees clockwise alright now we have finished the first so this is going to be a nice treat for loop because we are going through a row and column so we have finished your reading through the first run which is Rho equals to 0 J equals to 0 which is equal to real number as well row index as well all right then we finished swapping the first round of for Edmonds phone numbers we've finished swapping that now well Stan so it's still going to be the first row but we'll increment column by one so here row in that zero economy next is going to be incremented by one that means we're moving here we're moving towards from the right so we finished this one this is these four numbers and one group they are swapped right they're rotated 90 degrees clockwise next is going to be at this now we save this number top we still save it into a temp variable we do the swap so this number will continue so you see I is the row B negative 0 J is the column next incremented by 1 we're still in the outer loop which is this one this is the outer loop and then this is the inner loop so this one next step will work do is since this one we have already saved into a temp variable we can move the admin that should be in this position has its final position which is number 9 now we just move this one to here right this is step two step three will move since this number previously it used to be nine here but nine moved to his final correct position which is in dark red color will move the number that should be in this position as its final correct position which is which number 15 so we'll move 15 here then next thing is we move this number needs to be in the position where it used to be 15 right so we move in here this is the fourth step the fifth step is the final number which is the top number that we saved into the temp variable we'll put it into its final correct position which is here right after these five steps we finished in the second swap the second round of stop swap which is to swap another phone numbers rotate this was the second round of phone numbers into its final correct position so then well stack will continue will continuing with the column is going to be incremented by one so I is 0 but column is going to be 2 from 1 to 2 which is this number so well save this number into a temporary you see here and then so this position could be overwritten by a parent we can save this number of 5 so we move 5 here continue 5 is in the correct position it's safe to be overwritten so for 14 moved in here then 14 is going to be overwritten we move to health to 14th position and finally when you save will move the 3 that's saved into the temp variable into 12th position now the outer loop is done it's completely finished every single number in the outer loop is in its final correct position 1 what you next of course in the inner loop right we'll continue to do the same start from here but this time row index is going to be incremented so last time row is at 0 really Nexis time from 0 now we'll increment row needs to be incremented so row start from I J is always standing from we're running max a stunning so that means we're always standing from here well I'm always standing from the diagonal we'll talk about that a lot more in just a second now let's see so we saved it six into the temp variable so this position could be overwritten who should move to this position 10 right so we moved 10 here no 10 could be overwritten you haven't moved to this position so now the lemon could be overwritten which number should go to this position 7 so now 7 is good to be overrated so which number 6 should be moved to this position now at this point the England up this is their 4 by 4 matrix so there are only two layers outer layer outer loop and in the loop that's it so we are done with rotating the four by four matrix now let's put coordinates into the pit into the picture so that we can actually understand how we're going to write the code let's see this is the initial state 0 1 so the first is the X which is the x-coordinate second the X which is the x-coordinate second the X which is the x-coordinate second is the rope is the Concord animate first step X 1 resistant because there are multiple runs but it's always 5 steps 1 2 3 4 5 so this is the step 1 we save the top we save 0 into the temp variable next we move the left to the top 3 0 which is 0 right next step is that we move bottom to left 3 2 3 0 step 4 is that we move this right to bottom this right 0 3 2 3 step 5 is that we save that and we move the temporary ball into right into 0 3 these are the five steps that we'll have to do we have finished rotating the first two realm of four elements all of these four elements are in the correct position just to help us better understand how we can put the actual coordinates the numbers into the indices so let's go one more run so he here this is the second run well we'll increment the economy next so Jane becomes 1 so we're standing from this number right we're standing from this number so this number are going to be swapped with other three admins which and these three right these three this one go here this one goes here these phone numbers are going to be swapped then just one more round then we were done with this column index base in the phonic so here this is we increment J again to be two now to is this number this is the starting point of this rotation of this iteration the this number a parent is going to be spoken with other three elements in the outer loop so it's these three now let's take a quick pause and think about where do we stop and what point does J stop so J is two right now is from zero J starts from zero which is where the real index is so we stand from here and goes from zero to 1 to 2 now we stop you because here is the correct position final position for a previous number which one was used to be here but now it's moved here so apparently we don't need to rotate this one anymore because this one has been rotated already so that's the upper bound that's the boundary of the economy max so how do we denote that is J is bounded by three right so J is always must be exactly smaller than three how do we know it's three since this is a four by four matrix so this n is the length of the array or column or row size of the matrix is this n is 4 so 4 minus I minus 1 that gives us 3 so the J the economy next whenever we rotate the economy next needs to be exactly smaller than 3 than this boundary and why do we need a minus I because I is the row index that will keep incrementing so I'd say next time we start from here the I is 0 and the I is nonzero angle I is 1 so we need 2 &amp; 4 is nonzero angle I is 1 so we need 2 &amp; 4 is nonzero angle I is 1 so we need 2 &amp; 4 minus 1 so that is becomes to you well talk more about that in just a second when we go into the inner loop but here we say J is bounded by 3 J must be exactly smaller than 3 when we do the rotation next what we're seeing that well to the inner loop in the loop will increment I becomes one at this point so it's going to swap with other for with other three admins so it's four elements going to be rotated clockwise 90 degrees it's going to swap it's going to rotate with the other three happens these three other elements right this is the inner loop and then we can see at this point this entire four by four matrix rotation is done so we don't need to increment I and J anymore so I is bounded by what is bounded by two so I is only 0 and 1 you see I is only 0 and 1 then we're done that basically means we only rotate the quarter one quarter of this entire matrix is that right and we do it diagonally this is where the standing point is this is the starting point we do it this way from the top left you go from go-to along the diagonal so it's from go-to along the diagonal so it's from go-to along the diagonal so it's always 0 1 if the matrix is bigger than 4 by 4 then welcome what do to row me max is always standing from 0 and column index is always standing from where the row index started that guarantees us so it's always 0 1 2 3 if the matrix is a big is bigger in them for life all that way it guarantees us we stand from the time we go along the diagonal which is we only need to start we only need to work start from one quarter the top left quarter one quarter of this entire matrix we go this way this one rotates to here this one to here as you can see right so we go this diagonal so this eye is bounded by two is the half of the array length of the matrix size so that is 4 divided by 2 is 2 I is only I only needs to go through a half of the array why because as I said we only need to traverse we only need to start from one quarter of the entire matrix that's it because the other three quarters of the matrix they need to be rotated right this one written here so the starting point is only one quarter so we can stand from important but what just sat from the top-left corner so it just sat from the top-left corner so it just sat from the top-left corner so it goes this way well with that and now let's think about how we can put all of the four indices into the actual code how can we member right now these are concrete number is zero to four right zero to three bonded by four now we're seeing so the top one well just start from zero row mean X is zero economy next is never top this one let's just look at the dark red this is the dark red color the top one which is this well save this into a temporary bulwark on top this is the matrix which is I and J no problem with that there is three four now well get this one what is this bottom number how can we do know that in the index that is the left ones are in the left one the left index will use n minus one minus J and the economy next is just on economy max is zero you see economy max is zero here and the row index which is n minus I minus 1 minus J in this case J is zero so 4 minus 1 minus 0 gives us three which is three here right this is the left and then we'll look at this bottom this is bottom Panamint how can we denote that the bottom in X is 3 so what we have is sighs - n - 1 and the size minus Rho sighs - n - 1 and the size minus Rho sighs - n - 1 and the size minus Rho minus 1 that gives us 3 this is the bottom now the only one left is this right then how do you know right Hammond is 0 3 so 0 is this J it's 0 then this 3 is n minus I minus 1 with this figured out now we can take a look at the actual code the code is going to be written literally like this with just a swap we take turns we start from this row we start from 0 and we go along the die heck no we only need to stand only one quarter of this entire matrix so here the arrow stops here one quarter of this entire matrix so the code will look exactly literally like this so let's take a look at the code so n is the matrix length then we stand the row is going to be bounded by this half of the array length as we just described is going to be bounded half of the array length right we only need to go quarter of the matrix so here I is zero and one for a four by four matrix that's it right and then the column the economy is going to start we always go along the diagonal by diagonal in the actual matrix that means ax and wine these two colonists they are equal to 0 1 right so that's why we always start from the economy next will always stand from whatever the current I is whatever the current row index is and the column index is bounded by n minus 1 that is why we have it here is bounded by this and then what do literally what we just disk discussed five lines of code five steps which is save the top master we move left to top next step we move left it to top if we take a look here this is left we move it to top this is second step then next is we move this one bottom first step is move bottom to left which is bottom to left moving here right and then fourth step is from the right to bottom from move right to bottom the last one is moved top which we save into a temp variable here and assign the top into the right one assign the top a temporary rule into this one then next step will rotate by column first once we were bounded we reach the end of the column there we'll increment row and then after we reached the boundary of the road then we're done we finished a reading starting from one entire quarter along this diagonal that means at that point and then we're done rotating best matrix clockwise 90 degrees that is one way that we can do to solve this problem which is basically to follow exactly our thought process to start from the top left quadrant will finish standing that entire quarter of this matrix and just keep rotating I'll keep actually keep swapping all of these four elements in every single quarter of this matrix are there any other possible approaches of solutions to this problem yes I was inspired by one of the houses in the discuss before this problem we can actually transpose the matrix first and that reversed either row or columns so definitely they are at the possible solutions now we'll just go through one of them first we're going to transpose from this matrix to this matrix how we can transpose if we take a deep look at this the between these two matrices we can see the difference is 1 2 3 4 is moved to here 1 2 3 4 5 6 7 8 is moved here five six seven eight so first a row becomes first column second row becomes second column third row becomes third column how can we shift in this how can we transpose matrices like this okay let's do it one by one well start from the diagonal in the top left at an angle still welcome the diagonal all of the points that lie on the diagonal is our standing point that means it's time from 0 J starts from high ok so which is to move one by one green just indicates the one that we're moving to you what transposing to okay one doesn't change why what doesn't change because one I equals zero J goes to 0 then swapping is just swapping with itself so all of the diagonal elements just basically swapping with itself resulting in no change okay and then here I is so is 0 J is 1 right so it's going to swap with is one J is zero so I and J basically swap these two are going this one so five and two became three and five and then J is still zero J will continue to increment i 0 J 2 this one is I to J 0 so physics what i inj that's going to be the two elements is going to be spot between 9 3 they continue here the difference okay not what just continue to do this and you know so we finished at the outermost a loop and then we'll continue with this diagonal and the next one is 6i increment it by 1 so now is i is 1 right from 0 to 1 I is 1 now next J increments by 1 as well so here we stand I is 1 J is also 1 now J is increment by 1 so I 1 J 2 is here I want J 2 is here which is going to be swapped with I 2 J 1 will continue to do this is going to sweep what okay now we're done with the second loop the third loop is going to be 9 3 J 3 which is this 11 they continue J plus 1 3 plus 1 is 4 3 4 this is the index is going to swap with 4 3 which is here now the third loop is done the last one is just swapping with yourself because there's only one element on the diagonal then what death were done with this transpose next step you can see the this is the intermediate matrix that we're going to reverse into the final output this is the desired output you can see every single row just needs to be reversed 1 5 9 3 in the correct order is 13 9 5 1 sorry this is 13 1 5 9 13 95 one the same for the rest of every single row so what we'll do is that which is to reverse every single row this one gets reversed becomes this next one this one reversed guess this continued to refer continue to reverse then well done this is the correct answer which is the reverse I'm first we do a transposition of this matrix now we get an intermediate matrix and then which is the reverse every single row then that will be our final correct output so what's the time and space complexity of this algorithm by the way the first solution time complexity is o N squared right because this is the length of the Year matrix is in all the signs if the row and column they're both because this is a square so it's n so n times n is n square time complexity is o N squared yes and we have to go through every single helmet no doubt about that space complexities or what so this problem under this solution is also always squared time company because anyway we need to go through this entire matrix once and for this one we go through this entire diagonal not half of the diagonal right but the time complexity is still always greater the space complexity is also a 1 because we're not using any extra memory we're not advocating a new and by n matrix we're not doing that we are basic we're just overriding doing everything in paste this is doing transposing this history this was what's with this ones once we win this one's worth wing we're only using a one extra memory just want to complete this entire swap base transpose in Reverse now we can also quickly put that into code let's do that matrix length first step what we want to do is to transpose so we'll start from 0 J always start from hi J smaller than a j-class smaller than a j-class smaller than a j-class do a swap which is only using one tenth in matrix J we can change J I remember what always swapping the two elements on the diagonal two five three nine four thirteen that is indicated by these two indices I and J and I we all just keep swapping them and then here matrix J I assign temp to it so the this mastered for loop helps us do the transposition next step which is to reverse every single row right now let's do that also have a for loop from zero this is going to help us control every single row of course you can also do another transposition and swap every single column that's also possible but the idea is the same I'm just going to do it this way you can practice doing the doing it the other way and we'll have a start from the very left there and from the very right end which is n minus one then we'll have a wine with to do the swap start smaller than and we'll keep doing this one temp matrix-matrix all right start the side matrix-matrix all right start the side matrix-matrix all right start the side matrix I and to it and then matrix a matrix and tamper to it now we want to start needs to keep incrementing and ten needs to keep decrementing that's the idea so this I is the real number this is zero one two three we need to keep going through every single row and then we'll have a start and end to a point at the left and the right well keeps walking this tree right 13 one flops with 13 five swaps with nine we'll keep doing this that's one we have a wire loop here that's the idea now let's hit submit and see all right also accepted 100% one yeah those are also accepted 100% one yeah those are also accepted 100% one yeah those are the two solutions time complexity wise it's Owen square for both algorithms and space contacts and wise is also a one for both algorithms very interesting problem I hope this video helps you understand this and this video actually takes me three times longer time to make at it and put it online so all that I ask you is just drop me a like just smash the like button and subscribe to my channel that's going to help a lot with the YouTube algorithm I and I really appreciate it I'll see you guys in the next video
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
188
hi guys hope you're doing great our today's question is person to buy and sell stop for so the question says here you're given an array for which the ayat element is surprise the for given stock one day I design little want them to find the maximum profit you may complete at Milewski transactions you may not engage in multiple transactions at the same time that is you must sell the stock before you buy again okay so we can complete at most k transactions which will be a value given to us apart from the prices array and this question would follow the same concept that we have discussed in the other question which is best time to buy and sell stock three which is about being able to make at most two transactions so I strongly recommend that you go and watch that video first in order to be able to completely understand this solution so as discussed in the previous video about two transactions this solution will be mostly around generalizing that solution to K transactions right so there we wanted to find the relative values of the four values the first buy for sell second buyer and the second sell so here we will have case such values and we will maintain an array of those values for buy and sell and update them as we go through the prices array right but there's just one extra thing to look at so if I have prices of length 10 okay and my K is more than ten by two right so in that case or more than or equal to K by 2 in that case it is as good as me being able to make any number of transactions right because if I have n days the maximum number of transactions that I can make is 5 right I have to buy and sell and buy himself so what we'll do is that feel check for that first and if that is the scenario then we will just rewrite the code that we do for offer for the condition where we have prices given with any number of transactions that we can make and otherwise we will go for the generalization of the best I meant by a self stop 3 solution okay so let's look at the base conditions so first we need the length cement equals to crisis dot length yeah now if length is less than or equal to 1 or if you said that we can make less than 1 or less than or equals to zero in that case we'll just return zero because you cannot do anything here right okay now the second thing that we need to check is about so we'll just need to initialize profit to zero and we'll just check that if okay so if K is greater than or equal to length by 2 length divided by 2 so what we're trying to say here is that if K is more than length by 2 right then we will just be able to so this becomes like a question for us where we have any number of transactions that we can meet so what we will do is that we have a profit in issue we'll just move through the array less than play minus one okay I plus and then the profit will just add prices oh you will have to check so we'll have to check that if prices of I is smaller than prices of I plus 1 right so the next day the price is more than today so we make a transaction right so we'll just say that ok then I plus 1 minus prices of I ok yeah so we just calculated in this manner and after that when we are done all we have to do is return profit and we are done okay now otherwise if that's not the case then you need to as I was saying generalize the solution for two transactions so we will just create by and it will be an integer of size key and we'll fill it with array arrays dot fill and we fill by with integer dot min values because we want to get started with whatever value we get at first right and we also create a cell which will be same and its default 0 so we don't need to do anything here ok then we will just start with our travursel so now with this particular current day we have to update all the buy and sell values because they are relative to each other and if we try to maximize all of them as discussed in the other problem with two transactions we will finally be able to say that okay sell of the K the transaction the K the sell transaction will give us the maximum profit okay so what we will do is that we will say okay J equals to 0 J less than K and J plus so 4x4 by of now we are so every time we are updating values we're like we are maintaining the buy and sell J because we have K values so every time the update will be updating the by of jr. so we'll just say that okay it's math dot max by J the previous value or so if this is the very first value then I don't have a previous transaction whose amount I can use to basically reduce or deduct this price of this day from right we don't have that so we just have to check that basically if my J is equal to zero okay if it is zero then what do I need to do is just zero minus the prices of I okay price is fine else we use the previous transaction ended at cell I minus one so that the amount of money we had after completing that transaction - the price completing that transaction - the price completing that transaction - the price of today because we are buying it so what we are saying here is that for by J either whatever we have in buy off J or if J is zero that means that this is the very first transaction that I am doing so then just reduce prices of AI from that zero minus prices of AI or otherwise whatever transaction I completed before this which will be cell I minus 1 right so that minus the prices of facts and I'll similarly will populate cell J which is equal to math dot max cell J okay and so we don't need to be worried about the zero condition here because we would have done the buy in the first place before this always so all we have to do is that will be used by of J plus because we are selling it so we get that bunch of money plus prices Phi so we just keep doing that and then at the end we return cell 3 minus 1 that is our last transaction of all the key transactions and that is the amount of money we have made out of them transactions we make so let's say that works we kind of missed a condition here somewhere oh yeah sorry it has to be J minus one because we're dealing with cheese right yep yeah that works so the time complexity for this is conditional if you have your K greater than or equal to the length then we're just making one traversal of the prices array so that becomes off in otherwise if we have to do this then we are making for each element in prices we are traversing from 0 to K so that becomes n into K where n is the number of days like number of elements in the prices and K is the given K so I hope you guys find this video helpful if you do please like share and subscribe keep coding into K pets
Best Time to Buy and Sell Stock IV
best-time-to-buy-and-sell-stock-iv
You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `ith` day, and an integer `k`. Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** k = 2, prices = \[2,4,1\] **Output:** 2 **Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2. **Example 2:** **Input:** k = 2, prices = \[3,2,6,5,0,3\] **Output:** 7 **Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. **Constraints:** * `1 <= k <= 100` * `1 <= prices.length <= 1000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Hard
121,122,123
1,673
welcome to january's leeco challenge today's problem is find the most competitive subsequence given an integer array nums and a positive integer k we turn the most competitive subsequence of nums of size k now an array's subsequence is a resulting sequence obtained by erasing some elements from the array now we define a subsequence a is more competitive than subsequence b if in the first position where a and b differ subsequence a has a number less than the corresponding number b so for example if we have one three four and one three five one three four is more competitive because the four here is less than five now that's just a fancy way of saying the lower number right and really what we're trying to do is find the lowest possible subsequence here now they give you example here with 2 3 or sorry 3 5 2 6 and with a length of 2 the answer is going to be 2 6. now here's like every set of possible subsequences and this is kind of a red herring you might be tempted to start off by generating combinations and then find the lowest one out of that but we can't do that okay combinations isn't going to work here because this is a subsequence so the order actually matters so if order matters probably the better way to do this is to generate a stack using a stack approach we could add to our stack and whenever we find a number that is less than the last digit or the last item on our stack we pop that item off and we do that until that condition is not true anymore and then we add it to the stack so here we'll add three to our stack then five but then two is less than five so we pop off five and three is also less than two so we i'm sorry two is less than three so we pop off three and finally two is going to be left there the next six that's gonna generate two six there so that's pretty standard what we would do is use a stack and say 4n in nums we'll have a while loop while there's a stack and stack last item is greater than our number that we want to try pending we will pop it off and once this condition is not true we just add to our stack here and this should give us the lowest possible subsequence um but this isn't going to be enough like this might work in some cases for example with this example should work two six but what if we had something like two one this wouldn't work because what's gonna happen is we will pop up everything like put up until the one but we need our length to be at least two right so this is not correct so how can we account for this uh well the very first thing we probably want to do here is we just we don't return the k items on the stack because we can have more and we only want to return the length of k here so we can use that to do that um one way we can make sure that we aren't going to pop off any more than we can is uh get the length of nums subtract by our length and that's going to be the max number of items that we were allowed to pop off because at a certain point we're really not supposed to pop off anymore because our stack has to have at least a length of k here so what i'll do is call this m and this will be the length of nums and we're going to subtract k here these this is the max number of items that we're allowed to pop off so as long as the m is greater than zero we'll also subtract one from m each time we do that this is going to allow us to make sure that once we hit a point where we can't pop off anymore we're just going to add whatever's left and that's going to work because we want this to be a max length of 2. looks like i missed something up here while stack okay oh i'm sorry it's not from k it's up until k right and that should work let's go and submit this and there we go so this is an oven time complexity with ofn space it's pretty constant space and that would be it all right so thanks for watching my channel and remember do not trust me i know nothing
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
8
Hello everyone, today we do daily properties, problem number one student teacher is that keep that stick straight and we have to wait and whatever stain was taken was between zero to 200 and whatever system you have in that. In that or you can go back, you can go to the positive side and on it, any other base invalid string has also come, which means its decisions are taken, it means like the owner is there, if the fire brigade's investigation has reached, then we do the investigation on the 45th over, if plus .com will do the hard work, fine, similar, if plus .com will do the hard work, fine, similar, if plus .com will do the hard work, fine, similar, if - there was a profile, what do we do - - there was a profile, what do we do - - there was a profile, what do we do - sitting on the sofa, through the guest, we have the wrong England specific negative, this platform ₹ 500 votes, if anything suits me, platform ₹ 500 votes, if anything suits me, platform ₹ 500 votes, if anything suits me, then you have to select it, as long as it is Vaseline As if he is invalid, we will return him. Okay, Papa, subscribe to Augustine. If you have given then the edifice will not come. Okay, Pitwana is deleting it. All that should be added. It is as if I will fight. You have to go to the dance class. If you want the details till now, then we are in this. What do we do? First of all, okay, we have a function called Market. Okay, in this, first of all, we create a personality, Invalid Char, who will fight for Broke, how many children are there, Android is telling, wait, we will expand, we have to do internet, channel this trick. This will be the result of the test, we will start the oil in it, then there is one more part which will tell this number which is plus, if so, here we put a fine, we were checking that it is a complex space, so you ignore it and let us tell you, okay. This was done and then shared here that if the character is on the positive side, if the story has positive words, then go ahead, otherwise if there is a meeting tomorrow, then I request you to move ahead in the form of 'okay', move ahead in the form of 'okay', move ahead in the form of 'okay', finished the table and Political Science Fiction has been done, now after that we will check whatever digit is there, if he is tired of what we have, the one who had given the chapter says that the owner is wi-fi fine, then says that the owner is wi-fi fine, then says that the owner is wi-fi fine, then when there is more digit, then his is yours, which I have done. It is zero and will not feel okay, what has been done in this is isolation and fiction value, whatever it is - 06 size, which is its value, whatever it is - 06 size, which is its value, whatever it is - 06 size, which is its value - if we have done it, then we will be responsible for it, value - if we have done it, then we will be responsible for it, value - if we have done it, then we will be responsible for it, because if Hanuman ji had decided on tuition, then who would have faced the difficulty? You should check the condition of swayamvar here, whatever is there will be lift, power burst, one minus one and two take off - from 30th shutdown itself, if the burst, one minus one and two take off - from 30th shutdown itself, if the burst, one minus one and two take off - from 30th shutdown itself, if the usage number goes beyond this, then we should cool them that overflowing is happening and in such case. When we have the posting number then we have to deposit it in HE Metro, if it is negative then we have to set it as natural, right, our mother is a meeting loot is inside this and the properties, we check here, what problem should we set at that time? Printer 's sweater back match when you want to tell if we 's sweater back match when you want to tell if we 's sweater back match when you want to tell if we assume how much maximum interest we have which we have this season's most metro increase is 2147 486 now what we have taken is Motors Maruti will be done founder it's absolutely fine If we keep this in mind, if this is whatever recent start I have, if it comes more than this, then that means I will do it. The quibble is the condition, why because when this value of Mario has now become the face, which is going to be given to him in the future. Give it tight whenever you want to add inches, it is anything from zero to time, okay kill it here, what will happen if it becomes too much, meaning that if massage 6565 Rajesh that sexual object will come that is it is quick. That if the value stored in the result will be more than this because if it is more than this then we will put the digit like this and in this the higher value will be a little bit more and the day it is not put or will take because of my flight. It used to be that one condition was taken by us and the second one has been demonstrated that - taken by us and the second one has been demonstrated that - taken by us and the second one has been demonstrated that - What is the result? It is so good. In the result in the result, we have that the value of these t-shirt max value and we have that the value of these t-shirt max value and we have that the value of these t-shirt max value and diesel is sorry maths volume. Karmapa is airteling that. We have this green chilli sorry here also we had to see this here also bike happened tips here what we have kept that yes here what we had here we had to do bike stunt I have this rally white pearl I have this and then to happen Took back the digit which is greater behind MS Word Vikram auto mechanic reaches the opportune time Grass 737 will come and I will see whatever digit is there which meter to put next to it if it is the highest then it will start ok this condition So this research is equal to maximum value boil change it is white reddy jhamku has to be added he is dipped in its mode of merit oil change molu how much extra will he get if it exceeds this is tattoo this is so I am adding selected we star As can be posted on the website below, but suppose the applicant goes to Varua, then this is the clothes of America, how can I say, you get it printed, if Surgical Pune means question number, then now we should put a limit in it, otherwise apply it at minimum. If this word is not there then what should I do for the result? You keep the table and get the result done by Inter Airplane Mode of Medical Research into Science. If you have any doubt then message me on WhatsApp that I
String to Integer (atoi)
string-to-integer-atoi
Implement the `myAtoi(string s)` function, which converts a string to a 32-bit signed integer (similar to C/C++'s `atoi` function). The algorithm for `myAtoi(string s)` is as follows: 1. Read in and ignore any leading whitespace. 2. Check if the next character (if not already at the end of the string) is `'-'` or `'+'`. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present. 3. Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored. 4. Convert these digits into an integer (i.e. `"123 " -> 123`, `"0032 " -> 32`). If no digits were read, then the integer is `0`. Change the sign as necessary (from step 2). 5. If the integer is out of the 32-bit signed integer range `[-231, 231 - 1]`, then clamp the integer so that it remains in the range. Specifically, integers less than `-231` should be clamped to `-231`, and integers greater than `231 - 1` should be clamped to `231 - 1`. 6. Return the integer as the final result. **Note:** * Only the space character `' '` is considered a whitespace character. * **Do not ignore** any characters other than the leading whitespace or the rest of the string after the digits. **Example 1:** **Input:** s = "42 " **Output:** 42 **Explanation:** The underlined characters are what is read in, the caret is the current reader position. Step 1: "42 " (no characters read because there is no leading whitespace) ^ Step 2: "42 " (no characters read because there is neither a '-' nor '+') ^ Step 3: "42 " ( "42 " is read in) ^ The parsed integer is 42. Since 42 is in the range \[-231, 231 - 1\], the final result is 42. **Example 2:** **Input:** s = " -42 " **Output:** -42 **Explanation:** Step 1: " \-42 " (leading whitespace is read and ignored) ^ Step 2: " \-42 " ('-' is read, so the result should be negative) ^ Step 3: " -42 " ( "42 " is read in) ^ The parsed integer is -42. Since -42 is in the range \[-231, 231 - 1\], the final result is -42. **Example 3:** **Input:** s = "4193 with words " **Output:** 4193 **Explanation:** Step 1: "4193 with words " (no characters read because there is no leading whitespace) ^ Step 2: "4193 with words " (no characters read because there is neither a '-' nor '+') ^ Step 3: "4193 with words " ( "4193 " is read in; reading stops because the next character is a non-digit) ^ The parsed integer is 4193. Since 4193 is in the range \[-231, 231 - 1\], the final result is 4193. **Constraints:** * `0 <= s.length <= 200` * `s` consists of English letters (lower-case and upper-case), digits (`0-9`), `' '`, `'+'`, `'-'`, and `'.'`.
null
String
Medium
7,65,2168
1,406
hello everyone in this video I am going to cover the concept of dynamic programming using the problem stone game 3 so I'm going to tell you the step by step procedure how to approach a problem starting from the most easy recursive solution the most optimized dynamic programming solution so please go to the entire video to see how to approach this problem during an interview so let us see the problem statement says that Alice and Bob continue their games of bias of stone there are several stones arranged in a row and each stone has an Associated value which is an integer value Alice and Bob take turns while L is starting first on each player's turn the player can take one two or three stones from the first remaining stones in the array the score of the player is the sum of the values the stones he has taken the score of each player initially is zero the object of the game is to end with the highest score and the winner is the player with the highest score and there could be a tie as well the game continues until all the stones are being taken assume Alice and Bob's play optimally well written LS offense wins the game Bob if Bob this is the game and in all the other cases we have to turn tie so let us see the example the stones are 1 2 3 and 7 LS will always lose her first best move will be to take the three piles that is the first three the summation will be 6 now the score of Bob is 7 so Bob wins in this case then if we go to the next one alright so we can have the negative values as well so in this case LS winds s must choose all the three piles and the first move to win and leave Bob with the negative score ok in this example is a tie so I think I should go for the first example one two three and seven so what I'm going to do is I'm going to make a helper function so this function will return me the optimal move so let's say I am going to play the game so I will be having three options to choose one stone we choose two stones and to choose three stones from the start so I will try to choose one stone to stone and three stones and then see which one gives me the most optimal solution so let us say the array which is given to me is one two three and seven now I have three options so I will get one in this case because I am only choosing the first stone and the remaining array will be two three and seven this array will be passed on to the next player so the next player will be playing with this so this will get subtracted from one so this is my first option my second option will be to choose the first two so the summation will be three and the remaining array will be three and seven now this array will be passed on to the next player and he will make turn using this array so this will get subtracted and this is the second option that I have the third option that I have is to have the solution of the first three which is equals to 6 and then pass the remaining to the next player actually this is my third option now so this is what the current player is having the second player now second player will be playing optimally so he will be having three choices the first choice will give him two as the summation the second choice will give him five as the summation and the third choice will give him 12s the submission the added meaning in this case is 3 &amp; 7 the array remaining this case is 3 &amp; 7 the array remaining this case is 3 &amp; 7 the array remaining in this case is 7 only and here the air is empty now if we expand this so this will also get branched in 3 actually only in 2 because we are having only two stones so we are choosing the first tune only 7 remains then we are choosing the first two stones which gives us 10 and the area is empty now in this one we don't have any further option of branching because it will give 7 itself we are choosing the first one so from here the answer that we will be getting is minus 1 from here the answer is 10 from here the answer is 3 minus 7 which is equals to minus 4 the optimal is 10 so 10 will be returned 3 minus 10 is minus 7 so minus 7 will be returned from here okay we can further expand this by expanding this we will be getting 3 as the summation and 10 is the summation and an empty string or while here 7 remains so this will return as minus 4 again so the answer in this case is minus 4 and in this case is 10 so we have to return 10 we're running 10 to minus n is minus 8 the first option will be minus it here the option is 5 minus n which is minus 2 here the option is 12 so we will be returning 12 from here and 1 minus 12 is minus 11 so minus 11 in this case so these are the three options all of them are negative so in this case we can say that this was the move given to Ellis has three possible options those options are minus 11 minus 7 and minus 1 the best among these is -1 so the final the best among these is -1 so the final the best among these is -1 so the final score of Ellis is -1 this score is score of Ellis is -1 this score is score of Ellis is -1 this score is Alice's summation - Bob's summation so Alice's summation - Bob's summation so Alice's summation - Bob's summation so it basically shows that Bob can collect more number of stones than Ellis so always Bob wins the game so this was the recursive solution so one thing that we notice here is that there is an overlap so where did we see the overlap was found here okay so the overlap was here 3 &amp; 7 was the remaining overlap was here 3 &amp; 7 was the remaining overlap was here 3 &amp; 7 was the remaining 3 &amp; 7 here also it was remaining then 7 3 &amp; 7 here also it was remaining then 7 3 &amp; 7 here also it was remaining then 7 was remaining here 7 was also remaining here so these were certain overlaps which we could see so we now have a slight hint of dynamic programming here now first we look at the code how to code this problem using recursion then we will try to optimize our code using dynamic programming so let us move on to the pouring part so as I told you I am going to create our helper function which is going to return us the optimal solution for a particular player so this is my helper function I will be passing on okay let me change the variable name to s vector of string we do this and an integer I so this ID knows us the first position of the first stone so initially I is zero so this I initially I is 0 in this case I is 1 in this case I is 2 in this case I is 3 so this is I is noting as the starting point if I is greater than equals to L store size in this case there are no stones remaining so we have written 0 else we have three options so let us initialize our answer as int min we are going to optimize our answer so we are in initializing it with int min so answer is equals to maximum off answer comma s of I because we are taking the first two - the I plus 1 so taking the first two - the I plus 1 so taking the first two - the I plus 1 so we are passing one the turn to the next player next we have if I plus 1 is smaller than a store size so in this case we can have another option maximum of answer comma s of I plus 1 minus help of s comma I plus 2 the third option would be if I plus two is smaller than a stored size the third option is adding the first three values okay so we have to have done answer if we call the same function for LS into LS is equals to help of s comma zero so this will give us the difference between as his score and Bob's score if this score is greater than 0 that is LS f more number of zones we have to return LS as the answer if this is equals to zero that is there is a tie the last options that Bob wins the M so we have done Bob okay so this is the problem I think now we should compile alright so we are getting correct answer for this test case let us try to submit this should give us time limit exceeded all right we are getting tle now moving on to the next optimization which is to convert this recursive solution into a top-down recursive solution into a top-down recursive solution into a top-down dynamic programming solution so we are going to create a DP array of size what were the constraints given constraints for 50,000 so we are going constraints for 50,000 so we are going constraints for 50,000 so we are going to create this DP then utilizing this TP with minus 1 if the DP of this eye is not equals to minus 1 we have to return DP of I because the answer is already present and simply storing the answer for each eye let's see if it works alright it is working so we see that the solution what accepted now once we are done with this we are going to convert this problem phone top-down dynamic programming to bottom top-down dynamic programming to bottom top-down dynamic programming to bottom and dynamic programming for this we need to see that how this DP era gets filled so this DPR is getting filled for the 4i which is greater than exercise the BP 0 the answer is 0 we can say that then for each eye we are using the DP for I plus 1 the DB for I plus 2 nd P for I plus 3 so to fill a particular dpi we need 3d piece the I plus 1 at the I plus tooth and the I plus 3/8 so now we are going and the I plus 3/8 so now we are going and the I plus 3/8 so now we are going to convert this we are creating vector of inte D P of n plus 1 size and initializing this with 0 then int I is equals to n minus 1 while this I is greater than equals to 0 we can simply copy this code and try to make changes in this one so instead of help we will be using DP of I plus 1 DP of I plus 2 is 3 finally this Ellis is VP of zero the rest of the code remains same and we are getting rid of this part okay so we forgot to do I - - so it got accepted the next step is to see for further optimization so what we are doing here is to fill a particular DP let's say to fill DP of I we need DP of I plus 1 DP of I plus 2 and DP of I plus 3 so these are the only three things we need to have so even if we have a DP array so let's say this is the DP airing and these are the entries to fill this particular entry we need this one and this one is not required to fill this one we need only these three and the rest of them is not required so anytime we are going to require only these three so instead of creating the entire DP array it could be as large as 50,000 array it could be as large as 50,000 array it could be as large as 50,000 what we can do is we can simply have 3 variables so instead of using so much of space each time we can solve this in constant space so we are going to optimize this we are keeping instead of this we are keeping only three variables int let's say this is i1 this is for I 2 this is 4 I plus 2 and then I plus 3 so these are the three variables which you are going to keep all of them initially is 0 we will be using PI 1 in this case I - and in place of gp3 i3 will be equals to I 2 pi 2 will be close to PI 1 and I 1 will be close to answer this is basically in this case this is IA one so we see that we used constant excess space and you are able to solve this problem so the steps that we saw were first one the recursive solution the second one top-down dynamic programming second one top-down dynamic programming second one top-down dynamic programming so we adjusted the code accordingly the third step was to convert from top down dynamic programming to bottom of dynamic programming bottom-up then from bottom programming bottom-up then from bottom programming bottom-up then from bottom up the final step was the optimization space optimization so these are the four steps which we need to follow to approach any dynamic programming problem during an interview you have to go from the recursive to the dynamic programming to the bottom up and from bottom of finally to the optimization the final solution was constant space solution this was in terms of space and Big O of n in terms of time this was Big O of n in space and Big O of N in time and talked on was almost the same it is bottom up is slightly more optimized but the complexity is same so if you liked the video please subscribe to the channel and please share it with your friends thank you
Stone Game III
subtract-the-product-and-sum-of-digits-of-an-integer
Alice and Bob continue their games with piles of stones. There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`. Alice and Bob take turns, with Alice starting first. On each player's turn, that player can take `1`, `2`, or `3` stones from the **first** remaining stones in the row. The score of each player is the sum of the values of the stones taken. The score of each player is `0` initially. The objective of the game is to end with the highest score, and the winner is the player with the highest score and there could be a tie. The game continues until all the stones have been taken. Assume Alice and Bob **play optimally**. Return `"Alice "` _if Alice will win,_ `"Bob "` _if Bob will win, or_ `"Tie "` _if they will end the game with the same score_. **Example 1:** **Input:** values = \[1,2,3,7\] **Output:** "Bob " **Explanation:** Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins. **Example 2:** **Input:** values = \[1,2,3,-9\] **Output:** "Alice " **Explanation:** Alice must choose all the three piles at the first move to win and leave Bob with negative score. If Alice chooses one pile her score will be 1 and the next move Bob's score becomes 5. In the next move, Alice will take the pile with value = -9 and lose. If Alice chooses two piles her score will be 3 and the next move Bob's score becomes 3. In the next move, Alice will take the pile with value = -9 and also lose. Remember that both play optimally so here Alice will choose the scenario that makes her win. **Example 3:** **Input:** values = \[1,2,3,6\] **Output:** "Tie " **Explanation:** Alice cannot win this game. She can end the game in a draw if she decided to choose all the first three piles, otherwise she will lose. **Constraints:** * `1 <= stoneValue.length <= 5 * 104` * `-1000 <= stoneValue[i] <= 1000`
How to compute all digits of the number ? Use modulus operator (%) to compute the last digit. Generalise modulus operator idea to compute all digits.
Math
Easy
null
983
hi today i'm talking about leak code problem 983 minimum cost for tickets this problem asks you to write a function that will take a list of days and a list of costs and so days works by having a number of days that you're going to want to have a train ticket for so in this example you want to have a train ticket that covers day one 4 6 7 8 and 20. and costs is always a three element array with the zeroth element being the cost for a one day ticket so a ticket that's good for just one day the first element is a ticket that's good for seven days and the third element is a ticket that's good for 15. so the problem is asking you to write a function that will take days and costs and return the minimum amount you would have to spend to cover days with um tickets that you purchase through costs so in other words we want to cover like here i have this example written out we want to cover days 1 2 9 35 51 so we could cover them all with one day tickets that would cost two plus two but possibly there's a cheaper way to cover all of these days using tickets that cover more than one day at a time so what we want to do is figure out yeah what's the cheapest cost and so when i was thinking about this problem how i thought about it first is i wanted to approach it recursively so when i think about recursion i think about the what's the base case and i think about what's the recursive case so the base is just something where we know the answer and the base case would be if there were no elements in my days list like i'm looking for zero days then it costs nothing it's free if i'm looking for just one day then what it costs is the minimum of my costs list so if for whatever reason it was cheaper to buy a seven-day ticket or a 30-day ticket than seven-day ticket or a 30-day ticket than seven-day ticket or a 30-day ticket than it was to buy a one-day ticket it was to buy a one-day ticket it was to buy a one-day ticket then sure i just need to cover my one day with the cheapest possible ticket and then if i have anything more than one day costs that will be my recursive case and i guess i'll just cover that slightly i just saw i titled this section base so the recursive case here what we're asking is how can we break this problem up into sub-problems so up into sub-problems so up into sub-problems so the sub-problems get closer and closer the sub-problems get closer and closer the sub-problems get closer and closer to our base case and how i've illustrated that is i've just shown that okay we can think about the cheapest way to cover this whole list of days is going to be the cheapest way to cover the first section of days plus the remaining section so when i say the first section that's variable it could be one day it could be um seven days which would cover one and two could be 30 days which would cover up to nine so what's the cheapest way i can cover that section plus the cheapest way i can cover all of the remaining sections and so if i think about it like that then i can just divide this up to be recursive so let's take a look at implementing that what i did is i have here's the function that leak code requires me to write and i'm just going to call into my helper function cheapest cost i'm going to start it off with a 0 for the starting index and i'm going to supply actually this is slightly more complicated than it needs to be let me go to my first successful submission um and that will be a bit more clear i wrote it a bit differently just to be more performant so okay i'm going to call my cheapest cost function which takes a tuple of my days and my costs and the reason for converting the days and costs lists into tuples is because tuples are immutable and therefore they can be used as the key in a dictionary because they're immutable whereas a mutable list cannot be used as the key in a dictionary and i will want to use these items as keys in a dictionary for when i do memoization to speed up the recursive case okay so here's my cheapest cost function up here on line nine and what it says is i'm going to compose this tuple of my days and costs list if this is already in my souls solutions dictionary then just return the value that corresponds to this key so this is what i was talking about with memoization because the recursive case or because recursion may require me to recompute things that i've already computed so what when i compute this list of one when i next compute this sub list and this subsection i'm going to be recursively making calls that i've already calculated which is the point of checking to see wait have i already considered this pair of days and costs in my solutions dictionary and as i'm looking at it right now i realize i don't need to add costs are always the same i'll talk more about that in a minute but anyway that's the purpose of this memoization what it does is it speeds up the recursion by make by obviating the need to recalculate things that i've already calculated okay this is the base case i mentioned before i have less than one day so then i can just return zero i suppose there's another base case for um if i just have exactly one day although it can be handled by the recursive case as well so there's no need to special case that actually and so here i am with the recursive case i just store the minimum of and then this is just going to be a sequence of three items three options so the minimum of cover the first day um sorry cover one day from my days list cover seven days from my days list or cover 30 days from my days list so it's going to be the minimum of calling the cheapest cost with the first argument the days list being the result of calling my cover function um with cover 1 cover 7 cover 30. and to just show the cover function it's up here on line five it's just going to say okay starting from the first day in the list return a tuple of this generator expression which just says um all the days that have a difference uh from the start day of more than seven so basically we're just cutting out i'm sorry of more than in not more than seven so n is one of the arguments supplied so if i supply this with one it's going to cut out all the days that um have a difference of less than one with the start day so basically i would cut out the start day for one if i sent in seven into my cover function then i would cut out all the days that have a difference of less than seven from the start date so this is not the most efficient solution and actually when i ran this it ran in something like well i guess 44 um for speed um i thought it ran slower than that but i guess it did not but 44 for speed is not the best we can do um the best i got it up to was here where it was something like 87 for speed and so the way i got it to go even faster is largely by improving the memoization part and by changing the cover function so when i say improving memoization you may recall in my previous example let me show you my slowest solution in the slowest solution the key in my memoization dictionary was a tuple of the days and costs so that requires me to construct a tuple of these two other tuples and it requires every time i look up like is this key in my solutions dictionary every time i look that up i've got to hash this key and hashing the key could be relatively expensive given that it's yeah a tuple of tuples and i don't know how long they are for example they could be any length so this is a relatively small cost but it is a cost and so what i've done here when i've sped things up is i replaced my key it's no longer a tuple of two things of two tuples it's just the starting index so i just refactored this code a bit to use an index instead of modifying the days list so instead of cutting out a day every time or seven days or 30 days i just cut out an index to say okay start considering from the zero position of the day's array this seven position of the day's array whatever position i want to so i don't actually have to cut up the days i just have to adjust the starting index so the key is simpler so looking up in the solutions dictionary is faster and then the big performance improvement from using start index is that my cover function no longer has to generate a new list so i no longer have to make this check for every day in my days list so this is kind of an o of in operation to call my cover function or it was in the slow version but here we can just reduce that to what we do is we just say okay our start is the starting index of my days array um my result is going to be the starting index as well the length of my day list while our result is less than the length of my day's list so while we go through the whole day list and days sub result so the day of my current result less the start value is less than in the number of days i'm trying to cover then i'm just going to increment result so this is just going to push result up to be essentially the new starting index and if that wasn't clear you know maybe i can just illustrate that here um you know we can say our days are zero one uh five and i guess we'll say nine two just so we have one decent example okay so my starting index is going to be zero i'll write that below so s i is zero okay so while days sub zero and let's say we wanna call cover um for seven days so okay while my days sub starting index um less the start value which is zero while that is um less than the number i want to cover in well that's less than seven because we're calling cover of seven then we're just going to increment result i'm going to increment um yeah i guess i should say result as zero because result will um uh have the value of starting index when we start out okay result is zero good so we increment result and we're going to push it up to one um increment result to 1. okay 1 minus the starting value is still less than 7. so 1 minus the starting value is that's still less than seven okay we're going to increment um we're going to increment result again so that's up to two send that up here okay result days sub result less day sub start that's still less than seven so we're going to increment it again okay days sub result less starting value is now nine that's not less than seven okay so we're going to return three as my new starting index um i realize that's a messy drawing but hopefully you can just see the logic that i'm trying to illustrate there and so that's a bit more complicated to talk about and maybe to reason about but it has the benefit of being substantially faster so this was 40 milliseconds for the slightly more complicated version compared to what was 136 milliseconds so you know we're substantially dividing the speed um and then i realized i'm going a bit long but i also wanted to just start talking about things i learned while um working on this problem so one thing i learned was uh you know read more carefully and this is probably something that can apply uh generally not just to this problem so i expect if i continue to list my lessons for problems that um i may see some repeats but the problem for me was that when i read this i was a bit careless and thought that it just i don't know why i thought this but i thought that days was limited to be the days of a month so they have an example here with 31 days so my first attempt at a solution you can see i actually hit the time limit exceeded and that surprised me because i had i thought i was doing i thought i had tested it with the max input value i thought i had tested it with 31 days and my code worked so i thought like oh cool that's fast enough um but actually you know they say very clearly that the constraint is days should go between 1 and 365. so i hadn't tested the max case i just tested like a very small version of it and that's why i tried to submit code that was way too slow and i think what i submitted there was just this solution but without the memoization at all so i thought like oh i don't even need to do memoization that's cool um but then i immediately failed so that wasn't good um that leads to the second lesson which is test the worst case so if you're explicitly trying to test the worst case and for me that would have solved my problem i wouldn't have submitted bad code once so i would have said okay what is the worst case um i would have checked it would have said 365 and then i would have failed my test case as opposed to failing the submission and then the third thing is the key and memoization so i talked about this before and my i was pretty careless about what i was going to use as the key for my memoization um so yeah in my early submissions i just have costs in there for absolutely no reason in my early solution i was shortening days but i didn't even need costs at all yeah because it's constant and in fact i don't even need days to be the key i can just use the starting index that's a simpler key and it means that the code will be written such that i don't have to change the list so with a bit more thought i could have just written um the faster version of the code the first time um and that would have been better okay that's it for me if you enjoyed this let me know by clicking the like button if you want to see more content in a similar style you can subscribe if there's something you want to see in particular please leave a comment or leave a comment just let me know you're watching thank you bye
Minimum Cost For Tickets
validate-stack-sequences
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`. Train tickets are sold in **three different ways**: * a **1-day** pass is sold for `costs[0]` dollars, * a **7-day** pass is sold for `costs[1]` dollars, and * a **30-day** pass is sold for `costs[2]` dollars. The passes allow that many days of consecutive travel. * For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`. Return _the minimum number of dollars you need to travel every day in the given list of days_. **Example 1:** **Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\] **Output:** 11 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1. On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9. On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20. In total, you spent $11 and covered all the days of your travel. **Example 2:** **Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\] **Output:** 17 **Explanation:** For example, here is one way to buy passes that lets you travel your travel plan: On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30. On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31. In total, you spent $17 and covered all the days of your travel. **Constraints:** * `1 <= days.length <= 365` * `1 <= days[i] <= 365` * `days` is in strictly increasing order. * `costs.length == 3` * `1 <= costs[i] <= 1000`
null
Array,Stack,Simulation
Medium
null
337
hi all today we'll be talking about a lead code problem house robber 3. let us go through the problem statement first the thief has found himself a new place for his thievery again there is only one entrance to this area called route besides the route each house has one and only one parent house after a tour the smart thief realized that all houses in this place form a binary tree it will automatically contact the police if two directly linked houses were broken into onto the same night given the root of the binary tree return the maximum amount of money the thief can rob without alerting the police so basically this question is a continuation of the house robber problem where in the previous problems the houses were arranged linearly or in a circular fashion however here the houses are arranged in a binary tree the pro the constraint remains the same that the heart that the robber cannot rob two houses which are directly connected let us go through the first example here the thief has the has two options it can drop the route and then since the root is robbed it definitely cannot drop its children so we'll skip the nodes two and three and then go to its children uh go down one level so the total profit the thief can make in this case is 3 plus 1 which is 7 and the other possibility is the ru is that the thief did not drop the root node it robbed its children and in that case it would make a profit of 2 plus 3 however it cannot drop the nodes at level 3 again because its parent is robbed so the total profit in that case would be 5 however the payer profit of 7 was greater so it will rob the root node and these two other nodes in the second example if it drops the root node it will have a total profit of three plus one plus three plus one which is eight and if it doesn't drop the root node and goes for its children it will have a total profit of 9. so the answer is 9. we can again we might think of robbing on alternate levels starting once we drop the root node and once without robbing the root node but that wouldn't give us the correct answer suppose if we had a node the root node had a value of 100 here and there was another level fourth level with one node with value hundred the maximum profit in that case would be this hundred plus that hundred which is two hundred rather than going on alternate levels so we make two observations here that if the parent node if at the node we are currently at if its parent is already robbed if its parent is dropped and the thief has no option that then he has to skip the note he cannot rob two consecutive houses so if the parent is robbed there is no choice rather than not robbing the current node and if the parent is not robbed the thief has two choices now he could either rob this house or not drop this house we will explore both the options and see which gives us more profit and we'll con and we'll take the maximum from both the possibilities of robbing and not robbing when the parent is also not dropped so let us get into code we'll do the basic check here that is if root is null we'll simply return 0 otherwise field to recursion i'll write a function record here which will pass in the root and it will take a boolean variable which will tell us whether the parent is robbed or not dropped because that is the only information we need to make decision for the children nodes so for the root node since there is no parent we'll pass it as false that its parent was not dropped because to explore both the possibilities of robbing and not robbing the root node then we'll write this function wrecker tree node star root and boolean f denotes whether the parent is robbed or not dropped we'll do the basic check root is equal to null we'll return zero otherwise we keep two variables one for robbing case and one for not robbing case so if our parent is robbed if the parent is robbed the thief has no option but to skip this node that is it will go into the not robbing case and it will simply record for its children that is root dot left and what information will be passed to the children of this node will get the information that the parent was not robbed because its grandparent was robbed so the parent was not robbed so we will pass the information of false here and then we will recker again for the right child and we will pass the information that we were not robbed the current node that we are at is not rock because its grand parent because its parent was robbed else we get into the case where the thief has two choices either to drop the node or to not drop the node because its parent was also not robbed so if we go to the not robbed case it will again be the exactly same condition that we wrote here that we'll ask to our children that we were not robbed and will reckle for the children of the node however if we rob ourselves like if the thief drops this node the value of this node will get added to the overall maximum profit that we are attaining and then we'll go into recursion for the root dot left and we'll go into recursion for root dot right and in this case since the thief has dropped the current node its children should know that the current road node was robbed so the children node should not be robbed so we will pass the information of true here to signify that the parent that the current node is robbed which will become the parent in the next recursion finally we want to return the max of robbed and not robbed case let us try to compile this result and we will try to submit this so this will give us time limit exceeded because we have written a recursive solution and the number of possibilities to explore are a lot since the number of nodes could be 10 to the power 4. we need some kind of memoization here to make it a bit faster so we'll keep a map to memoize a result suppose we reach a node and if we have already reached this node previously we don't want to compute for it again we'll simply return the answer that we have memoized in our map so we'll memorize the answer for it in our map we'll keep a pair of boolean entry node and an end the pair of boolean and tree node signifies that the tree node is the current node we are at and the bool signifies that whether it is the robbing case by which we have reached the current road or a current node or the not robbing case by which we have reached the current node and the value for this map will be an individual with the answer the maximum value that we obtained at this particular node it will store the answer at this node so if here we'll check if our map dot find make pair of f and root equals to sorry not equals to and p dot and that means that this node was visited previously so we will return mp make pair of f and root and here we need to put the value that we have got in our map so we will put the value of map make pair f and root as not drop similarly here we'll put in the map of make pair f and root as max of rob and not drop looks good we have a moisture result let's try to compile this tree node okay then should be capital looks good let us try to submit this it is successful so we saw that recursion with basic memorization gave us an accepted answer thank you so much for watching
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
107
everyone welcome to another one of my league code videos and in this video you talk about number 107 which is binary tree level order traversal 2 so if you haven't seen the video on the binary tree level order traversal 102 I recommend watching that first because that gives an example of what in level order traversal is and also the algorithm in this video we're just gonna make one modification to that algorithm and make it work for this case so the previous one was a level order traversal from top to bottom so it was basically 3 9 2015 7 in the reverse order and in this one they want a bottom-up level this one they want a bottom-up level this one they want a bottom-up level order traversal so basically they want to go from 15 7 first 9 20 and then 3 so it's basically bottom up so again if you haven't watched the previous video go watch that one because that explains the whole thought process but if that in that video we ended up with this algorithm for the level order traversal now I'm just gonna make one change to it which is here when we add or the result to the result list we're gonna be finding the first one first right so every time we find something we're just gonna add it on top so instead of adding it at the end of the list we're just gonna add it on the top of the list and that should solve this problem so 0 is basically the index and then this is the result list so with this I think this should solve this problem yes it works and let's type submit' cool yes it works and let's type submit' cool yes it works and let's type submit' cool make sure you're subscribed to my channel and let me know if there's any other videos you want to see I'm happy to do them on demand as well thank you for watching
Binary Tree Level Order Traversal II
binary-tree-level-order-traversal-ii
Given the `root` of a binary tree, return _the bottom-up level order traversal of its nodes' values_. (i.e., from left to right, level by level from leaf to root). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[15,7\],\[9,20\],\[3\]\] **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
102,637
92
hello everyone welcome back here is van damson and today we are diving deep into fascinating data structure problem reversing a service within a linked list so you would be surprised how often this question like this come up in technical interview so uh let's get started but before we jump in if you are new here hit the Subscribe for more coding Adventure alright let's talk about the problem a bit we have a singly linked list and two integer left and right and our task is to reverse the sublist from position left to right simple right but here is the catch we need to do this in a single traversal now this might sound challenging but that's where the fun begins so today we are going to explore multiple ways to solve this problem starting with the most efficient one using two pointers so this method is a OnePlus solution which means we are not coming back we are going through the list just one so a two pointer method is super efficient and we will use this two pointer to Traverse and manipulate the linked list I have all in one go so the idea here is to handle the dummy node to edge cases making our cut more robust and elegant and we will also use Python Tuple unpacking to make our code as pythonic as possible so let's get into coding so first if not had or left equal right then return hat and then we have dummy Lincoln node zero hat and also previous dummy and four range left minus one previous will be previous next and current will be previous next four arrange right minus left we reverse so our next note will be current next and next note next will be previous next and next note will be next and previous next will be and next note okay and finally we return dummy next see yeah okay so now all good let's run it to verify I didn't make any typo okay as you can see we reverse this linked list so here is example one two three four five and we are requested to reverse it from left to right four so it's just a those notes and uh yeah we can exemplify this so we are reversing from two so here is Note 2 to Note 4 and 2 goes here three here and four uh here so uh it's in reverse order so uh yeah everything work and just like that we have solved the problem using a single pass through the linked list and that's the power of uh two pointers and a smart pointer manipulation so I will also provide a code for other languages like rust go C plus in the description below and in terms of complexity analysis we are looking at oh and time because we are then going through the list just once and all one space thanks to our clever uh pointer manipulation so also let's run it for on synthesis cases to verify it's working yep all good our implementation a bit 50 and 91 with respect to our memory uh so all good and yeah it took 42 milliseconds I think uh the best one I run was even 32 or something like this so to recap we use two pointers to Traverse and manipulate the link at least and it's in a single pass and we use a domino to elegantly handle those edge cases and Tuple unpacking to make our cut more a pythonic so all right that's all for today I hope you found this session exciting as I did and don't forget to like share and subscribe for more coding adventure and also let me know in the comments if you have any question or if there is another topic you would like me to cover and until next time keep practicing and happy coding
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
834
hey what's up guys this is chung here so it's lit called time again and today let's take a look at number 834 sum of distances in three this one is a really tricky problem and it's a hard one it's really it's kind of hard and the solution is hard it's really hard to come up with all right anyway let's take a look so you're given like an undirected connected tree with unknowns labeled from one zero to n minus one and then basically there are unknowns and n minus one edges so which means it's guaranteeing that it's a tree structure and the ice dice edge connects the node from h0 to h1 right so we have a for example we have this n equals to six which means we have six nodes and we have five address and it asks you to return at least an answer list whereas which is the list and where each element is the sum of the distances between the current node and all the other nodes so it means that you're we're returning an answer here so at each of the location at each of the element here it's the summarize of the distance from the current basically as the current node as a root right and the distance to from all the other nodes to the current root for example we have zero as root and the distance from zero to one is one from zero to two is one so here we have one and from zero to three we have two same thing for four we have two and for five we have two so the total is eight and for one right so that's for zero and for one we have from one to zero we have one for one to two let this root right one two we have two for one two three we have three and three so the total is nine plus three will be twelve so on and so forth yeah so basically that's the uh that is the idea of this problem and you know a brutal force way is simply just for each of the node here first we build a graph right we build a graph with each of the edges here and then we just choose from zero to n minus one as the as a root and then we for each of the root we do a dfs right to get the uh we do dfs to get the total distance for that route that's uh the naive approach i believe everyone can come up with right but the difficulty for this problem is that you know given like a number of notes here which is the one uh 10 to the power of four if you do a dfs for each of the note and basically the time complexity will be the end of a time of n square and it will tle for this problem so what's make this one a hard problem is that how can we improve that the performance and the way it works is really tricky you know so let's just use this one as an example okay so how can we improve that all right so here's the intuition here so we have zero right and 1 2 3 4 and 5. assuming we have already calculated the answer for zero right which we already did in this case is eight okay so that's the answer for zero let's try you know let's try to move the root from zero to two okay because one is a little bit of the special case you know since there's nothing under one let's try to move the this root from 0 to 2 which is like this answer right which is 6. if we if you watch closely you know moving from the root moving remove root from 0 to 2 what got changed basically there are like one two three four nodes basically as you guys can see we have two three four five and all these nodes are getting closer to the current root right because you know before let's say before the root is zero so the two to the distance for from two to the root is one for three two to the root is two four two is distance two five is also two and after moving the distance from zero to two now the distance for two to the root is 0 for 3 from 3 is 1 for 4 is 1 5 is 1. basically you know we have four nodes that gets closer to the root to the current root and on the other ha on the other hand we have what we have two nodes we have zero and one we have these two nodes which scat gets further right who are now further one step further away from the root so we have four here and then we have two here so with those two given numbers we can simply use those the base values to calculate the distance for the two as a root so the formula is like this so we have a base you know so we have a base right so first we miners the number the nodes the notes or you know the uh i'll just do this the closer notes how about this i don't know if it's a closer note right and then we plus what plus the further notes right you know that's the formula to calculate the uh the total distance for each of the roots and assuming we have we are using zero as a base right so as you guys can see from zero to two now as uh for two as a root the closer node is four right so we have because we have four nodes who gets closer to the current rule and we have two nodes that's gets further to the current roots and for those ones the number of closer ones we know okay we need to decrease the total sum and then for those who's further we know we need to increase that right so i mean the factor here is there they're both one here right i'm just removing that uh skipping that factor here times one so for 2 8 minus what closer nodes is 4 plus 2 is 6 which is exactly the number here right so then let's try another one let's try one here so for one how many num how many nodes who is closer to the current rules there's only one right because one is the only one there's one does not have any child nodes right so that's why we have eight miners minus one plus what and then how many nodes are fla against further to the current route is the uh basically you know the other side how can we get if we have the closer notes and how can we get the further note we just use the n right it's n minus one right so in this case it's a it's eight minus 1 plus what plus 5 which is exactly the answer 12. so same thing for 3 4 and 5. and also another thing and keep in mind that you know keep in mind the base here the base is not it's not always the zero so the base is the it's apparent base is the parent it is the value is the sum of its parent node so here is like the parent it's not the uh it's not the always the zero here that's why you know when we calculate 3 4 and 5 we have to use 6 as the base so now 6 is becomes to the base so why is that you know because since we're using like this formula right we need to know like how many nodes are moving closer to the node to the current roots and how many nodes are moving away from moving further to the current root so that's why we have to use the child comparing with its parent as a root so that there's only one distance difference that's why we can use this formula over and over okay yep so oh so okay let's see let's continue finish our calculation here so we have six right so now the base is six for three and the closer node is one plus what plus uh six minus one is five right six minus one which is what which is 10 right so that's exactly how we get 10 here same thing for four and five there are they're all there are 10. cool so that's the intuition and the next is how can how should we how can we implement so the way we're implementing is first we need to get the closer nodes right we need to get those nodes the closer nodes for each of the nodes here and the closure node is actually the uh the sub nodes what where the nodes that's the total nodes of the subtree right for example this is one and here the total uh the closer node for this two here is actually the total sub the sub nodes including this node itself right yeah and uh right so that's how that so that's why we need another uh we need a count we need the count array to store the other closer nodes where you whatever you want to call it for each of the node for you for each of the node you know uh assuming we are have like we're assuming this zero as a root you know we can use any node as a root to calculate the closer nodes but we have to stick with that but in our case since we are start starting from zero here i think it's easier to use just zero as the uh to calculate this closer root the closer node and once we have that and also while we're well while we're calculating this closure node we can also calculate the answer for zero right which is eight and up and this is closer note for each of the nodes here and a base case zero sorry a base value eight for zero we can just do another dfs and then we just use this formula to populate all the other the answer for all the other nodes all right let's see okay so let me write the uh that's that formula right the uh the formula first so that we can we won't forget so the way we're calculating is that you know the parent sum right minus what minus the closer nose plus the further right so that's the that so that's the formula okay so now let's try to build the graph first so we have a graph equals default since this is a byte bi-directional since this is a byte bi-directional since this is a byte bi-directional right so i'm just using a dictionary of a list dict and list right and then we have a for u and v right u and v in the address then we have a graph u dot append v and also graph v dot append u so up to here is where just a very standard building graph code right and then the next one is we're gonna have like the first dfs is going to populate the values for the answer 0 and also the closer node the closer nodes for all the nodes as answered as this zero as a base which means right so that's for one is one two is four three four one three four five is one and for zero it's like it was six right so to do that i'm going to need like another array i'm going to use a count to store that so since we have unknowns that's why the length of count is one maybe i'll call it like how about this closer nodes closer notes count maybe how about this i know the naming is a little bit long but you know during the interview no longer and more descriptive var variable is much better than a b c and d trust me try to make the variable like self-explanatory that will help you a lot okay so that's that you know all right so the first time is the dfs and okay so i'll also define the answer here since we're going also to populate the values for the zero okay so still right so to get the uh the closer nodes for the content while also populating the zero it's just a regular dfs we'll just use the uh the bottom up dfs right so the way it works is that you know we have a closer nodes right equals to one i'll starting from one and then we have a non-local from one and then we have a non-local from one and then we have a non-local we have a count and we have an answer right so for child in graph current right since we are building like this graph as undirected so and we will need we also i'm also going to use like a visited set you know to make sure we're not revisiting the visited node again and visited dot sorry if child not in visited i think since it's better because scene only has four characters which visited where i visited has six okay i will use thing here in c and then first thing first we add this child to the scene child all right so that's that and we have what we have uh we have child nodes count right equals to what equals the df as child and then i'm going to closer nodes here i'm going to accumulating that everything for the current nodes because for each of we have to collect all the other nodes basically and under this current nodes right that's why i'm going to use this thing to plus that and since we are we're calculating the uh and since we're returning these nodes we're returning these closer nodes so that the other dfis method can keep using it uh to since we're only returning this one values to determine to set the uh to calculate the values for the zero uh i have to use basically i have to hard code these things i have to set the answer zero right with the child this is child nodes count while for this closer nodes you know we're just using this dfs to populate that and for this answer here we are always we're always setting this zero because we are we're also calculating the answer for zero right so that's that you know and then after this for loop right we can simply check we can simply closer nodes count of current equals to what equals to closer nodes yeah so i said i starting from one started from one because the note itself also counts also needs to be included okay so that's how we populate the closer nodes count array while and also the uh the base the answer for our base which is the zero okay so that's the dfs right and then we also need to call the dfs so i'm going to visit it dot hat to zero so and then the dfs zero okay so that's how we uh here basically we are populating right populating closer nodes count answer zero okay with those things now we can just use this one to calculate the uh the answer for all the other nodes so to do that we need another dfs right so basically we have a dfs what dfs2 maybe just do a dfs2 here so now uh for the current right and then again we also need that for child in graph current right maybe we need another non-local i think maybe we need another non-local i think maybe we need another non-local i think local uh this time we don't need the answer we only need the answer so again we have to make sure we're not revisiting the same notes so now the answer of the child right so keep in mind so this one the current so this is the parent and this is the child so now the current ones so the cur is apparent and the child is the uh is the ones we're calculating because we're starting from zero which means the uh the zero is already calculated and now we're only using the parent one to calculate the answer for the child one which is the child right so this one is what is the answer of the parent so this one is apparent right so apparent minus what minus the uh how many the closer nodes so the closer node is what is we have already populated here closer count for the current child right plus what plus the uh the node who are moving further to the root which is the at the end minus the closer nodes right okay so that's for the current one always trial and we have to populate all the nodes that's why we have to do a dfs2 here and now the current child node becomes apparent right so we just pass this child nodes to do a recursive call okay so that's that now and i will just uh i need to reset the visited sorry yeah since i'm sorry not visited since i'm reusing the same scene set here i'm going to use a scene dot and then scene dot at zero okay now i need to do a df s2 right half zero so here we are using answer 0 as base to populate all the other nodes answer right so in the end we simply return the answer yeah i believe that's it let me try to run the code all right cool first time win or accept it submit all right so it passed and as you guys can see here i mean the time complexity for this solution is what so it's just the two okay so first we have a while loop but we have four up here to build the graph so we have on here and then we have a we just have one the first dfs and the dfs of course is o of n because we are only visiting each node once and then we have second dfs it's another o of n so the time complexity for this solution is it's o often right and the space complexity is it's also uh is also o of n for this answer and also for this closer count stuff yeah so i mean just to recap this problem real quick you know and i think for me it's hard i mean even for me it's hard i spend some time to understand this approach you know so the basically the way it works that you know you have to be a we have to be able to realize that you know after moving i mean with one answers as a base you know if we move the roots from one place from the parent to the child what so what got changed i mean i think this is another technique for us to master basically you know it's more it's a little bit it's i think it's kind of similar as a dp right because we are basically we're using like a base with a using a previously calculated result you know and then we're trying to use that one to populate to get the uh the values for the for each child and to do that we have to somehow i mean just bring it bring out like paper and pen and try to draw something you know let's say we have eight here you know okay assuming we move the uh we move from eight to two what's going to happen all right you see i think we just need to draw something and try to figure it out the pattern here and once you figure out the pattern and then you the next thing will become a little bit easier where you need to then you realize that okay so the next thing i need to know is that i need at each of the assuming we have eight and now we move from the zero to two here i need to know how many nodes below two here since i don't want to do it for each of the recursive for each of the uh for each of the nodes that's why i want to pre-calculate it so that's why i want to pre-calculate it so that's why i want to pre-calculate it so how can we how can i pre-calculate it how can we how can i pre-calculate it how can we how can i pre-calculate it i just use a separate dfs to calculate the uh the sub nodes for each of the nodes and with that and then i can just uh use another dfs to calculate all the other answers all right cool guys i think that's it for this problem i'll just stop here thank you so much for watching this video guys stay tuned i'll be seeing you guys soon bye
Sum of Distances in Tree
ambiguous-coordinates
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given the integer `n` and the array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Return an array `answer` of length `n` where `answer[i]` is the sum of the distances between the `ith` node in the tree and all other nodes. **Example 1:** **Input:** n = 6, edges = \[\[0,1\],\[0,2\],\[2,3\],\[2,4\],\[2,5\]\] **Output:** \[8,12,6,10,10,10\] **Explanation:** The tree is shown above. We can see that dist(0,1) + dist(0,2) + dist(0,3) + dist(0,4) + dist(0,5) equals 1 + 1 + 2 + 2 + 2 = 8. Hence, answer\[0\] = 8, and so on. **Example 2:** **Input:** n = 1, edges = \[\] **Output:** \[0\] **Example 3:** **Input:** n = 2, edges = \[\[1,0\]\] **Output:** \[1,1\] **Constraints:** * `1 <= n <= 3 * 104` * `edges.length == n - 1` * `edges[i].length == 2` * `0 <= ai, bi < n` * `ai != bi` * The given input represents a valid tree.
null
String,Backtracking
Medium
null
1,833
all right let's talk about the maximum ice cream bars so basically you have an ice cream and then you have you are giving the arrow of course and then for every single class i represent the i ice cream and you have a number of coins and you have to return the maximum number of the ice cream uh four coins so uh the boy can buy in any order so this is actually pretty easy so if you sort the array of cost and you actually uh keep using your coins to subtract the coset i and if that is still greater than equal to zero just continue else you break so i don't know what's the difficulty for this question so uh let me just write it the arrays of search cost now i will have to return my results okay and i'll start from the beginning to the end and then i will say in val so just making sure the current cost of coins minus faucet i so if value is actually less than zero we know like this is no longer purchased by purchase right so like i don't want to traverse the rest of the nouns in the array so i can create so i will just return a result right away so if everything else i can increment my uh increment my results so i can say i buy this one but also i need to update my points so it's going to be minus equal or crosshat i right so this is pretty much the solution so here we go so let's talk about the timing space the time is what uh unlock and rise and represent an end of the length of the class and for the follow is all of n right all right so this is pretty much the time for the space uh reality we're not i'll get any space so this is all of constant note of one for space time is an algorithm and this is the solution and i was doing this time by
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,189
welcome back guys today we are going to solve it for problem 1189 maximum number of balloons given string text you want to use the characters of text to form as many instances of the word balloon as possible you can use each character index at most once return maximum number of instances of word balloon that can be formed so let's just take a look at this first example so as you can see we can only form one little balloon here right if you remove this e and k the other using other letters we can form one balloon word so let's just take another big example over here and we will discuss the approach how to solve this problem so uh yeah let me just differ this one so we have uh to find uh as many word balloons as possible into the given stream so what we can do is uh we are only interested in the characters here a b l o and n right because that is the only characters that are there in the word balloon and so we will actually count the frequency of each of the characters in the given world and we will create an array of 26 you know 26 characters so we have created an array here called as frequency and we will just look through the given word and we will capture the frequency of each of the letter in the given word so this is uh the given word right so we will just uh let's just calculate the frequency of each of the world right so as you can see here a appears two times right so this a appears two times so we will just say the frequency of a is two then b appears here this is the b and this is the b so b appears two times so we will just say two here uh then let's see l right so l is here one two three and four right so we'll appear four times here and o again one two three and four right so appears four times here and n appears two times here like one here and one here right so n appears two times here uh so other characters we will ignore right we will ignore x we will ignore p because those will not be forming any world of called as balloon right because balloon does not have s and p so we have now the frequency of each of the character so we want to find out how many maximum number of balloon word we can form from this right so what we can do is uh we have to calculate the uh you know the minimum of frequency of what first we will iterate through the frequency array that we have created right we created the frequency array of 26 integer right because we are actually converting each of the character into integers because that way we can easily you know uh manipulate the integers right we can just increment the frequency using plus here since it is integer type so we convert each letter into corresponding integer by we have to just use this minus and then letter k then it will convert each of the character into corresponding int value so for example a will be converted as 0 then b will be converted as 1 c will be converted as 2 and so on right so z will be 25 so that's how we create this array of 25 um characters means it's integer array so now once that is done then we will be iterating through this integer array and we will check if any we will again now when we are retracing and we are checking the frequency we will again convert that int back into the character right now instead of minus a we will use a plus and that l character so it gives us a corresponding character so for example for zero it will give us a for one it will give us b equal to it will give us c so like that so if we are encountering any of the character like a b or n right so as you can see a b or n then we will calculate the minimum value for from the uh integer error so as you can see a here b here and n is i so you see that always it is 2 so minimum value is 2 here for a b and n and why we are just looking why we are not looking l and o in this list because n appears two times here right so as you can see l appears two times and o appears two times so we will separately look them uh in a different for loop so once we are done with a b and n we already captured the minimum value here that is two so now we will look into l and o here right so here again we are iterating the frequency array and now we are only looking for characters l and o in that array and we calculate the min minimum 2 value here so minimum 2 value as you can see the minimum true value is 4 here right for l and o so we can calculate a value 4 here but when we are actually uh since uh to create a word balloon we need two else and two o's right that's why we have to always divide this by 2 so that is the minimum value that we can get for the l and o actually so this is how that 2 came right from 4 divided by 2 so that is what in the implementation also you can see so minimum two is equal to main two divided by two and at the end to form uh you know the uh how many words we can form we have to take minimum from this mean one and min two right because uh we will need all the characters uh all these characters uh to form word balloon so we have to take minimum from this so is equal to two so that's why we have we can form two balloon words here in this as you can see the answer for this will be two here right so that's how to do it so this is the simple implementation uh here we are just using one array of int 26 so you can see it's just like a constant right so uh however bigger the word is the array only will be 26 characters okay 26 inp right and then we just use a couple of variables so on the space complexity is a order of one which is constant and then the time complexity is we are iterating you know like uh two times here through the n um character of the word so it is like order of n the time complexity is order of n so let's just you know like uh take these examples that they have given us here and make sure our implementation works so again just a quick summary so we first actually uh iterate through the word and we create a frequency array to capture how many times each letter in that word appears that is done here and then we have created mean one and mean two variables and mean one means we will iterate through the frequency array once and we will check for word a b and n and we will capture the minimum in the uh word like a b and n occurrences we will find the minimum and again we will iterate uh through the frequency array for letters l and o and again we will capture a minimum for l and o and we have since l and o both requires two times to form a word balloon we will divide them into by two and at the end we will just return the minimum from mean one and win two as the answer right so that is that many word balloons we can form so let us just quickly submit this code and make sure this works so as you can see we are getting correct answer one two and zero because list code does not have any word balloon so that's why zero came so let's submit the answer so the solution is accepted one ms and it is 100 faster so this is the way we can solve the maximum number of balloons so um if you like this solution subscribe to my channel and click on the like button i often create videos regarding list code problem solutions and java j2e related material for interviews so if you are interested in this then subscribe to my channel so you won't miss any of the future videos thanks for watching
Maximum Number of Balloons
encode-number
Given a string `text`, you want to use the characters of `text` to form as many instances of the word **"balloon "** as possible. You can use each character in `text` **at most once**. Return the maximum number of instances that can be formed. **Example 1:** **Input:** text = "nlaebolko " **Output:** 1 **Example 2:** **Input:** text = "loonbalxballpoon " **Output:** 2 **Example 3:** **Input:** text = "leetcode " **Output:** 0 **Constraints:** * `1 <= text.length <= 104` * `text` consists of lower case English letters only.
Try to find the number of binary digits returned by the function. The pattern is to start counting from zero after determining the number of binary digits.
Math,String,Bit Manipulation
Medium
1070
284
hello everyone so in this video let us talk about one more medium level problem from lead code the problem name is speaking iterator so the problem statement goes like this that you have to design an iterator that's supposed to Peak operation on an existing iterator in addition to the has next and next operation so you have to implement three operations on a partial iterator okay now the implement the peaking iterator class and a class has three or one two three four actually but actually this is the starting starter class like when you're on the initialize object you have to implement three functions as a result like how will you initialize this so you have to first initial an object with the given integer iterator okay time so you have to first initialize this and it is actually an iterator over integer array then it will the next function will return the next element in the array and moves the pointer to the next element as well you can just assume that it's an array you have a higher integer okay Vector of integers and the next function which is written the next element whatever iterator of Point let's say on any highest point you are on the next function will written next element in the array and also move your pointer to the next value element as next we'll just check that whether the next element exists and the peak will return the next element in the array but without moved on to the next pointer all right if we just Implement all these three functions that's it nothing much complicated here as well you're given this so because it's integer array it's very simple to just convert this into an integer Vector uh like vector of integers and then just do whatever it is asked to you so what we have done is that we have created a global Vector of integers and the current that is storing out what is the current position that I'm on okay so we'll initialize and like from all these numbers that have integer Vector we have stored here just post that inside This Global Vector so that we can use it in other classes as well or other function as well and then we have initialized with minus one because we have not started iterating over any of the values as of now okay then this peak function what it will do is that it will check that whether the next element the return the next element in the array okay so it will return the next element for next element it has to also check that whether the next element should exist so this has next we'll check it within the next element exist we will write down this implementation but this will just use the has next and just check it with a has next return true if it runs true repeat that this next element it exists if the next element exists we'll just return the a which is the array a current iterator value like current index plus one next element value or not and I'm not moving to the next element I'm just printing out 10 plus 1 million if it doesn't exist we just return minus one this has next week checked it whether the current value of R plus one it exists because it checks that whether the next element exists so next plus one current plus one if it is n b which is a DOT size it is less than in one which means that it exists so it is exist and next element just said that what is an excellent so what else we will move to the next element and just enter the next element so we'll first moved on to the next element so n plus and just print on it you don't know the next element that is a of current okay so it's very simple these three functions are implemented we just push that in the vector and just implemented three function according to the constraints and according to the needs of the problem that's the real problem uh it's not too much difficult if you still have not sequence of this particular problem thank you watching YouTube video till the end I will see you in the next one till I get coding and 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
135
well today's problem is candy and this is the lead code heart problem but actually this is very easy problem so we'll see the problem now so there are n children standing in a line each child is assigned a rating value given in the array ratings okay means like uh there's the array within size n and that array contains some integer value and those value known as the ratings the rating of the children's okay so some conditions are like you're given candies to these children subjected to the following requirements like each children must have at least one candidate like every children will get a candy at least one candy okay next uh children with a higher rating get more candies than their neighbors like those children is having higher rating then their neighbors will get more candies okay so what we have to do we have to minimize the number of candies we have to give okay well as we know the first condition says each child will get at least one candidate so we'll give one candy to each child okay and the second condition says with any child whose rating is higher than their neighbor will get the higher chocolate means higher candies so we have to compare the ratings with respect to their neighbors so as we see this one is having higher rating than its neighbor and this neighbor is having one value one candy so it should get more than one candy so that's why we should give two candy to that one because we have to minimize the number of candies so that's why we take it two not three four five so let's see for this one this zero is having low rating than this from its left side and from its right side so it will keep remain as it is because at least we have to give one candy to each student okay so now comes to two this two is having higher rating than its left side left neighbor so we should take more candies for him okay so means zero is having like one candy this one is having one candy so this should have at least two candy so we should give two candies to that child so total how many candies we have required two plus one plus two five as we know each child will get at least one candy so we'll give one candy to everyone okay so we'll see here like this is this having low rating than its right side and on the left side there is no one so it will get one candy at least we have to give one candy so this one is having more value than its left neighbor so it will get more candies than its left neighbor so left neighbor is having one candy so it should have at least two candy so we'll give two candy to that person okay next this one is not having more value than it's left because it's equal we are checking for more rating so ratings are same so we don't increase the candies so candies will remain one only well i hope the problem is clear to you so let's see the implementation part well most of the people are thinking like to sort the array then we'll solve it well this is not a correct way like if you sort the array then you don't know like which index which children is the neighbor of with children so you lose the index values so you're not able to get like which children is the neighbor of with children so this is not a correct way of solving so how will approach the problem is like first we allocate one candy to a children as the first condition says so we'll see from left side so like this is less from its right okay so it will remain as it is okay so we'll go this side will move to this side and we'll see this one is greater than this zero so what we'll do we'll increment it next we'll move from one to two we'll see this two is greater than this one again will increment will make increment rate as compared to one because it should be greater than one's value so two should get more candies than one so it will get three candidates okay similarly three is greater than this two so three will get more candies than two this one so it will get four candies okay so two is less than three so we'll keep it as it is and one is less than two we'll keep it as it is okay so this is the part which traverse from left to right so let's traverse from right to left well here you can see uh we'll leave this one value as it is whatever we are getting here from the traversing from left to right so we leave this as it is we will start from here and we'll check like if this index is greater than this one or not because before we compare this index with this one we haven't compared from the right side we just compare it from left side now we'll compare from the right side so let's check this two value is greater than to its right side if it's greater than this right side then we'll increment like it's having one candy so we will increment one candy to that and put it here so it will be having two candies but before putting two candies we have to check like this one and this two will get from incremented like one plus one from here so whatever what if there is value already three before so we should put the three only we should put the greater value only here whatever the greater value because first we have computed from the left to right so that time we will get some values here and now we are computing from right to left now we get some values here so we have to compute the greater one of both so greater value will be we will put here so here the value will come 2 because here 1 is there so 2 is greater than this one okay so now we'll see here this three is greater than this two so what we'll do we'll just increment this two we'll just increment here in this two plus one becomes three right it becomes three so before putting this 3 we have to check like this 3 is greater than this value which is present here or not so this is not greater than so the 4 will remain here as it is ok so let's see for this two is less than this three so we'll remain we'll keep it as it is this one is also less than this two will keep it as it is this zero is less than this one we'll keep it as it is from left to right the maximum like we are comparing particular indexes from its left side so from the initial there is nothing to compare so we keep it as one okay so we will start from here so here we'll check from the its left side like its rating is greater than this one yeah its rating is greater than this one so it should have more candies than this one so initially its having one candy okay so it should have two candy right and then this two is greater than this one it should have more candies than this one three this three is greater than this two it should have more candies than this two so it will having four candies and then this two is less than three so it will remain as one this one is less than this two it will remain as 1. so we are done with from left to right so let's see because we have seen the maximum candies we are getting from the left side only like we are comparing it from the left neighbors only now we have to compare it from the right neighbors so for that we'll compare we'll leave this as it is because there is nothing to compare on the right side so we will start from here to this two so this two is greater than this one so it should have more candies than this one so we'll give two candy this side because initially it's having one candy so we'll give two candy so now this three is also greater than these two but the tricky part is that it's having already more candy than these two like this is having four candy then these two will keep it as it is because it's already more so now this two is less than this three will remain as it is this one is less than this two will remain as it is this zero is less than this one will remain as it is so we will get this one so this is the picture representation so let's see the coding part now well we are returning the size of array so like if the size of error is 0 then we'll return 0 because there is no one to take the candy and if the size of error is one so we will return one because there is only one person to take so we are making the vector name well so of the size of array and putting the value 1 because every children is having at least one candy okay so we are starting it from one to n size of array okay means like we are not taking zero because we are comparing from left side so that's why we are taking it from one because there is no left side if we do minus one in the zeroth index so it will get minus one so it is out of one so we are taking it from first index so we are comparing like if the current value the current index value is greater than its left side so we just increment that value by one okay so we are done with left to right well here we are starting from the right to left okay because like here we are taking second last index because if we take the last index then it will go out of bound because of this condition because we are comparing the right side right so what we will do of the last index we just store the value of the last index in count and then we started from the second last index to zero okay so here we are computing with the right side so if the right side is smaller than the current value then what it will do it will put the value of the right side plus one in the value but here's the point it will compare it first like if the value current value is greater than the right side of value plus one of that so it will put the maximum of that and it will increment into the count okay in last we got our total candies what we have so it will return the total candies so what we will see like here we are traversing it from uh one to size of array and here size of array to zero okay so means we are traversing like a big of n okay if we take n as a size of array so the time complexity will be big of n and the space we are also using here of n size so the time complexity is big of n and the space complexity is bigger fan well if you like the video please click on the like button and subscribe button for such kind of videos thank you
Candy
candy
There are `n` children standing in a line. Each child is assigned a rating value given in the integer array `ratings`. You are giving candies to these children subjected to the following requirements: * Each child must have at least one candy. * Children with a higher rating get more candies than their neighbors. Return _the minimum number of candies you need to have to distribute the candies to the children_. **Example 1:** **Input:** ratings = \[1,0,2\] **Output:** 5 **Explanation:** You can allocate to the first, second and third child with 2, 1, 2 candies respectively. **Example 2:** **Input:** ratings = \[1,2,2\] **Output:** 4 **Explanation:** You can allocate to the first, second and third child with 1, 2, 1 candies respectively. The third child gets 1 candy because it satisfies the above two conditions. **Constraints:** * `n == ratings.length` * `1 <= n <= 2 * 104` * `0 <= ratings[i] <= 2 * 104`
null
Array,Greedy
Hard
null
528
welcome to June's legal challenge today's problem is random pick with weight given an array W of positive integers where each element describes the weight of index I write a function pick index which randomly picks an index in proportion to its weight this problem is poorly worded but here's what they mean say we're given a list like this 1 &amp; 3 we want to write a function that &amp; 3 we want to write a function that &amp; 3 we want to write a function that returns one of these index numbers either 0 or 1 either 1 out of 4 times or here 3 out of 4 times so basically the probabilities are represented by these numbers and it's going to be the number divided by the total sum ok so in order to do this my first instinct was to use a built-in method like random choices a built-in method like random choices a built-in method like random choices but for whatever reason it wasn't working I'm not totally sure why that's the case there's another way you could do this and it's to create another index just like this but instead of having these weights like this have it in cumulative sum form so it would be like 1 cumulative sum would be like 4 using that we can randomly generate a number between 1 and 4 and check down iterate down this list and say hey if this weight if this random number is less than or equal to this numbers value then we turn its index point so say we randomly generate a number like between 1 &amp; 4 between generate 1 we will return 1 &amp; 4 between generate 1 we will return 1 &amp; 4 between generate 1 we will return 0 if we generate 2 or 3 or 4 we would return one and that's equals the probability right that's gonna be 75% probability right that's gonna be 75% probability right that's gonna be 75% the time will return 1 25% of time will the time will return 1 25% of time will the time will return 1 25% of time will return 0 all right so how could we do this well let's start with creating a list that's gonna continue our articulate of sums will also initialize a total of 0 and for each weight in the W given to us we're going to append firstwithout calculate our total which is going to be plus or equal to W or weight and will append our total finally we'll just this initialize our total here as an instance variable now first we got the right and we generate a number right so we'll call that ran and we'll stay random ran into between 1 and self-taught total so it'll be between self-taught total so it'll be between self-taught total so it'll be between like 1 and 4 SI and using this number will say 4c index weights in enumerates self dot W if ran is less than or equal to the weight we turn the index let me just make sure that works and they're accepted so this isn't the most efficient solution you could quicken it a little bit by using a binary search here there's other ways that you could generate the random number but I'm a little busy today so I'm not gonna be able to go into all that but this worked for me and yeah thank you
Random Pick with Weight
swapping-nodes-in-a-linked-list
You are given a **0-indexed** array of positive integers `w` where `w[i]` describes the **weight** of the `ith` index. You need to implement the function `pickIndex()`, which **randomly** picks an index in the range `[0, w.length - 1]` (**inclusive**) and returns it. The **probability** of picking an index `i` is `w[i] / sum(w)`. * For example, if `w = [1, 3]`, the probability of picking index `0` is `1 / (1 + 3) = 0.25` (i.e., `25%`), and the probability of picking index `1` is `3 / (1 + 3) = 0.75` (i.e., `75%`). **Example 1:** **Input** \[ "Solution ", "pickIndex "\] \[\[\[1\]\],\[\]\] **Output** \[null,0\] **Explanation** Solution solution = new Solution(\[1\]); solution.pickIndex(); // return 0. The only option is to return 0 since there is only one element in w. **Example 2:** **Input** \[ "Solution ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex ", "pickIndex "\] \[\[\[1,3\]\],\[\],\[\],\[\],\[\],\[\]\] **Output** \[null,1,1,1,1,0\] **Explanation** Solution solution = new Solution(\[1, 3\]); solution.pickIndex(); // return 1. It is returning the second element (index = 1) that has a probability of 3/4. solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 1 solution.pickIndex(); // return 0. It is returning the first element (index = 0) that has a probability of 1/4. Since this is a randomization problem, multiple answers are allowed. All of the following outputs can be considered correct: \[null,1,1,1,1,0\] \[null,1,1,1,1,1\] \[null,1,1,1,0,0\] \[null,1,1,1,0,1\] \[null,1,0,1,0,0\] ...... and so on. **Constraints:** * `1 <= w.length <= 104` * `1 <= w[i] <= 105` * `pickIndex` will be called at most `104` times.
We can transform the linked list to an array this should ease things up After transforming the linked list to an array it becomes as easy as swapping two integers in an array then rebuilding the linked list
Linked List,Two Pointers
Medium
19,24,25
680
okay welcome back to algojs today's question is leak code 680 of valid palindrome 2. so given a string return true if the string can be a palindrome after deleting at most one character from it you do have the option to remove exactly one character from the string so in this question you have the option of removing one character so in the first example we have aba which is going to return true because it reads the same force as it does backwards so it's a valid palindrome and then in example two we have a b c a which initially is not a valid pandering but as soon as you remove one character say we remove c you get a b a or if you remove b you get a c a which are both valid palindromes so we have the option of removing one character so the first step in solving this solution is to make sure we know how to check for a valid palindrome the string has to read the same forwards as it does backwards and the way we usually do this in terms of checking for a valid pandering is to use a two pointer techniques we have a left and right pointer the left pointer at the start the right pointer at the end we check if those values are equal if they're not we return false because it's not a valid pandering but in this case we have the option of excluding one of these values right so the first instance where a value at the left pointer does not equal the value at the right pointer we have the opportunity to exclude either all of these values okay so we can choose to exclude b and then have this as the search criteria so we can search in here to see whether this is a valid palindrome in which case it's not or we can remove c and search here and this is reading the same forward as it is backwards so we can return true and in a very similar case say the left and right pointer are equal to each other to begin with we just increment the left pointer decrement the right pointer and then when they are not equal we search in this criteria so from the left to the right pointer we've already seen these so we don't have to use them within the search and we can just do what we did above so we can initially remove the left pointer and then search to see whether this is a valid pandering in which case it's not so it'll return false or we could exclude the b and then search this area here and then it will return true so time complexity for this is going to be o of n where n is the characters within the string and then space is going to be one so initially to start we create the left and right pointer so left is going to be at the start right is going to be at the end of the string we need to create a function that checks if the string is a palindrome or the current string that we're looking at is plundering so we're going to take in the string left and right pointer and then to check if it's a palindrome we just have a while loop which is left and right we check if string at left does not equal string at right if they're not equal then obviously it's not a palindrome so we can return false remember to increment the left pointer and decrement the right pointer so you don't enter an infinite loop and then we can return true otherwise because the while loop would have escaped we would have checked all the characters and they would all be equal to their counterparts so we can return true okay now back up to this top function so we need another while loop so while left is left and right if s at the left does not equal s at right so if the characters aren't equal this will be the first instance we find where the characters aren't equal so we have the opportunity to remove either or the character the left pointer or the character at the right pointer so in order to do that we're just going to return is pal we're going to pass in string we're going to increment the left so we're going to add one to the left so we're excluding the left side or the left character and passing right or is pal s at left right minus one so we're excluding the right here so if either of these returns true then return true and then increment the left pointer decrement the right pointer and return true let's give this go and there you go
Valid Palindrome II
valid-palindrome-ii
Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_. **Example 1:** **Input:** s = "aba " **Output:** true **Example 2:** **Input:** s = "abca " **Output:** true **Explanation:** You could delete the character 'c'. **Example 3:** **Input:** s = "abc " **Output:** false **Constraints:** * `1 <= s.length <= 105` * `s` consists of lowercase English letters.
null
Two Pointers,String,Greedy
Easy
125,1178
1,646
hello guys I'm anit in this video we shall see another problem on lead code get maximum in generated array so you given an integer n a zero index integer array of length n+ 1 is generated in the array of length n+ 1 is generated in the array of length n+ 1 is generated in the following way okay so they given an integer n and there is an array generated of length n + 1 so if n = generated of length n + 1 so if n = generated of length n + 1 so if n = 3 array of n +1 length is generated okay how of n +1 length is generated okay how of n +1 length is generated okay how is it generated in the following way where nums of 0 is 0 nums of 1 is 1 nums of 2 Star I is equal to nums of 1 and nums of 2 Star I + 1 = num of I plus of nums of 2 Star I + 1 = num of I plus of nums of 2 Star I + 1 = num of I plus of I + I + I + 1 so the conditions are given 2 I is less than equal n and greater thanal 2 similarly here also 2 St I + 1 is lalal similarly here also 2 St I + 1 is lalal similarly here also 2 St I + 1 is lalal 2 so first let's see how do we generate the array okay then let's see how do we get the maximum element in there if n equal to let's say 3 is given then array will be of n + one length this is array will be of n + one length this is array will be of n + one length this is Major you have to keep this in point so what is n of 0 I right nums of zero that is zero they given it's predefined again nums of one what is it one okay nums of two star I so nums of two how do you get it nums of two is nothing but if You observe 2 Star I you have and 2 Star I + observe 2 Star I you have and 2 Star I + observe 2 Star I you have and 2 Star I + 1 as you know 2 Star I means it will be always Z 2 I + 1 that will be always Z 2 I + 1 that will be always Z 2 I + 1 that will be always two starting from if you take I = to 1 two starting from if you take I = to 1 two starting from if you take I = to 1 if you do 2 Star I that will be two 2 St I + 1 will be 3 next for I = I + 1 will be 3 next for I = I + 1 will be 3 next for I = 2 Star 2 will be 4 2 Star I 2 4 + 1 2 Star 2 will be 4 2 Star I 2 4 + 1 2 Star 2 will be 4 2 Star I 2 4 + 1 5 similar for I = 3 how much will it be 5 similar for I = 3 how much will it be 5 similar for I = 3 how much will it be 2 3 is a 6 and 6 + 1 7 2 3 4 5 6 7 0 one 2 3 is a 6 and 6 + 1 7 2 3 4 5 6 7 0 one 2 3 is a 6 and 6 + 1 7 2 3 4 5 6 7 0 one you have for the next elements in the array for I equal to 0 to n we will find okay so nums of 2 is nothing but 2 Star I it is right 2 Star I means it's nothing but nums of I so nums of one will be equal nums of two that is one only then of three how much is it nums of 3 equal to 2 St I + 1 that is nums of 3 equal to 2 St I + 1 that is nums of 3 equal to 2 St I + 1 that is nothing but nums of I plus nums of I + 1 nothing but nums of I plus nums of I + 1 nothing but nums of I plus nums of I + 1 so nums of i = 2 right I = 3 so nums of three but we have I = 3 so nums of three but we have I = 3 so nums of three but we have I = 2 and I equal sorry okay nums of three we have how do I get this three 2 Star I + 1 Formula so I equal how much here 1 + 1 Formula so I equal how much here 1 + 1 Formula so I equal how much here 1 here so for I = to 1 means num of I plus num so for I = to 1 means num of I plus num so for I = to 1 means num of I plus num of I + 1 nums of I is 1 num of I + 1 is of I + 1 nums of I is 1 num of I + 1 is of I + 1 nums of I is 1 num of I + 1 is 2 so 1 + 1 how much will it give you 2 so 1 + 1 how much will it give you 2 so 1 + 1 how much will it give you that is nothing but nums of 1 plus nums of two because 2 I + one if you do in this two because 2 I + one if you do in this two because 2 I + one if you do in this three that is IAL 1 that will give so which is the maximum element of all this two right you have to return this so that is what the question says now we have a doubt once you found this next we will see nums of four it will be counted nums of five till I = 3 of five till I = 3 of five till I = 3 of 6 and M of 7 when nums of 7 what will be 2 Star I + 7 when nums of 7 what will be 2 Star I + 7 when nums of 7 what will be 2 Star I + 1 where 2 Star 3 + 1 IAL to 3 and we 1 where 2 Star 3 + 1 IAL to 3 and we 1 where 2 Star 3 + 1 IAL to 3 and we have Nal to 3 so till this condition we have 2 St I less than equal we want to take the conditions We Run The Loop I equal to 1 to n so but we need to take only two because nums of four will give you other value it will give you value as Su of four is nothing but two star 2 so that will be nums of two that is one but we need to take this maximum value not this one so how do you take this maximum value is in between the loop for I equal to run you run the loop I 1 check if 2 St I is less than equal to n then find that nums of 2 Star I okay similarly for 2 Star I + 1 also 2 Star I + 1 if it is 2 Star I + 1 also 2 Star I + 1 if it is 2 Star I + 1 also 2 Star I + 1 if it is less than equal to n then num of 2 St I + 1 also you n then num of 2 St I + 1 also you n then num of 2 St I + 1 also you calculate that's it so if you do like that only if the condition till here only the condition will be 2 Star I + 1 only the condition will be 2 Star I + 1 only the condition will be 2 Star I + 1 less than will be follow and maximum value we will take into account so here max value we will have one initially we'll initialize max value equal to 1 because out of these two pred different vales one is the maximum value so max value will be equal to one and later you find max value equal to Max of max value comma num of two star that is how you do so okay here I have written the code if you need I'll write it again so as say said first we will have a vector in and yeah then initialize nums of 0 will be equal to 0 and nums of 1 equal to 1 x for it I = 1 I less than or equal to 1 x for it I = 1 I less than or equal to 1 x for it I = 1 I less than or equal to n i ++ ++ ++ if 2 Star I less than or equal to n then what you find out max value so we'll initially ize in max value equal to 1 so max value equal to Max of max value comma nums of I because if you two star nums of I should be assign again if 2 Star I + 1 if that is less than or equal to n then again max value we have to find equal to Max of max value comma th of I plus THS of I + one yes so at last return the max value but one more case you have to look into this what if the length is z itself n equal to Z then if you return Max that will one so in the beginning you have to check if n equal to Z then just return zero okay so we'll run this 31 um okay before here assigning this we have to calculate nums of two star so let's do nums of 2 Star I equal to nums of I now assign thiss of two star I because for the next ration we might need the value of two star I know so that is why because you could see here for four we require of two star be this if you take two then be this so yeah similarly here also nums of 2 Star I + 1 that will be also nums of 2 Star I + 1 that will be also nums of 2 Star I + 1 that will be equal to nums of I plus of I + plus of I + plus of I + one and this should be instead 2 Star I + instead 2 Star I + instead 2 Star I + one yes yeah for Java also the same logic applies so we shall submit this yeah successfully submitted if you understood the concept please do like the video and subscribe to the channel we'll come up with another video in the next until then keep learning thank you
Get Maximum in Generated Array
kth-missing-positive-number
You are given an integer `n`. A **0-indexed** integer array `nums` of length `n + 1` is generated in the following way: * `nums[0] = 0` * `nums[1] = 1` * `nums[2 * i] = nums[i]` when `2 <= 2 * i <= n` * `nums[2 * i + 1] = nums[i] + nums[i + 1]` when `2 <= 2 * i + 1 <= n` Return _the **maximum** integer in the array_ `nums`​​​. **Example 1:** **Input:** n = 7 **Output:** 3 **Explanation:** According to the given rules: nums\[0\] = 0 nums\[1\] = 1 nums\[(1 \* 2) = 2\] = nums\[1\] = 1 nums\[(1 \* 2) + 1 = 3\] = nums\[1\] + nums\[2\] = 1 + 1 = 2 nums\[(2 \* 2) = 4\] = nums\[2\] = 1 nums\[(2 \* 2) + 1 = 5\] = nums\[2\] + nums\[3\] = 1 + 2 = 3 nums\[(3 \* 2) = 6\] = nums\[3\] = 2 nums\[(3 \* 2) + 1 = 7\] = nums\[3\] + nums\[4\] = 2 + 1 = 3 Hence, nums = \[0,1,1,2,1,3,2,3\], and the maximum is max(0,1,1,2,1,3,2,3) = 3. **Example 2:** **Input:** n = 2 **Output:** 1 **Explanation:** According to the given rules, nums = \[0,1,1\]. The maximum is max(0,1,1) = 1. **Example 3:** **Input:** n = 3 **Output:** 2 **Explanation:** According to the given rules, nums = \[0,1,1,2\]. The maximum is max(0,1,1,2) = 2. **Constraints:** * `0 <= n <= 100`
Keep track of how many positive numbers are missing as you scan the array.
Array,Binary Search
Easy
2305
1,171
hey everybody this is Larry it's November 9th uh 2022. this is the second bonus question I put today just because the other one was like a minute question so let's uh let's kind of take a look in another medium one or maybe all medium ones I kind of like that maybe I'm just you know I haven't done medium ones for a random once so uh okay let's take a look though and yeah okay that's uh let's do this one um hit the like button hit the Subscribe button join me on Discord let me know what you think about this poem and let's do it together so taste Farm it's 1171 we moved Zero Sum consecutive nodes from linked list so coming ahead of a linked list we repeatedly delete consecutive sequences of notes that sum to zero until there are no such sequences after doing so we turn the head of the final link let's you may return any answer okay so that's kind of interesting foreign I think the input here could have been explained a little bit better maybe oh no okay because I got that I mean there are a couple of ways you can do this I don't know that you can do it in constant space that's what I was kind of trying to do but if you imagine that web in a way or even a stack right I think a stack is actually a better representation here um in terms of mental ideas because now things are coming in um you know you're doing if you think about doing them live then things are coming in and you're thinking about well how many things do I remove you know pop off the top of the stack if you will right um so we can definitely do that um and yeah I think there is some um bookkeeping that we have to be careful about but otherwise I think that's pretty much the idea um okay and of course with linked lists at least for me the number one thing is also implementation because I think the idea and algorithm is pretty okay um this the way that I'm gonna do I don't know if there's a useless like a way of doing it but what is n oh N is a thousand makes it easier because I think the way that I was thinking is about is linear so o of n instead of you know with a thousand you could do n square e things and then keep on maybe um I don't know but okay so that aside that's actually kind of um let's just do it you know um so the way that I'm gonna do it is try to do a linear time solution and of course it is actually a little bit tricky because it requires this um idea of um well it's dynamic programming to kind of support it away but I forget there's like a specific term for this dynamic programming but I don't remember the term maybe um maybe zero some dynamic programming kind of but not really um okay so then the idea here is just to keep track of things you've seen right almost like you know how there's like a return any sub array that sums to X or something like this so that kind of dynamic programming is what I'm trying to do here except for now is zero sum right so the target is sum to zero so kind of let's get started as well um okay yeah let's kind of take a look at this um so let's just say about this um usually I would use um because this is a dynamic version of that way because as you pop things will happen so I think I have to be a little bit careful right so current as you go zero say and then we have maybe um I'm gonna start with something that's a little bit naive and like I said I'm overkilling this problem it is only a medium so like I think n square is probably fine but I'm doing it a little bit harder so definitely bear with me um as it you know it's gonna be a little bit um trickier right so seeing as you go to let's just say we have a collection that default dictionary of list and then now we have for oh I forgot that this is an array so that's a little bit awkward but yeah maybe that's fine so Kern is let's annotate this a little bit um just for myself because I'm getting old I don't remember stuff but this is current sum and then we have like an in and this is just index 0 which is the current index and of course it's as usual I always um have a new Sentinel head um let's just say zero so it was actually a good one I think maybe I don't know if that's true um and then head right okay so okay um so sorry one of my buddies is pinging me and I'm like not responding but it's still distracting uh my fault but yeah so then now hmm okay so then now what we want to do is look at the next item right so scene dot a scene of zero we want to append zero for the index so yeah so then now let's just say pointer maybe a secret to new head right so while pointer dot next is not none right then we do something with the next uh pointer so what do we do well we look at the number so let's just say the next X is equal to pointer dot next dot value right um and then now we're trying to see if there's a zero sum and of course there's a zero sum if seen of oh well actually current we add it to the current prefix sum almost right so then now if scene of um yeah if current um yeah if this is greater than zero means that in a previous index we've seen this number before and that means that we want to at least pop until that number so then uh maybe until I don't know if that's a keyword is it going to see in that current of negative one meaning the last element of it you can also do it from the first element I guess it doesn't really matter in the sense that um it's Auto up to index currently you can also um do the first or last you can pick any number in the scene away to be honest just because that's the definition of what you want to have here is that they all sum to zero um given the current number right um so then here this is the until um I did think about using a stack I guess I have to keep a stack then right um I did a stack or just to point to itself so maybe um yeah maybe I instead of keeping track of the index I would keep track of new head maybe I don't need index anymore but that's a little bit awkward so I'm um so then now this is to start right meaning that this is we want to remove all of the elements after this until the current pointer so basically while um let's say uh Delete pointer say is to go to start while delete pointer dot next is not you go to pointer.next is not you go to pointer.next is not you go to pointer.next then delete pointer.next is equal to then delete pointer.next is equal to then delete pointer.next is equal to delete pointer.next.next someone like this and then we pop this pointer off because is that true this is kind of tricky to kind of go I uh like you know the point is correct um so we definitely well we definitely want to do that but then now we have to remove all the other references that are in the scene away I think that's the tricky part or one of the tricky Parts maybe anyway yeah we can amortize that out that's fine but still so we can do something like and I don't know if this is not a great idea to be honest but I'm just going to set it up um and then maybe we'll figure out a little bit later um yeah so pointed that next so we want to delete up to a pointer.nex to delete up to a pointer.nex to delete up to a pointer.nex so we still want to delete one more I think that was the doorbell sorry friends usually that means that uh I don't know Amazon delivery or someone house um uh sometimes they just ring my belt for my neighbors buying stuff so I don't know so yeah anyway um do we want to delete scene itself no we put the thing so okay I think this is relatively right but and then the idea is that we also want to roll back the current but because they all should sum to zero they should still be current because you remove stuff that's sum to zero so that you don't have to update current for that reason and then here like I said this is probably very wrong to be honest uh but that's okay so we append a pen pointer and not pointer down next to that we could keep track the reference okay um anyway and we move the pointer for it and then we return your head down next I don't know if this is right oh I'm actually relatively confident that this isn't right but we can at least um take a look into because pointers things are always kind of hard for me I have a notepad to draw things out I'm trying to keep it in my head but uh got the first one right now so that's good but this one I deleted read three and then but I expected two so let's see what happened all right let's see all right I've added this deleted pointer but I don't actually um yeah wait I don't actually use it so that's kind of useless uh I need to use it so and looking like foreign that's going to run it real quick I don't know if that fixes it's just it's wrong anyway so we definitely need to fix it but yeah um okay so let's play around this way so okay um I'm just starting from I think we might have to delete the starting number as well but maybe not actually maybe it's just I think actually so I don't know foreign let's see what happens here yeah okay I mean Java you could do with this Auto boxing or Auto Motion but I guess not in here and I hope that I don't get any none our things not quite sure that I don't but either way like none type doesn't have a value or something yeah that actually worked out well okay so we start deleting from negative three starting from two hmm did I do this one I mean as far as I did this wrong hang on um so basically we have one two three so the prefix is going to be one three six and then with the negative three it's looking for a three right and the three starts at two so my math is a little over one maybe no it's okay so I see so it should be start Dot uh it should be just dot next because Maybe but then why is number example one right yeah maybe this is a little bit awkward let's see oh no I already wait I didn't shut the wrong one maybe I answered the wrong one do I move pointer I don't remove the pointer so why because why are we doing oh now because here one pointing at two updates the two so then that's the three okay so then I think this is true that starts to be because I'm like off by one in a way so I think this is true but then now I have a nine hour thing from here but why isn't it um which one okay why is it always or still starting from two though also this is just really wrong right because it's deleted the two hmm isn't ideal that if I had this next then this should be starting from the realities right the debug is real unless I'm looking into one case maybe I'm looking at the wrong case yeah maybe I'm looking to 1K so okay so this is the case that I'm thinking of maybe yeah this is so much easier I mean because I'm trying to also do it from the pointer perspective so that's a little bit tricky because it's pointing I do it because it includes that but it should be the next from that right so yeah okay let me just get rid of these two just because I think it's confusing to know which one I'm looking at I guess I could print it out I know that I'm gonna oh okay so that wasn't the case I guess all as well uh so was it this one did I change something I thought I okay maybe I delete the wrong one let's run it again okay what they don't tell you what test case that's why this is so weird right because I don't I didn't know which one I'm debugging from um and it seems like I don't know let's just print it out I suppose okay so it's one two negative three and one so actually the first case huh okay so I don't get to start from why is it starting from two if it's negative oh I think this is zero is wrong that's why thank you because now the new head isn't quite right because it should start from one but it's doing this thing that um foreign it should be zero and then it should be pointing a new head I think that's the idea yep so there should be new head and then new head is in the there's zero right and then so this should be new head.next why is so this should be new head.next why is so this should be new head.next why is it not starting from one hmm that's weird right or did I do it more okay so yeah so this is new head so we're starting from oh I see I've just foreign maybe that's fine I don't know let's see I think I messed up actually before that's why because before I put down next here and I was printing it out but my delete pointer always started at start so that was just really well like my printing is um not the same as the other one but yeah okay um how can this be none we've pointer that next cannot be none okay so then now sign three zero and then we delete 1 to negative three nice right good um and then the next number is a three okay getting from three um did we have three I guess one and two that's why let me think about this I thought that this would pop it but I think I forgot to put something in it um uh this is because this is after we moved the thing silly Larry okay still bad but hopefully it doesn't nope still didn't come through foreign what are we doing we should have already removed the tree that is as part of the okay let's see um so one two three so uh because as we remove we need to um yeah why isn't this popping let's take a look okay so yes so um so this was returning a no to the one but it's not in deleted is it why oh because I'm I see because deleted needed to um also I feel like I'm missing someone to see a bit because we're deleting the reference to the pointer and not the pointer to the next so that's why this was not popping it okay I think this is slightly better um it's still the wrong answer for this particular one but uh one three one okay let's see what we're doing here uh So currently we see Zero we delete from one to negative three that's good uh two and three um okay um I don't know what this means so let's take a look thank you it is a coupon annoying to get right as I protected but that's okay so yeah so we look at debris and then this node is here but do we pop it let's see like why do we not um is it not part of the answer okay so this cleans up the current that's good why does new head no longer have a reference to it did we delete it by accident hmm okay let's print out everything after every iteration okay so initially has zero one two three and then after deleting some stuff is just new head is weird well we removed Zero from new head so I think that's part of the issue do we have to remove this maybe that's why um because it removes so we would definitely do this but we removed Too Much from the deletion so then we remove um okay I don't know that makes sense but so after the three it goes to zero one which is already kind of wrong maybe because I thought we deleted the one what is this is the list of the frame um who am I returning we're turning one three one so okay so actually I misread this one we do return the one oh we turned the three and the one but we did not delete the one so starting from one but we don't delete it for some reason so that is the issue um because we start from start but we actually okay so this fixes this one okay that's good I think this is more and this was my first try I just got I guess I actually was just debugging this um the print statement because I think I messed up in the print statement um because the code actually deletes the next and not the current so um okay but then now this is wrong let's debug that uh so now I'm going one four two four why am I doing that uh I have too much stuff but okay so the in free the negative three maybe I did some math well maybe this should be negative current I think that's maybe why maybe the design because then now which we're trying to match the last three so it should be deleting from um why is it starting from one beautiful Ness three the one points at two that's why it's starting from one is that true did I mess up it's this way so okay so foreign I am struggling on this one um I mean they should be starting from gray oh wait no I'm not gonna wait right no yeah this should be starting from three because the two here I think I set up my zeros well maybe homemade servers are set up incorrectly here that's why um and then I just assumed that it'll fit but I don't think it actually does so my base case is a little bit long so for this one for example it also does a negative three to one thing why because I think this is actually um next Maybe okay is that really odd that it took to fix I don't know these cases are hard I and keeping track of where I need the next pointer and which one I don't it's also High let's give this a quick one it looks okay for these cases um let's actually add one more case or something at least um yeah like foreign that looks complicated enough fingers crossed okay so it's good that we have a wrong answer um I guess we're printing out where's my print statement I guess I left one in but oh on top okay that's fine that's just because I forgot what cases um okay um oh it's because I removed zero properly if I have to guess because it seems like I did remove it from here but I wasn't sure that um because basically we don't want to be okay so we want to remove it after we moved it um maybe in both cases I don't know maybe we don't need this one to be honest okay I'm still getting the wrong answer though that's uh yeah let's kind of print it out every time okay so last time where does these numbers come from oh maybe I just messed up oh no it's just here right so that means that oh this is second zero maybe well it cleared it out so but then maybe if we remove this um foreign how do we do it in a good way to point this is like not really easily debuggable um how do I want a debug so okay after the one after foreign negative two negative three and then zero again so zero now needs to have a pointer to head but it doesn't seem like that's the case because we might be removed it so let's say let's see if I remove this is kind of hard to eat actually this amortization thing maybe was expensive okay so that actually never even gets used which is actually really um maybe surprising hmm I guess it just doesn't come up again because I started using negative but and sometimes that's how debugging is you just kind of keep on grinding it um okay so XXX negative six and then we have this thing right and then the good one I'm gonna do three and then now it's negative six right oh because we added zero to this afterwards but after removing the other one but a negative 6 was removed so because we moved pointer dot next that's why so okay maybe I need something like this because we were adding the pointer but yeah okay so now this is good in that it doesn't have the negative 6 anymore but we moved to zero somehow so that was no bueno why would we though because of this park Maybe do we always pop now because now it's pointing to the next again because I was confusing myself but I needed to pop earlier actually so okay let's see if that improves it okay so then three okay now three sees the zero and then now what are we getting wrong then uh we still get the one the same wrong answer somehow but the state looks a little bit better because here and what are we pointing X okay X and then we see this thing do we pop is that why the video we were popping because it was just so okay so then we pop the zero before doing it that's why so then we were still deleting the thing oh because I guess the order doesn't matter if we keep on just using the okay because the Deep pointer is never changes so we all only delete the thing okay wow that is a silly mistake oh no one okay so then now hopefully uh after a long attempt let's give it a submit I mean that other one looks pretty okay but they're definitely possible oh no oh well okay that's fine um actually oh that's an easy one to fix though I probably should have tried it I actually forgot about zeros in general um okay let's run it real quick I was thinking about it earlier but I got so distracted by stuff so yeah uh that is weird maybe when can point if we so we move up to pointed dot next so we've deleted pointed.next okay but so this just delete pointer okay anyway yikes a bit of a hack on this one to be honest okay let's give her something again it got both the zero cases right so hopefully this should be good oh no I don't like what I had so many zero cases how is it that two zeros is not good that's actually surprising this is really I mean yeah I would have done it differently only well only the point to point is hard um at least for me so yeah so this one it moves to zero I think here I needed to add just delete nums Maybe foreign debug we also I don't know why it works for oh because maybe it was magic it needs to no I don't know okay so after one iteration it's okay and then we move this one but then pointed that next is I guess I say why because basically it's removing the current I'm just going to write something like this where uh if going to die next time zero then pointed 10 x 0. x dot next continue just delete all the zeros I think there's some weird communication with what by ones but okay that's gonna submit again hopefully this time it's actually correct we'll remove all the zeros that's what that does come on please maybe not it was taking a long time no wrong answer oh because I printed stuff still so okay so that if I mixed it slower but it's still one oh man huh I did I filtered out zeros so we remove the next one okay oh I did um no I mean that should be oh no uh okay I see basically we're at the one we removed and then uh okay so we're at the one we removed it and then we're at the where's the pointer uh okay fine let's just do it in another loop maybe tell me a little bit better oh really is my slight embarrassing now but that's okay um okay fine let me skip foreign because I think there's some like conflating things there that I was just being lazy um there's some comforting stuff that I maybe yeah all right well that was a mess to be honest uh but we did do it in linear time linear space so that's kind of good right um that kind of tells you how complex this is um I feel like there is definitely like an n-square Solution that's um an n-square Solution that's um an n-square Solution that's um okay I guess that's what I was kind of doing um maybe you could have done a backwards or something I mean this is basically what I'm doing but um yeah I don't know anyway uh that's all I have for this one let me know what you think um yeah stay good stay healthy it's a good mental health I'll see you all later and take care bye
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
60
hey guys how-how's is everything going hey guys how-how's is everything going hey guys how-how's is everything going to say that's a critical number 60 least updates codes permutation sequence we are getting a set 1 to n we will we need to find the cave permutation sequence like 1 2 3 1 3 2 1 and this is the restrictions say we're going to have the permutation sequence of totally 3 numbers and we are get we are going to get the third sequence which is 1 2 3 1 3 2 and third one is 3 2 1 3 so we return 2 &amp; 3 we return 2 &amp; 3 we return 2 &amp; 3 wow the first naive solution comes to my mind is that we just defined we can just find the a permutation one by one right if we actually did a similar question which is this one this is 46 if you haven't seen it please search on my channel about number 46 permutations here we're using backtracking with the RIC just to recursion and if I find the result so I was just caught first I copy paste to the copy the solution here okay yet this solution actually collects all the possible sequence in a final result but in our number sixty we don't need to get new we don't need to return all the solutions we just need to further ranking needs for the specific result so rather than collecting the results we need to get a counter I think right I say the final result will be ready to be undefined and let's count equals two we were finally we will stop the traversal when we met this target okay right so the count should start with zero and every time we found a solution we count we increment the count okay so the original solution is very simple we pass two parameters to the recursion function the first one is the temporary result and the other one is the rest of vailable digits right the first two we passed at the beginning we don't have any digits in our intermediate results so all the numbers are in the second parameter and every time we pick a number from the second parameter and push it into the first one and then we do the recursion one by one yeah that's pretty straightforward right okay so when the end when there is nothing in that second parameters that means all the digits are traversed this means a new valid promotion permutation sequence come comes around so if this is true you really know why we just push the result collect the result but here we will count Twp right count the count and I've added the check if count equals K we will have this result equals 10 right we join it convert it into a string yeah and if it is not the end we pick the one from the second barometer and just continue doing it yeah it's cool and actually yeah our solution is done I'll just say this is a the back tracking naive yeah it's very naive but there's a problem that because for the original solution we will continuing the possible solutions in a 1 wok in a while returning a function which means for the first three numbers like 1 2 3 4 this forward we watch 5 s 4 1 4 2 4 3 right even if we turn here but we will still continue so all the so oh all these possibilities will be checked and the result or of course it's right but the time is not good time complexity it is written now good so we need to stop this recursion right away that means we cannot just return here we need to add a second stage for this recursion function which means if it is fails I can continue if it is already match this result I will just I want just to stop right away right ok so if it is the cake it means we found the result we return this one and if not we return 0 yes we return okay return one and if we default we turn zero means we haven't met the end of the permutation each sequence yet so here for the rest we walk but we need to for this photo up here we say result walk if in this in from these we found that it is checked it is a nice town then I say we just return one yeah so that we can just cut the unnecessary recursion and walk return result I think we are doing good let's try oops there are some nuns is not our cut noms yeah we need to generate Jenner noms okay we say Nam see is empty and the end right and it's not used at all so Wow n1 nums and shift lumps okay and minus plus one this one n when n becomes zero so these lumps is right okay let's run it again hope it works oh yay let's submit yay we are accepted but it's super slow like we are only faster than 5% of the like we are only faster than 5% of the like we are only faster than 5% of the JavaScript 5s yeah % it's very slow it's actually we can't % it's very slow it's actually we can't % it's very slow it's actually we can't counter that because we need to generate actually track traverse all the possible permission sickness right the first one the second one actually we need to get these already we need to generate all the sequence one by one and wait here it's a it's actually not oh okay after can after we improve the solution the time complexity will be a B oh okay I think okay this is oh what's the time wait a second if I do like this every time I pick a number to it and then for loop and then walk again so every walk actually checks one every possibility so it's actually okay I'm not sure and space actually the maximum depth of the call stack is actually that ninth of the digits right so it's maximum and right and here we need to yeah here is oh and you see the K will be between 1 and N and factorial of I've even a fever Nancy no Nana factorial of n it's a super big let's try to improve it let's try how can we improve it let's just take a more look more into this example for one two three we need to get the third like we need to get the six of the permutation actually you see that if the first digit is one we know that this all the combinations all the permutations of the last two digits will be the count of it will be to read only two possibilities for two numbers and so for one the first for the number for the digits one and two as the first numbers there will be four possibilities and work we are asked to get the six possibility that means the first stitches must be three right so we can just deduct the first digits by purely math and then we can do this recursively and that the problem becomes like we after we decided it's three then the possibility is for when it's not three you were before so we are going to find the second permutation of two digits which is one and two right so I don't want to it will be two one and if you're going to get again generates the fourth sequence we can deduct by a pure math to decide the first stitch it to be two and we are going to get the second permutation of the number one and three which is not one to anymore so this also two to two videos so it's 2/3 1 so actually we can videos so it's 2/3 1 so actually we can videos so it's 2/3 1 so actually we can improve by avoiding now um this 3 I'm not sure I'm have the right spelling generation generating jump steps so for that case we means decide each digits from left to right in that case we need to do we need to know at before time that how many permutations would be for a specific n right so it will be we need to first generate the factory array of n right first get the factorial array is the factorial let's say factorial oh yeah hi Jo yeah it's factorial cool so the first factor of 0 will be 1 right but actually it's not used for one it's 1 R 2 is 2 okay so we start with 3 it's I equals 3 we push the previous one will be times right yeah times yes times in so this means there will be fact and possibilities for and digits this is very important so now how what is the first digit of K possibilities okay possibility Wow it's simple we just traverse through the factorial and find that find the target right yeah the K might be big and small so well Navy which is traverse through the factorial okay so for how we can find the first one so that so if this one they will be for each digit there will be back in minus one possibility yeah so the possibility would be so the index of the numbers right would be the K divided by n minus 1 right so for the first digit and math.floor right is the first digit and math.floor right is the first digit and math.floor right is this right yeah let's say for the 4i for the K equals 1 then the first index should be factorial n minus 1 it says 2 for so forth yeah it's 0 so it should be the first number which is 1 index right and the second one when they are when we are getting to number 2 if viewers you are the only two digits if there are only two digits right so we are checking 1 and 2 the N minus 1 will be 1 so factory will be 1 and the K will be 1 or 2 if it is 1 then it will be 1 so 1 will be always index will be 1 but it should be 0 right so actually this is not right considering K equals 1 and N equals 2 it should be CEO minus one this is a trick and it's actually right I think it should be the first it should be the next possible it should be that the permutation between the next possible permutation array so for K and E for K equals 1 and N equals 2 it should be always be 0 but mass for doesn't match that so it should be math sitting but minus 1 for now ok if K equals 6 and the fab factorial and a 2e before so it should be 1 right 1 minus 1 yeah 0 so the sub problem is should be smaller than 0 1 it should be 0 yeah that nothing's 1 between 2 it should be 1 issue so it's sale minus 1 yeah ok this is how we get the first digit right so how can we get the second digit it's the same unless K should be subtracted with the possibilities of things index number okay considering this we will first get all the digits nums the same we all just generates the digits by of wire loop let's make it to a cinder I'm sound okay now let's move to the here this is here okay now we will do the same thing we are about trying to get the first digit and get the second digit so there will be a result right so every time we walk at the four digit and push it to the result so there will be result ninth Wow okay we'll say Wow names noms as numbers Wow there is number we will get the first digit so this is the index right so this is the index and we will push the result right push nums index now we need to splice the results index of result right remove it right so splice index one and we need to reduce the K so after we push these numbers in it then how many possibilities are left to the rat to arrest right and there here is mistakes that this should be based on the market n this should be based on the nonsense yeah so here you should be numb stop then index remove the number gets the first digit okay update K by removing the pass Beeler tastes like this too just for this example we now decided the first metal should be - right now the first metal should be - right now the first metal should be - right now the possibilities would be so 1 2 3 1 3 2 it would be yeah you know that should be the possibilities when the first letters first become this number and that would be the counts of all the possibilities with a number smarter than this one right so the index would be if it's zero then there's no possibility index is 1 so there are two numbers the second numbers right the first number is the possibility are all taken so k should be divided to sub this abstract it with index times the possibilities of the previous one right just this one factory noms then but actually we splice it so the K should be updated first yeah we getting the X and then we update the K and then push numbers oh yeah and then we return results join it's wrong if we do this first these will cost us o n but this we will still it would be still Oh n right wow it's something wrong memory is hmm I think there is something o nums it sure did because of infinite loop so yeah so n so it's two o n time and space nothing special we holds the rest so it's o and hmm let's do something wrong I Oh quite why skate my god haha I thought up here is okay for here why do piece hurry okay this loop is okay yeah we're accepted let's try submit so the solution actually the first weekend came up with a pretty oh we got the wrong answer it's a debug why four nine one two one three four we've got two three one four is three four mmm result push I don't know what's the problem is let's cancel our index noms index okay this result so the rest is nonsense -1 this result so the rest is nonsense -1 this result so the rest is nonsense -1 this is right maybe this is wrong okay we got index the first one is K so we guess numbers of - right yeah and the we guess numbers of - right yeah and the we guess numbers of - right yeah and the final numbers will be okay - K is K now final numbers will be okay - K is K now final numbers will be okay - K is K now becomes 1 Oh in this one yeah this one so this will be six possibilities so we were okay will be K will be which is 2 then k will kill these three possibilities so K should be three now it becomes one hmm wait nonsense - okay he should be he wait nonsense - okay he should be he wait nonsense - okay he should be three first K was nine right factorial 3 will be Aiden God it should be I okay yeah we had a problem of the factorial ray wow that's a huge mistake haha it don't submit oh yeah except this time and we are running faster than 93% time and we are running faster than 93% time and we are running faster than 93% Wow it's improved a lot we improved the time from Oh k 2o n okay will be just wow it's a huge improvement you know case between the factorial of a n so that's a huge improvement so that's all for this problem hope it helps so the lesson I learned from this problem is that the first for any problems we can just come up with the naive solution with recursion or backtracking speed is based on recursion so everything could be basically done with the recursion and then we try to find some try to understand the problem finds find the way to cut down the unnecessary calculations like this one yeah we can just say some of the calculations are not we don't need to get the other final result we just need to get the count if that's true we can just account by the pure calculations and then decide the digits one by one so recursion and pruning recursion and purring recursion and pruning yeah recursion and pruning okay that's all for this see you next time bye
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
1,059
hey everybody this is Larry this is uh January 26th of 2023 and I'm doing a bonus question uh for y'all uh hopefully a premium one or I don't even care if it's premium or not just what it's going to be one that I haven't done regardless so let's do it um and of course we get a SQL question I'll probably do an asking a question one of these days but that's the one that's an actual question and today is a premium question 1059 or perhaps from Source lead to destination okay so let's kind of see what this question is about so given the edges of a directed graph okay uh so you have an etched list uh okay and source of destination or pass down from Source differential enter destination that is at least one path existed see I'm gonna be oh I mean I kind of get the idea of what they're going for but I want to make sure that I'm really precise with what they're asking for uh okay so at least one path okay if a path exists from nodes that have nobody then that node is equal to destination okay the number of possible path is a finite number hmm I mean I think this is just a death research thing where um I think this is that for search and you're just trying to see where um I'm just thinking about it a little bit just to make sure but I think that first search will work it may have self loops and parallel edges that's fine um I mean that's kind of to be expected otherwise this is a very well I wouldn't say very but more trivial question but I expect there's a lot of uh edge cases anyway um I think this is just that first searchable and yeah I'm trying to think about what is the best way to handle this because I think my inclination is to do some sort of memorization um but I think that could actually be technically well maybe there's like some uh coloring based thing and then maybe the second thing that I can think about is actually thinking about backwards but I don't know that I get anything from thinking about it backwards per se because I think it just becomes the same because then all your stuff has to I don't know that's true actually I don't know if you can play about this uh symmetrically so maybe I'm wrong on that one um okay so I think because the number of paths uh I think this one which I wasn't quite sure about but the number of possible paths from source to destination is a finite number means that if there's a cycle then we already have to return first so we can maybe um then now we can I mean well one thing that we can do now is separate it into two different problems if you will one where well we have to see if there's a cycle um and then the second part is whether um and then the second part is what you know just maybe some sort of simulation um and you have to be careful but I think once you realize or once you're able to prove that there are no Cycles then the other part should be easier because I think trying to do two parts at the same time maybe the tricky Point um this is kind of a heart of a medium one but I don't know maybe there's a simpler solution that I missed or something but uh yeah let's kind of think about this so okay so psycho how do we do psycho um I probably can't do that for a search right there may be a lot of badges I don't know remember how to do cycle detection anymore I mean I guess in a random I haven't done it in a while wow that's true but that part isn't I'm thinking about like uh tricky stuff with like artistic articulation points uh with that kind of depth research but maybe I think that's an Overkill so I'm trying to think uh and you know maybe this is just like me also again being tired and lazy and whatever today so um so we just try to think about how do I do cycle detection anymore well no I mean there's Floyd but that is obviously going to be it too slow you see because the thing that I'm thinking about is that um you can have a diamond right so you can't just be like you know we've seen something then it's a cycle because it might just be like a diamond so that's why I'm thinking about man I'm I've not been practiced about this so this is good and that I'm getting practice on something that I haven't done in a while which is kind of the point of this so thank you for joining me and kind of doing it together uh you know just but this is the kind of stuff that I'm so bad at because I haven't been practicing I mean um hmm how do I wow Larry foreign exit thing right I guess we can do it I mean it's not a big deal but I feel like there's a easier way and I'm just like blanking out on it today um all right let's uh let's do adjacency list thank you all right and then we want to man I am just not good at this um okay I don't remember this very well like even though articulation points stuff um lip begins foreign I think it's Well yeah if it's definitely if it's not done then we just go but in here we've got entry you know which is equal to two foreign and then basically if um if or else if it's done um and if we haven't exited yet then also I guess I don't need to done it's just entry right I'm like using duplicate views uh okay uh psychos you got a true right something like that uh what's a negative no I don't always return negative one but okay so if there's a cycle then otherwise we can just do it right and then basically it's just about I want to say I want so my initial observation was going to say that if it has no exit notes then like if any node has no exit node other than the destination then we're not good um and you can also even say that if yourself what you would call it is the adjacency list of the destination so basically if this is greater than zero then we return Force because that means that there's an outgoing thing from the destination which automatically means that you know it either leaves or it comes back it doesn't matter right it just means that it's bad and actually we can move this to the top because I don't know then we can it's cheaper um and then the other thing is that if I guess Y and range of n if we visited and um if we visit it and uh this is zero then that means that we ended there at some point so then we return first otherwise returns true I don't know that this is excessive enough uh and apparently it's not for this case but a Diamond Case diamond in the sky hmm I'm guessing that it is here but I could be wrong but let's point out the entry and then exit that was the thing that I was curious about so Zoom one foreign this is four and then this is five and then basically it thinks that no this is already exited so then that means that it is not going backwards in a cycle that's good right foreign oh so the cycle thing is correct so this is returning Force why is this returning Force oh I forgot to check whether I is not destination of course that's going to always return first because the destination does always true um silly mistake let's see that's kind of a hard one to be honest Maybe not maybe you could logic it out and I kind of made it more complex than it is I think the psycho thing I don't know like can you do it without a cycle like maybe like is the time like did I make it more compact I needed to be maybe or it needs is that no because you definitely need a cycle thing because this could be true um yeah this could be true but without the cycle thing then you don't get it um yeah so what is the complexity here this is going to be linear time linear space uh both of which is V plus e because adjacency list um this is all we of course I won't end with that Swiss test input but that's we um this is of course we perceive if that record that first search and yeah and this is obviously foreign I don't know if there's anything more to be explained about this one I think the core part about solving this is just breaking into components one the psycho part you know uh once you get rid of the Cycles then you can assume that everything is a dag yeah then it becomes a dag and then it just becomes where the um you can think of almost like a tree but not really it's a dag where there's multiple destinations and because Joey ruled out psychos then this could be true um yeah so it's really it's just case analysis but maybe explained in a much more complex way um I don't know I am really tired though so friends I am going to call it a night uh that's all I have so stay good stay healthy to get mental health I'll see you later and take care uh bye
All Paths from Source Lead to Destination
missing-element-in-sorted-array
Given the `edges` of a directed graph where `edges[i] = [ai, bi]` indicates there is an edge between nodes `ai` and `bi`, and two nodes `source` and `destination` of this graph, determine whether or not all paths starting from `source` eventually, end at `destination`, that is: * At least one path exists from the `source` node to the `destination` node * If a path exists from the `source` node to a node with no outgoing edges, then that node is equal to `destination`. * The number of possible paths from `source` to `destination` is a finite number. Return `true` if and only if all roads from `source` lead to `destination`. **Example 1:** **Input:** n = 3, edges = \[\[0,1\],\[0,2\]\], source = 0, destination = 2 **Output:** false **Explanation:** It is possible to reach and get stuck on both node 1 and node 2. **Example 2:** **Input:** n = 4, edges = \[\[0,1\],\[0,3\],\[1,2\],\[2,1\]\], source = 0, destination = 3 **Output:** false **Explanation:** We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely. **Example 3:** **Input:** n = 4, edges = \[\[0,1\],\[0,2\],\[1,3\],\[2,3\]\], source = 0, destination = 3 **Output:** true **Constraints:** * `1 <= n <= 104` * `0 <= edges.length <= 104` * `edges.length == 2` * `0 <= ai, bi <= n - 1` * `0 <= source <= n - 1` * `0 <= destination <= n - 1` * The given graph may have self-loops and parallel edges.
First define a function f(x) that counts the number of missing elements until x. Then use binary search with the given function f(x) to find the kth missing element.
Array,Binary Search
Medium
null
844
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem is backspace string compare it's very easy problem as i have stated it's easy so see what the problem is that we are given two strings s and d and we need to return true if they are equal when both are typed into empty text editors hash means a backspace character that is whenever hash comes it means that we are pressing backspace on our keyboard like we are in you know on our keyboard we have backspace so if hash comes that means we are pressing backspace so note that after backspacing an empty text will continue empty like if batch space is only there and if we press backspace the empty text will have been empty okay so let's see this with a test case so first of all let's discuss this example so in this example what is there that first of all let's say there are two persons a person and b person so first of all a person is typing the string so a b hash means that a backspace so first of all this person is pressing a then b then this person press back hash means backspace character so when backspace is pressed obviously the previous character will go because that space deletes one character right so this will go and then that person again presses c later so see so this is the string which will be on the text editor this will be on from the text editor now this is another person that another person is pressing a first then d then hash means backspace so again backspace means one character will be deleted and that will be distributed after that person is pressing what c now see these two strings are equal right that's same ac hence we will return true okay let's see this test case so here first of all a b so there is obviously no backspace so abcd this is the one string then bb cd this is another string so they are obviously not equal so they are not equal hence false okay so see you guys how we can approach these type of problems whenever see here when this hash comes backspace hash means backspace right so whenever hash comes what we need to do we need to remove this previous character right the previous character so from this like think of a data structure which can store the previous uh store the previous like character right show the previous correct okay so see what we can which data structure can store the previous character we can use a stack because in stack what can happen is that you can store see you can store like this string a b then you whenever hash comes so what you can do you can remove this top element now you might be thinking that i usually like okay you are staying you are saying that we need to store the previous character so why don't we take a variable only to store the previous character why we are using extra space that is stack we can use the print like we can have a variable previous and that can store the previous character so whenever hash comes we will just remove that previous character we can do something like that but see guys that will not work why because there could be multiple hashes for example this is a string a b c something like this is there then how we will do it how will go about it we have to store all these previous characters so then variables we cannot use to store the previous character to store previous character we cannot use a variable we have to store in a stack so see let's see how we can uh how we will uh use stack let's try iron so uh the string was a it was a b hash c so see i will be taking two stacks stack one for this string stack two for this string okay so now first of all we'll traverse the strings so first of all we go to a we push it in the stack we go to b we push it in the step now we go to hash so hash means backspace we have to delete the previous character so what is previous character the top element of the stack so whenever hash comes i will delete the top element now we go to again uh next character so it's character c this ad so this now i'll take a string and i will store this string this whatever letters are in the stack in a string so it will be ac okay now what i will do now let's do for the second stack uh string so first of all a will be there a will push into stack then we go to b we push in the stack now we're going to hash so backspace delete the top element then we go to c and see we push in the stack so now i will take another string which will store this s2 letters so ac will be again there so see this string and this string both are equal same they are same right so we will return true okay i hope you understood the approach just what you have to do is you have to try run this stack approach on this chest case in which we were returning false so try to do on this test case let's see the code now so see in the code as we discussed we will be taking two stacks each stack for each string then we have these two strings to store the final string so first for loop is for star uh first string s1 s string if it is backspace corrector sorry if it's hash and stack is not empty just pop from the stack obviously it will pop the top element otherwise just push in the stack similarly we'll do for the second string and at last we will be popping out the letters from the string from the stack and we will be forming this string and if they are equal at the end we return to so if they are equal so this give this will give us true and will return that true so i hope you understood the problem and the code very easy problem time complexity uh is the cbi just traversing uh the stack only so first of all we are traversing this first string so it will be o s uh let's say the string has length l one and this string has length so first of all l one for this for loop because we are going this uh size of the string and then l2 for the second loop okay this will be the time complexity and space complexity will be we are taking two stacks so o of let's say this has length n1 and the stack has length n2 so n1 plus 8 i hope you understood the problem and the approach let me know in the comments if you any doubt found the video helpful please like it subscribe to my channel and i'll see in the next video thank you
Backspace String Compare
backspace-string-compare
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t become "ac ". **Example 2:** **Input:** s = "ab## ", t = "c#d# " **Output:** true **Explanation:** Both s and t become " ". **Example 3:** **Input:** s = "a#c ", t = "b " **Output:** false **Explanation:** s becomes "c " while t becomes "b ". **Constraints:** * `1 <= s.length, t.length <= 200` * `s` and `t` only contain lowercase letters and `'#'` characters. **Follow up:** Can you solve it in `O(n)` time and `O(1)` space?
null
null
Easy
null
202
all right it's the second day of quarantine recoding challenge the today's question is happy number we need a ride our algorithm to determine if the number is happy or not so you're happy number is defined as the following process we start with a possible positive integer which I guess is the input number we replace the number by the sum of the square of its integer digits and we'll repeat this process on tyr the number equals to one where you will stay so it will stay means that you replace one by the sum of the digits squared that would just be 1 so that's 1 will become 1 and then become 1 so it's basically a self-loop but it's just one basically a self-loop but it's just one basically a self-loop but it's just one of the number here which is one or you can stuck in some kind of other kind of cycle which does not include 1 so anyway it's just gonna try to repeat this process by replacing that replacing the number by the sum of its digits until we're stuck in some kind of loop either it's a single node sink or it could be a circular sink without the number 1 those numbers for which the process ends in 1 happy numbers so if it ends up in this cycle loose it will be not considered as happy ok so the example we have here in input is 19 so if we do this process we'll get 81 plus 1 that's a 2 and the second iteration 82 will become 68 then 68 will become a hundred and one hundred will become one and two the ones we reach one will stuck there forever and since the process ends in 1 this in point number 19 years can be considered as happy number so I guess straightforward way of doing solving this problem is just to simulate this process right just for any given number I would try to do this process but then we have to sort of a reasoning we guaranteed to converge to these two cases are there possibility that this number will just blow up into infinity because we do notice that if we take example of this number 18 here if you replace the number by the sum of the squares you become 82 which is larger than 100 as for some numbers like 868 it won't become a hundred so that's a larger than the number itself so when you do just a delicious show that the this thing will actually get converged this process what I actually get converged so I guess the way of thinking that is let's say that if you have a one digit number the largest you can have is nine so you be the largest replacement to get out of this 81 if you are two digits 99 the largest replacement you can have is 81 plus 81 so that's a 162 and if there are three digits the largest that you can have is 200 plus 82 81 that's 243 and if you have four digits the largest a replacement you can have is 300 so the replacement that the situation that when the replacement will be larger than the input number itself is limited in the case that's under three digits wouldn't when you go up to four digits you will never see this kind of replacement larger than the previous number so this is just a sketchy of showing that for arbitrarily large number you won't eventually get down to 243 and after that it would just be two cases whether it's equal to one or equal to you will be stopping a loop that does not involve one so I guess for the cases that under 243 we can just argue that you're likely to be limited time steps that we can determine you it's in either one of the situations so the time complexity was the number heads below 243 we can argue that sort of like a constant you know in the worst case we could just pre compute everything that's under 243 and once it's in there we just lock it up so we have some overhead to do but when you have any input number we can sort of argue that once it's below 243 it become constant so the difficult part to figure out the time complexity is when how many steps we need for the input to become smaller than 243 you know into the known cases so if you want the for let's just take an example of number that let's say it's six digits six there's n equal to six the largest replacement it can has is if every number is nine so that's a t1 multiplied by n right that's the now an equal this thing and the number of digits it has is and two and right and the largest replacement that can has is this thing 81 which is constant multiplied by log base 10 to n so the effective size of reduction that we can go from the input of size and input number with end to the next number replacement is the worst case is to reduce it to a constant multiplied by log N and the next number replacement we can have is log 10 of this whole thing so that would just be that would be chopped because that's a higher order terms in terms of time complexity so we can say that the input number is and the runtime complexity for doing this simulation is going to be log n for space complexity if we are doing the simulation in order to detect the cycle there are typically two ways of detecting cycles one is using a hash set to store the number see you have been through the way you know just memorize the numbers that you looked at sort of the way when you encounter a known number then you pretty much know that - you are in a cycle which is the that - you are in a cycle which is the that - you are in a cycle which is the second case you will return that the number is not happy that will use some extra space that depends on how many unique numbers along the way you will have you can argue its log and in that sense similar reasoning towards these time complexity analysis another method is the it's the Bunny and turtle method which you have basically two variables one just looking at the next number or replace the number by the immediate the next one in the simulation process you have another variable that's actually doing twice during the process twice so after each iteration compare those two numbers the faster one there the bunny and they're slow on the turtle one if they ever become the same number meaning that the faster number is actually one loop ahead of this slower one then you know yes there is a circle so for that algorithm you will have just two pointers so that would be two variables that's just reduced a space complexity from login to constant so that's pretty much the analysis for the question I guess yeah and maybe another crazy one to do is actually just did go through one to 243 and just to try to figure out the all the cycle is there and to just store those numbers hard-code those numbers in there and hard-code those numbers in there and hard-code those numbers in there and just doing this simulation whenever the transform the number is in one of those numbers that you get by exhaustive search from 1 to 400 243 once you find such number there you just return false otherwise you it's guaranteed to be happy so that's the basically the analysis and so I'm trying to recover my coding ability in C++ so I won't try to coding ability in C++ so I won't try to coding ability in C++ so I won't try to code the most history forward method which is using a hashtag I'll call this helper define a help of a function to do this simulation simulate this process which takes the number as in the import what it would do is to replace the number by the sum of its digits squared initially the result accumulator is 0 and 1 determination criteria is the number is greater than 1 greater than 0 and each iteration we truncate to the realest of digits and we incremented a result the accumulator by the rare loss the digits squared and for this method which this function we just returned this as result and so for memory we will use an ordered set I guess it's called which stored the integers of the numbers we've seen so far doing the simulation process I can't sing at the beginning we insert the input number into it while the number is not 1 if we ever terminate this while loop means that the number is happy we return to otherwise we will just return false so in this loop here what we will do is my logic got stuck yeah God my code has to slow than my saw to say yeah I need to recover my C++ let me just stop to recover my C++ let me just stop to recover my C++ let me just stop talking and code s crossing up and talk a little bit out there insert the transform denominator and we need to find whether we can find this number or not it's if we couldn't find this number we would insert that otherwise we'll just return false because that means we stuck in the cycle once we reduce the number to one we pretty much the number just must be happy so oh sure I'm talking all the code yeah why I don't have time to record to re-record this thing so this is the code re-record this thing so this is the code re-record this thing so this is the code yeah basically we have a helper function to do this simulate this process we return the replace the return the sum of the square digits of the given input number and the meta logic here is that we use a hash tag to store the numbers that we sing throughout the simulation process and if we find the number in the known numbers along the way then we must hit a starting to enter the cycle then we just return force otherwise we just memorize that number here we need to do the simulation simulate yeah so it's looks so right to me I'm not blocking anything no okay so yeah this time should find you see you should be able to see the code this is not the optimal solution it's just the pretty much the beginner most straightforward solution you can improve upon using the fastest low-point error upon using the fastest low-point error upon using the fastest low-point error message or maybe go hacky and just figure out all the possible cycles below 20 43 and hard-coded that you just 20 43 and hard-coded that you just 20 43 and hard-coded that you just get that message you still have to just hit the entrant of those numbers you know argue that the time is still logins but it's a constant space you know so let's submit this compiling error what I have here use of undeclared identifier for n okay that's just a quick check this time looks fun okay yeah that's the daily challenge for today
Happy Number
happy-number
Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: * Starting with any positive integer, replace the number by the sum of the squares of its digits. * Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. * Those numbers for which this process **ends in 1** are happy. Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. **Example 1:** **Input:** n = 19 **Output:** true **Explanation:** 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1 **Example 2:** **Input:** n = 2 **Output:** false **Constraints:** * `1 <= n <= 231 - 1`
null
Hash Table,Math,Two Pointers
Easy
141,258,263,2076
368
welcome to the daily challenge today is February n and it's New Year's Eve so I have a lot of time to record this video and this time I try to using different ways to display I wrote down the solution idea first and then it hope it will be more clear let's started this problem is largest divisible subset it's kind of it's a relative difficult problem for these days we are given the set of distinct positive in integers and what we are going to return is the largest subset of the answer so every pair in this set we have the following ration whether answer I is divis divisible by answer J or the other way route so how we going to approach it notice that if we didn't know that a n is the largest divisible subset containing n and well the maximum item in a and if we find o A1 T A minus nus one then we can find a because we just need to look at all the divisor of N and we look at a m we know the size of a in and then we compare we find the maximum then we hand this will work because for all the elements in am it divides um for all the element in am we have this relationship because m is the largest so K will divide M also we have m n then we get kide n so it's a value set next look at the example we're given the numbers 2 3 6 12 four we start oh although it's sorted um if even if it's not sorted we just sort it first here Restort it first and we start from the smallest element two then we use an array to store a so each entry in the array is a set not just a number it's a set so A2 it is easy it there's no nothing smaller than it so it just two itself A3 is three because two is not dividing three now come to A6 there are two possibility we can have 2 six or 3 six but either way it's okay and they have the same size so which just randomly pick one and go on A8 look from two to six and then only two divide it so we take it is the max the largest divisible subset and then we append eight here and 12 we look at we Travers again and we found a and six and it is the largest one we look at one more ter 824 this we it is clear that 12 is dividing 24 and six dividing eight dividing this are the divid there of 24 so which one is the largest this one and we because you have a size three then for this one we will get 2 six 12 and we return this if you're a math mathematic addict and you probably would like this expression so it is a very concise relation which summarize all of this for each n how do we find h n we look at of a sigma n what is Sigma n it's the index is a index what is the meaning of this syex it look all the N the index n less or equal to n oh also we have to add nums but look at all the small smaller or equal subset of it and M divided n which we argue here before then this Sigma will give us the index in which has the largest divisible subset lesser equal than an index in and then we append in that's coded up okay let's Implement our algorithm I'm a little bit nervous every time I wrote the code from scratch because there are a lot of some higho in it and have to debug for a while so please forgive me the first thing we're going to do is we want to Traverse the numbers from small to uh the smallest to the largest so we have to sort it anding and then we have it array remember array a and each array each element in Array is not number it is a set storing the um the largest divisible subset containing in here we make a little modification at is storing the largest we just right LD divisible subset containing numbers I so AI is the subset is a is the largest divisible sub containing Su this is to do going to do then what we are going to return is oh have we need a index pointer two to store the largest one then we return a result index it is a subset each I go through everything number and then we want to update AI so we have to look up all the entries before I including this um below the it's just an empty set because we haven't updated and by default it's empty this will work we'll see it and if I is divisible by J we would like to see oh we want to keep track of the mix keep track the max index so there's n index equals to negative because we will check whether if m x is one at the end if it is it means we didn't find anything if M index = 1 means we haven't anything if M index = 1 means we haven't anything if M index = 1 means we haven't it is the first item to update or the size numbers size index is smaller than the curve so it means we have to update it and sh then after the loop here we find the largest in uh the index of the largest divisible set before I and we have to append the set by Nal to we be outside of it we would like to use it and weend push back let's check is there any bug we go through the logic if I equals to zero then one and zero it will just run one time and numbers that definitely will div divide itself because I equals to J and then the max index is one so you go here and the max index is zero then you just appin in this case I when ials to zero it just it does nothing but after that we push back the first item then I think it's so that's here's the arrow let's figure out what happened and okay I found two bug in this program and one of the fu is the same as I did it this last time so here if it's divisible it will be zero and then it will not execute this line so what we are going to do is just equals to Li and then the next bug is we never update the result index so what case we have to update if the result index size is smaller than the current one and we update this hope it will work nice submit it 8% let's analyze the time complexity of 8% let's analyze the time complexity of 8% let's analyze the time complexity of this algorithm here we sort the array and loog and for each outer loop we execute n times and for each in Loop here I + 1 n times and for each in Loop here I + 1 n times and for each in Loop here I + 1 times so it's a n Square check it um here push back at most I atom we can view it as a o i it's O2 I and others are just 01 yeah so the time complexity is n² plus n this is bigger so this will been the wrong time thank you very much hope to see you tomorrow and hope I can finish or record finish recording all the videos in previous days and happy New Year bye
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
896
foreign let's take a now we run the follow or in I equal to 1. from here till the end of the y i equal to will compare I with I minus 1 that's what I equal to 1. I lesser than uh num start length and I plus by any time let's take for the ascending Arena ascending order so by any time if we get like terms of I is less than numbers of I minus one it will be like 2 1 2 then again one and three if I is pointing here you can see that 1 2 is greater than one fine but 1 is lesser than two it should be greater than 2 right so I minus 1. so numbers of I whatever is lesser than the so if I minus 1 is any time greater than I minus 1 is better than I that means you have to set the or you set the flag equal to false it's not in an ascending order or not only for the ascending Advantage descending order here to do itself now after this for example if you take the this example you can see I is always greater than I minus 1 for all levels 2 is greater than one who is greater than or equal to two and three is also greater than or equal to great depend 2. so yeah this is a monotonic increasing array by this time this condition won't happen fly equal to false will not be set so after this for Loop if flag is equal to true after this volume also if lag is equal to zero that means it's a monotonic increasing that array so you just return them as true so once you written it will go out of the entire program if what if the flash is set to false in this case Supply will be set to false here so else condition will come flag is not equal to true then comes the alpha and it's five so for else part we'll take the other example six so if you take this example else part again run the follow for entire equal to 1 2 IO length and I plus now you have to check my meat and if the given array is like 5 comma 6 comma four comma 4. again you can encounter that this 6 is greater than I minus 1 I is greater than I minus 1 that should not be happening I should be less than I equals one so if any time you will figure I as greater than I minus 1 times that means again before this here is just assuming that it will be in a monotonic increasing order so again you false that means it's not an increasing either decreasing order so one I've done it increasing multiplication so flag is but here in this case once flag is set equal to True after this condition and you got to know that it's not an ascending order so to check for descending order again you set value equal to true when you check whether IE is less than I minus one yeah five less than 4 is less than five four is less than equal to four so it is in decreasing order so this condition would happen plan will be true itself so if flag is false if you encounter then we just engage because that's further I attracting to the Rope is not required because you found here itself that it's not in either uh decreasing order so at last you have to return the flag so if I need to code this now Boolean flag equal to True let's set equal to 2. I equal to 1 and I lesser than numbers dot length I plus if by any chance anywhere if you found in this case if I is lesser than I minus one in terms of I is less than numbers of I minus 1. that means it's not in an ascending order so you say flying equal to false is equal to X once I said trial then false you just break from the loop no later so as you get into this uh you come out on the loop right now how to check if flag is equal to true or if flag if you write flag is equal to true just return the flag because yeah we got to know that it's in monotonic increasing model if this is not the case where the flag will be set up so you will get it right if that is not the case else condition will come again you have to check whether it is in a decreasing order so again I tried to look for INT I equal to 1 and I lesser than Mouse dot plan I plus if here you have to check for the condition if anywhere you should consider here comes of I is greater than in terms of 5 minus 1. so if I if it is greater than terms of I minus 1 here it is less than n here it is so that means yeah it is not a decreasing order as well so again you said flag equal to fonts here because here we might have got flag report walls one second flag equivalent you come to the else part again checking it whether it's in decreasing first you assume it is whether any element is in non-decreasing whether any element is in non-decreasing whether any element is in non-decreasing order or something then you set value control oh so that's it and now at last you can written okay let's see here I see and you can see the grid is 100 if you have any words please drop it in the comment section we'll come up with another next section until then subscribe to the channel and keep learning thank you
Monotonic Array
smallest-subtree-with-all-the-deepest-nodes
An array is **monotonic** if it is either monotone increasing or monotone decreasing. An array `nums` is monotone increasing if for all `i <= j`, `nums[i] <= nums[j]`. An array `nums` is monotone decreasing if for all `i <= j`, `nums[i] >= nums[j]`. Given an integer array `nums`, return `true` _if the given array is monotonic, or_ `false` _otherwise_. **Example 1:** **Input:** nums = \[1,2,2,3\] **Output:** true **Example 2:** **Input:** nums = \[6,5,4,4\] **Output:** true **Example 3:** **Input:** nums = \[1,3,2\] **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `-105 <= nums[i] <= 105`
null
Hash Table,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
1,425
hey what's up guys chung here again so today i want to talk about this like uh let's call the problem here uh 1425 uh constrained subsequence sum yeah this is like a hard problem and this one this problem like actually consists of few sub problems so let's take a look at this uh description first so you're given like an integer arrays right and the integer k notice that the integers in this rate could be positive and also negative and you need to find the maximum subsequence so that i mean it's sum is the it's a max and what's the constraint for the subsequence right so the constraint of the subsequence is that uh any two of the consecutive numbers in the subsequence it's distance i mean the index right the put the index between those two cannot be greater than k right so what does it mean it means that for example this one it if the k equals to two right and for subsequence you can basically remove any letters uh any element from the existing array and while we uh keep the out the remaining keep the remaining uh elements in their own in their original order for example here right so from if the k equals to 2 it means that you can skip one element at most right for example here 10 two and from two we uh we jump from two to five right basically we jump and we skip this ten here all right so why we're skipping 10 because we want to get the maximum value of everything right so that's why we're trying to basically trying to skip the as many uh negative numbers as possible right and then if it's a if it's like an integer if it's a positive integer then we know okay fine we want to uh we don't want to skip them because that will make the subsequence have like uh have a bigger uh sum a sum right and when it's like uh a negative 10 here right we want to skip that in this case we can just keep -10 right we can just keep -10 right we can just keep -10 right and then the final result will be this one that basically that's going to be our biggest sum so let's take a look at another example here right for example this one we can still case also 2 which means we can still skip at most one inch or one negative one element right but in this case there are like three consecutive uh consecutive and negative numbers here right so as you can see we can only skip one at a time right and that the next one is we cannot skip that so from here 10 to minus 2 right we can either skip 2 and then we're at minus 10 and we cannot skip miners anymore right because that will make this distance greater than k so we have to keep 10 but we can then skip minus five or we can uh from 10 to negative two we don't skip but we skip minus ten right and then minus five and twenty that's how we get the relative like biggest sum right among all the possible ways okay so and this is like we can solve this problem with the dp idea here basically this is like i think it's a classic k knapsack uh problem basically as dp i right and since this is like a array here right so we can just use a 1d uh dp array to store all the states so the dpi means from zero to the current index what's our what's the maximum sum right then what so how can we get this one from maximum sum right remember since we're it could be like we could get dpi from multiple state right it's not it's different as the other one you know if you guys remember the other like if you try to find the summarize the maximum sub consecutive sub uh consecutive sub arrays right that which in that case it means we can only get to the i state from d i minus 1 right because they are consecutive but in this case it's not right in this case we can skip at least at most k minus 1 element right so it means that let's say there's like uh so here we have i right we have i and then we have a i minus k minus 1 right and 2 i minus 1 right so this is the k this is a case window right and this is i so within this k case size window here anyone can jump into i directly right so that's the difference here because as every time when you see this like k size sliding windows uh for if you want to solve this one with the dp solutions you have to use like um you need to use like this basically this gonna be the maximum of dp dpr i minus k minus 1 to dp i minus 1 right plus the current number right so that's the difference this is a traditional one because here the dpi will can be deduced from any of those right and well actually if you guys remember there's like another uh easier easy like dp problems basically it's the same uh similar uh description you're also given like a raise here which is not either positive or negative numbers here but there's no case here basically it just asks you to find the maximum sum of a continuous sub array here so how if you guys uh try to recall that's problem how what do we do about that right we do uh we also create a dpi here right d dp sorry the dpi here and since for that problem since the uh since all the sub arrays there has to be i mean continuous right so we can only get the uh the dpi from dp i minus one right i minus one and then what do we do a basically we simply do a sorry simply do a max of the dp i minus 1 and 0 right plus current number right so that's how we uh solve that easy problem with the dp idea here because the what the reason we're using a max uh compared with zero is that if like if this dpi minus one is smaller than zero right then we would simply use zero because we don't want to carry over any of the uh the negative values to the current state right basically if the previous state has a negative value then we just simply discard it right because that will make our current state has a last summarize sum right okay same thing here right same thing here basically here max of that and then we also need to add like a not uh not only we need to compare everything from dp i minus k minus 1 i and to my i minus 1 we also need to compare with the added 0 here right because let's say if everything basically if all of them the maximum around among them is always it's an active we still want to like a bound set of boundaries upper bound so a lower bound for the previous like result the maximum result is zero same concept here right if everything from the previous state is negative then we will discard often what is zero all right so that's the first idea here right and okay so with that right and then the problem comes down to uh i mean how can we find the uh is this case uh case like window a case window here how can we uh find the maximum value from this case sliding window right it's guys as you can you guys can see here so the k can be up to 10 to the power of 5 length which is pretty big right so basically it means that if we use a brutal force or like we just simply search you know for dpi we need n right we need n and to find the maximum values for dp uh for in for case window right we'll be also using an n with traditional way basically we loop through everything in here right we find the maximum and then in the end we'll get like n square right and with this kind of like 10 to the power of 5 quantity this will tle so with 10 to the power of 5 so ours our algorithm has to be either n log n or n all right so for unlock and with this like dp uh for this problem we can use a priority queue right basically since we're going to get the maximum right so when we're gonna maintain like a priority queue like the uh and every time we see a new uh we move basically move this like uh this i forward every time we see the eye here right we'll update this priority queue basically we'll move this the last element out of the uh the sliding windows and then we'll check if this last element is the first element in the priority queue if it is and then we pop the priority queue right because the priority queue will give us the current maximum a maximum value for uh within this range of k and with priority q the uh the time complexity to maintain a priority queue is unlocked right uh sorry it's a lot it's log n uh it's log n let's see yeah so for priority q the push and pop the action is log n and for n and then we times n so the total will be n log n right and there's also like a even better a better uh state structure to uh to make this time complexity from unlock and to lock to n that's called a monotonic cue basically like in this case it's gonna be a decrease in q right so this decrease in q like is maintained right it's maintained the first element of the decreasing q will be the current maximum number within this k range right and to maintain like a decrease in q is a it's n right so and the uh the each uh insert or update or a pop for the dq will be uh for the queue will be one or one and uh and the n element it's still going to be like the total going to be n plus 2n right it's going to be a 3n which is also like a an o n time and okay i'm gonna try to write the code now the code is not long but the idea behind it is kind of like so you have you guys have to uh i mean remember that basically every time when you see it's like when you try to get like a minimum or maximum value from a sliding window best way is to use the uh the molecule the monotonic queue right and that can make this uh time complexity to o in time okay so with this dp one here with dp and with this two of this like boundary up set as a lower bound boundary to zero and with this like uh mono queue to keep track of the maximum values within the range k we can start our coding all right cool so uh first i'm going to create a d crease q right it's going to be a collections of the dq and then a length of n of the numbers right and then of course the dp right excuse me the dp so and okay so the dp is this so one thing to notice here that we use the n here so not um plus one and then we so that we can it's safe that we set this one to zero otherwise if you use m plus one uh for the first element we have to set it to uh what to uh to an active maximum number because the uh the result could be below zero right if we set if we have an unused space that has a zero that will affect our final result basically if there is a like if the biggest one of our calculation is a negative number but we have a some orphan zero here in that in the dp array right and then in the end when we do a max of dp we'll get zero instead of that correct negative number right so and now so soon i'm gonna enumerate right enumerate numbers right so basically so every time right what do we do here we uh every time when we move into the new like positions we're gonna update it right we're gonna update our decreasing q first so how do we up what do we uh we try to uh basically uh once we have wearing the i here right and so we check if we need to pop if we need to remove the uh pop the first element from just decreasing q right basically if this one is not empty and end of this dq q the first one is the same as the element that is about to move it is about to move outside of the sliding window right so which means that the element will be moving out of the sliding window is the nums from current i minus k minus one right then if that's the case we simply do a pop right so what does this mean okay let me draw a quick example here so uh basically this is the element out when we are at i here right so this is the i minus k let's say here 10 uh minus 2 minus 10 okay so we're at i here right so the i is the uh let's say the i is here i is 2 right and the k is also equals to 2. i equals to 2. so uh since this like okay let's have another number four here right so i think that will be better here so and if this is three here right zero one two three i equals to three and k equals to two right and then which number will be the one that's being moved outside of the sliding window right it's the uh we're we are at i right and then so basically either 10 or minus 1 can be jumped to our current like window right but the four is the one that will be moved outside of the sliding window because the lighting window is a size of two right the sliding window were i mean was here before we moved from minus one to minus two right now since we moved the uh since we moved the sliding window uh to the right by one the sliding window will be at this i will add the 10 minus two and this one not for the uh this index right so this index will be moved outside of the sliding window and then remember here i think i made a mistake here so remember here the decreasing q here it stores the dp value right the dp not the numbers right restores the maximum numbers we can get at this position right at this dp position so basically here so first you know to make sure the uh this one the dp won't get any negative values right we have to do uh if the i is greater than k right when i is greater than k then we can do this right otherwise the dpu will have a negative volume which means which doesn't make sense and so if i is greater than k and then we can try to remove the element from the this four this index out of the sliding window and by doing that we will try to update our decreasing q y right so the way we're where we are updating is we check if the uh if the dp element is try it's being moved out outside of the sliding window is our maximum value right if it is then we know oh we lost our current maximum value we have to pop this current max value out right and then it will give us the next one will be that the current max value if it is not the biggest value right then we don't do anything because we still have our current max value somewhere right later on somewhere for example this one right for example this one the uh the current max value is at this moment is 10 right and by removing four sorry it's not the uh yeah i was confused so it's not the actual number it's the dp values here it's the maximum of the dp values and if the one we got removed let's say if the dpi minus k minus 1 is not the maximum value inside of this d uh decreasing q and then we don't have to pop it because we still have the uh within the current k range we still have our maximum value right so that's how we uh update our decreasing q here and now it's time for us to finish the dp function right so basically dpi equals to what equals the maximum right maximum of the uh remember the first ones we stored the decreasing q is the maximum value of the dp which is exactly what we need now right and then remember we have set up the upper bound the lower bound with zero right and then a plus number right and since we are having this one after that we also need to maintain uh our decree our decreasing q right basically while decreased q is not empty and right and the decreasing q dot q that the last element right the last element so it should be pop left because the first one is the biggest so that's why we put to a pop left smaller right smaller than the number sorry smaller than the up sorry dpi yeah always keep in mind we are maintaining like dp values in the decreasing q not the current number uh then we simply do a decreasing q dot pop all right then in the end we do a decreasing q dot append with the current dpi right and in the end we simply return the maximum of the dp right yeah so that should just do it let's try to run it out of index oh here i think yeah so at the beginning of this these this uh it's decreasing q it could be empty right it there could be nothing in this decreasing q and which means right let's say for example the first i when we enter this thing for the first time right there's nothing in the decreasing q and so if you do a d dq 0 it will be out of the bound out of index so we'll do if dq else are zero right if there's nothing we simply do at zero all right cool let's try to run it yeah okay so it's passed all right so let's do a recap here so a few sub problems here first one is the uh it's a dp so the main idea is this is a dp so you have to come up with this like the dp function here basically for the current dpi there are like a k ways there are k ways you can get to the current dp right that's from the i minus k minus 1 to the i minus 1 and among all those k ways we need to get the maximum between them right and also and then the next one will be uh between the maximum we also need to set the upper lower bound to zero because we are one we don't want to carry over any negative values right if they're all negative if the maximum from the previous state is negative we simply discard all the previous data we just have a fresh start right so that's number two and the number three is the uh since we have this like huge kind of pretty big uh inputs uh quantity here we cannot use like a naive linear search for the maximum values we either have we have to either use like a priority queue to maintain the maximum or even better data structure which is what we are using here is called a monotonic q we're using a decreasing q and we're using a decreasing q to maintain the current within the current case range case window range what's the biggest value among all those dp values right and then we always uh the first step will be uh update that the sliding window and then with the updated sliding window we calculate the current dp with the maximum value inside of the decreasing queue and then in the end we'll update our dp window sorry we update the inc uh the decreasing q again right since we have this like a new number here i will try to uh pop anything before the current eye which has like smaller number right that's how this like decreasing q works right because um this current with this current bigger value right with the current bigger value which even has a bigger index the previous the pure the previous smaller number will never get picked because we need the maximum value right because we need the maximum value basically the later one has since the later one has like a higher like higher values the previous one the previous smaller one it's useless right because we are using we're trying to get the current maximum value right so and this one will always get picked because our process is moving it's moving to the right and this thing and this eye will be moved outside of the sliding window after all those uh after all the uh after the previous elements and if this one has a higher values and this will always be the ones that gets picked in here right that's why we can simply pop the previous like small ones outside of the out of the decreasing queue and that's how we maintain the time complexities right basically every time we're maintaining these like q's here right the pop and append is only one and we'll go we're basically in uh basically uh pushing at most an element and also popping at most an element so the total operation of this q is 2n right and plus the outer loop is also an n so the total time complexity for this is three n which is o n right and the uh the space com space complexity is pretty it's a dq is in and the dp is also on so it's also on right uh cool so very cool so there's like i think for this molecule problems there's also like a very similar problems it's like a little bit easier than this one but using the same concept i think it's number two three nine and basically using the same similar concept by maintaining like a decreasing q but it's instead of storing the dp problem and storing the uh the actual sum so that's why it makes that problem a little bit easier than this one like this one just combines several ideas in into one problem okay cool guys i think uh this video is a bit long because why i there's too many things i want to talk about in this problem okay i think hope you guys enjoyed the videos thank you so much for watching it and stay tuned and i'll be seeing you guys soon bye
Constrained Subsequence Sum
weather-type-in-each-country
Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied. A _subsequence_ of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. **Example 1:** **Input:** nums = \[10,2,-10,5,20\], k = 2 **Output:** 37 **Explanation:** The subsequence is \[10, 2, 5, 20\]. **Example 2:** **Input:** nums = \[-1,-2,-3\], k = 1 **Output:** -1 **Explanation:** The subsequence must be non-empty, so we choose the largest number. **Example 3:** **Input:** nums = \[10,-2,-10,-5,20\], k = 2 **Output:** 23 **Explanation:** The subsequence is \[10, -2, -5, 20\]. **Constraints:** * `1 <= k <= nums.length <= 105` * `-104 <= nums[i] <= 104`
null
Database
Easy
null
12
welcome to march's leeco challenge today's problem is integer to roman now i'm not going to read the problem because it's fairly simple we want to convert an integer to roman numerals here we have the symbols and values that the roman numerals represent if these were the only ones that exist it would be easy but the problem is what about these values for like 4 9 40 90 stuff like that is represented differently with iv ix so on and so forth so the easiest way i believe we could do this is to simply start with the largest symbol value and see if that's less than the number that we have so far if it is then we could add that symbol to some sort of output and then subtract that value from the integer itself and continue the loop until we can no longer see that this value is um less than whatever we have left if it's no longer less we move on to the next smallest number and continue the loop until we um take care of the entire integer now uh the only trick here is we need to add extra symbols here for like four 900 440 and 30. but this algorithm will remain the same so what we'll do is first create a lookup i'm going to make it a dictionary and luckily in python these dictionaries are ordered so we can just reverse it later to go from descending order what i'll do is make these a string and i also will need to take care of all those values i talked about like 4 and 9 that would have to be put here like this so make sure to update these values for nine now we need 40 and 90. the x l x c make sure it's 90 40 and 400 900 m this would be d so all right so now we have our lookup dictionary so the rest of the algorithm is fairly simple what we'll do is go in reverse order first create an output with just an empty list and we'll say four key value in lookup dot items but make sure to reverse it because we want to start with the largest number first now you could have restructured this with the largest on top but i mean this is still oven so i don't think it's a big deal we'll say while we still have a number so num is greater than zero if the value we have is less or equal to num then we're going to add to our output the key and we're going to subtract from the num v value now otherwise if this is not the case we're going to break out of our loop and move on to the next number so finally we should have our output so we are just going to do a string join to return it in string format all right so let's see if this works that looks like it's working let's submit it and there we go now time complexity wise i believe it's o of n being the number of symbols we have here because at most each one of these we're going to be adding four times keep in mind that the constraint is this is going to be less than four thousand so each one of these we can only add four times so i think that's in the end of n space complexity is also the same because of our output i suppose we do use some extra space here because of this but i don't think that makes it any big difference now i did see some of one solutions where you could write every symbol for each digit value from like one to nine and then uh 10 to you know 99 whatever 10 to 99 get all those digit values and write those symbols and do it all in all of one but that requires a lot of work in terms of creating the lookup dictionary so i decided to avoid that would be faster but i think this is fine it's more intuitive anyway alright thanks for watching my channel and remember do not trust me i know nothing
Integer to Roman
integer-to-roman
Roman numerals are represented by seven different symbols: `I`, `V`, `X`, `L`, `C`, `D` and `M`. **Symbol** **Value** I 1 V 5 X 10 L 50 C 100 D 500 M 1000 For example, `2` is written as `II` in Roman numeral, just two one's added together. `12` is written as `XII`, which is simply `X + II`. The number `27` is written as `XXVII`, which is `XX + V + II`. Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not `IIII`. Instead, the number four is written as `IV`. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as `IX`. There are six instances where subtraction is used: * `I` can be placed before `V` (5) and `X` (10) to make 4 and 9. * `X` can be placed before `L` (50) and `C` (100) to make 40 and 90. * `C` can be placed before `D` (500) and `M` (1000) to make 400 and 900. Given an integer, convert it to a roman numeral. **Example 1:** **Input:** num = 3 **Output:** "III " **Explanation:** 3 is represented as 3 ones. **Example 2:** **Input:** num = 58 **Output:** "LVIII " **Explanation:** L = 50, V = 5, III = 3. **Example 3:** **Input:** num = 1994 **Output:** "MCMXCIV " **Explanation:** M = 1000, CM = 900, XC = 90 and IV = 4. **Constraints:** * `1 <= num <= 3999`
null
Hash Table,Math,String
Medium
13,273
1,197
That welcome back to much of satyam 10 video latest white python code to return dhund number of steps needed from modi night in this point to destination 2518 possible for the right to in shakti left right top and bottom and moon can be defined in such indefinable The first to strictly indicate movement in the bottom directional next two years that subscribe to this presentation just gives the earth movers left side addressed current position of this unknown Egypt where to find the number of waste oil fast first search al Qaeda crop hot indicator in simple five Step First To In This Location Roop Note Subscribe Not End Comment Subscribe Find The First Report Did Not Need But Subscribe To Know Well Destinations Not Found 10 Minutes App For Further In This How To In This You Will The Child Not Know What Are Difficult Dialed Note Is Nothing But Possible Maximum From Current Position From Back Side Subscribe 9 10tv How To Reduce Bluetooth On Difficult To Meet You Know With Which Cold Not Specific Subscribe Reported A Level Of This Child Not And With This Which AIDS Patient Number Of state in the voice of how to do you think she tried not to reduce subscribe in the play list in heaven for third double end notifications model not coming ardhya algorithm fasal purchase amrit fasal first step meanwhile how to start position form not defined The Black Pearl To Change The Third This Mix Subscribe Destination On That Explain Destination Boyd F4 Parameters To Our Minimum Night Mousse Function That Navi How Does Institute Start Position Original Note And The Return Of The Rebel Through Which Help In Life Wealth 168 Accent Developed Bad meter to this function along with that i and comfort two-fold day 1150 nod in this i and comfort two-fold day 1150 nod in this i and comfort two-fold day 1150 nod in this fuel soe purse plunder initial available 220 and have nots in two some suggest rider chaplin that which is selection tube 960 x send a specific routes which made Step Next Going To Do You Know Death At Current Levels With This Love You All Subscribe Values ​​Will Not Holding Subscribe These Notes I Will Not Come Will Move To The Third Step Factory Destination This Account Deficit To Report The Levels Of No Return On Equity Research Subscribe To A Chronic This And Current This White Say Add Distance Of benefits of the match is not for diabetes how to do i will not withdraw it to the first half inch you know how to draw a specific is good i have gone after 10 sheets with births posts now you edit sunidhi Kyun na ki end to aap andher titishuddhi in thyroid tu abduction one person reason they bihar wa pending oil direct oil notes to our tube days virtual them and the city channel subscribe our is the fourth step ki bf real hot but qualitas four this yes be one More Thing It Ying Suen Adheen And The Alternative Bluetooth On It And Not A Yes Aave Set Open 10 Biscuit Subscribe To That And It's Fly G A Fright So Before Opening A Fuel Child Not A Visible Set He Simple The Armed With Wick A New Notes On has happened the current tax deduction current wali placid his shadow dividend set subjects will hold all no data yer do the tube b4m are doing it's not benefit to check if oo that the new child notice already between center and not give it is not withdrawn It's how to do subscribe our algorithm and director of not only not visit all subscribe maximum not from north to all who consider them not going outside the country will not go outside of flight hai 200 ko try now will do now them channel and also will Do the no data has not been set up at here that i show rent act with blood decree porn 1502 avya celebrity dongri em fine arts and all ko long direction is a wide plus the world is listen the boundary conditions and that they are new Position dabish di a chronic hai a it us plus b Position Tuel-Tuel-Tuel-Tuel Along With Loop Subscribe Certificate Course In The Child Not Only Didn't Wish To A Week And Getting Dark Child Got Subscribe Not Attempt In Repeat From Chapter If Sa Ball Se File Not A Destination For You To Repeat Specific That Provider Why Is Not Name Hua Hai 102 Hello Viewers Is Not MT Repeat Step Chul Ki And Exam Is The Current Question Is My Chaturdash Liye Ek Siddha Vrat First Search Report Igloo Not Difficult You Dark Child Not Know How To Get The Program Will Return - No More Sun Latest Not Define Our Person Boundaries Him This Sum 702 Subscribe And How To The Number Of Subscribe Our Define Name Subscribe Destination Commando 2 I am my executive officer a you slept in one step with good day that modi night from its current position ok we last initiative was With Ann c12 on the right side is 158 sure in which we can achieve destination nor change through the destinations sorry 6 and the meaning of tips subscribe loot strengthen understanding simple algorithm is the best on fast the first search for a hope you liked Our Video Please Subscribe Our Channel Star With Your Friends On
Minimum Knight Moves
parsing-a-boolean-expression
In an **infinite** chess board with coordinates from `-infinity` to `+infinity`, you have a **knight** at square `[0, 0]`. A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. Return _the minimum number of steps needed to move the knight to the square_ `[x, y]`. It is guaranteed the answer exists. **Example 1:** **Input:** x = 2, y = 1 **Output:** 1 **Explanation:** \[0, 0\] -> \[2, 1\] **Example 2:** **Input:** x = 5, y = 5 **Output:** 4 **Explanation:** \[0, 0\] -> \[2, 1\] -> \[4, 2\] -> \[3, 4\] -> \[5, 5\] **Constraints:** * `-300 <= x, y <= 300` * `0 <= |x| + |y| <= 300` "t", evaluating to True; "f", evaluating to False; "!(expression)", evaluating to the logical NOT of the expression inside the parentheses; "&(expression1,expression2,...)", evaluating to the logical AND of 2 or more expressions; "|(expression1,expression2,...)", evaluating to the logical OR of 2 or more expressions.
Write a function "parse" which calls helper functions "parse_or", "parse_and", "parse_not".
String,Stack,Recursion
Hard
null
724
hello everyone and welcome back to another video so today we're going to be looking at the question fine pivot index and we'll be going through two solutions so first the brute force and then a way more optimized solution in constant time okay so real quickly we're going to be given an integer area called nums and the goal is to find the pivot index of this array so the pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum and all the numbers strictly to the right of the index is equal to its sum so both the left and the right sums are the same essentially so if we are at the index zero the left sum is zero and if we're at the last index the right sum is going to be zero so now the goal is to return the leftmost pivot index and if it doesn't exist we return negative one so in this case let's just look at this example of one seven three six five six where the answer is three so let's see what that looks like okay so we have the example over here and the small numbers on the top over here are the indices okay so let's see what that actually means so well we know this is the answer so let's take a look at everything all the elements to the left of it so these are all the elements and its sum is 7 plus 3 plus 1 which is nothing else but 11. now everything to the right of it are the numbers five and six so that is also a sum gives us a sum of one so they both equal to the same thing which makes sense on why the index three is the pivot index so let's first look at a brute force solution now the solution here is going to be to keep track of the left sums at each index and we're also going to keep track of the right sums of each index and then we're going to just compare the two of them whenever they're the same well that's the index we're looking for so let's just see what this looks like real quickly and once we understand this we can actually move on to another concept okay so we have the left sum over here so the first one is going to be our v0 because the left of the zeroth index is nothing it's going to be zero cool so now we go on to the first index so what is the left of the first index well that's the number one cool so now we have the second index so what is on the left of the second index well we have the number seven and one so now this is where we can actually apply a small trick so we can add the number seven plus one but instead all we can do is we can just look at the previous number the cumulative the previous cumulative sum we have and add it with the current number we're at so that's one plus seven which is eight so this is going to make more sense when we're at the third index for example now over here we can either do one plus seven plus three so that's three additional additions right instead we could just do the previous cumulative sum which accounts for both of these values and the current value itself so now we're just doing one addition instead of three additions which are already just going to be repeated so in this case it's just three plus eight which is eleven right so now we go to the fourth index so now that's going to be six plus 11 17 and now at the fifth index is going to be 17 plus 5 which is 22. perfect so now this is the left sum now let's see how we can get the right sum now in the right sum how do we find the first element so there's two ways we can do this so we can actually go to the zeroth index and find all the elements to the right of it so it's sum right so what is that going to be so 7 plus 3 10 that's going to be 22 27 right so all of this together is going to be 27 but let's actually try to come up with a algorithm or formula that is going to be a lot more intuitive so instead all we could do is we could get the entire sum now the total sum is of the entire area is going to be 28 right so 27 plus 1. so total sum i'll just write it over here is equal to 28. now how do we find out what is the right sum of the zeroth index so in simple words that is going to be the total sum minus the current value that we are on got it so that's just gonna be 28 minus one okay so that's nothing else but the number 27 right so we're just going to kind of continue that pattern so now we're at this index the first index so over here it's going to be all the values to the right of 27. so now we're actually not going to include two values we're not going to include the value 7 itself and we're not gonna include any values to the left of seven so that's just going to be 28 minus seven minus one which well is 20 right and another way to look at it is it's just the 27 minus seven so let's just kind of follow that pattern and then let's make more sense of it as we go on so now at the second index well we don't want to include the number 3 as well so 20 minus 3 is 17 okay so now we go on to the third index so that's 17 minus three sorry 17 minus six which is going to be the number 11 and then we're at 11 minus five which is six and finally the last value is zero which is what we expect because there's nothing to the right of it so now in this case now we're going to compare the values so 0 27 120 8 uh 17 and then we have 11 and 11 right so this is perfect right so we have a match and that means that the third index is going to be a pivot index okay perfect so now the question over here is how can we actually further decompose the right something we were doing so just to look at it further more let's take the third index for example right so what exactly are we doing so we have the total sum now we don't want to include the number itself and we also don't want to include everything to the left of it what is another way to say that another way is that we're taking the total value we don't want to include the current number which is well 6 in this case and we don't want to include the sum or all the values to the left of 6 and that is nothing else but the left sum in this case add to index three right so this is going to be a very useful relationship that we can use to actually improve our solution so let's see how we can do that but before that let's take a look at what the time complexity is going to be and space right so to make the left sum table it's going to take n and uh space and time and for the right sum it's going to take an additional uh n space and time now we're going to make the comparisons which is going to take an additional end time so that is a total of theta 3 n for the time complexity or just big o of n and the space complexity is going to be 2n or just big o of n right so now can we try to get any of these down to constant space or constant time obviously we cannot do constant time because we will have to iterate through the entire area at least once but we can try to do constant space and the previous relationship that i pointed out is going to be very helpful for that so let's actually see how we can do that and avoid making these two tables and just keep track of everything inside of a variable okay so now like before we're going to keep track of left sum in a variable well in the beginning it's zero and we're also going to keep track or just we're going to have the total sum with us okay and the total sum was 28 right it's the same as before so now what we're going to do is we're going to go in a for loop right where we're going to iterate through each of the values okay so now in this so now what we're going to do is the first value right so we have the left sum and we want to compare it with the right sum okay we're checking if this is if this condition here is true now how do we find the right sum well the right sum is like we said right it's going to be the total sum all right so the total sum minus the current value itself because we don't want to include that so let's call the current value curve and we want to exclude everything to the left of it now everything to the left of it is as good as excluding the current left sum we have which in the beginning is zero so right now we're going to be comparing so i'll just kind of make a table so it's easy to look at so we're gonna have the index we're gonna have the left and we're gonna have the right so the index over here is zero okay now okay sorry uh now we have the left sum which is also zero now the right sum is going to be 28 minus the actual value one and the left sum which is zero so that's nothing else but 27. so now we compare the left and the right values are they the same they are not so we continue so now we go on to index one so the left sum well now we have to add the value over here right so now we add the add to the left sum by adding one so that's zero plus one which is one so l is one and now the right value is going to be well 28 minus the current value which is seven and everything to the left of seven which is nothing else but one in this case okay so that's equal to twenty so they're not the same again so now we go into the index two so at the index two before that we had to increment the left sum so that's one plus seven which is eight so we have eight and now we're going to do 28 minus the current value three and everything to the left of it seven plus one in other words which is eight right or the l sum and that is going to give us a value of seventeen cool and now they're not the same again so we go to the third index before that we increment the left sum so that's going to be 8 plus 3 which is 11 and so we're comparing 11 with 28 minus the current value which is well 6 minus the left sum which is 11. so that is nothing else but 28 minus 17 right and that is just going to add up to the value 11. so in this case the left and the right are equal so we end up returning the index three so now with this condition over here so finding the sum is going to take big o of n that is going to take n time then we're going to take another end time in the worst case condition to actually do this calculation over here so that's going to be theta 2 n or another which is big o of n and finally the space complexity is going to be constant space right we're not using any extra space everything is just being stored in these two variables over here so that's going to be it and this is going to be the best solution that we could find so uh and a big o of n and constant space and now let's see what this looks like in code okay so we're going to have a variable for the left sum and we're also going to keep track of the total which is well just the sum of nums okay so now we're going to go in our for loop so we're going to do for index and range length of nums okay so now over here we have to make our check which is if the left sum is equal to the right sum now if this condition is true then in that case we that means we found our pivot index and we're going to return the index now if this is not the case we have to increment the left sum with the current value and the current value is nothing else but nums index now we also need to define the r sum over here so i'll just define it over here so that's just going to be the total sum minus the current value we're on which is just nums index subtracted by everything to the left of nums index which like i said is just left sum so since we're not using this variable ever again i'm just going to replace it right over here right and so storing it in a variable so this is going to be our code now if we don't if we go to the entire for loop not returning anything that means we don't have such an index and we return negative one so let's submit this so thanks a lot for watching guys and do let me know if you have any questions thank you
Find Pivot Index
find-pivot-index
Given an array of integers `nums`, calculate the **pivot index** of this array. The **pivot index** is the index where the sum of all the numbers **strictly** to the left of the index is equal to the sum of all the numbers **strictly** to the index's right. If the index is on the left edge of the array, then the left sum is `0` because there are no elements to the left. This also applies to the right edge of the array. Return _the **leftmost pivot index**_. If no such index exists, return `-1`. **Example 1:** **Input:** nums = \[1,7,3,6,5,6\] **Output:** 3 **Explanation:** The pivot index is 3. Left sum = nums\[0\] + nums\[1\] + nums\[2\] = 1 + 7 + 3 = 11 Right sum = nums\[4\] + nums\[5\] = 5 + 6 = 11 **Example 2:** **Input:** nums = \[1,2,3\] **Output:** -1 **Explanation:** There is no index that satisfies the conditions in the problem statement. **Example 3:** **Input:** nums = \[2,1,-1\] **Output:** 0 **Explanation:** The pivot index is 0. Left sum = 0 (no elements to the left of index 0) Right sum = nums\[1\] + nums\[2\] = 1 + -1 = 0 **Constraints:** * `1 <= nums.length <= 104` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 1991: [https://leetcode.com/problems/find-the-middle-index-in-array/](https://leetcode.com/problems/find-the-middle-index-in-array/)
We can precompute prefix sums P[i] = nums[0] + nums[1] + ... + nums[i-1]. Then for each index, the left sum is P[i], and the right sum is P[P.length - 1] - P[i] - nums[i].
Array,Prefix Sum
Easy
560,2102,2369
1,732
right hello guys so the today's challenge of finding the highest altitude is the interesting problem and we can solve this problem in a very you know different many different ways I have already posted the video for you know solving this problem and you know it's just that you know when you solve an interesting problem you just after some time you come up with a new way to solve the problem so in my first solution I had used a secondary agree of length one more than the input array then I use two variables and now I am suggesting that with using only one variable we can solve this problem so one variable you know just one variable and sum is equal to zero Max obviously we need one variable Max to take care of the you know Max when you've seen so far and they can do this thing okay for and I is equal to 0 I less than n Dot 11. plus I sum plus is equal to gain also I if sum is greater than Max is equal to sum what are some okay and this is about but it is about the term Max perfect so this is one way to solve the problem let me know if you have any doubt I'll definitely try to answer those doubts
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
1,625
hello everyone next unsolved question uh is 1625 lexicographically smallest string after applying operations k so let's go to the question it's taking time to load it second yeah so many disliked it so it must be pretty easy question still it's medium so i'm going to solve it you are given a string s of even length consisting of this 0 to 9 and two integers a and b you can apply either of the following two operations any number of times and in any order on s and uh add a to all indices of s zero index okay add a to all indices of s so you are give there is a string s let me write it there is an string as even length okay now 0 to 9 is inside it and there are another two integers a b given you can apply either of the following operations any number of times in any order okay add uh a to all indices of s a to all indica surface okay digits post nine are cycled back to zero okay it will be taken like mode nine not mode nine other mode ten for example if my sister's a is five then three four five and six add five to each okay and then take models so six plus five is eleven but taking mode to ten it will become one five plus five is ten more taking mode two okay one second yeah five plus five okay this is a bit problematic all in that okay odd indices so only this and this will be considered it will remain five that here don't add here for four plus five nine and the three nine five okay rotate as to the right by positions by b positions so three nine five one by one means okay four three four five six it will be converted into buy right now so three five six and stay five sorry so three four five and six will come at first okay at the end of it lexicographically small string way is needed okay so these are examples further the length can go up to 100 and a and b are given let's see what we can do here it looks a bit pretty straightforward like if we have 0 1 and a is 4 and b is 2 okay it's already okay it's already so much small hmm and every time we are adding like if it is eight by addition yeah addition to it eight nine like if we have the number eight and our a is equal to one let's see let's take an example eight it is our number and a is equal to one then eight nine then again after that it will convert into eight zero okay now reverse it so zero eight now oh that's why it was telling like not reversing it reversing is not the right thing to do here we have to go right so if any number is given like suppose n1 into n3 dot nk what we can do is we convert it into the minimum possible value okay from nk to the previous one then we rotate it to the right okay now we will try to now this will become our ordinaces and do n dot daughter then we will convert it after that okay let's see what else can be done hmm and one and two and three dot unknown so five two five convert into two zero five let's try it on let's try that so at first it is rotating then adding hmm it is a bit difficult to understand let us suppose let's do some kind of bfs traversal like we can start we like it's a if we have a number we can either go for rotate or we can go for add this i haven't found anything like i haven't found any dd solution in here it is not anywhere near anywhere so rather than thinking about greedy let's rotate it and add okay then further rotate it and add it add one more time and let's do the same thing until we will find 5525 again okay so all the rotations and all the addition will count up to at max what let's see the hand dressing yeah 10 gross 10 cross ass dot length so is it going to check all of them start length suspended oh even length is given now so we have to check all possible yeah that's what that's the same thing if you go for bfs um and if n at any place okay now i want it like i have taken the hint just because to reduce the time i will put into verifying whether i am correct or not i'm going on wrong path but somehow whatever i thought was correct because i should have also taken the constant into account but i haven't but now if you take it like we have 100 digits okay possibilities of each is like 10 possibilities are there okay and if we rotate them this is 10 constant length is even so okay this is a bit but conventional not trivial nonetheless of five two five and if it's four it's if it's length is four if we try to add at odd indices first all the rotations after doing all notations there can be ten rotations and for each ten notations we can do it on if we add one like five and two if we add one to each of them it will become not five and one so five and five if addition of one will be done it will convert into six okay at one again adding one so there are can be like ten possibilities now like either five six seven dot again four still four so there can be ten possibilities here that's why it was saying that string length cross total rotations cross the total possibilities so these are not that much big you can see that this is order of like the 10 to power 4 operations since the string length act is at max is 100 cross 10 is the digit length or not 10. this should be also 100 i don't know like 100 cross 10 to power 5 it is what i could think of okay let's not go there let's uh try our bfs thing okay we will start from the number we will add and rotate if the current number is already in set we will stop as execution or we will go further cool and at the end of it at the end of everyone until as we reach the end we will do this operation and finally we will return the main offset okay return the main offset so it should work let's see let's try to go ahead string we have to return string cool lexicographically smaller so it is like whichever is small but we can't miss at a place like 0 is there so we can compare string to let's sort it first not sorted put i in okay let's take a helper function and put the string okay now this is the set a visited set visited is equal to set it will it is an hash set actually and we're going to also pass a and b okay so the new value that will be called is okay yeah if the current s if s in visited then return okay i don't have to go further but if it is not there then we have to convert the s array into types like first we are gonna add b to its odd indices okay let's convert it first let's take a temp one or let's take a addition okay let's add that's add and the another will be s rotate so what will be our s add i in range length of s interface let's go let's convert s into an array it will work better or double this is equal to double office seo printers okay yeah it's converted into tuple now all we have to do is add it and rotate it so rotation will be a bit non-trivial okay how will i rotate it divide it and add one to it that could be a possible solution um divide it by 10 and more to be added at first okay let's take this string and it would be difficult so we are taking the string and so what are we gonna do now let's write that we will take the string as okay we are going to take a string as we are going to call we are going to create a new function it will do something like dfs okay or bfs node it will do dfs so it will be like define helper as comma a comma b so it will do helper on s add after adding a okay and the other one is helper s rotate we're gonna do these two things we call on it and recursively we are going to call it and finally we will get the answer okay and we have to also put the base cases so let's do it here so instead of trying this thing um what i in working with a string is a bit non-trivial also while i have to use non-trivial also while i have to use non-trivial also while i have to use help yes add and as um rotate and a b will be same you can also have added a b as non-local you can also have added a b as non-local you can also have added a b as non-local let us suppose like we are going to add it as non-local a it as non-local a it as non-local a and b okay so we don't have to worry about this taking a test parameter will get problematic okay fs invested return and we are going to create s add here so how are we going to create a set for i in range length of s i we can't change it's immutable so we can't change si i think let's try it on terminal okay so we have an string s of zero let's try to change this f of zero is equal to one click sorry string doesn't support item assignment see we can't assign anything we have to do something else but the taking list would be only our option so we will pop it and open push lfs so to add variant range length of s i saw one second two zero five zero to add we are taking these indexes these are all indexes according to it we are adding it on or now okay no we are from starting from zero to good so for i indians length of s if i mode 2 is equal to 1 s of i is equal to plus equal to um a is a string no end it is an end s of i is equal to end of s of i less a then take the tickets mode what if i would have converted all of them yeah convert all of them as end before okay this is equal to enter 5 for i in s so now it is an end okay now it is looking better for index in length of s what we are going to do if it is an odd index we are going to add a and we will take more to 10 okay but this will convert our s i k so we are gonna use tuple instead of it or str or tuple okay restart is going to settle yes okay now after dealing with this i will rotate it so s pop and start kick s is equal to s dot pop yes so if it is popped okay now system so we finally got our asset said is join the string join it okay join the all s so htro yeah htro oh cr of i or i n this is our sl same thing i will do for s rotate join all the string but currently okay so i've called it and i have to also add both of these instead of adding them i should better add it okay now i will call the helper and return men of s now let's run this where am i adding it i'm adding yeah i'm adding that's a problem so rather than adding a list it should have added string so how to add a string by joining it again okay join s same i don't know like i have i put a lot of effort in it like it wasn't something that should be taken okay this is hmm string does not support okay s is a string you know but i have passed a list yeah as is supposed to be uh okay here i okay that's a problem so instead of doing this i could have directly copied s every both of the time but it will take a lot of memory but no problem it will work because all the length is 100 that's fine what is two um let's try to print okay temp is good to go no problem in term at four five four two adding one adding two adding nine plus four thirteen okay that's why it is becoming like this it's as rotated but as rotate is there and str of i is also there all are in string s is i should be taken as an end yeah that's a problem here it's of i off and okay let's remove this and write as a list of now what i have passing oc so here are none local abs tv given okay now this one is checking whether a string is not inside checking whether visited or not okay so if a string is already there then return else now add the string okay it i'm taking str5 instead it is already string so i don't have to do this now that only s will work fine yeah joyness join us visitor.join s for i in range join us visitor.join s for i in range join us visitor.join s for i in range length of s if i mode 2 equals 1 then s i change the sign into this should be converted into hdr that's the thing i left and you convert into str and then okay here i am printing the temp pop it and then append it back okay now do it until unless you'll find same again inside the vegetable and here i'm returning the min of s so what is it returning okay i'm getting min of s should be mean of visited by mistake but we should also continue now it should stop output now okay zero three triple zero three what's input 0.525 what's input 0.525 what's input 0.525 so somehow i raise triple zero three okay let's see where i have reached triple zero three there's no pause button okay uh what we can do here is once again okay it is recording so i am really foolish like i haven't studied i haven't gone through the question really good we have to rotate rotated b times okay see we have rotated b times integer b so we have rotated three times and we are rotating it like not b times so let's rotate it bead in here we have our s again so what we will do is let's see how to rotate it we have an array two three four five six we have to rotate it one if we want to rotate it once we have to do it like this so array from zero to ines minus b now our new adder will become numerical booth g2 to length of five minus t here we have to add an array of right now yeah from here length of array minus b to last then software will be like length of a minus b to last plus this okay let's try to do this our newest will become s of length of minus b from starting plus same to end from minus p to n now if this weren't what i don't know what oh print listed oh not as instead we should use us not id yeah so this time we are going to return minimum it should return an integer no string oh five zero two zero it happens three two zero five zero y um b is one let's print wasted five zero two zero five two five okay five one two one is also there it should be two zero five zero uh we have five triple two everything is there two triple five no it's like five triple two why is this happening and but we presentation is a bit bad yeah it's really pretty bad like we have to do this now from last so this was easiest question in which i was left up let's see finally we have to print it also god knows that here they will come okay it's done thank you guys subscribe for more questions thank you
Lexicographically Smallest String After Applying Operations
group-sold-products-by-the-date
You are given a string `s` of **even length** consisting of digits from `0` to `9`, and two integers `a` and `b`. You can apply either of the following two operations any number of times and in any order on `s`: * Add `a` to all odd indices of `s` **(0-indexed)**. Digits post `9` are cycled back to `0`. For example, if `s = "3456 "` and `a = 5`, `s` becomes `"3951 "`. * Rotate `s` to the right by `b` positions. For example, if `s = "3456 "` and `b = 1`, `s` becomes `"6345 "`. Return _the **lexicographically smallest** string you can obtain by applying the above operations any number of times on_ `s`. A string `a` is lexicographically smaller than a string `b` (of the same length) if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`. For example, `"0158 "` is lexicographically smaller than `"0190 "` because the first position they differ is at the third letter, and `'5'` comes before `'9'`. **Example 1:** **Input:** s = "5525 ", a = 9, b = 2 **Output:** "2050 " **Explanation:** We can apply the following operations: Start: "5525 " Rotate: "2555 " Add: "2454 " Add: "2353 " Rotate: "5323 " Add: "5222 " Add: "5121 " Rotate: "2151 " ​​​​​​​Add: "2050 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "2050 ". **Example 2:** **Input:** s = "74 ", a = 5, b = 1 **Output:** "24 " **Explanation:** We can apply the following operations: Start: "74 " Rotate: "47 " ​​​​​​​Add: "42 " ​​​​​​​Rotate: "24 "​​​​​​​​​​​​ There is no way to obtain a string that is lexicographically smaller then "24 ". **Example 3:** **Input:** s = "0011 ", a = 4, b = 2 **Output:** "0011 " **Explanation:** There are no sequence of operations that will give us a lexicographically smaller string than "0011 ". **Constraints:** * `2 <= s.length <= 100` * `s.length` is even. * `s` consists of digits from `0` to `9` only. * `1 <= a <= 9` * `1 <= b <= s.length - 1`
null
Database
Easy
2335
676
hi everyone it's albert here and today is a special episode of solving the code question so last week i have a senior engineer friend helped me to do a mock interview and we were solving this question together and he really gave me a lot of good uh feedback and suggestions how to approach and solve coding questions in uh real interviews so today i would like to share my experiences and the feedback he gave me to every one of you so let's get started and jump to the lethal interface the first suggestion he gave me is to have the right mindset don't treat this as an interview just think of it as solving a problem with your co-worker as solving a problem with your co-worker as solving a problem with your co-worker or having a pair programming session this mindset will really help you to relieve your stress and perform normally in the interview and for this problem there are basically two tasks we have to do first is to design a data structure that is with a list an array of different words and then we will be provided a string and we have to check if we can change exactly one letter in this string to match any word in that data structure so the two apis we have to implement is first build a dict we can transform the dictionary array into any kind of data structures we need and then the search api will be given the search word and we have to check if dictionary has a word that is exactly one letter different from search word okay and after understanding the question let's try to think about a feasible solution and discuss with the interviewer and for the data structure for dictionary since we need to constantly check if search word has a similar word in dictionary and also it's kind of obvious from the api name builddict so maybe a hashmap is a proper data structure we can use since we can utilize the constant time lookup but what key value pairs should we put in the hashmap so if we look at the requirement in the question again the search word and the matching word in the dictionary can only have exactly one character difference and also your length should be exactly the same you cannot add any letter or delete any letter in search word or the word in dictionary so maybe we can use the length of word as key of the hashmap and then the value will be a list of word which has that length in the dictionary so in the search api first we can retrieve a list of words from the hashmap and that word list every word has the same length as search word and then we compare every word in the list to search word if uh if there's a word has one letter difference from uh the search word then we will return true otherwise return false this approach is pretty straightforward and intuitive but possible on time complexity so we have to check every word in the word list and also every letter in search word so possible time complexity could be square time and it's not good enough so if we look at the constraints of this question the dictionary length can go up to 100 and the search word length can go up to 100 as well given this layout size this approach seems not too bad and we can also try to think about some edge cases and some possible optimization for example if in a dictionary there's no word has the same length as search word then we can just return false immediately and also when we are looking through search word and we found that there are two letters are different then we can also break and return false so the approach to solve this question is first convert the dictionary list into hashmap and this hash map the key is the length of word and the value is a list of words which has that length and given the search word we can check if the hashmap has a key of length search word and then we can retrieve the word list and for every word in the word list we will check if there is a word that is uh exactly one letter difference from a search word and this approach will have a big of m times n time complexity m is the length of the word list and n is the length of the search word and space complexity is big o of m and up to this point the interviewer also think this is a reasonable and intuitive approach so i started to implement my code okay now i finish up my code so first is to initialize the hashmap using python's collections default dictionary and the build addict api we will just add every word in dictionary into the hashmap with the corresponding key and in the search api first check if that search word is in a hash map or not if it is not in the hashmap then we can just return false immediately and next is to retrieve the word list so for every word in word list first we will have a counter count which is the number of different letters in between a word and search word and then we will iterate through the search word if the letter is not the same then we will increment count by one then if we found that count is bigger than one it means that there are at least two letters different than we can just break and if a count is equal to one then we can return true and then finally return false and now i try to run my code it passed this test case but when i submit the code it actually has a bug somewhere and i was kind of struggling here for a long time didn't really figure out what the problem is and the interviewer he really gave me a very good suggestion it may be different from company to company but the interviewer suggests that i should have my own development environment or coding tool ready so that if i have some bug in the code on the decode or hacker rank platform i can just test it using my own tool because in that way i can use like console.log console.log console.log print to easier uh figure out what the problem is so in this case that this if condition they should not be executed inside the for loop it should be they should be checked after the for loop is finished because uh we have to first finish checking every letter in the search word and then run this check so if i fix this and then submit a code again now it works okay and now let's review the key steps uh for coding interview first is to read through a question and then discuss a feasible solution with the interviewer and based on your approach select a proper data structure and algorithm to use at the same time try to think about the edge cases and some possible optimization and then code implementation and debug is as well as important in coding interview and if we can finish the intuitive and straightforward solution we can also try to bring up a more optimized approach which is using the tri data structure to achieve a better time complexity and the key takeaways i have from this mock interview is first work with the interviewer communicate and interact with him treat this like a peer programming session or as if you are working on the same problem and even before writing any code try to analyze the time and space complexity of your approach if your approach works with the given data size and also easy to understand then it should be good enough and finally is to learn how to find fixed bugs during the interview in a professional way like using your own development tool or ide and for this i would suggest to check with the recruiter or interviewer beforehand if you are allowed to use your own development environment and that will be all for today thanks for watching if you like this video please give it a like and subscribe to my channel and i will see you in the next one you
Implement Magic Dictionary
implement-magic-dictionary
Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure. Implement the `MagicDictionary` class: * `MagicDictionary()` Initializes the object. * `void buildDict(String[] dictionary)` Sets the data structure with an array of distinct strings `dictionary`. * `bool search(String searchWord)` Returns `true` if you can change **exactly one character** in `searchWord` to match any string in the data structure, otherwise returns `false`. **Example 1:** **Input** \[ "MagicDictionary ", "buildDict ", "search ", "search ", "search ", "search "\] \[\[\], \[\[ "hello ", "leetcode "\]\], \[ "hello "\], \[ "hhllo "\], \[ "hell "\], \[ "leetcoded "\]\] **Output** \[null, null, false, true, false, false\] **Explanation** MagicDictionary magicDictionary = new MagicDictionary(); magicDictionary.buildDict(\[ "hello ", "leetcode "\]); magicDictionary.search( "hello "); // return False magicDictionary.search( "hhllo "); // We can change the second 'h' to 'e' to match "hello " so we return True magicDictionary.search( "hell "); // return False magicDictionary.search( "leetcoded "); // return False **Constraints:** * `1 <= dictionary.length <= 100` * `1 <= dictionary[i].length <= 100` * `dictionary[i]` consists of only lower-case English letters. * All the strings in `dictionary` are **distinct**. * `1 <= searchWord.length <= 100` * `searchWord` consists of only lower-case English letters. * `buildDict` will be called only once before `search`. * At most `100` calls will be made to `search`.
null
Hash Table,String,Design,Trie
Medium
208,720