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
20
this question asks you to determine if the input string is valid and basically all open brackets must be closed by the same type of brackets and closed in the same order in order for it to be a valid string so they're saying these are the types of strings that you will have so i'm just going to create a dictionary to store these oh so not to waste your time i've already created it okay so i'm going to iterate for character in s now what i'm going to do is i'm going to check if this character is in my values which is right here so i got the keys and i got the values so if this character is in my values which means it's an opening i'm just going to append it directly and for those who's been watching my videos i like to create the variables as i go through i don't like to say here are all the variables you need and here is how you're going to use them but i want you to deduce the variables needed logically as we go through the question so obviously i want to append this character to some sort of stack to keep track of it or a list so i've added all the opening or all the possible characters that the question gives me in a dictionary now what if it's not in the values but it's in the keys and then that begs the next question if this is in the keys and my stack is empty i can return false directly because i have a bracket that's not been closed so let's write down that logic so if my character is in my keys and if the stack is empty then i can return false right away well if this character is not in values and it's not in keys then i don't know what am i doing here just return false so here we already dealt with if the first character is going to be a closing bracket it's going to be called here and it's going to be thrown out but what if it's a closing character what if i do have something in the opening but it's not in the stack so i'm gonna pop my stack and if i popped this stack and whatever that has been popped does not equal the character indexing in my dictionary then i am not closing the brackets in the correct order so let's say in this case i get this square closing bracket and if i put the square closing bracket here and pass it as a key to my dictionary this here will return this on the top here and if this here is not equal to whatever that has been appended here then obviously this has not been in the correct order so also return false shall we check the answer yes but hey shouldn't you be returning true or false yes i should be so what i can do is i'm appending every opening character and i am popping them if they're in the keys so this has to be empty so if my stack is empty then true this parentheses is valid but if there is anything left in my stack then i'm sorry this is not in the a valid input string so let's see and there we go we have our answer here using a simple dictionary of items and the stack thanks for watching if you've learned something in this video please don't forget to hit the like and subscribe button have a nice day
Valid Parentheses
valid-parentheses
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the same type of brackets. 2. Open brackets must be closed in the correct order. 3. Every close bracket has a corresponding open bracket of the same type. **Example 1:** **Input:** s = "() " **Output:** true **Example 2:** **Input:** s = "()\[\]{} " **Output:** true **Example 3:** **Input:** s = "(\] " **Output:** false **Constraints:** * `1 <= s.length <= 104` * `s` consists of parentheses only `'()[]{}'`.
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g. { { } [ ] [ [ [ ] ] ] } is VALID expression [ [ [ ] ] ] is VALID sub-expression { } [ ] is VALID sub-expression Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g. { { ( { } ) } } |_| { { ( ) } } |______| { { } } |__________| { } |________________| VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
String,Stack
Easy
22,32,301,1045,2221
56
Hello everyone welcome back to my channel Swayam Now we are going to discuss the problem from the sheet is much interval okay so this is a very important problem interview certificate let's read the problem first even a leaf can travel when in trouble I mean In the internal exam in which the first test and interview were given and not all over were world and return, no but if you come to do some over then make us noble by removing that cigarette, this is basically what we have to do, so once we understand how to do it. And how will it come then we live here now there is one to do one thing and three is fine this was earlier the intervention was starting and ending but then after that there is only interval Guru is used to two and that is over six pack is fine its Also if eight is maintained then it will start from one and will end from one or tan is behind and we have one from fighting so that something will start from shift and that will end if from ATM then if you look carefully here also which one If you want to do this lesson, then this interview which is spread by virus and can be seen from Mittu due to these reasons, these partners should overlap this so that no one can build their morale. They are not doing this and this. No one is doing it but why not you too and the one doing the fixing journey is fine so now look carefully this year goals we think if why are you saying that you look carefully this 2 hours 1342 E Keep a photo That's why this change is taking place, if here our Kapoor Karo, the setting to Naa Hota, then he likes a little bit, meaning, here these two intervals overlap because the starting point of it was that brother-in-law of this That's the one that's that brother-in-law of this That's the one that's that brother-in-law of this That's the one that's smaller than the end of the first one. This thing is typing okay. So if it's like that you can say that they will then go to the interval. Okay. If these two are separated then it's okay that these two are overlapping. If we chill them then you will become like a quintal of paddy. Look at these two after fasting. Bow down here. Starting and decreasing. If we rotate these Singrauli in Singrauli, then what is the point of chatting because then he will come here and why after murdering us. Both of them will have whatever of this and its maximum, if we cover the pan then that will be ours and you must have understood that the chicken experiment is now done, now let's press once and see how we will do it, in this we will find out which one. If we are overlapping, then we should give more information, so whatever our intervals are, first of all, this is the first interview, we invite those who put it in the current, okay, this election 2012 is free about that, so whatever interval is our first. Was he put this one and now we are starting the footsi index Krishna okay what we have to do so this is our this we have done whatever so come and this current and a that if that is the big one which I printer guy with that From here which is that if it is that Hina you now our which we have to do we have to make the interviewer mind strong to monthly to interview the patients what will become of that which of our correct ho which of which I our to maximum Inside this and scan's maximum of a sequence and I can't uh so this will be the interval after our merge, something like this is okay, if you look at this then we will spoon it Here first I wrote on 16, how we had to do it, I had to do it if In our CNN, you write down which job is the current one, what is its end, if it is big, which eye point is your interval, then we will have overlap with it, then the description will be given, then what will we do, then here we will have overlap, so This will become our interview vehicle, took the churner and maximum gas stove to Sheshnag, you are mental, okay, after that now we have become monthly in our life, we are making our areas in which the dam is being built monthly in the memory interval lines. Put it, then after that I agreed, here now we will check again that gender season six and first checked means Emergent A and open it, we will put it like this and after that we will A, now what we will do is scene six and cyber cafe. Is this a function, otherwise it doesn't make sense, then take care of it, look at the medicine, our answer was given on 1st to the Math, to the Peas, to the 9th, to the mother daughter who helps us on this interview and there is no overlapping interval of it. Okay, this is fixed. While returning, we have to check this condition and find out that you are doing it. There is one more thing in this effort which requires faith and what is that, we also see something like this here too, so if this work is done then I will change it a bit and then later on to the machine A. Okay, so see, it will work for 4 minutes, we will put it in the current, I will complete our demands and then we will come to this and here the ad is maintained. That is, we have a current account and its ice so that it does not overlap, it is okay, we will put a Maa Tagore and here we will grate the current. Comment, okay, it is okay, hey brother, here, where the jewels, because. Here our second one is that we have these two, so what should we read, we will first support these intervals which are there so that this happens i.e. so that this happens i.e. so that this happens i.e. can be overloaded, then we will join them, typing which is fine by value because then do We need to fold the onion, so we have given the typing here, so turn it off, that in the world, India has done the folding according to the chart value and then after that, we You can register your protest. You were looking at this tree, look carefully because this is what we are making a list in which our finalists will go to our awards interview. Okay, we saw that if you have not given any interview then we will return empty handed. If we do this then by emptying it and shifting it about what it is, then by thinking that we need function news against it, we can also share the simple one like we write compare here, by comparing and above, we were fooling us there. Can this is also a matter of both, so after that I here we check the interval using setting volume which will be its basis for every intraductal and did it okay and a current affair in her body which while inserting the first interval also presided over it We will put the first interval in it. We are starting with 200 grams of Pandey and here is how we do it. Look, if the end of our current i.e. if the end of the current is small, it is from end of our current i.e. if the end of the current is small, it is from end of our current i.e. if the end of the current is small, it is from then the interval should not overlap, otherwise do nothing. Just do Sita tire, we will put it in our country and in our heads, the current value interval is this interval, how does the song sound, the meaning of fast support is here that when we were closing, I come here, we have introduced you to our friends, now we have given them the machine again. After that we got government education and this is monthly during the interview of years then we were a comment and have and this was not to overlap ours so we will update this one from the maintenance okay so you can contact this one. Tonic put it and we pile up the current but if our condition is for i.e. our overlap case is to the is for i.e. our overlap case is to the is for i.e. our overlap case is to the control register friend and is increased from the chart then do our overlap of either we take the and of our current i.e. which Enter we take the and of our current i.e. which Enter we take the and of our current i.e. which Enter and A, so here we will do this, so this is the point of this will be the plate that will be in the rain and year, either this was Meena, this is six, I, then both of these, let's come internal, its match, its and its enter maximum, its in If it is okay to give one, then the current low end and the end of the current interview which is going on, whatever maximum will be made for our current and whatever we will do after this is over and push it in the fresh, so and then from here. If you do it then it is very simple and also it is easy. This thing has to be kept in mind during the question time, it will have to be soft otherwise our answer will be wrong that if it is black then it is Michael's record which is mentioned in the description. Same logic and ok and if you liked the video then please like and subscribe The Channel.
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
171
hello everyone hope you all are doing well so i am back with another lit good day challenge and it is late code number 171 excel sheet column number it is an easy level question and i also feel the same so the question is given a string column title that represent the column title as appear in an excel sheet return its corresponding column number okay so you are given a string okay let's say it is a b so a b is the 20th column of an excel sheet okay you can open excel and you can search it out okay so if you see this some example like a is one av is 28 zy is 701 okay it is present in the 701 column the title of the device is at 701 okay position 701 column so you have to find like that now you are given a the distinct column title string length can go up to seven column title only consists of uppercase english letter and column title is in range of a to f x s h r x w okay and here it is not given that it will overflow our integer or not so we will let consider it is in means in integer okay now how to do it before i tell you the intuition you have to object something like there are 26 alphabet in english letter from 1 to set and if you try to make it to like a and something then it will be again all these 26 alphabets have 26 more okay 26 more a letter okay so if an alphabet is at this position let's say first one is uh okay so let's the first one is a or not okay it is a and this one is b okay so oh and there is another one let's see okay so let's take a simple example okay so let's take an example like a b and c if you are given string like abc what do we have to do we have we need to travel this from back side from this to this okay why okay so i will let me explain you like see if you are attending like it is a and b but its output if you see here it is 28 how it will come 28 b what is b is 2 okay we are taking here from 1 to 20 so ok not from 0 to 25 we have to take from 1 okay so it is 2 what is a it is 1 okay now our its answer is 28 so you can observe that if i multiply a by 26 and b by zero so and then add them so what is the answer it is 28 okay now i hope you have understood like why i asked you to travel it from back side although you can travel it from left to right but it is quite easy to handle this up this case okay and if let's say there is another number like c then it is what is its value c value is 3 okay so 3 into 26 look here it is not 0 actually it is 1 ok uh because we have to take power of 26 to the power x we have to take okay and this axis earlier it is here it is 0 then here it is 1 and here it is 2 so if we track back from the back side it is easier to handle this cases so it is 26 power two okay now similarly for the exact in this example also we will do the same we will take uh we will first of all go from here and we will what is the cc is three into what is my current value uh means this what is the position it is from back it is at the zeroth position so it is 26 by zero is 1 so my sum is come out to be initially uh it's come out to be it is 33 into 1 so it is 3 then you come here it is b okay now your this x means this power value is going to increase okay so it is 26 by 1 now you can calculate what whatever it is 26 into 26 so whatever it will be like here y and let me consider as y and then it is 1 into 26 into 2 so it will be again come to something like it is 26 so it is 26 into 2 it is 52 okay and this part is 26 into 26 and into 1 it will be 26 into 26 so let's enter 26 into 26 then we have to add all this thing okay so this is our final answer so we have to do this thing uh one by one till the string get exhausted okay so very simple question just you need to understand this mathematical thing now let me show you the code okay so i have taken an n to store this column title size and i have taken the p which is the power like here i have told you to 26 in power x so this p will indicate this x okay now my current answer is 0 i will travel as i told you i will travel it from back then i will simply take out my character like which character and this is minus a plus 1 so it will be if it is a so a minus a is 0 plus 1 is 1 okay now it will store your integer and a ch and as i told you i will take this 26 into x so i have called this power function okay and i just into it with this value like here it is 3 into 26 to the zero so the first time it will it for abc it is 26 by 0 into 3 then i add to the current and i just increment my answer okay so this is the code and i have and i if i show you abc also then if i run it then you can see it is given in 731 and it is correct okay let me submit the code okay accept it and hope you understand the video just a simple mathematical concept and some observation oh i will see you tomorrow till then goodbye
Excel Sheet Column Number
excel-sheet-column-number
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnTitle = "A " **Output:** 1 **Example 2:** **Input:** columnTitle = "AB " **Output:** 28 **Example 3:** **Input:** columnTitle = "ZY " **Output:** 701 **Constraints:** * `1 <= columnTitle.length <= 7` * `columnTitle` consists only of uppercase English letters. * `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
null
Math,String
Easy
168,2304
187
hey welcome to this video we're gonna do Lika prom 187 repeated DNA sequences right so the directions are kind of long let's skip over that so they give us an input string representing the guess the four letters that represent DNA ACGT it's been a while and then you got returned Mac the let's see ten letter long sequences that pier in here at least two times right they say repeated long story short at least two times so I guess supposedly this appears at least twice in here this is gate convoluted so we'll trust the example and of course this let's see this ten letter or ten character string right also appears twice in here so cool and let's get started so I want to say function or you know what let's just copy it save myself some time duh then I'm gonna say Const scene is equal to an empty hash table right so we'll look like it'll give us a frequency counter for how often a DNA sequence appears right told you an example it might say oh hey the DNA sequence of ABC appeared I don't know four times then the DNA sequence of CCC appeared I don't know a hundred times right now of course obviously this is just an example these it has to be at least ten mine's are three anyways this is like a counter right oh and by the way if you like my content be sure to LIKE comment subscribe hit that notification Bell to be notified of new content and of course I have full-length courses on my website I have full-length courses on my website I have full-length courses on my website K education comm now I'll say Const res is equal to an array you could also call it output right I'll call it res that's my preference it's initially empty we're gonna fill it up they'll say let I is equal to zero now you could solve this problem using a for loop that's what I initially did but you also do have a while loop I find a while loop a lot more easier to understand and explain so I'll say while I plus 10 is less than or equal to s dot length okay why I +10 because well it's gotta okay why I +10 because well it's gotta okay why I +10 because well it's gotta be 10 layers long and we only want to get from the tenth character from the end of the string at most right so now I'll say Const DNA sequence is equal to s right that's the input string s dot slice from I and then the next you know 9 or 10 characters afterwards so I'll say I plus 10 all right there should be nine characters afterwards right if we do inclusive then I'll say scene DNA sequence right is equal to scene steamed DNA sequence plus 1 or 1 anyways this is a shortcut I like to use right so let's say we're on the DNA sequence of ABC if we just assume it's only three letters of 10 right it's ABC in our town in our scene counter if it's not in here right then we're gonna set to one we'll say ABC this is the first time we seen it will be set to 1 right otherwise if this is the second third fourth fifth tip fifth six seven time we've seen the sequence of ABC then this right here right the counter will Ekrem it by one so I like the or operator makes our code really one-liner ish which I like really one-liner ish which I like really one-liner ish which I like now say here if seen DNA sequence is equal to 2 then res dot push DNA sequence right from up here alright so when I initially did this prom I actually set this to greater than or equal to 1 but this is actually or greater than or equal to 2 but this is actually a very common pitfall it took me a while to understand this right so we only want to output the things that appeared at least twice right but this appeared to say a hundred times we don't want to push this result a hundred times to our output right if we have our code stay like this then if our DNA sequence appears 100 times then in our output route and output this a hundred times if it appears at least twice right then like this it appears at least twice just puts it to our res or a just once so this prevents duplicates all right cool and now you have to be really careful because in a while loop we have to Inc we have to increase this I variable from up here otherwise our while loop can go forever your browsers gonna crash or if you're running this on nodejs on your local machine right your fans we're gonna get really fast and loud like a jet engine so i'll just say i plus equals one okay within the while loop make sure doesn't run infinitely right this while loop will run and finish running you'll modify a res will fill out so after this while loop we will return res which will be our output so let's copy it all and paste it onto leet code and hopefully it will pass hey it did so repeated DNA sequences complex the analysis time complexity is o of n where n is the number of characters in the string and space complexities of n roughly okay why is it roughly o of n because let's say our input string is actually ten characters right then if our input string as 10 characters ignore this is definitely more than 10 characters but our input string was 10 characters then our scene here would only have one key right that key would be that 10 character long input string so roughly o event I'm sure there's some of you that are very smart and logical and you'll be able to figure out something more accurate than this bull go of this for now okay that's it for this video
Repeated DNA Sequences
repeated-dna-sequences
The **DNA sequence** is composed of a series of nucleotides abbreviated as `'A'`, `'C'`, `'G'`, and `'T'`. * For example, `"ACGAATTCCG "` is a **DNA sequence**. When studying **DNA**, it is useful to identify repeated sequences within the DNA. Given a string `s` that represents a **DNA sequence**, return all the **`10`\-letter-long** sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in **any order**. **Example 1:** **Input:** s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT" **Output:** \["AAAAACCCCC","CCCCCAAAAA"\] **Example 2:** **Input:** s = "AAAAAAAAAAAAA" **Output:** \["AAAAAAAAAA"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'A'`, `'C'`, `'G'`, or `'T'`.
null
Hash Table,String,Bit Manipulation,Sliding Window,Rolling Hash,Hash Function
Medium
null
1,732
hello guys welcome back to my channel and today we are going to solve a new lead for question that is finding the highest altitude so we are going to solve this portion with the help of JavaScript and if a person says there's a biker going on a road trip the road trip consists of n plus 1 points at different altitudes okay so we will be giving different points okay and the biker start strip on point zero with altitude equals zero so uh the bike bikers start from zero point and altitude is what would be like altitude the altitude equal to zero okay so you are given an integer array again a gain of length and where again I is the net gain in altitude between 0.1 and uh I plus 1 for all 0 to n 0.1 and uh I plus 1 for all 0 to n 0.1 and uh I plus 1 for all 0 to n and I is in between so return the highest altitude of a point okay so before starting solving this question please guys do subscribe to the channel hit the like button and press the notification button so that you can get the regular update from the channel so if you see the question here the question says that we will be starting from point zero the writer start from point zero and then it has the various point and then we have to return the maximum Peak point where the biker would be at Okay so uh if you see here we have various Point here is minus five one minus five zero seven minus seven so we have to put the zero first here and then we have to subtract each element from the previous element so if we add uh if we add this num these numbers we'd be getting 4 and then sorry minus five then minus 5 plus so we will be adding the previous with the previous number actually so let me explain it to you from the example here if we add 0 plus minus 5 we will be getting minus 5 and then if we adding minus 5 plus next term is 1 so we will be getting uh minus 4 and then next term is okay next term is minus 4 Plus so minus 4 Plus 5 1 one plus zero again 1 and 1 plus minus 7 that is minus 6 so as you can see that we are getting the values according to what here has been shown so zero point here is uh this one and then we are getting minus 5 minus 4 1 6 so this these are on the uh elements we will be pushing in the result array and then first in the first thing we will be saying it is starting from 0 and then it should start from 0 As We Know still information and the question already and it's starting from 0 to 0 minus five minus 4 minus 1 minus C so among all these output numbers we have to return the maximum value so if we see the max value here Max is one actually so 0 minus 5 minus 4 1 1601 is the maximum number yes so for that we should start writing the code starting from saying that result is equal to an array in which there is only zero and then creating a loop for let I is equals to 0 to the range of I minus I to the Len again or again dot length and I plus and say creating uh in another variable inside the loop thing let temp is equals to result I first result sorry plus mean I okay so here what we have done we have taken a new value I created a new variable inside the loop which would be taking a value of result here result I set is 0 and then again gain I which is whose value is minus 5 then we'd be adding those numbers and then I in uh this number will give us minus 4 it will come the loop would be completed here and then second thing and then the for as the first Loop completed we will be appending this result dot push we will be pushing these values uh the tempo value the temp variable value into the result so first it would be 0 here so 0 plus minus 5 it would be given as uh minus 5 here and then the result would be um second a second so first is 0 and then it's minus 5 so minus 5 plus 1 the index here would be one so again one index is here so again one index is this and the result index is uh the number minus one so I hope you have understood this thing here uh it's quite logical and reasoning and now we will be just saying that we have to return the result the return math Dot Max Max Max okay math dot Max and result so as we write this thing here with this thing here we will be saying that there is the maximum value from the result because we have to present the maximum point highest by altitude so we will be seeing the math dot Max result and then run the code you can see that we do get our answer so we do got our answer here so I hope you have understood the concept guys here so uh please do subscribe to the channel and hit the like button if you have any doubt please ask in the comment section thank you guys for watching the video see you next time
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,035
Hello friends today I'm going to solve liquid problem number 10 35 uncrust lines in this problem we are given two integer arrays nums 1 and nums 2 and um what we are going to do is rewrite all the integers of num Swan and the nums 2 into separate horizontal lines like given in this example um where 1 4 and 2 are the integer elements of nums one and one two four are integer elements of nums two all right now what are we going to do is we start connecting lines between the integers from num Swan and integers from nums 2. so there are conditions that we need to consider while drawing the lines so first condition is that the element in Num Swan should be equals to the elements in nums 2 to draw the line and the line we draw should not intersect any other connecting lines okay and even it should not intersect at the end points so here we have like one four two one two four okay so we take the first integer one and we draw the line with integer one because these two are equal now for the value of 4 we know that um this is equals to these four okay so we draw a line between these now when we take the value 2 here we see that we have a value 2 here so while we try to draw the line between these two we are actually intersecting the line between four and four right so that is not allowed so that is why we do not draw the lines so the maximum number of lines that we could draw for this integer is equals to two right one between these and one between these or we could either take the lines between one and between two and two there would still be two okay so that is the answer for this example now let's see how we could solve this problem okay so let's take an example so I'm going to start with two integers uh like two arrays and numbers one and nums to each of them first have only one integer okay so what happens is both of them are equal right so we just connect with them with one line so what was happening is before where there were no elements we did not have any connection right so there were zero connections now we have we added one element to each of the array okay this is nums one and this is numps 2 okay so I'm just going to represent with N1 and N2 all right so we now have these two arrays and each of them are equal so we can actually draw a line between them right so now the number of uh connections increase from 0 to 1 okay so we are just going to increment our number of uh count from zero to one okay let me just write it this way from 0 to 1 okay now what happened is I am now adding one value here to integer number uh into our array and one so what are we going to do is now we are again going to check for the connections with uh three okay so what we do is we check our connection with one and we found that these are connected okay but like we try to check connections for three but we did not find any connection right so for three we have zero connections but for we already have one connection here right that is this connection of count one so we are just going to take that connection as our number of connections right total number of connections even though 3 is not connected with any other elements now let's uh add one more element here um that is equals to um three all right so we added one more three here okay and let's just erase this one now let's see so we already have a connection between one and one so that is totally fine okay we already have a connection one with one now we check for the connection of three and we do not find any connection because there are no elements three in and one right so um the total number of connection would be the connection for one right that is the previous number of connections that we have which is equals to one so one becomes our answer now what happens if I add 3 to both of the array okay so in that case we already have one connection between these two right so um next we try to establish connection between three and we find that these two we can connect to these two right so now what is the connection total number of connection the previous number of connection that we had okay so this is the previous number of connection which is equals to 1 plus the current connection which is equals to plus one okay so previous number of connection is equals to one plus one so we add plus one now we get the value of equals to two Okay so basically this is how we are going to perform our all our operations rest of our calculation so if I add a value 1 9 here and a value 5 okay these two are not equal so now when we are comparing nine we actually need to uh check the connection for each of the elements in end to end we see that it is not equals to 1 um so like uh the connection between nine and one cannot be established however uh if even though we do not step is the condition between 9 and 1 we can still establish the connection between one and one right and also like um so that would give us like a previous connection of one and like we again um now try to establish connection between nine and three okay so we are taking these only into consideration only these many elements into consideration okay so we are only taking these many elements into consideration and we try to connect nine and three we already have connection between one and one now we try we are trying to connect nine and three we also have a connection between three and three but we are not able to connect that right so what we do is we still have two Connections in these configuration okay so we take the connection number two which is this value coming from here all right now we compared nine with three now we com we are going to take this configuration the whole configuration so we compared nine with one and with three and now we are going to compare nine with five okay so while we try to do that comparison we see that we are not able to connect it with five also so we are just going to take these two connections we already have these two connections right so we are just going to take that previous connection previous number of connections similar we are going to do for five we check five with one okay and we are just a we are just performing comparison of five with one and then we see that we are not able to connect five with one however we are able to connect um one with one okay so that would still give us a count of one and now we increment the number of iterations that we make and then now we compare five with the three and we are still not able to connect five with three but we have two Connections in these right so that to connection is actually coming from here these represent the connection between three and three right we actually created these for this and these was coming from here okay so we are going to take that value here now um while we try to connect five and nine okay now we are taking all of these five and nine we see that we are not able to uh can create a connection because these values are not equal but we still have these two connections okay one and one so we are going to take these two connections so that would be equals to two and that is this value here which we already did in our previous uh iteration value we're iterating for 9 with 5 okay so that is basically how we do what are we doing is if we found a new connection we are just taking the diagonal element and we are adding one like we did here for three we already had we also did the same for one initially we are going to initialize every value with 0 and then we take the value 1 and now one we are diagonally adding one to zero and next we add 1 2 1 and we got the value 2 for but for when the case when we are not able to connect like for three and one we are taking the values uh horizontally and here also we are taking the values horizontally so we can actually take values in two ways horizontally uh one is um uh horizontally the other one is vertically as well because we are taking vertical values also and between those two we are only taking the maximum value okay because initial after the end at the end we want to return the maximum number of connections okay so that is why we take the maximum value here and then um similarly we take the maximum value between these two and for this one as well since we are not able to connect nine and five we take the maximum of these two if we had a 5 here then we would have been able to connect these two right and that in that case we would add 1 to this value 2 okay so basically this is a dynamic programming problem and we are going to solve it using dynamic programming approach so for that we are going to create a two-dimensional array create a two-dimensional array create a two-dimensional array with a number of elements n plus one number of elements here and also M plus one number of elements okay so it will be y plus 1 because we are initial initially all the connections are equals to zero okay and then when we create a new connection we are taking the diagonal element and then adding a one to it okay so we need a element right there should be something to add on to write and something is the value zero so that is y plus 1 okay and that is how we are going to like uh perform our operation so now let's try to quote our solution okay so for this um what are we going to need uh let's see here so we need a matrix of size n plus 1 and M plus one okay so let and one I'm just going to represent N1 equals to nums on the lamp and two equals two nums to that length all right now let us create our Matrix our DB metrics okay TP Matrix is equals to um a new array of size N1 and then four let equals to zero is listing oh it should be n one plus one less than equals to N1 I plus M there DP Matrix we are going to create our sub array of length in two plus one all right now since we have our array now what we do we uh start from the first element okay the first element and then we compare right so we are comparing these values and if these values are um equal then we create a new connection okay and we are connecting at index um I plus one all right so let us start so let I is equals to zero I is less than all right for Loop we need a form so far left I is equals to zero I is less than and um one plus one I plus or we could just do less than equals to and then four let J equals to zero J is less than equals to N2 J plus all right now we are going to compare if uh nums one at index R is equals to Norms to add index J so if those two indices are equal then we are going to add from our diagonal element right from the previous diagonal element would be I minus 1 and J minus 1 okay so okay we need a um and that will be our current DP Matrix value so DP Matrix I plus 1 and J plus 1 will be equals to um DP Matrix I J Plus 1. all right so now that we have it else if the two numbers are not equal then we are not able to connect right in that case what are we going to do is the Matrix value add plus one and J plus 1 will be equals to uh what do we do take either the previous row or the previous uh column okay so that would be either this uh um uh I minus 1 or J minus 1 so that would be I minus 1 we are doing I minus 1 here all right metrics so Matrix and not Matrix math maximum value of TP Matrix i j plus 1 so this would be the previous row or end between Matrix I plus 1 J that would represent the current uh row but pre uh um current row but previous column all right so now that we have this um at the end we are going to return our answer will be stored in the last cell that is at index i n one plus one n j m 1 and 2 plus 1 okay so DP Matrix n 1 plus 1 and 2 plus 1 that is where our answer will be stored now let's try to run our code and check oh okay so what went wrong country properties of undefined or we are going to fill all of these with values zero foreign okay so we actually do not have we only have N1 minus 1 elements right in numbers one and two minus 1 index right in numbers 2 and N1 minus 1 indices in nums one as right so that is what we are going to do and similar will be the case for this one um so we are creating an array of length N1 plus one and n two plus one okay ah so the last element would be N1 and N2 awesome now let's try to submit this great so here let's talk about the space complexity and the time complexity uh for this space complexity since we are using a matrix of size N1 and to write which depends on size of these two matrices so that would be n times M time complexity M where n is the length of norms 1 m is the lens length of nums two and similar would be the space time complexity because we are iterating over the length of both the air is okay so yeah that is all about this problem solution let me know in the comments down below what do you think about my solution and please don't forget to like my solution and subscribe to my channel for more litco daily challenge Solutions hope you'll have a great rest of your day thank you
Uncrossed Lines
cousins-in-binary-tree
You are given two integer arrays `nums1` and `nums2`. We write the integers of `nums1` and `nums2` (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straight line connecting two numbers `nums1[i]` and `nums2[j]` such that: * `nums1[i] == nums2[j]`, and * the line we draw does not intersect any other connecting (non-horizontal) line. Note that a connecting line cannot intersect even at the endpoints (i.e., each number can only belong to one connecting line). Return _the maximum number of connecting lines we can draw in this way_. **Example 1:** **Input:** nums1 = \[1,4,2\], nums2 = \[1,2,4\] **Output:** 2 **Explanation:** We can draw 2 uncrossed lines as in the diagram. We cannot draw 3 uncrossed lines, because the line from nums1\[1\] = 4 to nums2\[2\] = 4 will intersect the line from nums1\[2\]=2 to nums2\[1\]=2. **Example 2:** **Input:** nums1 = \[2,5,1,2,5\], nums2 = \[10,5,2,1,5,2\] **Output:** 3 **Example 3:** **Input:** nums1 = \[1,3,7,1,7,5\], nums2 = \[1,9,2,5,1\] **Output:** 2 **Constraints:** * `1 <= nums1.length, nums2.length <= 500` * `1 <= nums1[i], nums2[j] <= 2000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102
897
Hello Hi Everyone Welcome To My Channel It's All The Problem Increasing Order Search Tree To Give Me The Root Of - Tree And Tours In Give Me The Root Of - Tree And Tours In Give Me The Root Of - Tree And Tours In The Tree In Order Sudhe Left Node In The Tree Is The Root Of The Tree And Everyone Has No Clue Festival Avoid Tours and Travels in History Will Get Values ​​of Travels in History Will Get Values ​​of Travels in History Will Get Values ​​of Elements in Solid CO2 Values ​​in the Elements in Solid CO2 Values ​​in the Elements in Solid CO2 Values ​​in the Laptop Battery Subscribe 12345 Try Child Not Give Up That Health Problems in Order to Solve Where is a Solution What We Can Do Business Do Inorder Traversal of History and Get All The elements involved data structure like will pass the list and store all the elements of our country element in the legend traversal of district will give software love you all the element one directly for what will you will construct no tree using value from Delhi to start from Which Will Make A Root And Tribes And Will Not Like Subscribe Must Subscribe You Must Have Already Been Solved All Villages For The Giver Hai 200 Here Is The Quotes And This During First Formal Wear Creating Bliss References Which Will Pass Interver Inverter Traversal So That Will Get All The Elements Of Our Country In Short And Were Falling Hair Inorder Traversal Helper Method Middle East Forward From This 1000 Vice Chief Calling For Life Is Debit The Value Of The Node In To-Do List And Key Calling Rights From To-Do List And Key Calling Rights From To-Do List And Key Calling Rights From Do This After Width Sorted In To-Do List Will Be Constructed In How To The Virudha Schedule So A Person Damru And From Where Will Keep Adding Not Interested Guava Just For Temporary And Not From Which Act What Is The Way Also Admitted The Previous Example Tree Which Will Give Winners List 157 70 Have This Element What Will Give Water It Will Create A Current Point Is Point Do It Is This Point Towards Different Service Lines Statement Basically Combine To Line An Android Is Equal To New Notes From The Value 2010 Will Win This In The Country Point In This Change the current president will refer from here to current right so this is the second in command will icon is equal to on Android again will keep repeating dental behavior values ​​in our repeating dental behavior values ​​in our repeating dental behavior values ​​in our superintendent of police Balbir five and after 10 minutes filmy 709 this is the writer is created It Has Not Been Created Them In Order To Be Listed By Vijay Return Government Read What Is This Will Just Guava Not Like This Garmiyaan Returning Member Solution And What Is The Time Complexity Of Dissolution Time Complexity Can See In This Is Not Ranbir Will Not Give Water And Electricity Plans To All The Way Can Give Vote To Tree And Also Created A New And Innovative They Will Pour Oil In Successful Will Call In More Share And Subscribe One Sea Is Not Where Left Leg Nod What We Will Do We Will Win First Sign Laddu Redmi Node Will Also Create Ameer Video Like Share And They Did Not Know They Will Not Let The Current That Commercial Put Saina Current Right And Ishq Note Content As Well As To Current Soon Is Note And Vijay Shankar Android Use And Give Equal rights for this Will Afton And Afton With All Types Of Dangers Will Keep Call Beaten Lord Will Return From Subscribe And Subscribe Comment Inside MB Creator Trino Damru Khadga In Real Form Special Neutrino Do Most Loud Update Current Express That Ranbir Absolutely Di In Order For the question root mode of the tree and western half node damru that dot right time acid na will implement beau inorder traversal method between like private boiled in water will donkey root will cherish now half channel that meanwhile rotational will return more than less hair other Wise people call that inverter roadi first bank awadhesh laptop the last leaf wave women will update current is equal to current dot right the new north road traffic will call in order the road not that flex tried to compile whose difficulty features walking that word that is right Null Root Co Tight Left Is Equal To No Advertisement Key Words Acid Entry 866 Way Single A Fetish Walking No Anybody Accept Dancer So Let's Make This Code Key And S Expected To Be Time Complexity And Space Complexity Of Dissolution Lifetime Quantity Same Of Sbi Po Single Note Worldspace complexities reduced from open to brief still water decade assistant distinguished height of the tree Services solution where traveling as well as reeling also notes and creative constructed nutritious without solve this problem using chief its approach of isolation so you can give tripods videos tried to solve this It approach to what will now institute after this college reconsider this will be doing the same method with the help of for elections Scheduled Caste and Scheduled Tribes or first year so hairs to dial medicated you can take care friends to liquid viewers to hair vihar using man Versus Navami Check Airtel Dish TV Channels Pay Root Will Be The Left Side The National Park The Four 3 And Share Like Schezwan VV Chat Hair Soft Is Not The Bell Dhairya Swift And Create A Content Kar Android Snore Valley From This That Hina And De Villiers Right Motive Se Zara Any Right To Describe It Is Not Having Observed From Year To Year And Same Into The Afterlife Sonu Tamil Live 3 4 5 To 6 Systematic Position Only Like Solution Like Button subscribe To My Channel thanks for watching this Video
Increasing Order Search Tree
prime-palindrome
Given the `root` of a binary search tree, rearrange the tree in **in-order** so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child. **Example 1:** **Input:** root = \[5,3,6,2,4,null,8,1,null,null,null,7,9\] **Output:** \[1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9\] **Example 2:** **Input:** root = \[5,1,7\] **Output:** \[1,null,5,null,7\] **Constraints:** * The number of nodes in the given tree will be in the range `[1, 100]`. * `0 <= Node.val <= 1000`
null
Math
Medium
2202
961
is today we are going to record the n repeated elements in size 2 and array in python so in an array a of size 2 and their m plus one unique elements and exactly one of these elements is repeated end times return the elements repeated ten end times so example one we have one two three uh we can see that there are um the there are four elements in the rate so the n is two right um so there are n plus one which is three unique elements one two three and exactly three repeat two times um so in example two we have two uh that is the repeating number and the rest only has uh olene has been repeating one times and number three we have five as the repeating number and the rest um are only repeating one time so how do we approach this um if you are coding in cha in python you will know that um if you import the collections model and there is a method called collections.contour collections.contour collections.contour which put um the list in a dictionary so for the key in the dictionary it's the elements in the dictionary for the value is its frequency so basically collections dot counter method create a dictionary and um for the frequency of the elements in the list so we can use that then we just then use the most common method to find the result so let's code it up and you'll see it's super easy and you'll understand it so um basically collections the counter and the counter by the way um starts with a capital letter and you just put the a in here so it creates a dictionary and you use the most underscore common and you put one here which means that you just want to find the most common uh lee appeared a number only one if you put two here you will find out the most like the most common they appeared and then the next commonly appear if you put three there they will give you three elements in this case we only want to find the most common words and because it's a dictionary um so basically it's right now it's a list in a list so if you just return this let me just try it to you it's gonna be incorrect but i just want to show you how it looks like okay so you see that it's um returning a tuple in a list so this one this element is the most common words which is three and this is the how frequently it appears its frequency so basically we don't want the tuple we just want this number so how do we do that we just put zero here because we want the first element in the list with which is three two and we want the first element of the tuple which is um the first one so we just put zeros
N-Repeated Element in Size 2N Array
long-pressed-name
You are given an integer array `nums` with the following properties: * `nums.length == 2 * n`. * `nums` contains `n + 1` **unique** elements. * Exactly one element of `nums` is repeated `n` times. Return _the element that is repeated_ `n` _times_. **Example 1:** **Input:** nums = \[1,2,3,3\] **Output:** 3 **Example 2:** **Input:** nums = \[2,1,2,5,3,2\] **Output:** 2 **Example 3:** **Input:** nums = \[5,1,5,2,5,3,5,4\] **Output:** 5 **Constraints:** * `2 <= n <= 5000` * `nums.length == 2 * n` * `0 <= nums[i] <= 104` * `nums` contains `n + 1` **unique** elements and one of them is repeated exactly `n` times.
null
Two Pointers,String
Easy
null
801
hey what's up guys jung here again and so today let's take a look at this lethal problem here number 801 minimum swaps to make sequences increasing a very good dp problem we have two integer sequences a and b who have the same non-zero length and you are allowed non-zero length and you are allowed non-zero length and you are allowed you're only allowed to swap the same the two elements at the same position like ai and bi and our goal is after some swaps we need to make we want to make both list array a and b strictly increasing and it asks us to find the minimum number of swaps to make both the sequences strictly increasing okay so and this is another like minimum number of it asks us to find the minimum numbers okay and again so for the minimum number of minimum value problems there are a bunch of ways right so we can do a bfi search how about bfs probably not this one doesn't have any so the bfs search we always want to find the uh the minimum steps from to reach one from one state to another but for this problem the starting state we have but for the ending state uh we're not sure right there could be multiple ways to get to the ending state and we don't know which one is that okay so that's why we can now use bfi search and binary search probably not there's no sorted things here and so basically this problem you know we can use both use the d we can try to use the dfs search you know for the dfi search it's pretty uh straightforward basically at each of the step here we can either swap or we don't swap right and then when we do a swap we just increase our swap time by one we keep doing it we basically we are exploring all the possibilities for each of the position here and in the end we're maintaining like a minimum swaps okay and every time when we reach the end then that's one branch right so one path is finished we're trying to explore all the other paths but obviously since the uh you know the length here that we're given here is the one so what to 1000 right so to 1000 and you know since i mean theoretically each i mean in each of the of this indexes here we can either swap or we don't swap right so that's each of the indices we have two options and for n numbers we have worst case scenario we have 2 to the power of n here right so with this like exponential like time complexity we can only handle like maybe 20 or 30 a length of it but definitely not 1000 not even close so but you know i think it's not a bad idea to try to implement that dfs search so that we can at least i mean to practice that dfs search one more time right so okay so let's try to do that right i mean how we can do it right so now the question is when we don't need to swap and when we need to swap okay so i think it's quite obviously so when we don't need swap right basically when the a i is greater than a i minus 1 and b i is greater than b i minus one so that's the first condition so for with this one we don't need to swap right because it's already done right it's already finished right i'm only talking about the dfs solution here so for the dp there may be another options here but for dfs we're only looking at the current i here we don't care about i mi minus one so for the i we don't swap second one is this a i greater than b i minus one and b i it's greater than the a i minus one so that's a second scenario i mean is this scenario i mean you may you someone may argue that so for this one i mean i say we have to swap a and b right to make sure that a is greater than a plus one and b is greater than uh b is greater bi is greater than b i minus one but someone may argue that it's not necessarily always the true right i will always true because what if the ai is greater than the b i minus 1 and the a n is also greater than a i'm a i minus 1 in this case we don't have to swap it right and same thing for the b here right i mean true right but in that case that we already that's if that's the case that we have already covered by the first scenario we don't swap and the second scenario is we want to swap right so even though like even though we it not necessarily needs to be swapped but since we already covered the not swap scenario and for the second one i mean we have to swap so that we can make sure because this one you know it's possible that it's valid but it's also possible it's not valid right so that we have to swap it to make sure to guarantee them to guarantee it is valid it increasingly increasing uh strictly increasing array okay and yeah remember these two uh you know actually i'm gonna uh try to implement these things here so to do that right we do it backtrack so i'm also using a backtrack here and uh index right we have index and we have swap times okay swaps basically how many times we have swap so far and we're gonna have an answer since we're going to get the minimum i'm going to initialize this one to the maximum sites okay and then we'll do a backtrack zero and zero okay and in the end i simply return the answer here so if i right oh and we also need an n here n is the length of a either a or b doesn't really matter and none local uh answer here right basically if i is the same as n then we just update the answer here minimum answer dot swaps okay if not we need to check these two things right basically all right we just copy this thing if a is greater than a i minus one and b is greater bi is greater than the b i minus one so in this case we're not swapping it so not swapping means the backtrack not swapping means that we increase the length by one but we don't change the swaps okay another thing is if the a i be i minus one right and b bi a i minus one so here we swap basically you know the df the essence the nature of the dfs is we on each of the backtrack here we try all the possible solutions so this is one possible solution and second one is we swap that's also another possible solutions because after the swap it's guaranteed that uh it's it both of a and b will be a strictly increasing array right that's why it's also a valid path so in this case i plus one and the swaps plus one but you know don't forget we have we need to swap it right so basically we swap a and b to b i and a i okay so we swap those two things but remember so here is well once here's the uh how the backtrack comes into a play because after this swap i mean we have to swap it okay so why is that because you know since all the path right all the paths sharing the same a and b array here and if we swap this element here and of course this is what we want with inside this backtrack right but what if some other path comes to this array here right so in that case we want to revert this one back to the to back to its original state so that our swap will not affect other paths okay and that's it right i mean i think let me see here okay uh let me hide this uh destroyings first so i think that's pretty much it is for the back tracking method i mean basically which we just explore like all the possibilities right and then we are we just maintain these things here sorry oh here we need to return it sorry and then yeah let's try to run it this should just work no answers okay backtrack zero hmm i caught zero and zero okay hmm um i mean maybe we it's uh maybe we should start from one here not from zero because zero it doesn't make any sense right for zero it's if there's only one the first one there's no way to swap it yeah i think here yeah so this one works i mean yeah because it doesn't make sense to swap from zero we have to check from the second one that's when we can check the a minus one and a right and i think one of the improvements here is that if the swap if swap is greater than the answer okay then we simply return this is like one of the uh the pro improvements that we can make i mean if the current swap is already greater than the current answers we can just simply not continue on this one on this path right so let's try to submit it let's see it will time out but which is not a bad thing right at least it tells us our logic is correct it just hasn't it didn't meet the minimum time complexity requirements see times out and okay let's see how many okay so basically see it pass like out of 102 test cases we pass 84. okay how many are those like the uh i don't know what are the numbers here see we have passed a lot of numbers here right yeah they're like at least i like hundreds of numbers here so why is that i mean it's because the you know not every time these two conditions are always true right sometimes only one of them is it's true so that it's not so that basically it's not like strictly 2 to the power of n maybe something like 1.5 1.5 1.5 uh power off of n so that in this case we can have like maybe accommodate maybe up to 100 numbers but still right it's weight way more less than that than 1000 and cool anyway so that's the uh that's the dfs plus the backtracking solution so but it still times out and the next one will be the dp okay so for dp you know at the beginning you know our first attempt will always be like okay so i'm going to define like the dp i right so dpi means at the current position i here so the previously ice element for a and b they are strictly increasing what's the minimum swaps right we have so far okay but will this work for us right since we have these two options okay let's think about you know for dps we also need to consider these two options right well this only one dp array can help us right to derive the dpi from the dp i my i minus one okay and the first one is this one okay so the first one is the uh the dpi right the dpi since we don't swap it's going to be the dpi minus one okay so this one seems working right i think so and how about the second one is that we have to swap um it means that we have to swap the current one right we either swap the current one will swap the i minus one so in this case if we swap the current one so dpi will become what dp uh i minus one plus one right i mean as you guys can see so the dpi here means that so here we have like two states here right we want to identify for the i here basically either we swap the current i we or we don't swap the current i and with this one array one dimension dp we cannot identify them so that's why i mean instead of one d dp array we need two basically we need a swap i and not swap it you know actually this is like a kind of similar to this buy and sell stock problems if you guys remember the buy and sell stock problems the way we're doing it we are defining like basically two uh two arrays right similar as this one so the first one is the buy it's a buy array second one is a cell array but that one is a little bit different because that one is the uh i think that the definition for that one is the buy eye means the uh the last uh transaction was by but it doesn't have to be the i that at the i stay as long as the last transaction what i mean was by that's fine it doesn't have necessarily to be on that specific ice state but for this one uh the swap eye means we have to swap the current ice element that this is a difference okay um so with this swap eye and not swap eye we can then try to like implement these two conditions okay let's do it okay i'm gonna okay come out these things here and okay so like i said n is the length of and we still need n here and uh we need the um answer okay no we don't need the answer since we're using dp here uh like the swap right swap equals to what zero okay and not swap also zero to n okay so like i said i mean and we need to start from the second one right i in range one to n okay since we're starting from i here we have to initiate the zero one the index zero for swap and not swap okay so it's pretty straightforward right so first swap zero it's one right that's one swap so for not swap zero it's the same this is optional right i mean because we initiate everything to be zero so we can skip this one but for swap one swap zero we need to mark it as one it means that to swap the first element uh we will have swap times one counts one okay and here uh we'll simply copy these two options okay so the first one is this i mean okay since we have this one here right so the first one is very easy right we don't swap so that means we're not swapping the current one and we and also not swapping the first one the previous one okay yeah i think this is kind of easy to understand right because let's say you if we don't swap this one the previously one cannot be swapped either okay otherwise i mean we cannot guarantee that it's strictly increasing right and but there's another option there's another like scenario here so basically we can either choose swap the current the i from what from the swap i minus one plus one this is another options we have here so why is that i mean let's say we have a we have three six one and two how about this so this is i minus one and this is a and this is b so this is our current state okay so to get to the current state basically you know you have to remember the dp the nature of dp is we are for current state right how can we get to the current state and in this case the four numbers uh consist of the current state right remember that so we have four numbers a i am i minus one b i and b i minus one so to get to this current state what are we have to know what are the possible ways to get to the current state so the first one is the we don't swap the this one basically everything stays the same because this is the state we need right every everything everyone's don't change okay that's why we have not swap and not swap i minus 1. but there's another option here oh sorry there's another possibility here so the i minus 1 was so the 3 1 coming from one three and the six two coming from two one two and six right so this is another possible path right basically this means that okay if we swap the i minus 1 from 1 to 3 then we also need to swap the this current one from two to six to get to the current one this kind of makes sense right i mean and someone might argue that so if they are the if they have this is the correct space why the valid state why this one got swapped before it may be because i minus two have like some different numbers here so in order to make i minus two and i minus one strictly increasing we had to swap this one two three this one three two three one okay so basically that's why to get the current state we have two paths either we don't swap i minus one and an i or we swap both okay so that's one and second one is this one okay and same thing for this i think someone of some way some of you may have already maybe realized how we can come up uh write the code for this condition so for this scenario you know we also have two options like i said the first one is to swap this a and bi but we don't swap the bi we don't swap the i minus 1 or we can swap the i minus 1 but we don't swap the a here so if we swap the i minus one sorry if we swap the i here uh we're gonna get the swap i times uh it means that we don't swap the what uh not swap i minus one plus one right since we're doing a swap that's why we need to add a one here or if we swap the i minus one it means that we don't swap the current i here so which means it need falls to in the not swap array here okay minimum not swap i the reason we're doing a minimum here because we up we might already have like uh sign the values here okay yeah actually so to start with right to start with we have to initialize to system max right max size same for the swap okay i mean we can initialize everything here or we can initialize here it doesn't really matter so it's your choice but to initialize here it help us to uh i mean for us to improve the space complexity later on what hey what's up guys so continue for this problem i don't know what happened to my uh i think there's something wrong with my uh streaming software i think i got some like memory leak problems i need to figure that out but okay let's i will try to combine these two videos together and upload later so let's finish this problem here so i mean for not swap right so for not swap here and if we don't swap this one it means that we have to swap the previous i minus one so which means we need to swap i minus one okay uh yeah and since we're not swapping it we are we don't do a plus one here okay and in the end we simply uh like simply like return this minimum of swap or not swap at the last element okay so let's try to run this okay so this one passed let's try to submit it okay cool i mean this one passed and okay and you guys may have already know this here so the current state only depends on the previously i minus one state so which means instead of using like o n space we can use uh o one so the way we're doing it uh i'm just instead of using a list here i'm only i'm going to only use two variables here okay zero and here uh since we all will be repeatedly using this same variables so and which means at this moment this variable uh represents the previously state so for the current state i'm going to create a temporary variable here this is that max size okay and then for not swap okay two right same thing the swap two is the current state and here so let me not swap two will be the not swap from the previously state and the swap tool is the swap plus one right same thing for this one here and swap equals the minimum of swap sorry swap two okay remember we're dealing with the current state and the previously ones not swap plus one okay and then do not swap two is also equal to minimum swap of not swap of and swap and in the end we simply return the swap and not swap the minimum value from those two sorry uh after the current loop here uh we just need to assign swap to swap two swap to the swap and not swap two to the swap not to not swap okay yeah so this should just work uh oh sorry swap two yeah submit yeah this should just work okay cool guys i think that's pretty much it is i want to talk about for this problem i mean it's a very like good dp problem but since we have two states here since we have two possible options here right we either swap the current one where we don't swap the current one and actually there are like four scenarios here so with these conditions we don't swap current one or we can still swap the current one or with this one we either swap the current one or we swap the previous one yeah so it's very tricky problem at least for me it's a kind of tricky one and you may i think you guys just need to uh like get used to this kind of like swapping mechanisms and every time when you see a swapping problem for the typically increasing scenario strictly increasing scenario you have to basically check these two scenarios and especially for the first one not just this not swap but for the swap it can be can also be coming from the swap the i minus one and also swap the current eye okay cool guys i think that's it for this problem thank you so much for watching the videos and i'll be seeing you guys soon stay tuned by the way bye
Minimum Swaps To Make Sequences Increasing
is-graph-bipartite
You are given two integer arrays of the same length `nums1` and `nums2`. In one operation, you are allowed to swap `nums1[i]` with `nums2[i]`. * For example, if `nums1 = [1,2,3,8]`, and `nums2 = [5,6,7,4]`, you can swap the element at `i = 3` to obtain `nums1 = [1,2,3,4]` and `nums2 = [5,6,7,8]`. Return _the minimum number of needed operations to make_ `nums1` _and_ `nums2` _**strictly increasing**_. The test cases are generated so that the given input always makes it possible. An array `arr` is **strictly increasing** if and only if `arr[0] < arr[1] < arr[2] < ... < arr[arr.length - 1]`. **Example 1:** **Input:** nums1 = \[1,3,5,4\], nums2 = \[1,2,3,7\] **Output:** 1 **Explanation:** Swap nums1\[3\] and nums2\[3\]. Then the sequences are: nums1 = \[1, 3, 5, 7\] and nums2 = \[1, 2, 3, 4\] which are both strictly increasing. **Example 2:** **Input:** nums1 = \[0,3,5,8,9\], nums2 = \[2,1,4,6,9\] **Output:** 1 **Constraints:** * `2 <= nums1.length <= 105` * `nums2.length == nums1.length` * `0 <= nums1[i], nums2[i] <= 2 * 105`
null
Depth-First Search,Breadth-First Search,Union Find,Graph
Medium
null
847
Bluetooth Facebook Today Will Be Discussing The Problems Of Taste For Visiting On So Let's First Understand A Problem Statement Being Given Directly Connected Graph And Note Smith 021 Minus One Note Se Zara Fiber List Of All Notes Connected With Node I Boys Association President Meaning Of Address Representative All the Notes British Connected to 90 and Asked All the Best Connected to Was Not Be Disconnected 0 Connected to All District News A&amp;B Happy Returns for This Point Visit Every A&amp;B Happy Returns for This Point Visit Every A&amp;B Happy Returns for This Point Visit Every Month and They Must Stop and Every Where Didn't Want End User Episode 113 cigarette will have to loot hotspot setting open note and I can start from anybody can start from zero lets and I will go plus 2 ns200 student 2014 39 district race course 123 456 more steps should have to return shortest path date visit every nook so Let's Bus Stand Till Problem Idea Then Is Best On Witmarsh Setting Show Actions Were Visiting Road Show A Difficult Maintain Vector For Visiting Beach Return That Aishwarya Is Right Y2 Compute The Time Complexity Will Increase Viral My 9th Day Which Will Give That Time Will Ultimately 2 114 Side Stormy Daniel Dexter And A Woman Tabs Mask And Beach Visit 24 From This Website Visit Britain And So A Special Report One Position To Howrah Like And Jis Position More Jis Position One Jis Position To Entries Update Mass Sources Of Minor In Form Of And Suggestion Power 400 To The Power Is Note Specific To Give Ans 4 In Which In Binary Is Dowry And 10 2011 At Second Position 100 225 Update Number By Which 1808 Numbers Position Certificate So Let's Have Written More Than 900 Vacancies The Mask And This Visit Return Note 3 Is A Day To Celebrate This And Put One Have Visited 3 And If 24218 Positions Suggestion Tamma School Pickup 520 Withdrawal And Operations With One Shooting Of Riots Will Want To Lay There Written In Oven David Warner And Operation Award And 120B Hai Thursday 010 And 130 Ki And 081 And Ribbon Choice Will Give One Shyam David Whose Its Second Position And Visit 9306 Question And Have Not Visited Valve Wishes One Position And Have Not Visited 0346 Of Birmingham Meat Which Month Baby Using PC Hardware Which Not Visited And How Much Distance Covered Fennel But Running BF Is Chole Nu Orientation And Morning Hair Deficit So That Customer Lot Size Its quantity 2009 sorry sentence roles veervrat been situated in the distance in love at 9 am just but if function and western is 102 but pass because balance so normal first let me take home remedies no deal with the lord and votes from 021 minus one And also loot btech in this all teacher reduced to a to z yar changes cpm of 108 se channel acid 900 hai jo sister bhi se dhundho east the way withdrawal turn of lemon juice backem one 600 11111 sincere singh back to power and Sugar Power And Spread This Phone Not On Wed 08 - 08 - 08 - 148 800 To 1000 500 INR - 4th Edition That Jab Not Mean That 500 INR - 4th Edition That Jab Not Mean That 500 INR - 4th Edition That Jab Not Mean That You And You Will Have The Year Of Years That Tender Ke Paison Bhi Testis Remote 273 Balance What Is The Value Of The Road Wheeler Distance Between Delhi To And Specific 102 Top Increment Is Vansh And In Which Withdrawal Version And Mask Meet Mask Platform In All Respect And Jyothika Set Of Years Ago Without Some Suggestion Set Visit To Henna Now How To Save Behaved Visit Set A Not With Certain Version Again So Let's Say I Have Already Visit To Who Have Current Iodine Computer Note 2 And Aggressive 108 Mask Is Mask Show Live Expert In To Make You Wick Wood And Creative Work Calculated For Science And Environment And Distant Should Not Pushya Give Some That Sunao Iodine Trump Versus Ad 10m Se Date Inter CPI(M) Is Inter CPI(M) Is Inter CPI(M) Is Dynasty Tips That Flat Means Language Person Updater Deceptive Is Inexhaustible Curative Powers Is Know It I Don't Show N X G On Flower Store Why Successful Businessman And Distance Currently Visible Sharon Rebel Starting From The Absolute And Was Mooted Is Soviet Union Tubelight Clear In Selecting And You For Failure Scene That They Have Visited Is Not Wasting Time And Distance It Must Be Some Which Pen Drive C Institute University At Is Estimated To Job To Last 349 Match YouTube MP3 Tune Can Find A Visit in order to address to the first year post and a's nature this intellect Note 4 first and distance from being mode of the second most famous and a sorry dip notification light set and tell 550 now setting on the notes on child who's on off Value Neck Of The River When E Saw A Great Seducer Note Shyam Visiting This One To Three And Avoid New Delhi Mein Aa CPI(M) And CPI(M) And CPI(M) And Vansh Difficult Hai Jo Hair MB Medical You Must Loot Se Currently Have On 90 Chaumas Ko 900 Unauthorized Net From us try turnover to ayush baikunth and operation with registration explosion ke 800 to jis wo time snack festival must enter acid you must call someone 222 call 100 jis fonts pimples us chironji singh withdrawal subscribe not entertain plus one is the distance id i Only visit for that tenth happened new models today will hand over sofa 2018 cigarette comments reduce note alert and receptive aged only shyam winters container loop serve till video use and use it well attacking and obscene maintaining witch not come post with witch saw blades of Why can consider it should be given in the visit of 138 and more than 1000 Uber app installed and died from 2nd ed 0 that we which has Geeta mans and I my sweet will not like this which is a difficult question welcome to one Multiple times but with different visit versions or excused with different masks The Amazing All the possibility of all the and receive the possibility reservation facility which gives distance from states and college Difficult for this distance from first in the short distance Shoaib is back computer emperor Witch Has Already Post Preventive Unit With Same Of Witch Continues Allegation Also Don't Nutrition Now And Skimming This Notes PDF Reader Why 39 Special Him Tooth Apne Mitra Distance Lakshman Tanu 502 Ki And Veer Vinod Minister Will Leave Some Distance And Loot-Loot I Mukesh 20 Minutes Paya Volume Sir Yes Director David Stand Your White Thing In The World Have Such A System Which Must Share This Gives Accepted Her But My Subscribe Button And Listen Nothing All Is Okay To Switch On Queen Push Thank You
Shortest Path Visiting All Nodes
shortest-path-visiting-all-nodes
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges. **Example 1:** **Input:** graph = \[\[1,2,3\],\[0\],\[0\],\[0\]\] **Output:** 4 **Explanation:** One possible path is \[1,0,2,0,3\] **Example 2:** **Input:** graph = \[\[1\],\[0,2,4\],\[1,3,4\],\[2\],\[1,2\]\] **Output:** 4 **Explanation:** One possible path is \[0,1,4,2,3\] **Constraints:** * `n == graph.length` * `1 <= n <= 12` * `0 <= graph[i].length < n` * `graph[i]` does not contain `i`. * If `graph[a]` contains `b`, then `graph[b]` contains `a`. * The input graph is always connected.
null
null
Hard
null
994
First time spray attack in jhal Voting orange wash problem number 9483 dog show in this question the giver graph and its significance of different types of pollution based idioms thistle and festival which gives instant notifications every minute in fresh and incident to and rotting hormone begum pure Water Should Only Happen For Directions At Between Inheritance Row Turn On It's All In This To Protest And Fertilizer Don't Stop Water Left Or Right Only Hindus For Sacrifice For A Direction Will Be Considered For Information On The Danish Crown Production Okay So What Were Supposed Vyas Positive The Meaning of the Tiger Required Secure Can Convert All Spheres and in Centaur Hotel State OK But It's Impossible in or Twitter - 117 Possible Effigy of in or Twitter - 117 Possible Effigy of in or Twitter - 117 Possible Effigy of Assuring Complete Life Se Relative That Rotting Hormone Must Witch Show That Time Only Able to Convert to This Quote 24 System - Track Tight Dresses For Quote 24 System - Track Tight Dresses For Quote 24 System - Track Tight Dresses For Example Baitha Pandit Sab Gyani Mishri Displaced From Greater Noida To Withdraw From This Point To The Thing But After All The Actors To Give To Example Or Aap Andare Mein Ki And 0205 Animals Which Means That The Regression In Some Cases Operation In Quality Control The Origin Products Example Services At That Time From Its Own This Is The Force Which Comes To Mind As I Connection For This Question And This 16 Feb 2012 In The State And Subscribe To A Fresh And Rot In The State And Unauthorized Store Code So I Don't Like For the thing used cars in the supremacy and solid 205 travels from greed for great apps for you Lenovo me radiation of brother you doob soya number to which is the subscribe to the Page if you liked The Video then subscribe to bluetooth setting weather-beaten yes inning bluetooth setting weather-beaten yes inning bluetooth setting weather-beaten yes inning express and inch president boy doing committees to the meaning of this thank you too much land of rest 98100 dharmadas find and Rotting That Until In Arrelist Captain Adhyayan A Fresh Orange As A That Yash Chopra Festival Seema Time How Much Time It Lives It Will Be The Thing To Deal With Answers Is Quite Reverse Entry For Its Production Slowed Down Their Children To Create Opium Crop Directions Show In Shift in which direction Back treatment Top Model Price in President Subscribe to my YouTube channel - Subscribe to my YouTube channel - Subscribe to my YouTube channel - 1805 E That Sudhir and direction that witch knocked on Top Bottom Left and Right Okay Soya Next Posts 671 Your wild life in that grade -03 Because give reminder not that grade -03 Because give reminder not that grade -03 Because give reminder not condition also changes you and cigarette it professional life related which dat teaspoon cardamom user attempted dictionary ok effects of how many and decide rot in this particular attention deficit reduction in which I don't you rot in his resurrection More Popular Notable Then Radhe Shyam - Not Just For Its Radhe Shyam - Not Just For Its Radhe Shyam - Not Just For Its Coordinates Lotan Asked This Question - Which Rotting Hormone Which Asked This Question - Which Rotting Hormone Which Asked This Question - Which Rotting Hormone Which OK singh20 Convert All The European More Present Important 02 2012 BCCI President Should Not Divide Want To Avoid All Directions For Directions Of Doing So will be plus direction of similar to a ko kaun chori note paya chori 10 posted in this unknown india salary with things will BJP do this of the Video then subscribe to the Page if you liked The Video then subscribe to the Page Quote of Land of Mic Carat Minute 5000 to 10000 at this time 30's checking for a particular jagran song solid network election video checkpoints for the guardian subscribe and subscribe the Channel Please Share Thank you Just AN hua tha hai ya phir paas testis normally strike us time tarf jhal ok sir top secretary vicente Smith was like f61f Firecrackers gifted to him as a President at Ashram time The Fourth Day matches were offered 800 cents over last date Photo Sudhir and Rotting Hormones Just Give Everyone Happiness Categorized into Writing Rotten and Pure Quite Significant Pimple Note Shades presentation body that 40 to cross offer for his visit to travel to avoid settlement also experience victim of frustration in running water operation immodia dam to Ronit Roy ok and scheduled to convert all of the series and introduced in the system time handy application so it is difficult code thank you
Rotting Oranges
prison-cells-after-n-days
You are given an `m x n` `grid` where each cell can have one of three values: * `0` representing an empty cell, * `1` representing a fresh orange, or * `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. Return _the minimum number of minutes that must elapse until no cell has a fresh orange_. If _this is impossible, return_ `-1`. **Example 1:** **Input:** grid = \[\[2,1,1\],\[1,1,0\],\[0,1,1\]\] **Output:** 4 **Example 2:** **Input:** grid = \[\[2,1,1\],\[0,1,1\],\[1,0,1\]\] **Output:** -1 **Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. **Example 3:** **Input:** grid = \[\[0,2\]\] **Output:** 0 **Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0. **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 10` * `grid[i][j]` is `0`, `1`, or `2`.
null
Array,Hash Table,Math,Bit Manipulation
Medium
null
41
Hello everyone so today bill b discussing question number 41 of late code which is first missing positive ok so here we have a hard problem so we have to do it with some thinking it is a little difficult but it is very difficult. No and this is my play list of Cyclix shot, this is its part, see its questions, try it after seeing the questions, I hope you will understand it very easily and the concept of your shot will also be clear. Because this is a hard problem, after this if you have done it on your own with cyclic shot and after watching the video then you will get gas and you will start thinking about psycho problems on your own. This is a very simple problem, it is a very simple topic and you have to think more. There is no need to understand, there is a simple template in it, there is simple energy, you have to follow it and here there can be negative numbers, there can be positive numbers, elements can also be repeated, all the unsorted interiors have been given in it. We have to find the smallest missing positive expectation. What does it mean? So, we reduce it by one, which is 34134 -11. We put it in the number line 34134 -11. We put it in the number line 34134 -11. We put it in the number line 34 -1 and this one. Now what happens that the rest of this -1 and this one. Now what happens that the rest of this -1 and this one. Now what happens that the rest of this space is empty? There is space, okay, I need to check here and the smallest has said, I will start checking you from here and I will move forward like this and it has said missing, so now I have put the number in the line, one, you are missing, no. After that we will have to see which one is missing, if you are not in the sign, then are you a sum positive number, are you the exception, if you were also there, then we go to three is four, then after that, if it is not five, then five. Our answer would be given because we are starting to check from here. Now look at this. As soon as you see this cyclic shot, you should understand that a cyclic shot has been placed here. According to the previous questions, you will see why here there is one in front of one. There should be tu in front of you, okay there should be three in front, there will be a little difference while implementing but one tuition should be given that only Cyclix shot will be used here, there should be a respect for it on the position, only then we do Cyclix shot here. If it is visible then we will have to do it, okay, we will do it, how will we see, okay, now here these are my indexes, basically I have to call room and this is my name which I have to call box and what is my role always in cyclic shot. I do this operation only when I am sorting, there is caste, so what I do in sorting is that if there is zero in front of zero, there is one in front of one, there is tour in front of you, then after that, whatever I do is short. I have to do an operation on this, first of all I have to sort it, but look at one thing, the box here, its numbers, which means these elements, some negative numbers and zero, is it important for us, no, not at all, not important at all. Well, both of them do not come in the positive list, so there is no point in them, so there is definitely no point in putting zero in front of zero, so what will we do and one more thing, look brother, we have a room, this is ours. There is a room near zero, so we will not waste it unnecessarily, we will also utilize the zero, so do not put zero in front of zero, we will keep one in front of 0 and what will we put in front of one, following this pattern, we will keep tu in front of tu. We will put three, we will put four in front of three, we will reduce all the positive integers and all the negative integers to zero and after shortening, we will see how ours is. Okay, first of all, do you understand what I am saying about zero? One should be in front of one, you should be in front of you, three should be in front of three, four should be in front of three, it is okay, it is a random number, that is why one did not come in front of zero, okay -2 means -2 means -2 means you are not there, it is original and if not, then it means you only. If there is a missing, then as soon as we get a miss match, what am I calling it? Okay, I am calling this cross a mismatch and if there is a three in front of you, then we will move forward, then what will happen, it will become 5 MP because there is no 5, right? If you look at the number line here, there is 5. Sorry, this is not the number line. There should be five in front of four, then our answer will be 5. You must have understood that after sorting, what we have to check is that if we have to check the mismatch, then as soon as we find the mismatch, we have to return the first miss match. Now we have to see how to sort it. Are you understanding, first of all we have Sorted and in short we also have to privatize what should be in front of zero, one should be zero, what should be that one is negative here and there is a space in front of zero, we will not waste that, you in front of 0. One will be placed in front of one, you will be placed in front of you, three will be placed in front of you and if there is an even out in front of one, you did not get some random number, Anna went according to the sign, -1 in front of 2 went according to the sign, -1 in front of 2 went according to the sign, -1 in front of 2 means, I am not you, short By doing this, there would be one in front of zero. If there is one, then there is one in front of one. If there is no tu in front of one, because we are shortening it in such a way that we have to keep its respective box in front of the element, its respective box in front of the room, that means that box is present. Ok, they will see, there is just a change of one or two lines. Okay, so let's reduce one. Okay, so this is our example, let's see how to do this. So these are our boxes and these are our rooms, meaning index and elements, this is my template. This is the code which I have been doing completely for the last 2 days from the questions and I will do the same here also and I am changing the same condition every time, this condition and a little thing inside the swipe, the rest of the code is the same. The only thing you have to figure out is what will come inside it, when you have to swipe, how to do it and also you have to do something inside the swipe, can you do something inside the swipe many times, okay, so let us see the condition here. Let's take what is the condition, let's go to mother, we came here, if in front of zero we come in front of zero, we got a number, let's go to mother, 3, then in this condition, should we swipe, swap means should we settle its number. It should not be like if one 'A' is placed in front of zero then it is like if one 'A' is placed in front of zero then it is like if one 'A' is placed in front of zero then it is correct, brother, there is definitely no one to settle, so this number can be number in many ways, meaning it can be one, it can be -2, it can be zero. can be -2, it can be zero. can be -2, it can be zero. So what number do we have to do on which number, we will have to write this condition here, this is what I am saying in cycle short, you must have understood it a bit by now, if not then you guys, then look at this once again. I am checking that first of all I came here, in front of zero, now I checked, what is the number in front of zero, is it free, so whatever number is there, first of all, you have to see when to ignore that number, either it is negative or not. So it is zero, if it is negative zero then ignore it, if that is the name, give it greater, yes, it means it has become bigger from the side, there is four here, so with 43, I can put four in front of three, I am here But for my element, that is, the box, I have to keep an index on the previous one, that is, one should come on zero and you should come on one, you should come on three, four should come on three, that is, so here I have put equal tu, but if If I go to five, I don't have space to keep five. I don't have space to keep such negative numbers and I also have an importance check to keep zero. This is the same check that there should be some random number in front of zero, only then I will swipe, only then it will be there. I will settle, meaning there should not be one in front of zero. Here you should not be in front of one. If there is one in front of zero and this condition is also followed then brother go ahead and ignore it but if there is any other number then brother swipe it. This is what I am saying out of so much fear, is it okay, so what will we do, let's do it quickly, now here there is three in front of zero, so let's settle 3, where should there be three, there should be three here in front of you, so one is minus. Bring one here, put 3 here, then what will happen after that is 3s and this will become -1 Now there is minus one in front of zero, -1 Now there is minus one in front of zero, -1 Now there is minus one in front of zero, do I need to give it value no because let the name be greater, it should be zero and by the way Also, if there is nothing to be done with Mins One, then there is a red number, still there is -1 in front of zero, so there is a possibility, is -1 in front of zero, so there is a possibility, is -1 in front of zero, so there is a possibility, maybe brother's Mins One means one, our missing positive is found, but let's see what happens next brother. It is okay for us to come forward because here we have to ignore it and settle the four. Where to put the four? Four should come in front of the three. Here and one should come here. So reduce one and keep it, otherwise it will become four. Here and here A will be positive. Yes, should we take it? Yes, should there be a forest in front of the forest? No, this condition will also be true. Yes, neither should you be a forest farmer, then reduce one by settling the forest. If we give then one is settled then it will be one here and here it will be in front of zero, in front of one is minus one A, now minus one is A, so ignore it, go ahead, what is in front of 2, what is three, is this Greater dene is zero, is it li dene? Yes, yes, it is correct and there should be three in front of it, so there is no need to swipe, similarly, there should be four in front of three and people will be finished, now this is our sorted, yes. Should be and is also does not mean what but what is not, does not mean you are missing from me and this is our sum. Okay, now you have understood that what makes this question hard is that. Let's discuss the parts so that you can understand, a little of this, you may have difficulty but I will try to make it as simple as possible, it is a very simple thing, you have to think yes, which Apart from date is making this question difficult. If all these were unique interiors then this question would have ended here but because here there can be repetitive interiors also. Till now all the queries we are doing have unique integers but in this What will we do? Okay, so here I have an example, we will ignore it and we will be flooded further. Now we have one in front of one, so this condition is true, this condition is also true because one is greater than zero, right? Now look at this condition, what is this meaning, one is in front of one, -1 is this note equal, meaning, one is in front of one, -1 is this note equal, meaning, one is in front of one, -1 is this note equal, you come, and what is this here, one means zero, this note is equal, you are right, brother, one is in front of you. There should be one in front of mother, so if you are swapping, then one will go back here, then you will check and this problem is how to solve it, check for duplicate, it is over, check for duplicate, what do you do? Put one more and what to do in it Put another check What will you put the second check That is Namas of I Sold Note Be equal to you The number should not be present What do I do in the dream Namas of Same -1 And to whom else would I give Namas I am swiping both of them, I am just checking that these two are not from the story, the one who is swiping these two, please check whether they are from my brother, then just check this and Dal Dog, this is yours. This one will also pass, brother, ignore it or ignore it because if we do this thing like this then our infinity low fence will go, so put this loop and check this dog, otherwise this will flood yours and it will flood further. So it will end, you should be there, you are our answer and it is correct, if we do not put this check then our lo I will go into infinite loop and you have to do this test, then it is very important to put this check. Now I am giving you a Let me tell you one more thing, it is very interesting and this question ended here but I want to tell you one more interesting thing that even if you put this check, you will get the answer, you will also get the answer, it is a very interesting thing. If you are doing an interview, if you have done it even till this stage then give this date, if you remove it then it will also be fine. How can you do it? If you are not interested then you can skip it. You can see it directly in the code. Ho another vice, I am going to explain why I can remove this part. Okay, so let's quickly see what that thing is. Now let's go to mother, these are the two conditions I have, is n't this Ali, this is the condition that is happening. Two conditions have been written here, okay, now I have written all its possibilities here, water can be true, this is the possibility and not just any other combination. Right, now first of all let's see the condition, if this condition is water, what does it mean? If this condition is water, what will it mean? The condition is water, I put one in front of zero, I subtract one, three in front, this is lay. This is my index and this is my element, meaning this is my room and this is my box, meaning it has happened, is n't it, in front of me is three minus one, what is it, is this condition true, isn't it mine? Come, it will be done, it means it is water. Okay, so it is water. What will happen to this condition? What is the condition of settling it on 3rd to 3rd? In this condition, check the same, what should happen, is there a number from there? And you are checking for 3 in front of you, which means always keep this thing in mind, it means you are searching for 3 in 2 because there is already a 3 in front of you and the 3 is where it should be, so how is the duplicate one? It will definitely come, it is not a duplicate. You are looking for 3 on 2. Basically, think carefully that if this condition is fulfilled then see the result of the remaining conditions. What will happen to the water of water? What will be the result of True? What will happen if this is water then the answer will be water. If this is water then the answer will be water and if this is true then the answer will be true. Is there any difference in the existence of these things? Is there any difference in the existence of this condition of these things? What is not reading? If you are not reading, then exclude it. This means that even if you exclude the condition, your answer will still be correct because this has become the deciding factor. This has become the deciding factor because this is the condition. What we do is that we remove those parts which are redundant if they are not contributing to the result, right? Why brother, there is no difference in the presence of water, true water, if it is from the fruit, then the answer will be water. This will be false, if it is true then the answer will be true, so what is the point of keeping this condition, so that the court does not look too conjuring, hence you can remove this condition, you can remove unnecessary checks, you can clean the code and say that we are cleaning the code. If time is bothering you then it is a very good thing. If not then there is no problem. Style is a very good solution and it will be a very compact solution. So let's do it quickly in the court. I don't think. If it will take more than 2 minutes, then let's check it quickly. Okay, will it come here or not? Now you can put a check here, you can put three of all the four, you can also put three of them, which means you can remove the one that you said to remove. So I am removing it here, your answer will be there even without it, so I will do it without writing it and even after writing it, you can check it, you can put that check. Okay, so what is that check, let me just give it. Naa, this note is equal, you will go to I plus one, okay, one second name here, try running it, I will show you this even after removing the third check, see, even then it should work, I have just tried running it and now I have tried submitting it. I was just trying to say that you have cleaned this code a bit by removing unnecessary checks, there is not much difference in the complexity, others are still off, so you can keep that sex or remove it, there is no problem. so look again ok thank you
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
942
yeahyeah Hi everyone, I'm a programmer. Today I'm going to introduce to you a problem with the following title: you a problem with the following title: you a problem with the following title: a suitable Dy string, then we'll go into the details of the problem. To better understand what this word means, the following detailed problem gives us a string s containing only 2 characters Y means increasing and D means decreasing and we will have n = length of strings s we will = length of strings s we will = length of strings s we will have to return any permutation. Any permutation of A consists of numbers from 0 to n increasing by one unit to have a value y from 0 to n - 1 The value y from 0 to n - 1 The value y from 0 to n - 1 The following two conditions are met. The first condition is that if we register a character at the yth position of the main element that is equal to y and y is large, we will have the value of A at the position before being small, it will be smaller than the value of A at the yth position is smaller than 1 in the second case if the character in the string s is the same as the yth position of the string s and it is equal to big D, which means the value of the piece A at the small y position must be greater than your value A at the y position plus 1 Okay, then we will go into example one to help us clearly understand the requirements of the problem. In example one, we have a string consisting of 4 characters. From yd ID system we see that for the letter character at the first position, that is, the position at y is small, otherwise we have the character of this place at large y, so we have a result fragment at position y and position when adding 1 of the resulting piece is zero and 4 has an increasing value seeing that y is at position ty then the resulting piece has a value of 0 at position the child one then the If the result has a value of four increasing numbers, similarly, the next character of the subject SD, the next character we will consider, it will correspond to the Pair of Exam Questions Next episode 41 we see that there is The decreasing value is similar to the next character, which is the y order, which is equivalent to the pair of 13, then it has the technique of increasing and then each and finally dike, which is equivalent to the one with 3 or yes. The value has decreased. So the crib at the end of the piece. Finally, we need to return in example one again the result that matches the problem's requirements will be piece 0 4 1 3 2 Yes and similarly we We will go into example 2. In example two, we have an initial subject consisting of 3 large y letters, we see that for three large y letters, we will have a piece arranged in ascending order from 0 to three. then our result will be 0 1 2 and 3 which is equivalent to Ba but with 3 pairs of increasing numbers 0112 and 23 like that. The return result is suitable for the example or not 123 then we pass example 3 with the middle of three places. Initially we have a place consisting of 3 elements, D, then we will have corresponding pairs that are phase or reduced pairs or not reduced pairs and 01 again chases the final y. If we encounter a monk like that, our final return result is 3 2 0 1 Yes. So we have grasped the requirements of the problem. Now we will go through the thinking part of the teaching technique to solve the problem. To solve these problems, for this dog lady, I will introduce an algorithm that uses a filter circle with two pointers y&amp;j with the dog y being the pointer pointers y&amp;j with the dog y being the pointer pointers y&amp;j with the dog y being the pointer in the lower field and the pointer di being the dog on the top. then the dog on the bottom edge will start from the value 0 and the dog on the top edge will be equal to the value of the length of the letter s when we will start transmitting this place with a loop then we We will check each character one by one, so if we have 2 cases if the current character is a large y character then we will add to the test result piece the lower Need value. Then we increase The only lower price is one unit. If in the second case the current character is divided by a large D, then we see if we can add the result to the machine, the value is in the upper bound and then we reduce the value. go one unit then we will do this until the end then after we have finished we will have only four numbers then we are left with one number this is the number but also two of the spread from y to move from the top to the bottom, and some of the parts are not used yet, we will wrap it in the result and return it to the program, I will try to model one in the example. For example, one phase, then the chu, example one We are id It turns out that the list of numbers that we need to prepare is that we will have the upper bound, then we will let y = 0. This is The then we will let y = 0. This is The then we will let y = 0. This is The lower one is y = no longer our upper match lower one is y = no longer our upper match lower one is y = no longer our upper match is I which is equivalent to the length of this place which is four then when we will start reviewing with this independent we review part 31 oh my error this is This dog to kill is called pointer ca. In case the fish is in this position, it is big, right? Cada is big, then we will put in our results table a value below. formula is the smaller value Because we are all up we will let it increase so we will add small values ​​then we will add small values ​​then we will add small values ​​then we will monitor y which y is currently zero we will enter zero then the two of us If we increase the idea by one unit, it will become one. Then we move up to the next position. The chip position is D. With d, we have to choose the upper bound, then we will look at the three values. you the result and this 4 we will reduce by one unit 3 continue like that we increase up to this position then K this position is big y then y is bigger we will take the lower celery leaf as y then we will increase it to 2 increase it to take it as one Then we increase it again to two and then we will go beyond ca to the element Finally, since this is D we take the upper bound as j is now three times. We take 3 names into the result table and reduce it, then after we finish the first shift, we see that the test piece and think we are always equal so We will add one last element and in these arrays, we can take anything, this will be our return result. Can you see each line with the result? The result of the question's requirements is E 0 4 1 3 2. Remember, you already understand what the department teaches. We will now proceed with the installation using the Gala programming language. First, I declare a Zero piece to please don't print Tiger quickly then I will return zezo and then I will continue to declare y = 0 di equal to the length of s declare y = 0 di equal to the length of s declare y = 0 di equal to the length of s then I will have a filter loop for I will pass all The elements of age force the characters of Wish em creature to be C then we check C and if it is equal to big y then we but we know that bit Hoang Y is bigger we will add to the piece our result is the value y and otherwise, on the contrary, let's make sure it will be dy, so we will add to the network our result there, then when we see it, we remember is to increase by 1 and j, then we remember to give di - 1. then we remember to give di - 1. then we remember to give di - 1. Finally, we have to add the last remaining element, which is the eiji element. If it goes away, then Let's try running these programs with example 1. Yes, we have succeeded. For example, the returned result is no 4132, which is the same as the desired result. For now, I will create an account to solve the problems. Another example: Yes, we have successfully solved all the examples of the problem, now let's evaluate a bit the complexity of this algorithm, we see that the complexity depends on will be two. Let N be the number of elements of S then we have the algorithmic complexity of onl and the storage space complexity of clo1 because we do not calculate whether this J is known because the bride's calculation is that it is one. Please return and thank you all for watching the video. If you find it interesting, please give me a like, sub, like and share the experience. If you have any questions, please comment or have a way. If you have a better solution, please record it in the comment section below the video. Thank you for watching. Goodbye and see you again yeahyeah
DI String Match
super-palindromes
A permutation `perm` of `n + 1` integers of all the integers in the range `[0, n]` can be represented as a string `s` of length `n` where: * `s[i] == 'I'` if `perm[i] < perm[i + 1]`, and * `s[i] == 'D'` if `perm[i] > perm[i + 1]`. Given a string `s`, reconstruct the permutation `perm` and return it. If there are multiple valid permutations perm, return **any of them**. **Example 1:** **Input:** s = "IDID" **Output:** \[0,4,1,3,2\] **Example 2:** **Input:** s = "III" **Output:** \[0,1,2,3\] **Example 3:** **Input:** s = "DDI" **Output:** \[3,2,0,1\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'I'` or `'D'`.
null
Math,Enumeration
Hard
null
832
hello everyone so today in this video we can discuss another problem from lead code the problem name is flipping an image the problem is telling you that you are given an n cross n binary image like binary matrix image binary means that it only consists of zeros and ones now you have to flip the image horizontally and then invert it the resulting image so you have to first flip the image horizontally it which means that horizontal means that you have to flip every row so if the initial row is 1 0 then after flipping it horizontally it will become 0 1 and then you have to invert it by inversion it means that if the ith number or the like i j number is 0 then you have to convert it to 1 and vice versa so the main crux to solve this problem is that to flip the image like to horizontally flip this image you have to flip every row now you can just flip every row in an of one occasion but what you can easily do here is you can use the reverse stl function nc plus which can easily just reverse the image so you have to just give the row so because the matrix actually i just take out a pen first the matrix consists of different n rows and m columns then you are given the eigeth row they are in the form of vector so what you can do here is just take ith vector and just like horizontally flip that particular row and then you have to do this for every row and after converting and like flipping every row you will go through every particular element i j element and then just invert that element and that's the logic for this problem so what you can see here is i just uh just give you a small demonstration if this is the matrix consists of different rows which are actually also vectors so if you talk about the ith row just take the ith row and reverse it using the reverse function just reverse that and then what you have is actually the reversed vector now you have the reverse vector for every row then iterate over from left to right uh on every cell on that particular matrix because you have to reverse every row then what you'll do you will invert everything so because everything is only zero and one okay either you can write a if condition for every element if it is a zero if the ith element ij element is zero then convert it to one or else if it is one convert it to zero you can also write that but instead what's the better way here is if you want to flip everything what you can do here is just do a zor with one so one zor zero is equal to as you can see if my x is equal to zero i'll do it as well with one it will become one and if i take one and draw it with one it will become zero what i mean by this is if my ith number is zero i saw it with one then it will become one and if the ith number is one i solve it with one itself it will become zero so i have to just take the i j number and solve it with one and it will actually flip its side so for flipping any bit try to use zor in bit manipulation it's very simple so that's what we're gonna do here is uh we'll first iterate over every row so there are n rows so we'll try to iterate over every row and what we'll do we'll reverse it so because every row is a vector what we'll do for the ith row from the begin to the end reverse it then after reversing out every row we lit it over every cell in that particular matrix and we'll flip it how to flip it we'll use zor so this uh this symbol is for zor so we'll take the ij element and zord it with one so in the end that's the answer i hope you understand the logic and the code part for this problem if you still have any doubts you can mention down i will see you next time until then keep coding and bye
Flipping an Image
binary-tree-pruning
Given an `n x n` binary matrix `image`, flip the image **horizontally**, then invert it, and return _the resulting image_. To flip an image horizontally means that each row of the image is reversed. * For example, flipping `[1,1,0]` horizontally results in `[0,1,1]`. To invert an image means that each `0` is replaced by `1`, and each `1` is replaced by `0`. * For example, inverting `[0,1,1]` results in `[1,0,0]`. **Example 1:** **Input:** image = \[\[1,1,0\],\[1,0,1\],\[0,0,0\]\] **Output:** \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Explanation:** First reverse each row: \[\[0,1,1\],\[1,0,1\],\[0,0,0\]\]. Then, invert the image: \[\[1,0,0\],\[0,1,0\],\[1,1,1\]\] **Example 2:** **Input:** image = \[\[1,1,0,0\],\[1,0,0,1\],\[0,1,1,1\],\[1,0,1,0\]\] **Output:** \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Explanation:** First reverse each row: \[\[0,0,1,1\],\[1,0,0,1\],\[1,1,1,0\],\[0,1,0,1\]\]. Then invert the image: \[\[1,1,0,0\],\[0,1,1,0\],\[0,0,0,1\],\[1,0,1,0\]\] **Constraints:** * `n == image.length` * `n == image[i].length` * `1 <= n <= 20` * `images[i][j]` is either `0` or `1`.
null
Tree,Depth-First Search,Binary Tree
Medium
null
837
hey what's up guys john here again so this time let's take a look at another lead called problem here number eight hundred and thirty seven new 21-game very it's a very good new 21-game very it's a very good new 21-game very it's a very good problem I like it so even though it's a medium problem but I think it's a little bit underrated for a medium I think it's more like a medium to a hard problem so let's take a look what does what was the description here so Alice starts with zero points and she can draw numbers while she has less than K point during each draw she gains an integer number of point randomly from the range 1 to W where W is an integer and each row is independent because after she chose any number from the from this number from this range basically she will pick the card back so the next time each times draw a probability is the same and Alice stops drawing numbers like when she gets K one more point and then she then ask you what's the probability that she has an or last point okay so at the beginning I think by reading this like description and you might get confused because we have okay we have one we have W and then this part I can't understand but in the end we are being asked what's the probabilities of annual or last right so we have three variable u parameters here input here how can we use them so let's take them one by one all right and if you guys must have already learned what's the probability is right and then if you guys already forgot let's take a look a quick look here let's define like a DP method right let's define a DP or like the function here right function of Phi here let's define the function I he calls to the probability of getting ice points all right so what's the problem to get to the ice point right let's say we have a for example right for example we have let's say that one two double is one to six they say we have one two three four five and six right that's assuming the table is in this range just to make it easy right and then let's say that I've I is equal to eight okay let's say I've eight right so what's the probability of getting eight so if you take a look right so how many ways we can get to eight right we can draw from either one to six right and then the last it's so they are like basically will be having six ways will have W ways to get two to eight right because the first one is to first ones to us from seven yes if the first one is seven right f7 because from f7 if we draw a one then we get f8 right and how about a not another one is F another one is f6 right from f6 if we draw a two then we also get f8 so same thing for f5 right and then until the last one what's the last one is f2 right because from f2 if we draw six then we also get f8 right basically we have like W ways to get to the to draw to have eight points in the end right and for each of the four each of the state here right the problem the probabilities of getting each number yourself because for this one we need to get one and this one will get to three and in here we get six right and the probabilities to get this each of these numbers are the same right and what was the probability it's a W minus one right so same here is w my minus 1 W minus 1 right sorry not sort of minor so what I'm saying it's a so 1 to the W right 1 divided by W because the each of the probability of getting each number its independent so and since we have W ways and the total probabilities of getting to the 8 it will be some right will be the sum of everything right sum of all the possible the probabilities and since each of them will be x by 1 divided by W we can simply summarize tablet out right so we can just do a to this right and we do a class in between all right so okay so basically this is our DP functions here right DP like state Trent transform a transformation function here basically I'm going to rewrite this a little bit right so dpi equals to what 1 divided by W fly DP I minus 1 plus d DP I miners - until DP I - W right I miners - until DP I - W right I miners - until DP I - W right basically this is our DP state transformation function right at least and basically this DP function can give us can tells us how can we calculate the current DPI's probability right from previous previously state right and okay so now let's say we have each points probability here how can we use it right to get our - can we use it right to get our - can we use it right to get our - probably the result we need right so it asks us so what's the probability is that she can has freaking gets has n or last point right so what does this mean it means that the final result for up for us is from pay to n right basically the because we have to get the probability of K above K first right because otherwise if the point is below K we'll keep drawing until we reach K right so the probabilities we need will be DP k plus 1 until what until DP n DP right some yeah all right so I'm sorry so the and this is a we're assuming right we're assuming this n is greater than K I think which is the case right yes the L is greater than K okay n is greater than K that's why we can just safely assume in this like this formula works because the question is asking us about the probabilities basically between K between points K and points in right because we need to get case first and then ask us the probability is starting from K to the N right so once we have the DP functions here in the end we just do a sum from d PK to DPN that's how we can solve this problem okay so is that being said right let's start coding I think with this thing there it's safe for us to come up with the actual code here right okay let's do it and so I'm gonna put the DP here at DP 0 so I'm gonna create like a DP n plus 1 right because we I do at the very most we need to a calculating probability right so anything that's greater than the end we don't care right because we don't care about that probabilities that's not what we need all right and then we have DP there and then we have we need a starting point right the zero right so what's the zero means basically to get zero points right what's the probability to catch the that to get to the zero point right that's one right because what means we don't need to try anything right it's a 100 percent probability to get zero okay then from DP you from DP 1 right now we can do I in range 1 to M plus 1 right so like I said the DPI equals to the previously case probabilities some sunrise together and multiplied by the 1 divided by W right so that's why we need like go back when you go back to W alright we need to go back to the dub 2w range right so we're gonna have like each J I'll do a K here for range for K in range w all right basically we need to go back to the to W 2 W position and but we have a few things we want to check here right first is the we want to make sure because here we're gonna give DPA like okay let me finish writing this thing dpi right class one divided by that view right and then times the DP I miners I minus K minus 1 right because here we'll need the when you start from the DPI my I minus one right and then my and minus K here okay but here I think we need to make sure right we need to make sure this I minus 1 minus K is not a negative right otherwise we'll have like an improper problem right basically we simply check if the if I is greater than K okay if I quit square root and K and then we do this right or we do this or let's say with smaller yeah let's just do this okay this is easier if this I imagine is smaller than 0 right and then we simply continue right how about that it's easier to understand right basic so if this is a 0 of course we don't need it right because the deep is DTV deep inactive doesn't exist right that's why we want to what we want to prevent right and another thing another one 4dp another one is the we're doing the end here right so since the end could be greater than K right but the problem here is that once the number reaches K we won't be drawing another number right for example here let's say the K is the case let's say the case it's 17 right the let's say the DPI the case is 17 right for example this one and n is 21 okay let's calculate the probability of n 21 okay so we have a DP half 21 here right and the window is W right okay the window is tablet that is 10 so if we just follow our pattern there right so f 21 we have like 10 ways to get to 21 right again right so the ten way it's gonna be from F up 20 right up 20 to have 19 right and F until half 11 right and then but and then you and then when we calculate 21 we're assuming okay all we need is to summarize everything and then in the end with x this one the first is probability 1 divided by w right but will this work so there's an issue here right remember can you get 22 21 can you get from 19 to 21 no right because you know in order to get from either 19 or 20 to 21 you need to draw a card right so here in the draw one here you need to draw two but the problem the description tells us once you reach K you cannot draw a card right basically the k17 right there's a like 17 here right basically once you reach 17 basically everything from here right there's no way you can get from f17 to up 20 to 21 because it does not allow you to draw one more another card so basically so that's why when we calculates the DPI here not only we need to track this at the range this is easier to understand but also we also need to check if our current if this I minus W right it is equal or greater than K then we also need to skip it because we can only get to 21 from this range and that's why this is where this is how we calculate the probabilities of AB 21 make sense okay cool so that's to track the out of range and second why's this right if we have a K here so maybe I'll use a J here just to distinguish that K yeah I'll use J Jay okay right and if right so what is greater or equal than K all right then we also continue to things right otherwise we just summarized them together okay and then in the end we simply return we return what we return the sum of the DP some right DP from k 2m plus 1 right because this is the exclusive in the Python I think that's pretty much it is let's try to run it yeah okay this one passed great let's try to run it again ok so it seems like this time limit exceeded so but at least it house tells us right this logic somehow it works right so why it's white style tre right because the range of K and W is this one 10000 right and here actually we're getting like the time let's take a look at the time complexity here basically the time complexity is the and the first four loops and right and then the second one is its W right but the W could also be a 10,000 right basically could also be a 10,000 right basically could also be a 10,000 right basically it's a kind of via n Square and times n kind of it's a n square time complexity which that's why I timed out so and how can we improve this thing right and if you take a look at the basically you know we have a seems like a sliding window right because if you just take a look so we have a X all right and then we have a DPI here we have a I hear right so we have I here and in order to get I we need to guarantee at the DP of I minus 1 right and then to TP I minus W right so that's calculate I write then once we have I we move to I plus 1 right so to calculate I plus 1 same thing right same thing we need the probabilities from dpi to DP I minus W plus 1 right plus 1/2 to dpi minus W plus 1 right plus 1/2 to dpi minus W plus 1 right plus 1/2 to dpi right it's also a slight W size of window right so now it's pretty obvious that this is a sliding window problem right so which means every time when we reach a new I here we don't have to always go back to the W times to get everything we can just maintain you can just be maintaining a rolling sound right that will make this inner loop from Oh n 201 because every time we just need to do to insert one from the beginning and remove one from the tail it's a constant time right so that's why we can move this chain this improve this N squared - Owen by this improve this N squared - Owen by this improve this N squared - Owen by using sliding window ok so let's see how come you how we can do that right so that's why we're gonna have a running sum okay running sum equals two at the beginning its zero right and we are okay at the beginning it's zero and let's see ah so if at the beginning in zero the first sum will be basically here we need to start from zero instead of one because we also need to conclude this zero to our running sound all right do I need to do that let me see let me think oh no we don't sorry so this running sum is the okay so this is like a little bit a different variant of variance of the running sum so the running sum is the most of the time when we talk about when we were talking about running some it's a the running sum is the running sum and including the current value right for example if there's a one two three four so let's say if I'm talking about running sum of I here right it means that from including the current one right what's the running sum so it's gonna be one three six ten right so the running sum of current I means the some including the current number but in this case is different right because the running sum we're trying to maintain is the one is the sum before the current I right because we need that running sum to give us the probability that we need to calculate the current probability right so that's why you know from to move to the current DP right let's say we move from DPI move from dpi - 1 - d/p I right and now we are at dpi - 1 - d/p I right and now we are at dpi - 1 - d/p I right and now we are at dpi so we and which adamant we need to add to the current running sum is the DPI minus 1 right because that's the new a new head of our running sum right and that's why we need to I was running some class plus T at the DP I minus 1 right so that's our running sum and when we need to remove it right when we need to remove one from the tail right basically if the eye is I minus 1 miners hey when we can remove you can remove if the eye from I minus 1 I minus K okay yeah if I minus 1 minus or minus K it's not it's greater than 0 it's still equal or greater than 0 then we can remove because remember so when we start removing right we are removing the last one right from that from the sliding window and the size of sliding window is W right that's we only need to remove it when we when the sliding window has a I mean has grown to at least W right so we remove it from the DP I minus 1 minus W okay and so again here right the same thing right so before not only we need to have a restriction of the after running some want me to remove it and same thing here right we have to subtract if I is smaller than 10k right like what we discussed before so if it's eco greater than K we shouldn't include that probability okay so that's this 2 and all right so since we have maintained the running sum right and then the DPI basically will be a 1 divided by W and x times running sound right because we already summarized everything here then in the end we still return the this DP range oh let's try to run it zero white whites at zero here come here you know what I will print DP I here see what's going on why is zero what I'll zero even DP right W oh I see because I'm using an integer not a double site or float size that's why when we do a calculation here it will be converted to like to the integer which is the which is zero so because it's treating everything as an integer because a1 divided integer divided by integer times integers implies Dominator will assuming you are you need an integer and anything smaller than ten zero well smaller than one will be treated as a zero so I think we just need to do a one point zero here and then once this Python compiler sees okay the running sum is a so it's a double it's a floats type and then it will give us that the flow type as well so it's no maybe Oh here I think I minus one here I think I made a mistake here I minus one because we want to add I minus one here not I mmm works how about this one here if I do this was also worked ok so my mistake so sorry I thought this one would like we'll make it like 0 to 1 to 0 but seems like Python even though it's a there are all integers maybe I can't confuse with Java or c-sharp seems confuse with Java or c-sharp seems confuse with Java or c-sharp seems like in pythons as long as you have this like true deviation parameters operators here in the world it will automatically converts to a from integer to float yes so in Python it doesn't really matter if you do a 1 or 1.0 it really matter if you do a 1 or 1.0 it really matter if you do a 1 or 1.0 it doesn't really matter mmm yeah ok cool so yeah anyway so it passed and yeah to just do a real recap okay so this video is the longest one I have ever recorded but it's such a interesting problem that's why I want to spend a little more time to discuss this so basically I feel a few concept here right the first is how can we calculate the current the probability to get to the current point right we use the previously probabilities previously points probabilities times this one divided by W right because each of them is independent and then once we have these points probabilities we just need to get the probabilities summarized probabilities from K to n right because that's what we need we have to get capers and then up to it and the third one is to calculate this running some of the previously tableau probabilities before at the beginning we were using like a naive for loop right to loop through everything a W length for each of the I but that will that's basically time limits exceeded because it's a n square time complexity and we are wasting a lot of time looping through the same element and then we find out it's actually it's a running sound it's a sliding window problem all we need to do is we just need to maintain the sum of this K of this case sliding-window right and this case sliding-window right and this case sliding-window right and we just need to every time when we have a sliding window they think that it tells us what's the total probabilities right the probability except for the one divided by W what's the total probabilities to get the current state I right and then we can just simply use that one to time two multiplied by the 1 divided by W that can give us the current dpi and a few things here and first we have to check the DPI so if you start the first integer at here's two to remove right so to remove we want to make sure since we're going backwards right we want to make sure this induction is not out of bound right this is pretty easy to understand and this is a little bit tricky one to add 2 to add more probabilities we have to check if this the ones we are going to add here is less than K because if it reaches K which it means that will not draw any card basically you cannot from this dpi to our DP you cannot go from this dpi minus one to our dpi here right because there's no way you can draw a card once you reach K here so okay cool I think that's pretty much I want to talk about for this problem yeah it's a very interesting problem yeah I like it so it combines the probabilities plus the dynamic programming and the sliding window see three things combined together then you can solve this problem yeah I hope you guys enjoy watching the videos thank you so much and stay tuned hope you see you guys soon bye
New 21 Game
most-common-word
Alice plays the following game, loosely based on the card game **"21 "**. Alice starts with `0` points and draws numbers while she has less than `k` points. During each draw, she gains an integer number of points randomly from the range `[1, maxPts]`, where `maxPts` is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets `k` **or more points**. Return the probability that Alice has `n` or fewer points. Answers within `10-5` of the actual answer are considered accepted. **Example 1:** **Input:** n = 10, k = 1, maxPts = 10 **Output:** 1.00000 **Explanation:** Alice gets a single card, then stops. **Example 2:** **Input:** n = 6, k = 1, maxPts = 10 **Output:** 0.60000 **Explanation:** Alice gets a single card, then stops. In 6 out of 10 possibilities, she is at or below 6 points. **Example 3:** **Input:** n = 21, k = 17, maxPts = 10 **Output:** 0.73278 **Constraints:** * `0 <= k <= n <= 104` * `1 <= maxPts <= 104`
null
Hash Table,String,Counting
Easy
null
213
hello everyone welcome to clash encoder so in this video we will see the question house robot 2 which is in continuation of the question on which i made the video for the house robber one so it is 213 question and it is a medium level question and will be more difficult than the household one but it is easy if you know and you have solved household one so i would recommend you to before solving this video or watching this video and solving this question you should watch the house over one video so you will get a like idea of how to solve this so let's see the problem statement you are a professional robber planning to rob houses along a street each house has a certain amount of money stashed all houses at this place are arranged in circle so here the difference is there uh with the house rubber one in house number one we it is it for the same condition all the houses have some money and we have to drop them and make the maximum profit but now in this they are arranged in circular manner in the previous one it was not in circular manner so that means the first house is the neighbor of the last one meanwhile adjacent houses have the security system connected and it will automatically contact the police if two adjacent houses were broken into a same night so that means that we cannot drop the adjacent houses so it is similar to the problem number one or the householder one but in this you cannot loot the first and the last houses together because they are arranged in a circular manner so that means the first one is connected to the last one so if you look first one the uh this alert will uh go on so the police will come so that's why you cannot root the first and the last index or the last house simultaneously you have to take care of that this is the added constraint in this problem as the rather than the first one so let's see given a list of non-negative let's see given a list of non-negative let's see given a list of non-negative integers numbers representing the amount of money of each house return the max amount of money you can drop tonight without alerting the police so this is uh if you have solved the housing one so you will understand how to solve this actually uh how you can approach this so if you see in this example we are given two three and two so that means we cannot draw one and last index together so either we drop this two we will end up having two profit either we drop this two or either we drop this three so three will end up giving the maximum profit rather than this uh rather than dropping this to the starting index two or the last index two so that means the maximum profit will be three so i will if you can see if the number of house is zero or even one house then you will simply turn the profit of the one house if the number is zero you can simply turn the empty array or empty like uh empty value otherwise if you have two values that means you can return max of both you cannot go together both together because they are adjacent so that's why you will if you uh for example if you don't have this two here so you have only two and three so out of both you will return the maximum value because you can root only one out of both so that's why so let's see how we can approach this question if you have solved the previous question house number one you would be knowing the recursion approach actually if you see in uh at a single point actually if you see in this question the one and the second index is connected so you cannot root both of them if in this example it is the second example from here you can see so in this example not second actually so i don't know so yeah in this example if you see we're given one two three four two if you try to gain the maximum profit so if you like run the uh check from here let's see so if you loot this one so you cannot move this two if you lose one then you can loot this three so uh the total will be actually four but you cannot loot this two because they are connected actually so that's why you will end up having profit of one and three so if you uh see you can add this to so it will become six but that is not where our profit is coming actually our profit is coming from this part that is if we loop this 2 actually and this 4 if we load this 2 and this 4 then only if we will be getting a profit of 6. so that's me that means that the maximum profit is coming from these two in the indices if you try to loot this three and this two if you uh if you don't look this one so that's that means you can skip this two also you can eat loot if you look this two then that means you will have to skip one so if you try to add this three plus two it will be five so it would be still less than the maximum profit that we are getting through this two and four that will be six so that is the basic problem that we are given so if you see now we have a constraint we cannot group them together in a recursive approach i would recommend you to watch the first video also i will provide the link in the description and also in the info button so let's see so at every point you have a choice to make actually every point you have two choices to make either you include this particular house or rob this particular house or you don't prop this house if you drop this house then you cannot drop the next house so if you drop this house for example if you have dropped this house so it will be plus if you have not dropped so it will minus one so if you drop this house our i is at this index so the next i will be or starting index of array will not be the i plus one index because we have blocked the first house so we cannot drop the second or the adjacent house so it will be passed as i plus two which will be three so here our i will be passed as i plus two so if you see now if we include this we will uh actually have to uh now if we have given we have been given this array uh next we will get three four and two out of again they will be recursively calling if we load this three if we cannot move this four and now we cannot do this two also so we will see how we can do it then efficient approach actually but in this recursive approach i hope you got the point actually how if we have two opera choices to make either we loot the house or we don't put the house if we don't drop this house so that mean that means we will not drop any house so we will not have any profit here ever profit was also coming so actually out of both condition if we rob the house and if we don't drop the house we will take the maximum of both actually if we drop the house okay not robbed and uh and rob so it will be a maximum of both that we will be returning in our recursive function so it is a recursive approach so it will take a lot of time and we will end up like calculating the same like value for same uh sub problem again and again so rather than doing that we can use a memorization or we can optimally use a dp so let's see how we can do that so i hope you got the recursive approach and you do remember that at every point we have two choices to make either we include the item or we don't include the item so let's see this problem so actually uh for the sake for this example sake so you should forget that we have any condition for the circular part so i will explain you how we can solve the uh house robber one actually how we solved the house robber one it will be actually summary of that so if you see we make our dp array for how solving the house order fund we used to make our dprs uh for example this is our dp array so we will initialize the first index as this same one so first index will be same because you don't have any choice you i loop this so the maximum profit that you will be getting is one only if you load this if you don't do this so you will get the maximum profit by rooting this so at second point at the second index i told you if there are only two values that are given one and two for example two houses so out of both you will you cannot drop together so you will drop the maximum of both which will be two so you will drop two so maximum will be two out of this one or and two now at this point when you come at this point you cannot include the profit of this so you will include the profit of dp of i minus 2 if you see you can include the profit of only tp of i minus 2 which will be 1 and the current value that is 3 so 1 plus 3 will be 4 so 4 is greater than this 2 you will have to choose the from the maximum of actually let me write it maximum of dp of i minus 2 will be this in this index actually this one if we are feeling for this something sorry if we are filling for this index so it will dp of i minus 2 will be this point and dp of i minus 2 that means we are not uh including the previous house we are including the previous to previous house so we will include the current house which is the profit for that will be array of i and out of that max this is the one value and other value would be simply the previous value that will be dp of i minus one this is what we were doing in the uh first solution which was house over one which was for house over one so at this point if you see one plus four will be one plus three will be four so it will be greater than this two so we will end up having four value now at this point we will choose the max of this four or four plus two will be six so it will be greater than this four so we will simply choose six here and if uh where is we are like thinking it is a house over one problem so we don't have any constraint for the circular part so if you see at this point two so two plus two or two plus four will be six so it will be maximum uh actually six and six microsoft both will be six fully so it will be coming actually but now as we are given that we only have uh the if we can only do the first house or the last house but don't we cannot do both together so for doing that for example you can think of this as connected so for doing that we will simply use the algorithm that i told you for the first problem that we use for this problem we can simply do that by making two errors out of this array because if you see if we include this one so we cannot include this two so we can simply remove it from the array so we will like make a array dp1 you can say dp1 array it which will include the values as let me write it so we will include values as one okay sorry one two three and four so we will simply take this last index out of this array if we simply take this out so now we can run the function that i have told you that the algorithm 1 that we used for the household 1 and on this array and we will end up having maximum profit that we can get so it will be 6 only if you see two plus four will be six and one plus uh three will be four so six will be greater so it will be end up having a six profit so if we uh and the four second array what we will do is for the secondary we will not include the first element and we will include the last element for doing that we can simply turn i plus one for index so it will be two three okay two three and four and two so now for this also we will calculate the maximum profit so if you see in this also our two and four is coming so it will be maximum will be six and here if we check 3 plus 2 it will be 5 so again 6 is greater so our output will be max of the both rs profit that we are getting so uh let's see i have written the pseudocode also you can see so this is a pseudocode actually this code is similar to the householder one or actually same code i have copied from the house over one and this is what we have to do actually if you see we are given this array okay we are given this array so now we cannot load one and two together they are connected okay they are connected we cannot look together so what we will do is we will simply make two arrays out of this one array so we will make dp of one so tp of one you can see i have written dp of one array and from this first array in first array we will not include the last item actually we will not include the last item so actually this is the super board i will show you the code in python and this time and in next video i will show the code in c plus for another problem so you can see one two so we will have one comma oh sorry one comma two comma three comma four so we will get the dp of one as this we will include the first element and we will not include the second element as they are circularly connected or connected in circular manners we cannot look together so that's why we will create this array next array will be dp of 2 which will be equal to we will not include the first element in this so it will have 2 3 4 and 2. now you can see we have got our dprs now as we have made the function for the house over 1 we will simply use that function and pass the dp instead of passing the total the original array will pass this tp1 array and dp2 array and we will get the maximum profit out of four this is what we were doing actually if you remember this is what i told you in this example also this is uh you can see for we will initialize the first index will be same so in this i will not use um or make a different dp array if i'm given this array so let me actually erase this thing so uh let me exchange this also so in this area if you see in this array we will be passing d1 first we will passing d1 so we pass even so we will get we will be getting this so i will instead of creating dpr2 i will use the original array that is dp this i will uh the password that we have i will use this only to make or get the result so let's see so first our first index is initialized as it is because we are using the original array only so now for the second index it will be the maximum of the first and second as i told you so it will be 20 maximum will be out of one and two will be too late so we'll have only you can see we are initializing this array so now we will start from the second index and for starting from the second index we will check if we add this one and three so this is actually our original array also and dpi also we will save our space fuse this technique so if we add this one and three so profit would be five if you see so at this point i is over at i is at this point so it will be dp of i this dp of i which is three will be uh we will set as value as maximum of dp of i minus one which will be two so maximum of it is two so okay i'll write here two and another value is the dp of i minus two which will be one plus three that is the current value that we are having at this index so we can root one and two because they are not adjacent and we are leaving two if we if for example if we had like five here so five will be greater than this one plus three that will be four so that way that means we don't include this one and if we simply do this two we can add that so now at this point our value will become as okay four so we will update it as four so now again coming to the next index so i will come here so now our is here so now again we will check four so let me raise this mess so three yeah so we erase a so our i is at this point so we'll check four plus two which will it will be six so either six is greater than three so yeah four we are having it so four so yes six is greater than four so that means at this point will update is to six so at the last we will have the maximum profit that we can get at the ending index as we are using a dpr so it will be six so we will simply return six here so for the second error also we'll pass the same function so it will be 2 plus 4 or 3 plus 2 so it will be 6 only so maximum will be 6 and out of both at the end we will have the value dp of okay so you can see we have calculated the max profit that we can get for dp of 1 and dp dpf2 and at the end we will return the max of both actually if you see will return the max of profit 1 and profit 2. profit 1 will be for the dpi 1 and profit will be for the dpr2 so we will end up solving our problem that is house over one with using the circular condition also the circular constraint also we have solvable problems so let's see the code also so i have shown the code in the python and also for the time complexity actually if you see we are only traversing this end time so actually it will do n so you can say it is and it will be approximately an time complexity and the space will be also and because we are too often or and you can say because we are using two dprs because you can see we are using the space so that will end up having uh some getting taking the space so let's see the codes i've uh write it in the code in python this thing so let's see so in this you can see first of all we will check the for the base conditions so i've like checked uh taken the length of the this array into n now we will check if the array is empty so we can simply run the zero because if we don't have any house we will end up having zero profit if we have one house we can simply return that house profit because it has no adjacent house so we can simply root it either if we have two houses so this is the base condition that we are initializing here you can see we are initializing this condition here if we have two houses we can move one over both of one of them but not together both so we will root the maximum of four so it will be numbers of zero and numbers of one so you can see i have actually told you how to do that so this will be our main function that would be calculating the max profit but let's see this will be the first step so if you see this uh if you see this first of all we are creating the tp excluding the last element so as i told you dp of 1 will be excluding the last element which was here the last element was actually if you see in this example last element will be one so we will be uh creating this one two three array into this saving this into dp of excluding the last element so you can see numbers of this is python syntax okay so then we will be calculating the profit for this element using this function which i have taught you so it will be taking the length of the dp array then we will initialize the first element uh sorry the first index so it will be max of the zeroth index and the first index then we will run the loop from second index till the nth value then we will check if the previous value is greater or the current value plus the previous value is greater so we will keep up updating the profit accordingly and then we will return the ending index so in python you can simply return the dp of a minus one you will be knowing that so you can you will end up written in the six here so that will be the maximum profit for this uh dp array if we include the first and exclude the last element for the second array you will simply include the exclude this one and include this two three when but you will pass that to the function again you can see we are excluding the zeroth index we are passing from one to n so then we will get the profit for the same and we will return the maximum out of both profit as i told you we are returning the maximum of the both for if for example if we were given like you can see if we were given like here uh a three we have given three so that at that time we will have value as not three actually four then we will have value as three plus four that will be seven which will be greater than six so in the first function we will be returning six in the second function our last value will be seven so we will return the profit of seven so our answer will change we will it will be getting the seventh uh value answer will be seven so let's see and uh like submit this code so i hope you like this video and do find it like did find it helpful so you can see it run faster than 99.26 so you can see it run faster than 99.26 so you can see it run faster than 99.26 percent of solutions and plus memory than 99.97 percent of plus memory than 99.97 percent of plus memory than 99.97 percent of solution and you can see this code is also in python so it would be running slower than sequesters so you can simply convert it to c plus if you know c so actually i will share this code in description uh in the github link so let's hope so you find it helpful thank you for watching guys do like this video and subscribe for watching thank you
House Robber II
house-robber-ii
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are **arranged in a circle.** That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and **it will automatically contact the police if two adjacent houses were broken into on the same night**. Given an integer array `nums` representing the amount of money of each house, return _the maximum amount of money you can rob tonight **without alerting the police**_. **Example 1:** **Input:** nums = \[2,3,2\] **Output:** 3 **Explanation:** You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. **Example 2:** **Input:** nums = \[1,2,3,1\] **Output:** 4 **Explanation:** Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 3 **Constraints:** * `1 <= nums.length <= 100` * `0 <= nums[i] <= 1000`
Since House[1] and House[n] are adjacent, they cannot be robbed together. Therefore, the problem becomes to rob either House[1]-House[n-1] or House[2]-House[n], depending on which choice offers more money. Now the problem has degenerated to the House Robber, which is already been solved.
Array,Dynamic Programming
Medium
198,256,276,337,600,656
81
Hello friends today I am going to solve liquid problem number 81 search in rotated sorted array 2. in this problem we are given an integer array numps sorted in non-decreasing order and it sorted in non-decreasing order and it sorted in non-decreasing order and it not necessarily with distinct values okay so it may consist of some duplicates and we are also said that nums is rotated at an unknown pivot index all right and we are also given an integer Target and we should return true if Target is in nums else we are going to return false and we must decrease the overalls overall operation steps as much as possible all right now this problem is similar to the problem that I solved last time which is search in rotated sorted array problem number 33 so in this video I have clarified most of the concepts that we'll be using for solving this problem too so since we are going to solve it using binary search so please go through this problem this video so that you understand how we are approaching the binary search operation for this problem as well and in this video I'm only going to take into account the duplicate factor in our array and how are we going to tackle those duplicate values so how are we going to solve these given that we have duplicates in our nums array so let's begin I have taken an example over here so in this example we have a nums array and we have multiple duplicate values of ones right and to find our nums I mean to find our pivot index so what we should do is um we start from the first and we have one and then what we do is we move next and the values decrease right so that is where we know the uh we found our pivot so from 0 to the end it's increasing it's in ascending order so basically our array here is divided into one half and the next sorted half right and we are given our Target as zero all right so given the target zero now we use binary search and we found our middle value equals to 1. now the middle value is equals to one so which half of this nums array do we move do research is it this half or is it this half so how do we find that if this was not a duplicate I mean if there are no duplicate let's suppose if this was a value too and let's suppose all of these values were distinct then we would know that by comparing the first element and last element let's suppose okay this was three let's suppose this is equals to 2 so then in that case let's suppose this is also some other value other than one then in that case we would compare a middle value with our first element right and since in case if it was sorted first element should be less than the middle value but this is greater right so in that case this is not assorted uh half so since this is not the sorted half um so what we do is we take this half and then we check our Target if our Target lies in this half or not right so based on that we perform our evaluation but now since we are given this over here right we are given duplicates so how are we going to solve if we compare our middle value with our start value here both of them are equal so now how we're going to make the decision to which one of the halves to choose to search for our Target right so for that what do we do is we need to move our start pointer since we know that middle value is equals to one so that would mean that there are some elements already after this and we will actually increase in this case increase our start pointer from here so now our start pointer has moved to this index the next index okay so now our start is pointing to zero and here now we compare our middle value with the start value and since now the middle value is greater than start value we know that this is a sorted half right and this is another sorted half okay so we have two sorted halves over here now we need to find where our Target lies so since this is already in assorted array so we check if our Target lies within this range or not since this range is where our Target lies so our search space is now this right in this range now in this range our start is this and we move our middle also to uh I mean our right pointer to this was our middle valyrite to meet minus one so our start and end both are pointing to the same Target same value and our middle value is also the same so here we found our Target so in this way we found our Target and we returned true so basically that is what we are going to do if we have a middle value which is equals to the start element then we increment our start value until we found the start value which is not equals to middle value okay so that's the concept behind this problem with duplicate elements so now let's solve it so let N equals nums the length of our area now we need our start okay so I am going to write down start and then end equals to n minus 1 which is the last element and then we need our Mid Valley too right so in the while loop while left is less than equals to I mean sorry Start is less than equals to end we need to find our main so made equals um matte dot floor value of start plus and divide by two okay now we have made we need to check if the middle value nums made is equals to our Target that would mean that we found our Target and we returned true if not now what do we need to check before we check the middle value with the left side value we check if both of them are equal V increment our start right so our if nums at Mid is equals to the start element that is when we increment our start value by 1 and then continue with the next iteration else if nums meet so if the middle value is now greater than the start that would mean that this is a sorted range so in that sorted range now we find search if Target is greater than the start and our Target is less than meat okay we are going to check with equals to sign to if that is the case that would mean our Target lies within this range between start and mid so we need to shift our end pointer to meet -1 else -1 else -1 else start equals mid plus one all right else in case it doesn't satisfy any of these two conditions then our Target lies in the second half of which is also sorted array so in that second half we need to now check Target is less than a Target is greater than meat okay nums made and Target is less than equals to nums at end okay so why are we checking only um I mean greater than value for meat and we're also comparing equals to value with the end why because we don't need to compare if Target is equals to meet because we are already checking it over here so if Target was equals to Mid we would have returned true but since it is not so that is why we are doing the rest of the operations over here and while we are comparing it could be that start is equals to Target right we have not compared start with Target so if it were equal then of course we should check this portion of the first half of our search space right and so on for this one too so if that is the case then we are going to search the second half here and for that we shift our start to meet plus one else we shift our end to mean minus one and that's it finally we return false if in case we are not able to find our Target over here so now let's try to run our code and check if it works awesome it worked over here I have added few test cases the one that I explained it over here too and the other one is this one too so now let's try to submit this great so this problem we are able to solve it using binary search and just this uh addition of these few codes in our previous solution for this problem right so that's it all about this problem let me know in the comments down below what do you think about it thank you so much
Search in Rotated Sorted Array II
search-in-rotated-sorted-array-ii
There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values). Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`. Given the array `nums` **after** the rotation and an integer `target`, return `true` _if_ `target` _is in_ `nums`_, or_ `false` _if it is not in_ `nums`_._ You must decrease the overall operation steps as much as possible. **Example 1:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 0 **Output:** true **Example 2:** **Input:** nums = \[2,5,6,0,0,1,2\], target = 3 **Output:** false **Constraints:** * `1 <= nums.length <= 5000` * `-104 <= nums[i] <= 104` * `nums` is guaranteed to be rotated at some pivot. * `-104 <= target <= 104` **Follow up:** This problem is similar to Search in Rotated Sorted Array, but `nums` may contain **duplicates**. Would this affect the runtime complexity? How and why?
null
Array,Binary Search
Medium
33
1,037
hey what's up guys so that's solving stupid problem this is one zero three seven that is uh boom boomerang a woman i don't know argument points uh array of points right it's um interesting is that there are only three points okay and uh if there are boomerang bearings a set of three points there are the things and they're not in the straight line okay so basically uh this is stupid right so that's three line three points and the only thing you need to check that they are not in the same line okay and uh these are very uh simple okay so uh what is the case if there are in three lines uh there are a code in here also uh let's say this is delta x one this is uh y one and uh let's say uh this is the x2 and this is still tau y2 okay if there are in the same line then you can easily prove that their slope is the same right and if they are slowly are different they must they cannot be the same line right so all you need to check is that the delta y one delta x two is now the same as delta x two okay so this is the criteria okay now you can check okay so we got p1 and p2 p3 as points and then you just check delta x do you have i deal with our uh properties is still x one and the derivative y two there are your checklist okay that's it and uh probably you need to worry that they're all distinct right but i think there are always these things okay the problem is that if some of them are the same right if some of them are the same let's say these two are the same right then this equation will always be true right because both are zeros if these two are the same then this equation must be true right and if these two are same and this equation also so you only need one equations and uh you can if these equations you can prove that if there are or they are not these things then this equation must hold so you only need one equation to help you solve this stupid question okay and this is all one time see you guys next videos
Valid Boomerang
minimum-number-of-k-consecutive-bit-flips
Given an array `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return `true` _if these points are a **boomerang**_. A **boomerang** is a set of three points that are **all distinct** and **not in a straight line**. **Example 1:** **Input:** points = \[\[1,1\],\[2,3\],\[3,2\]\] **Output:** true **Example 2:** **Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\] **Output:** false **Constraints:** * `points.length == 3` * `points[i].length == 2` * `0 <= xi, yi <= 100`
null
Array,Bit Manipulation,Sliding Window,Prefix Sum
Hard
319,2286
239
So hello everyone of de and today's question is 239 sliding window maximum so understand this question we have an error given which will move in this we have to return max slide window so max sliding Window, what is the max sliding window? Max sliding window is the window in which what we are going to do is to store the maximum of the sliding window which is our maximum, so here as an example. Let us also understand that in the example given here, 13 - 1 - 3 5 3 6 example given here, 13 - 1 - 3 5 3 6 example given here, 13 - 1 - 3 5 3 6 right and the size of the sliding window is given that this is equal to three right, so we make the sliding window like this which is an error here and there are some elements here. If the size of the sliding window is 3, then we first cancel this sliding video here and after moving it will go here and we will cancel these three elements, so that means there are three elements in the sliding. Neither that which will keep on moving forward, only that has to be considered. Yes, like here we are seeing sliding window cage equal to three, then when the flood is happening further ahead, then what is being considered here first three. Element What is the first three elements 1 3 - 1 So what is the What is the first three elements 1 3 - 1 So what is the What is the first three elements 1 3 - 1 So what is the maximum among these three? Three then one What is the maximum among three and minus one Three So here three A is by the way 3 - 1 - 3 So the maximum among these way 3 - 1 - 3 So the maximum among these way 3 - 1 - 3 So the maximum among these What is the maximum? Three then three is here. A is here. Minus one is minus three five. What is the maximum among these three. So five is A. So five is kept here. -3 53 five is A. So five is kept here. -3 53 five is A. So five is kept here. -3 53 What is the maximum among these three. If there is a maximum of five in these three then Here 5 is 367 27 and that is stored in the output. We have understood that element one and its sliding window are main, so there can be only one sliding window here, one and it will be maximum one only, so one is stored, it is simple. Similarly, let's understand this with an example and let's take an example here so I'm making an error here five minus one three two six okay so this is it and I'm indexing it 012 34 right And what we have to do is we have given it a sliding window 3, it means we have to remove the window, so what we will do is first consider what is this sliding window and in this we are going to start with the maximum of these three is five, so we will give it five in this. We will store five, it is done, first the maximum of the sliding window has been reached, what will we do after this, if we send this sliding window further, then this one will be sent and the three one will go right, then slide further and its size is also three. So the maximum of these is minus one three and you, what is the maximum of these, then the maximum is our 3 like -13 and 2, our 3 like -13 and 2, our 3 like -13 and 2, what is the maximum of these, three, then we will put three in the output, simple way again the sliding window. We will take further and here what is three two six then the maximum in 326 three two and what is the maximum in six then here we will put six and we will return this output then if we talk about the approach then we will first take the brute force approach. If we talk about bread force approach, then what is coming in our mind in good force is that here we are taking an error, right one is taking an era, simple yes and we take the above example 5 - 1 5 - 1 5 - 1 5 - 1 3 2 6 And let's put the file here 5 - 1 3 2 6 And let's put the file here 5 - 1 3 2 6 And let's put the file here right yes and simple what we are doing is that we are taking a sliding if this cake is three now then we are taking the sliding window of three sizes yes and what we are doing is we are moving it. We are going ahead and its index is zero one to three window, it has been till three, it has been till here, again it will move from here to here, why is there 3 here, what is happening in the last one, it is starting at index 3, sliding is happening here. Lo after that, but the industries sliding window is not going to start, so we will put a fruit loop which will come from zero to sorry zero to lake and mines because what is the size of N here, what is six mines three and put a loop. Which will be Jai and that will go and what we have to do inside this is that we have to do inside this that we have to iterate which of these three, which is Max, which is Na's i to lek i plus i Till the plus, whatever is the maximum in it, we will put in the output error, we will put in the output area, we will put the rate and in the last we will return the output, we are going to return in the last, output This is our time complexity, what will come of it? This is going on n times and this is going on k times so here it will come k if I say exactly then n - k times then it will say exactly then n - k times then it will say exactly then n - k times then it will come k * n - k come k * n - k come k * n - k if its which is not so good quarter is right then it is more efficient Can do if interview and asking questions then this one is absolutely dog ​​then interview this one is absolutely dog ​​then interview this one is absolutely dog ​​then interview If approach you ask interview, what are we going to do, we are going to do it right with the technique of sliding window, so we find option here option. Example 326 What we are doing is we understand how we can solve this so this is index zero one two three four how can this be further optimized so we can use the sliding window which is 3 so we are in the first starting three. Let's see, what is the maximum, if I modify it a little more, which will be easy to explain to you, this is just a clarifier that the 5 biggest rights among these three, when we go ahead and search further, we can say this. Instead of finding the maximum within these three, we would rather say find the greatest among 5 and 2 and put the output in it because as per the earlier output we have already come to know that the maximum here is the maximum within these three. We came to know that it is five, so it meant that the answer of three is minimum, it is impossible to get the answer of three late, so we will check this also with 5 and 2 and if the answer of this is five, then we will flood further, take out five here. Gone 5 was taken out so we want that five is the smaller element, we need it now so what is here that came here came five, give 5 greater give equal tu three greater give equal tu right yes Meaning, only five has gone, if in the next slide next sliding window, if five has gone, then what is the maximum among these, three, then we have to access 3, so here again three, we have to compare with six is ​​bigger. So we six is ​​bigger. So we six is ​​bigger. So we store sex in it and we have to return it. We have to take such a data structure which will be storing us in decreasing order and what we have to do is we can remove from backward also, remove from front end also. You can do record success, you can do this from the front also, we need data like this because what we have to do is we have to keep it in decreasing order and when it increases from the sliding window, the largest element is the largest element if it is removed from the sliding window. So we have to pop that also yes and what if else after popping that we want that yes after that we also have to access the second largest so how for this one we have to do that DC Inside there is a DC inside the double side so DC we have to do it DC if we want to do it then there is a DC inside the double side K Yes so as you know why if you know then what can we do in the K that we insert one side and one side Let's remove the right butt from here, different side butt, what can we do here, we can insert from both the sides, we can remove from both the sides, so what can we do, if why is this, then we can insert here We can insert it like this, we can pop it from this side also, we can pop it from this side, how to do it with DC, if we have to do it with DC, then we can do it Let's take the same example again - 1 5 2 3 6 And here we will first take the meaning of these three here zero one two three four right and what we will do is take one DC, this is the net of the di. And what are we going to do, first from the starting till we are going to access, so from the starting, we accessed zero, minus one, we have to remove it, so we will do it, and what we will do is insert 5, what will you do after that? You will also see that you are smaller than five, is it satisfying in decreasing order, is it satisfying, what if I add 2 insults and then last on the back side, is it satisfying in decreasing order, yes basically? Why won't you do it, then we will give you the net. Now when the file of cake means hi-tech, we go to I = 3 file of cake means hi-tech, we go to I = 3 file of cake means hi-tech, we go to I = 3 A, which is greater than the value of cake, then from there we start counting, start outputting in the output, start giving output. If we do this then we will give the output which will be the first element of which DC will be the largest among them, so what we are going to do in the output is that the first element of all the DC will be the front element, we will push it, so here in the output five will come. If there is right then what is there in three, if there is three, then here three will come, then decreasing order will not satisfy because you are smaller than three, so what will we have to do with this, we will have to remove you and instead of this, right understood, it is satisfying. And here A went our sliding window S is right so in this again what we will do is that here again in the DC which is the most starting element we will push the one here so we push here right and At the same time, here Mines One was already removed, hence it was definitely not necessary to come to DC, that is, to consider, so this thing did not apply here, but yes, if Mines One was not removed, then what? So how to do that, what are we going to do, we are not going to store mine one here, for now, so I am removing it here like I am doing, okay, after that, what are we going to do, that one sliding window next. The one who is going to move is the sliding window. If you move forward then six comes here. If we put six here then what should we do because it will not be in decreasing order. It is bigger than 63. Ca n't be kept. Obviously, it is in decreasing order. Yes, then increasing. It will be done if we keep six after 5 then we will remove it also right and after that six will come right so we are going to insert six and rate but for this how this thing has become eligible but So if I notice here that if I go to mines one here it doesn't pop no pop does n't pop for some reason yes and it goes ahead like I'm here and let's take another example in which the set is in decreasing order. And if I add three here, it will be set comfortably and if the maxima of ours is our five, then what will happen after that I will insert it, you also set it comfortably, but in this one also the greatest five is A is coming which should have come, inside this we should have come four which should have come here four but here five is coming. Why is this happening because while considering these three, we also remove five. We will have to do this, we will also have to remove it, so how do we do that, for that we can do this that instead of passing the element to 5 4 3 2 1 3 2, we pass its index which is the index. If we pass, then now when we are checking the I, we will see the I from the LI, we are going to remove the Income Tax LI as well, so here we can do this with the right, what should we do with it, this is what we have. The pass which is output DC and this is I so here what we are going to do is in this one how it is 0123 so I am going to pass zero one and you because all three of the three are comfortably set in decreasing order right so zero one. You have been inserted in DC. Yes, now the maximum has come. The maximum has come which is the first element of the hope. If zero is zero, if zero has come then that is the index. Keep in mind what is happening in DC. If the index is being stored then if it is zero then zero. So here we are going to name it zero, we are going to exercise it as zero and put it in the output, if zero is in the index then five is done then right up to five inches and after that we will see if three which is index 3 is set in decreasing order. What is happening? Yes, it is getting set smoothly, so we will give three pulses here also and along with that we also have to keep in mind that if we are accessing three when Accessing three is 3 - k means index which is accessing i. Whatever is 3 - k means index which is accessing i. Whatever is smaller than i - k will be the element. The smaller than i - k will be the element. The smaller than i - k will be the element. The smaller index will be the smaller index. Now whatever is in the di has to be removed, like here if it is 3x² then 3. - 3 What is coming from zero and is 3x² then 3. - 3 What is coming from zero and is 3x² then 3. - 3 What is coming from zero and zero? Whatever is coming from zero, we have to remove it. After removing it, what is the greatest thing that is coming in DC? What is the first element that is coming to the right? So the first element is one and what axis is happening in one is four, so here it is four clearly, so I am hoping that you guys must have understood how to solve this question and if I tell you its time complexity. Its time complexity will be Big of N which is optimized, so this approach must be understandable, I am hoping and further I am going to code it, try the court once yourself, if not then I will tell you further. I am going to tell you the code also, I am going to explain the code, so let's see further, so I am hoping that you all have understood and you have tried to code once by yourself, then if you are not able to code, then I will tell you. Here the one who explains completely and line by line, there is no tension, so here as I told in the approach that here DC has to be done and Diku has to be kept in decreasing order, then how to keep it in decreasing order if In my document, a small element is present and we have to insert a big element, then we have to remove whatever small element is there, if a small element is present then we have to remove the small element, it is a big element, after that we have to remove that small element. If they are to be inserted then create it here as if here we had given minus one and removed it after that I have inserted five because we have to keep mine in decreasing order where do we start to check that i is equal to k. Have you gone till A? Then what happened? A seeding window is created, so a sliding window is created, so we have to go till K - 1, so a sliding window is created, so we have to go till K - 1, so a sliding window is created, so we have to go till K - 1, from there we have to start putting the output right because a sliding window is created there. And how we will give another one where the sliding window is moving forward, so when the slide moves forward, we do not want to bring the five which was earlier in the sliding window into the sliding window when the slide moves forward. So what are we going to do to make it like that, we are going to store it from the index to the DC and where the index means the index, the small one started coming there - how are you MS small one started coming there - how are you MS small one started coming there - how are you MS when we got broken here. So if we have come in three, then in three, when in front, three minus means three minus three zero, then zero has to be removed, so we are moving forward, then the one behind which we are removing also has to pop out, meaning. We will have to do it, we have written the index cricket, you do the code here, we are going to do it here, DC, so I am writing di, we will install it in di, where we will store the index, so it is di. I am giving the output name, there we will store the output, the complete index will give the complete address that it has to be removed, that is, when there is a small element, if we have to insert a big element and there is a small element inside, then the small element has to be removed till the last element. The smaller element in I means it is not eliminated when the bigger element is added, after that we will insert our element which is smaller than the bigger one, so we are going to do it here, first of all we will check whenever we will check in DC. Also we check that the front is the last one, first we have to enter whether the DC is empty, there will be a syntax, so to avoid it, first we will check, then after that we are going to check the name index. So we will do the index there, then what will we do for the index, we will check the back of DC, which will be at the last place, like we checked here that there was minus one here and we will check it like five. Which we were going to insert, then how to check the back of DC of five and when it is small, the last element of this DC comes small, which comes small from Namas dot I, so what do we have to do with DC? Pop back has to be done whenever a greater is found, it will be taken out from the log and we have to push the index that whenever a is going to be equal or greater than -1, then we equal or greater than -1, then we equal or greater than -1, then we also start storing it in the output. To start pushing what to push which is bigger in the sliding window which is bigger which will come in the sliding window which is in the first element of DC then IF i = IF i = IF i = greater give equal tu's minus one's minus one then what we We are going to answer what will be in the first element, then it is front, after this, what are we going to do, we are going to do this, after that here, satisfy the different ones, what we will do, insert all the DCs in decreasing order. And whatever document is in increasing order, A is going to increase, the biggest one is A, what are we doing to that? Answer, push us when I = greater, give equal tu's when I = greater, give equal tu's when I = greater, give equal tu's minus one, go right, so what to do now. Now what we have to do is how to do this, we also have to consider where we had seen that when the window is already available in the decreasing order, it does not pop there, then when the sliding window goes further, that sliding window does not pop. The element that has been taken out of the window is not getting popped from the DC, so if it has to be popped, then we have to check that I - then we have to check that I - then we have to check that I - K, which is in the front, like here three came in three, when it was checked. So K = 3 bands of this in three, when it was checked. So K = 3 bands of this in three, when it was checked. So K = 3 bands of this equal, you are three and if we check in 3 indexes, then when we are checking in three days, here we have three indexes, which means which is zero one when you checked, when we checked three, then what is three for us? In the sliding window, only three sizes can be kept, only three elements can be kept, that is, if we have to keep 432, then what can we do, if we have to remove 5, then we have to remove five, then what if 3 - 3 - 3 - 3x - 3 then K - K If we have to remove - 3 - 3 - 3 - 3 0 then if 3x - 3 then K - K If we have to remove - 3 - 3 - 3 - 3 0 then if 3x - 3 then K - K If we have to remove - 3 - 3 - 3 - 3 0 then if zero is in the first element then we have to remove it so the approach here is simple so if we are accessing the front equal tu. So before that we have to check, put it there, then it should be running here, how is everything set, let's submit, you guys must have understood, give feedback in the comments that how did you like this video, so today's This was purity, see you in the next period, till then bye.
Sliding Window Maximum
sliding-window-maximum
You are given an array of integers `nums`, there is a sliding window of size `k` which is moving from the very left of the array to the very right. You can only see the `k` numbers in the window. Each time the sliding window moves right by one position. Return _the max sliding window_. **Example 1:** **Input:** nums = \[1,3,-1,-3,5,3,6,7\], k = 3 **Output:** \[3,3,5,5,6,7\] **Explanation:** Window position Max --------------- ----- \[1 3 -1\] -3 5 3 6 7 **3** 1 \[3 -1 -3\] 5 3 6 7 **3** 1 3 \[-1 -3 5\] 3 6 7 ** 5** 1 3 -1 \[-3 5 3\] 6 7 **5** 1 3 -1 -3 \[5 3 6\] 7 **6** 1 3 -1 -3 5 \[3 6 7\] **7** **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `1 <= k <= nums.length`
How about using a data structure such as deque (double-ended queue)? The queue size need not be the same as the window’s size. Remove redundant elements and the queue should store only elements that need to be considered.
Array,Queue,Sliding Window,Heap (Priority Queue),Monotonic Queue
Hard
76,155,159,265,1814
629
hello everyone welcome to quartus camp we are at 19th day of june eco challenge and the problem we are going to cover in this video is k inverse fast array so the input given here is a two integer values n and k with where n represent the elements starting from 1 to n in the array and k is nothing but the number of inverse pairs that should be there in the array and we have to return how many combination of arrays can be there with k inverse pairs so let's understand this problem with an example so here is a given example where n is equal to 3 so our arrays should be having the values 1 2 and three so the possible permutation of these three values in an array can be having these six combinations so considering our very first combination of permutation which is one two three in this case every number is in ascending order so an inverse pair in that is said in the problem statement is nothing but if any number i and j where i is less than j and nums of i is greater than numbers of j so if this condition is satisfied then in that case it is said to be one inverse pair in the array so we have to count how many inverse pairs are there in the array and that should match the k given so here they have given k as only one so it should have only one inverse pair so moving on to our next permutation which is one three two in this case three is greater than two so we have one inverse pair so this can be added as one of our output so moving on to the next one where 2 and 1 if you consider 2 is greater than 1 so this also can be added as another pair to our result so the next permutation is 2 3 1 in this case if you see 3 is greater than 1 this is 1 inverse pair same way 2 is greater than 1 so this is another inverse pair it is having 2 inverse pairs but in our case k is equal to 1 which means our array should have only one inverse pair so this cannot be added to our output so moving on to next one where 3 is greater than 1 and 3 is greater than 2 so it has again 2 inverse pair so this also cannot be added as our output so finally 3 to 1 is there so in this case again 3 is greater than 2 and 2 is greater than 1 and 3 is greater than 1 so it has 3 inverse best so this can also not be considered for our output so overall there are two arrays that satisfies the given condition that is having only one inverse pair in the array and that is going to be our output so how are we going to approach this if we are approaching this using brute force then the possible solution is we are going to generate all possible permutations of our given numbers and once it is generated we are going to pause each permutation to a function to check whether how many inverse pairs are there in the given array and compare the count with the given k and if that satisfies then increment the count of our result so this is going to take we go of n factorial time as we have to create all possible permutations of the array and that is going to take factorial time and also another method to check how many inverse arrays are there that is going to take big o of n time for each n created so how do we approach this in the optimal way so instead of creating all permutations of the given array what are the other ways to find how many sets in a given array is having k number of inverse pairs or how do we create the permutation that has k inverse pairs for example here in the first alignment or the first permutation all the numbers are in ascending order which means none of the numbers are greater than the other number in the given array which means k is equal to 0 so in other words if k is equal to 0 that there should be no inverse pairs then in that case the only possible solution is this all numbers in ascending order so now from this set how are we going to create the inverse pairs so as the numbers are higher we have to shift any higher number towards left in order to create a inverse pair because a higher number should be before a lower number so in that case we can shift any number before to create it for example if suppose we are shifting 5 towards left then if we shift 5 to 1 position then it the number becomes 5 4 so here the roll number of inverse pairs are going to be 1 because 5 is the only number which is greater than 4 if suppose i'm shifting 5 by 2 positions then in that case it is going to become 1 2 5 3 4. so here the number of inverse pairs we have is 2 because 5 is greater than 3 and 5 is greater than 4 as well so it could form 2 pairs and again i'm shifting 5 by 1 more position then the number is going to become 1 5 2 3 4. so now the number of inverse pairs is equal to 3 because 5 is greater than 2 greater than 3 as well as greater than 4 so what we conclude from here is if we shift a higher number towards left the number of positions we shift the number is equal to the number of inverse pairs so if we shift the number by two positions then the number of inverse pairs we get is going to be two if we shifted by three then the number of inverse pairs is going to be three by using this logic we are going to come up with a solution so let's see so now consider this example n is equal to 4 which means the number should be 1 2 3 and 4 and we have to form the k inverse base for k is equal to 0 1 2 3 and 4. so now let's start with k is equal to 0 as i said the only possible combination we have is having all the numbers in ascending order so when k is equal to 4 the only possible answer we have is 1 2 3 4. if suppose k is equal to one what are the possible best or how many possible pairs we can form so as i said if we shift one number by one position then we gonna get one inverse pair so let's first shift four to one position then we get the pair of 1 2 4 3 or if we shift 3 by 1 position then it is going to be 1 3 2 4 or if we shift 2 by 1 position then 2 1 3 4 so these three combinations are the possible combinations or permutations of the number one two three four to form one inverse pairs so moving to k is equal to two so here as i said we can't shift one number by two position for example from one two three four we are going to shift four by two positions so in that case the number is going to become one four two three which means it gives two in inverse pairs same way instead of shifting a number by two positions you can shift two numbers by one position for example i am going to shift four by one position and two by 1 position then the number is going to become 2 1 4 3 so we have shifted the 4 to 1 position and 2 to 1 position which also gives us the pair of two inverse pairs so because 2 is greater than 1 and 4 is greater than 3 same way the other numbers you can form is 1 3 4 2 where we shifted 4 by 1 and 3 by 1 same way we have other combinations as well similarly for case equal to three you either shift one number by three positions or you can shift three numbers by one position similarly for case equal to four you can either shift one number by four positions or two number by two positions and two number by two positions or one number by three position and one number by one position so either of this will work for k is equal to four so once we fill all possible values or the combinations of the number 1 2 3 4 for k is equal to 0 1 2 3 4 the count of the permutations is going to be 1 3 5 6 5. so now our requirement says or our problem statement says n is equal to 5 and k is equal to 4 so n is equal to 5 means we should have 1 2 3 4 5 as a numbers and we have to form permutations of these numbers with four invalid inverse pairs so here we have the set of solutions for n is equal to 4 and for all possible combination of 0 one two three four so now our job is to add one more five to this numbers and have four inverse pairs so for example we already have a set of numbers with k is equal to four if suppose we are adding 5 to these numbers then it must be end of the numbers if we add 5 as the end these combinations are not going to give us the different result it is again going to give us 5 for n is equal to 5 how because 5 is the greater number out of all these numbers so placing 5 at the last position will not change the number of inverse pairs we have in the set so by adding five at the end we still gonna get five more the same solution just by adding five at the end so moving on to k is equal to three so for four numbers we already have form the permutations with three inverse pairs so we totally need four inverse pairs for this question we already have formed three pairs so our step now is to add five to this numbers so that we will get 4 inverse pairs so we already have 3 we have to make it to 4 so as i said if we shift 1 number by 1 position then we are going to get one inverse pair so in this already having three inverse pairs we are going to insert five one position before every number so if suppose we are inserting 5 between 3 and 2 then the number is going to become 1 four three five two and now we have four inverse pairs because four is greater than three and two and three is greater than two and five is greater than two so in total we have four inverse paths similarly we are going to add the 5 1 position before every number in this permutation which is between 4 and 1 in the second number between 1 and 3 the third number and so on same way moving to k is equal to 2 we already have 2 inverse pairs we still need to make two more so to make two more and we have one more number to be added to the set we are going to insert five between the first two and the last two numbers which is nothing but we are shifting 5 consider this number we are shifting 5 2 more positions before the number so that we get 2 more inverse pairs in that number similarly we are going to add 5 in between all these numbers to get k is equal to 4 for n is equal to 5 and coming to this point k is equal to 1 we already have one pair so we need to make three more pairs to reach case equal to four so to get three more pairs we are going to add five three positions before so at the second position we are going to add five at all these numbers to again get count is equal to three with n is equal to five and k is equal to four and you must be aware now what will happen if k is equal to 0 to achieve 4 we simply directly add 5 at the first position so that we will get 4 pairs so now all said and done this is the pattern we are observing while adding a number and getting the inverse pair so if we represent this in the form of formula then we can say count is equal to already existing count plus 0 to k count the again form the method of n minus 1 comma k minus i where i is nothing but 0 to k so here every time k minus i is nothing but if we have 3 already then if i is equal to 3 then we need to form k is equal to 4 so 4 minus 3 is 1 so we need to form only one more inverse pairs when the set of permutations are there for k is equal to 3 and one number reduces per iteration so here we did is we have formed the numbers from zero to four so in our program we recursively gonna start from n is equal to five and k is equal to four and we're gonna make it both zero and is equal to zero and k is equal to zero till we reach zero comma zero we are going to do perform this formula recursively and achieve a solution so hope you are understanding the solution this is gonna work and we go off n square into k time where k is the number of inverse pairs and n is the length of the given numbers or in this given input so let's go to the code now so let us first check the base conditions if n is equal to 0 then directly we can return 0 and k is equal to 0 the only possible solution is one which is in ascending order so now i am declaring k count is equal to zero and finally written we are going to return that as the output so in between i'm going to iterate my k from i is equal to 0 to k and count is equal to count plus i'm gonna call the same function recursively and pass n minus 1 numbers for k minus i pairs so yes this is it finally count will have the number of permutations with k in inverse pairs so let's run and this solution is definitely gonna time limit exceed okay the answer is strong because so sometimes k may go equal to k minus i in that case when we compute k minus i is going to become less than zero so in order to avoid that we are checking the loop either minimum of k or n minus 1 so yes it is time limit exceeded as we have duplicate number of operations so we are going to define a tp array to do a memorization and we are declaring this in integer variable because we are going to check whether the data is null or not we generally check for minimization if the data is zero or not but this may have zero as its output so we are going to check if our dp is not is equal to null then return the precomputed value and finally return dp of n k so here instead of storing the count we are going to update the value of our count to our dp every time once it is calculated for that particular n and k so one more thing we missed it we have to return the output in modulo of 10 power 9 plus 7 so i'm gonna perform a modulo here where we calculate our count so that's it let's run and try yes so let's submit yes a solution is accepted so thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
K Inverse Pairs Array
k-inverse-pairs-array
For an integer array `nums`, an **inverse pair** is a pair of integers `[i, j]` where `0 <= i < j < nums.length` and `nums[i] > nums[j]`. Given two integers n and k, return the number of different arrays consist of numbers from `1` to `n` such that there are exactly `k` **inverse pairs**. Since the answer can be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3, k = 0 **Output:** 1 **Explanation:** Only the array \[1,2,3\] which consists of numbers from 1 to 3 has exactly 0 inverse pairs. **Example 2:** **Input:** n = 3, k = 1 **Output:** 2 **Explanation:** The array \[1,3,2\] and \[2,1,3\] have exactly 1 inverse pair. **Constraints:** * `1 <= n <= 1000` * `0 <= k <= 1000`
null
Dynamic Programming
Hard
null
6
another day another problem so let's Solve IT hello guys I hope everything is going well for you all so today's this video we're gonna solve the problems exact conversion I think this problem it's not likable by people as we can see that they have like 10K dislike so we're gonna solve it uh so let's read the problem the string paper is hiring is writing and a zigzag patterns on a given numbers of row like this so the string is Bible is hiring it's writing in a zigzag bar and we have a number of row which is three and this first example so the idea here is that the first character gonna be this and the second character is gonna be this and at this last row is going to be like this so the approach to solve this problem we need first to know how many steps we're gonna jump to read the second letter if you look closely to this picture I have added and this is of which characters so that you can see what I try to explain you'll find that if you're gonna go to the last character at the First Column and go back to the first character in The First Column you will need four steps so to get to the next letter in first row we need to apply the same logic the difference is that we cannot return to the first character and the First Column but we're going to switch the direction to the next layer and row as we know we have a zigzag so we can get the first letter but then get harder when we try to read the second row so to read the second row we're gonna reduce the step by two because let's say we're gonna read the letter P how many steps we're gonna need one and two so if we do the basic calculation the difference between the first row and second row is to each time we read a letter for the last row it's gonna be just like the first row we're gonna need four steps the same amster and if we only have one row we're gonna return the input string so for the code explanation the first thing we're going to do is the basic condition if the input string is equal to none or the number of rows is less than zero we return and also we need to return the input string if you only have one row and after that we initialize our result string that can hold the final result string and we also declare a variable that's going to hold the steps that we're going to jump to get the next letter and we start looping for each row after that we're gonna start looping at each character and string with the step that we're gonna jump to get to the second letter after that we're gonna add the first layer to the first string and we're gonna jump four step to read the next letter and add it to the result string this condition is for the first row and the last row so for the second row we're gonna check if we are at the second row first things and we're gonna reduce the number of steps to two because the first row and the last row takes four steps to read the second letter but for the second rows we say we reduce the steps by two foreign thank you
Zigzag Conversion
zigzag-conversion
The string `"PAYPALISHIRING "` is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: `"PAHNAPLSIIGYIR "` Write the code that will take a string and make this conversion given a number of rows: string convert(string s, int numRows); **Example 1:** **Input:** s = "PAYPALISHIRING ", numRows = 3 **Output:** "PAHNAPLSIIGYIR " **Example 2:** **Input:** s = "PAYPALISHIRING ", numRows = 4 **Output:** "PINALSIGYAHRPI " **Explanation:** P I N A L S I G Y A H R P I **Example 3:** **Input:** s = "A ", numRows = 1 **Output:** "A " **Constraints:** * `1 <= s.length <= 1000` * `s` consists of English letters (lower-case and upper-case), `','` and `'.'`. * `1 <= numRows <= 1000`
null
String
Medium
null
1,921
Hi Everyone Welcome Back To A New Video In This Video We Are Going To Solve A Question Name Eliminate Maximum Number Of Monsters Which Is A Medium Level Question Now Lets See The Problem Description We Have Been Given Two Array Namely Distance Array And Speed ​​Array Distance Array And Speed ​​Array Distance Array And Speed ​​Array Distance Array Shows the distance of the monsters Distance of the monster from the city and speed is the constant speed of the monster at the moment they are moving Now we have the speed and distance of the monster but we have also been provided with a weapon that once fully charged can eliminate A Single Monster Now Once We Have Eliminated A Monster We Have To Charge The Weapon Again And It Will Take One Minute To Charge Once The Weapon Is Fully Charged We Can Use It Again But The Thing Is If The Monster Reaches The City At The Edge Mutt If the weapon is fully charged it is counted as loss and the game ends before we can use the weapon now we have to return the maximum number of monsters we can eliminate before we lose and end if we eliminate all the monsters t have reached the city So we've been given here to we need two maximum number of monsters we've been eliminated Maximum number of monsters we can eliminate and we will return n If We Can Eliminate All of Them Now Let's See the Approach to Solve This Question First Step to Solving This Question We will be calculating the time taken by each monster to reach the city Which means that we will be going through it in a loop and we will be calculating the time for each and every monster now. The Second Step We Will Be Sorting The Time Taken Here Now The Third Step We Will Be Identity Is Taken By The Monster To Reach The City Is Less Than Or Equal To I Here I Will Be Kind Of Weapon Charging time and if such thing happens then we will be returning the i now let's run the code to see how it is working so we have speed array s in example given here wave and distance j th 4 so wave and distance j n r and four Now we will calculate time for each of them so time i distance by speed there for we will get the time taken by each monster as number three and four after sorting the array we will get the same array number three and four now we will it and Check if time at given i position is less than or equal to i and not if it is so we will return the i value from there i here and then we will take here s time at given position so first we will be starting from zero and At zero position we have one so one we check this condition if it is true and not condition it is true so now we will be moving to n Now we will check at first position we have value so this value is lesson this is Also correct now will have here second position and here we will be having for this is also correct now we see that all the conditions are correct right we have seen all the conditions in true cases where all the conditions are correct that means we are able to Eliminate all the monsters there for we were asked to return the a value So here is the length of distance and speed so we Will be returning as the answer here let's see the code now so first we will calculate the length of the array and basically it is the number of meters present so now we will calculate the time taken by them to reach the city so we Will be calculating the time here now A if it is then we will return the i and now if all the values ​​are correct means all the values ​​are correct means all the values ​​are correct means all the monsters can be eliminated then we will directly return the length of the error so we will run the question and see problem now try to submit it So this has been accepted thank you for watching the video and like the video if you understood the problem also share it with your friends
Eliminate Maximum Number of Monsters
eliminate-maximum-number-of-monsters
You are playing a video game where you are defending your city from a group of `n` monsters. You are given a **0-indexed** integer array `dist` of size `n`, where `dist[i]` is the **initial distance** in kilometers of the `ith` monster from the city. The monsters walk toward the city at a **constant** speed. The speed of each monster is given to you in an integer array `speed` of size `n`, where `speed[i]` is the speed of the `ith` monster in kilometers per minute. You have a weapon that, once fully charged, can eliminate a **single** monster. However, the weapon takes **one minute** to charge.The weapon is fully charged at the very start. You lose when any monster reaches your city. If a monster reaches the city at the exact moment the weapon is fully charged, it counts as a **loss**, and the game ends before you can use your weapon. Return _the **maximum** number of monsters that you can eliminate before you lose, or_ `n` _if you can eliminate all the monsters before they reach the city._ **Example 1:** **Input:** dist = \[1,3,4\], speed = \[1,1,1\] **Output:** 3 **Explanation:** In the beginning, the distances of the monsters are \[1,3,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,2,3\]. You eliminate the second monster. After a minute, the distances of the monsters are \[X,X,2\]. You eliminate the thrid monster. All 3 monsters can be eliminated. **Example 2:** **Input:** dist = \[1,1,2,3\], speed = \[1,1,1,1\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[1,1,2,3\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,1,2\], so you lose. You can only eliminate 1 monster. **Example 3:** **Input:** dist = \[3,2,4\], speed = \[5,3,2\] **Output:** 1 **Explanation:** In the beginning, the distances of the monsters are \[3,2,4\]. You eliminate the first monster. After a minute, the distances of the monsters are \[X,0,2\], so you lose. You can only eliminate 1 monster. **Constraints:** * `n == dist.length == speed.length` * `1 <= n <= 105` * `1 <= dist[i], speed[i] <= 105`
null
null
Medium
null
1,762
hello everyone today we're going to do buildings with an ocean view which is lead code problem 762 this problem holds a place in my heart since I live in San Diego and I wish I had a building an apartment with an ocean view anyway it's a medium problem stating there are n buildings in a line you are given an integer array Heights of size n that represent the heights of the buildings in the line the ocean is to the right of the buildings a building has an ocean view if the building can see the ocean without obstructions formerly a building has an ocean view if all the buildings to its right have a smaller height so the ocean on the right return the list of indices zero index to buildings that have an ocean view sorted in increasing order so we don't care about the buildings themselves if buildings themselves we just want their indices so let's look at example one here so we have Heights equal 4231 so the output is 023 so what does this mean so this is the index so the four obviously is the highest building so it's going to have an ocean view the ocean over here to 0 1 2 the three will have a view because the only thing to the right of it is the one and the one will have a view because there's nothing to the right of it obstructing it example two 4 through 21 so this is all of them because it goes largest to smallest so they all have a view and then in the last example 1 3 2 4 well four is the tallest so it's obstructing all these other guys so the output is just index three all right so how are we going to do this well basically we're going to use a CU and we're going to add the index we'll assume that the first building can see the ocean and then we'll if we come across another building at higher then we'll have to take that building out of the queue the previous building and stick the new one in there so we'll start with so this DQ or deck however you want to pronounce it this allows us to pull from the top or the bottom of the stack we're going to do integer because we all we care about are the indices I call it stack and I'm going to instantiate it okay so we got that going so the first thing we're going to do is take the first uh integer and assume that it is the tallest that is a zero not a o okay so Notice come on Scott okay notice that this is pushing the zero index it's not pushing the first value in Heights it's just pushing the index zero into the stack all right so now we just need to go through each element in Heights we're going to start with one because we already pushed the zero index into the stack so it's less than the height oops Heights length I Plus+ pretty standard there okay so what we're going to do is basically a wild Loop because we need to compare the current building with all the previous buildings so while the stack is not empty no sense of going through it if the stack is empty and height spell Heights height sub I is greater than or equal to Heights and this is we're going to do some fancy see stack. Peak which just looks at the Top Value doesn't actually do anything with it so if it's taller than that then we need to stack. pop so we need to pop off that so let's say we have the array is one two and three and we get to three well three is taller than one and two so we got to while the Stag is not empty and three is greater than you know one or two so it's going to keep popping those off so get rid of all those buildings because three is the highest all right so now we assume that we have the highest because we popped off all the smaller ones so now we just need to push this current building or in this case the index onto the stack all right so this will get us the buildings that have an ocean view but the order is messed up so we need to um reverse the order here so we're going to do an INT result and this is going to be a new int of the stack size because we've gone through all of this point we've gone through all the buildings and we have the list in the stack okay and we're going to in equals stack size all right so now we need to do for in I = nus 1 0 index I is greater than or I = nus 1 0 index I is greater than or I = nus 1 0 index I is greater than or equal to zero and I minus so this will get us through the entire stack and we just need to do results we're going to sign the results equal to stack.pop so it's going to pop them to stack.pop so it's going to pop them to stack.pop so it's going to pop them off in reverse order and give us our answer and then finally we're just going to return that result and that should give us what we're looking for so let's debug this all right so let's debug this I picked the example the first example 4231 so the answer should come back building four which is index zero building three which is index two and building one which is index 3 so let's debug this and see what we get all right so we're going to push the number zero into the stack so we're going to walk through the list of buildings so height into I equals 1 so we're comparing the two with the current height in the stack which is four so it's not this is not greater so we're just going to push the one onto the stack well now we've got index 2 which is the three well that is greater than index two so we're going to pop now we have to pop the two off and it's not higher than or greater than four so we'll leave four in there and push the three on there or index two and finally we've got index one or I'm sorry index 3 which is the value one so we'll push that on the stack so now you look down here and you see the stack size is 0 1 and two so we have uh three 2 and zero stack size is three and we just need to reverse these so that's what we're going to do and then pass the result which is 023 so that's index zero index two and index three which is what we expect so this is the value four the value three and the value one the three buildings that have views to the ocean and actually their indexes or indices onun this through lead code and Hope I coded this right submit that whoops well let's run it first sounds like it's going to pass because I already submitted okay that was and submitted faster than 25 less than 43% memory let's try it again now he 43% memory let's try it again now he 43% memory let's try it again now he like to do it y we're getting better 32 and 51 so let's look at the time and space complexity the time complexity is O ofn so it just depends on the size of the input so we're creating a stack the stack is dependent on the size of heights the in Array Heights is that if that increases we're going to increase the time to go through it uh all those numbers and the space complexity same thing where input parameter Heights increases well it's going to take more space to pop and push all those numbers and that is it so thanks again for watching let me know if you have questions and we'll see you next time said
Buildings With an Ocean View
furthest-building-you-can-reach
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line. The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height. Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order. **Example 1:** **Input:** heights = \[4,2,3,1\] **Output:** \[0,2,3\] **Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller. **Example 2:** **Input:** heights = \[4,3,2,1\] **Output:** \[0,1,2,3\] **Explanation:** All the buildings have an ocean view. **Example 3:** **Input:** heights = \[1,3,2,4\] **Output:** \[3\] **Explanation:** Only building 3 has an ocean view. **Constraints:** * `1 <= heights.length <= 105` * `1 <= heights[i] <= 109`
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
Array,Greedy,Heap (Priority Queue)
Medium
null
7
good morning my name is Alan singana in today's video I'll be explaining you the solution to the lead code number seven with the title reverse integer it is a medium difficulty level question and says that given a 32bit signed integer X return x with its digits reversed if reversing X causing the value to go outside the sign 32bit integer range which is fromus 3 31 till um 2 31 minus 1 then return zero assume the environment doesn't allow you to store 64bit integers signed or unsigned okay so uh it is a pretty simple question but U it has given us some constraints now what is happening over here it is that uh we have been given a in int data type number and we know that the data type int can hold till only 32bit integer value only so what it is saying that we need to reverse the integer order of the digits within that integer and return that integer now if while reversing the integer if it exceeds the 32bit range inside the uh which is uh given for the int data type then we need to return zero and the 32bit range should not exceed uh minus 2 31 till 2 31 minus one range so it is a simple question and you can see that in the example number one you can see that the x is 123 or you can say 123 but the output is 321 so you can see that the order of the digits within the integer has been reversed now coming to the example number two over here as you can see that the integer input was minus 123 but the output here is changed and the reverse digit uh would look like minus 321 now in the example number three as you can see that it is 120 but when we reverse the uh placement of the integer placement of the digits inside the integer the output would be 0 to one but zero is insignificant if it doesn't have any integer value before it then it is consider considered zero and we need do not need to print it that's why the output is 21 over here now coming to the code uh the code is pretty simple now as you can see that first the very first step is very crucial over here I did uh I created a integer soorry I created a long data type variable with final num its name and initialized it with zero now why did I use long over here I used long over here because long data type has the capacity to store 64-bit integer has the capacity to store 64-bit integer has the capacity to store 64-bit integer and we also need to check whether I our answer when reversed uh does not exceed the 32 32bit integer so for us to check it we need something to hold a number which can be greater than 32bit integer that's why I created a final uh variable with the data type long because it can easily store a Vari a number or a number which is which exceeds the 32bit range as you can see I as I told you Ive initialized it as uh zero after that I created a v Loop which would check if X is not equal to zero this condition is crucial for the while loop to keep running now why I did it is that because we will be taking out the each and every integer or digit in behind the each and every integer and adding it to the final number uh so if the x is zero then it would simply terminate the whole value now as you can see that I initiated another uh in data type variable which is large digit which would store the remainder of the division of x divided by 10 so and after that the division it would store inside or update the final num which would be which would look like final L is equal to final L into 10 so first this calculation would be done because according to board M Lo it would first multiply 10 to the final L then it would add the remainder or that is stored inside the last digit to the final L after that we simply uh update the X variable with the quotient of the division of X itself divided by 10 now I show you how this calculation is working for example we have been given a number one let's take the example as well only now uh what the last dig would store is the division or the remainder this percentage sign repres and the division between uh sorry the remainder coming out of from the division between X and 10 so uh if we divide uh 123 with 10 the remainder would be three so the last digit uh is so the last digit is storing uh this integer which is three after that as we can see that uh the final array the final I am representing it with final uh the final first St zero just a second the final First St zero after that the calculation was that final should be multiplied by 10 then I would add the remainder that I got from the integer division to the final number now so if we multiply zero with 10 then nothing's happen because 10 zero m z is the multiple of with anything the answer only answer you would get is zero and after that we added the last digit and so now what uh what would our answer become uh the final would become as three as you can see that uh the last is stor three so it would become three now what we are doing we are updating this value uh with the quotient of the division uh with the quotient that we will get from the division of X and 10 so X would become uh the quotient of division of by division of X by 10 would become uh would be the uh 12 as the quotient so now X is 12 again uh the last dig now the last the while loop will check if it is zero as you can see that X is not zero so again it would uh reinitiate the while loop uh and loop and it would again do the same steps again and again so now the last digit will store the again store the uh remainder from the division of X and 10 so now 12 divide by 10 would give us two and the uh now final num would be updated like how it would now as we know the final num uh so just a second as you know that the final num is currently storing three so according to formula first we will multiply final with 10 so it would become 30 and then we would add the last digit to it so after adding last digit to it what would happen now the final num uh final num would become just a second uh now final would become 32 because 30 + 2 is 32 and as become 32 because 30 + 2 is 32 and as become 32 because 30 + 2 is 32 and as you can see that we can you can already picture that the starting the reversal of the digits within the integer has been started reversal of the digits of the integer has started and the pro this same process will keep on going till X reaches zero and after that uh we get the final number which contains the Reversed digits uh that was originally uh which reverse digits of the integer now after the Y Loop has been terminated it would go to the final uh if else check it would first check if the value of the final num exceeds or precedes the integers maximum uh range and the minimum R respectively so that's why I'm using this if command over here which would check if par is greater than integer do max value now integer do max value is represents the maximum uh value a integer can hold which is a maximum 32bit in value that the integer can hold or means if either of the condition is true then the if command would initiate or if the command inside the conditional statement if would trigger if either of these two condition is uh true now uh the second check is that if the final num is less than the integer minimum value integer do mean value it would it represents the minimum value the integer can hold so if the final num is like I said if final num is exceeding the integers max value or if it is less than the uh integers minimum value then we would simply return zero as been told by the question itself after that we know that uh the number reversal of the digits has been taken place but we do not uh have not taken account the uh its nature if it is positive or negative because as you can see that in the second example uh we have simply reversed the digit but we have not take in account the sign that it currently holds so because uh we need to uh return the output in the negative only as you can see that the input was negative and output is as well is also negative so to retain its nature uh the numbers nature we will check if x is greater than zero then what would happen is that this it would return int now this bracket converts the whole number which is currently in the long data type in uh converted it would convert it into the integer data type and it would Min it would multiply final num with minus one to retain its nature as you can see as we know that um if we multiply any number with minus one it would convert that number into negative if that if the number was already negative then it would become positive uh that was just the basic math concept now as I told you if the number is negative uh if x was is negative then it would convert it into the negative integer by multiplying minus one with the final and this as I'm repeating again this in within the parenthesis would convert the whatever the result after the multiplication into the integer data type again if uh this command is not triggered it means that the X was greater than zero or the X nature of X is positive so the final return statement simply Returns the positive in integer type value as you can see that again I'm using the in data type within the parenthesis before the variable name which would convert the whatever value inside the variable uh into data type and that's how the code would be running uh now I'm simply checking all the test cases as you can see that my code has been successfully uh has successfully given the right answers for all the test cases now I'm submitting the code as you can see my code has been successfully submitted and my code beats 90. 23% of the test of the user who 90. 23% of the test of the user who 90. 23% of the test of the user who submitted the solution for the same code so for the same problem in Java now coming to the time complexity of this whole code uh the time complexity is mainly dependent on the iterations number of iterations done by the Y Loop and the number of iteration done by the W Loop is totally dependent on the number of digits inside the uh integer or the input integer we have been provided with so the time complexity of this whole Loop would be o of n and n represents the number of digits inside the integer well uh that's all for the this question in lead code uh thank you for watching
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
225
It has happened that most of the time you guys will be good and having fun, you are healthy till now we are on this side because then we put a lot of questions in it to make sure that the person who understood the whole thing was the one who explained the most the basic concepts like why is the lift stopped and what happens? See, now I told you that we will learn all this on a question to question basis and move ahead. Okay, in the last section we had made time payment, we had made a claim. Today, with the help of this type, we will do stock investment because it is better with help. Maybe that's what I always request, friend, whenever you watch all these types of videos of mine like Fear and Not Feeling, Spoon Confident and Strike Entry, then please watch the playlist from the beginning, then you will understand many things better and many things. Be clear, you will be able to understand. Okay, while watching the video in the exam, in a sweater, expecting that you will pause this video and see some development in it. I am also here, you too are like this, if you pause the video, I teach weight, you attend the institute. Italy will not grow much according to you, it is on this sequence, you will start watching the video and I think the question will be from you, Divya Prem Shu, see how it was solved, how it is updated and discussed, you could have thought of it, right. It is possible that everyone's experiment is different, its use is different to solve a particular question, Vrindavan Effect will cover everything, Vikas tutorial is only for those people who know a lot, this is going on from business to dinner. And if it is an editorial, then what you must have read means that this question has been painted and it must have been asked by many people, it must not be a question but you must have understood what the rider is saying, basically I have brought this last, you must have seen the ending. What we have to do is basically we have to improve our strike with the help of why it means that we who are used to this kind of festival, we have to use it and we have to use it. We should not do this because why is it necessary to complete a step with help, all the functionalities in it are from the front, right, which is the front function, we do the cutting with people, start with us, if there was functionality, it would be push-distic functionality, it would be push-distic functionality, it would be push-distic angry. Man post the points element extract the top statement of account statement that has to be found out and MT step is to remind all these things that we have given this function in the question to do skin treatment Okay so if you Discuss in that for the stock like for like we have the stock ride we first set in two then three and four like to mute the plot of attacks is n't that all to do the climent it means that when the toolset on it for the first time If it is, then the message to you will be shirt, then 360 feet, then it means that here we have it on the front, okay, so now as it tells us that if we want to pop, then we will top, then for this minute there should be a basic lift because in this Elastic element will be top, it will say that it means that the topic element will be the last element here in the sequence. If MP says simple, death, don't size, it will be ok because it will be debited. In this also it is due to tension, if it is anti, then it will return, it is true quantity. Okay, so this stock limit will be written in WhatsApp, if you do this, whatever element is happening, why I am not at the end but in the front, as if two was inserted, then first we wrote two, then human became three in the stock. If there is a shift in its front, then it is fine in its front, so it made our work easier. If pop says, we will turn off the cute hotspot, then it will automatically turn off the prank element. It means that it is also gone from the stock. If we say that, what? If we take out the top element then we have q.no front, take out the top element then we have q.no front, take out the top element then we have q.no front, it will return till the minute we do the top, if we talk about size, then why will we scold for size, then it is simple, we have just improved it, okay, but brother, how can we do this? That's why we set the front element as inches, this is 4 inches extra, the camps are going to pay in that function, okay, so how can we do this, so simple, what will we do, why make one in one? Youth and due to friends will make basically end like now we have 1438 so one this has been insulted till now in life suppose somehow limit it and this has come now we have cute which is anti and in problem u20 The first stuff is the second item, what will we do that now like we want to do it on the inside like this heave to three and four legs then we have to set it on the right side, okay basically we want it to be at the top and go to the front so that it is insulted. What will we do with those laddus? First we will make life anti and add elements of cute. If we add 432 in it, then one will come for sure which is this monk. Okay, now the truth will be revealed, this will be the second attack of the first step. Now q1 element will be put 5 ok and this third one will go 432 so one ok what will we do in North Eastern will empty the cute and put in life pipe and 432 and add q2 basically now the opposite is taking it like a tree or else It is fine like a temporary space, so now why do we have this in three steps, which is our work in off and time complexity, then Narayan said that by applying this simple loop, we emptied the queues and put it in cute. given ok first step q12 YouTube second step why dot push best acute him fast we have done this in three steps we will post the dot of bigg boss so if it is anti ok if this entry has already been done blog post only in the second step If you do this, then automatically that same element, the friend is also the same and the treatment is also the same, if you start doing a job, then edit this element will pop up and by reducing the for per to two, the whole of it becomes interested in the front, from then on, this is how to do it. As for the drop, we invest it in the code. First of all, you work on pausing the video but after making some improvements, you will see whether you are doing it or not, the balance gets blown away, that is, you slowly start building confidence in the code. Do it buddy, register, you will understand the problem, what is the problem, brother, since I came riding easily, my butt has always been like this, we solve it basic like this, then if the rapper is in the mood for a hard bite, then this is my favorite, now we will cut it. It is very simple to give one public, what do you do, why do you make it, why and give one example, do one and acute, do this, there is no problem, till now you have to pop, then poptron was simple, print value, do you extract oil earlier too, or one dot print now? So everything has come in the front, we are assuming that the police has been deleted last, there is the element of doing 'I am the calling', there is element of doing 'I am the calling', there is element of doing 'I am the calling', there is nutrition in the front, you have the element of front, brother, basically, if we pop, then the potato has come, now this dot. Will pop very correct and will return the value. Okay, the front element is exploded in it. While shifting the value and also returning an element to us, this is turning off the statement and will do WhatsApp, so basically what it did is that If we talk about top, then one dot print of return is fine because the front element will be our hidden top element. If we talk about redemptive, then the return key will be 120. If MT is there then it will start this return. If not If it happens then it will pause. Now things are flower so what is our first step that the first step is to move from human to cute so that is not equal to one dot mp until give one mp is done then we It does not come empty, what will we do that one dot will make a flower, what will the flower make, sorry, feel cute, the first thing is that the machine was emptying them, what will we do, one dot front, which will make the front element and this dot pop, so simple, second step. What is that if you will flower in life then simple that dot asset register to So what will we do now in life, if we go to Pushkar in life then we will do one dot posts, front element of cute, then q2 dot front will be top of simple and cute, decade of decade, now let's run it and see or diet, have you understood how we That's all, it was not rocket science, just a little quantity in the front, two were considered as extra and one was considered as contemporary and one was considered as male and the logic behind this was that we invested in the front and went on, now we could have done a lot of variations in this, you can There are some points, you could have put your mind in it, you could have put some in the top, I am developed, how do you handle the one who has approached one approach, you can commit. Okay, if you like the video, if you think that my channel is very helpful and If you like this then please share it with your friends. See you next day celebration. In MP3.
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
129
Hello Welcome Reaction Record Broken In To-Do List Ko Baikuntha Problem In To-Do List Ko Baikuntha Problem In To-Do List Ko Baikuntha Problem Loot-Loot Rule No Ki Return Total Arm Hole Paluto Note 5a Ek Photo Pal Ji Deep Wound De Koi Man Prabhat Ki Vid Vasundhara id porn in loot voice straight thread on its side left side is the party went with difficult hare and routine life's temple run looted all this loot has nine forms of protest loot on this stage and regulations for affiliated companies on Ko Fold Want To Search Which Picture Waqt Singh Pundheer Ubhe Plate A Prem Toli Naam Hai Which Water Into Effect From Tak That Bank Note Channel Thank You And Sab Tell Me How Are All These My Mother Ne Nal Dhule Number Naam Ki In A phone number will be given number loot sliding into its position s ki mumbai cricket ka naam se tire murgi not commit suicide in do a boy padharana half people and subscribe to it to ki torch light fictional ki cigarette ko attuk kam plus no jhal luta Let me tell you that there is history so much that this bill has been passed by the Parliamentary Board, I am the value of Mathura and simple, that I am a little difficult, this is the love light that you are like a mom, that you can rob this person, is it a torch light, food habits of differences, or a woman, when it is the media's birthday. I wish one text pimples video subscribe to
Sum Root to Leaf Numbers
sum-root-to-leaf-numbers
You are given the `root` of a binary tree containing digits from `0` to `9` only. Each root-to-leaf path in the tree represents a number. * For example, the root-to-leaf path `1 -> 2 -> 3` represents the number `123`. Return _the total sum of all root-to-leaf numbers_. Test cases are generated so that the answer will fit in a **32-bit** integer. A **leaf** node is a node with no children. **Example 1:** **Input:** root = \[1,2,3\] **Output:** 25 **Explanation:** The root-to-leaf path `1->2` represents the number `12`. The root-to-leaf path `1->3` represents the number `13`. Therefore, sum = 12 + 13 = `25`. **Example 2:** **Input:** root = \[4,9,0,5,1\] **Output:** 1026 **Explanation:** The root-to-leaf path `4->9->5` represents the number 495. The root-to-leaf path `4->9->1` represents the number 491. The root-to-leaf path `4->0` represents the number 40. Therefore, sum = 495 + 491 + 40 = `1026`. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `0 <= Node.val <= 9` * The depth of the tree will not exceed `10`.
null
Tree,Depth-First Search,Binary Tree
Medium
112,124,1030
991
Hello hello everyone welcome back to my channel short today introduce bhaiya on naad problem 51535 so please like share subscribe my channel get bell icon to notify members whenever possible so without any further delay started problem is broken calculator a pro content creator rathore day Teacher Start Value 19 Display Initially in one operation you can multiply the number or display between them or you can attract one from the number with all its place ok then give number this will give one of them in multiplier number two or they can travel from back number 120 Start Value Topics and Display and Target Twitter Minimum Number of Nations Needed to Display Target on This Thank You Left Right with Me to Convert Start Value to the Target Ritu Convert 22182 Operations Hydride Quintal Multi Plast Value Bittu and Vision World Surprise Book with 140 Charts Please Subscribe Now To Solve With Multiple Benefits From You To I Love You To All So Much Will See You To But Ironing mid-2013 Two Tomorrow Morning Meeting Threads mid-2013 Two Tomorrow Morning Meeting Threads mid-2013 Two Tomorrow Morning Meeting Threads Nominations Is Doing This Generation And A Co-Creation Wedding Tourists Co-Creation Wedding Tourists Co-Creation Wedding Tourists A Fight Surya Answers To Valid Rate Countries Can You To Two Which Will Get For His Vehicle Act Flv Video I Secure This Request * Operations With This I Secure This Request * Operations With This I Secure This Request * Operations With This Method Tiffin So Surprise Minus One From And How Operations Will Be Required To Convert To Target 12304 100 Indore Problem * Return Minimum 12304 100 Indore Problem * Return Minimum 12304 100 Indore Problem * Return Minimum Number of Operations and in Fact They Will Win Election 2014 111 Busy with Pure Problem Busy Five What Will Sprout 145 Will Get More in the Life in a 180 Person Initial Serious Problem Life That Approach Which Comes to Mind is That We Can Do Si For Any Number Ki Lete Courier Behavior Ki Ahir Si Ki That Person And Tagged Starting Systematically Multiply By Two And We Can This Week -1.5 1332 Detailed Will Get 6 -1.5 1332 Detailed Will Get 6 -1.5 1332 Detailed Will Get 6 Ajay Devgan's Two Options Is Difficult To Multiply By Two And Video Subscribe - Multiply By Two And Video Subscribe - Multiply By Two And Video Subscribe - ki uske aaya hai apk file which continues in five doing multiply by two of the twelve year again for this 12th and multiply by two and they cancer breast - multiply by two and they cancer breast - multiply by two and they cancer breast - 124 members swing and we can do multiply battu strong morning time country- Foreign Voices Also You That Topic country- Foreign Voices Also You That Topic country- Foreign Voices Also You That Topic Tomorrow Morning York Minus One From Which Will Get 5 Days What I Can Do East Direction This Two Options Iron 122 And - 134 A Multiple Of Your Options Iron 122 And - 134 A Multiple Of Your Options Iron 122 And - 134 A Multiple Of Your 10 Which Is The Great Who Is The Target A To Feather Otherwise Festival - 1ST Year Otherwise Festival - 1ST Year Otherwise Festival - 1ST Year Environment Continuously Two Minus One Dissolves in the Digestive Sub Script Protest Started 20's Send WhatsApp to A Vendors Values Going But Still Multiply Bittu and When the Safar Active What Will Be the Best Is That's the Question A suis approach ki is co-chair ki co-chair ki co-chair ki adi pet ko office approach what will happen if due noble host team is available so only minimum and maximum volume and selected in which he is doing multiplication of valuable lessons and attractive and the observations affecting time in english Meaning of nation but this board and e the water based on that a monk you might see the straight school wheel chair for a multiplication between interview letter this 2014 this great dane target that last days target just off 's first white heads white gold so 's first white heads white gold so 's first white heads white gold so ok i agree andar to its value will be coming let this target written e a bird watching this is the best k is left side sell this water need some taste cyclist start value2 now it has 10 and need to reach hands free targets thi to Ko morning in english tennis greater the three types of values ​​are 12th types of values ​​are 12th types of values ​​are 12th that sunanda case your rhythm will give winners simply return from chronic a special how not checked reach it smart karen to yo mike shesh inverter to stop this minus one they can have something like It is the value it is responsible from England will not be correct that worthy of it basically choice approach will not work like a minute to think of something stayed in 200 how we can do it how can go but this electrolyte to 100MB movie full movie enemy What we can do Do that this study road also any multiply chart value bittu and tubelight target were and vep test - wonder car's together to get right something is test - wonder car's together to get right something is test - wonder car's together to get right something is 10th a's extension amrit aage nadu and will approach wali hai tomorrow morning storm target so starting from Target that two options only hours best all Garhwali to chart volume exactly to the detention Dubai that target divider to inside volume exactly to target plus one oo tiger wali profile jis - Anil Good time and divide 2.1 a the 2.1 a the 2.1 a the greatest value than and hear Google Bhaiya setting Okay like this is the opposite of the year approach prithvi thought of this completely opposite words for the benefit of giving that such leaders approach which can be used in subscribe to that this notification for justin bieber se beau test case chart value I invented market That in the country, what you think Sukhbir and the output chart is valueless is 0n target istri suit with k what you will do so in this you have to go between it into than what would you prefer to input and will multiply by two and blue forest something On That Now Slide Witchcraft Bluetooth From 10am To 300 Novels Written Or Gives Equal To Target This Discerning Letter And Start Value 8 - Target 8 - Target 8 - Target 10th Number Operations At Times - 110 - 70 10th Number Operations At Times - 110 - 70 10th Number Operations At Times - 110 - 70 Subject - 151 - Subject - 151 - Subject - 151 - 9 - - - - - - 9 - - - - - - 4 - 134 A 4 - 134 A 4 - 134 A Yes Yaar 12345 6 And Which Destroys Value - 12345 6 And Which Destroys Value - 12345 6 And Which Destroys Value - 17 This Video Chat Start Value To Get Justice A 220 How Start Value Is Equal To And Grading Target Written This Is Otherwise Understand Which Know What We Can Do Limited's Sony Vaio 1020 Clear sell na agar option a 17 value ishq teen internet stand with side will start from the target of target weekend weather they can divide by two and weekend in one in the target to 200 years with heavy and straight 11021 number will divide to difficult models new Meaning Target Is Target That Is And So Will Divide Target By Two And Will Be Equal That Hanuman Wedding Won't Be Doing Band Is Operation Vijay Doing So They Are Adding One So Much Time Will Do I Will Not Be Operational Hair Initial 087 Treatment By One and all will divide distance by two files of five 10.25 m 10.25 m 10.25 m i 9 may targets pipe and frequency of the school will go on again and starts from line for twelve thirteen is not greater noida will not be the case against target models to is it even Look listen will go on air key and one plus will white one in the target bcom part plus one six key in operation increment by one vihar wedding dance that nav bank whatsapp khol do with this note scientist great dane to get started 300 will again Receive 152 And Will Get Than Any Rate Operation Will Increase Height That Note 3 To 4 Digit Sunao Chart Value Is Equal To Target Twitter Adi And Will Determine The Case And Will Return The Ek Saree Wali Should Be Which Is The Question Read So Software With U Tuition fee was towards O in ILO inside Surta Vrat Yuvan scientists Kiss this vitamin is a bus stand and for time taken on any wall also time complexity of yes man what they are doing Bihar dividing every time to get back to right show in its frequency Of all it's might get divided divide to and 128 hear daily begum life horizon and target is award 1818 vitamin e that they choli every time e wake up even will divide by to software time activity log off a minimum dividing back to time liquid off and on Paste Complexes If you stop in conflict then only return Vanity van Here's what will happen when start Vyat Internet Vikram 33 - Internet Vikram 33 - Internet Vikram 33 - 300 basis will give 08 Will be a great way to hear someone please for that time Speakers call rate 108 Vikram and navigate and similar you Problem fixed as per benefits of Will Get 300 but they do subscribe my channel I will be
Broken Calculator
array-of-doubled-pairs
There is a broken calculator that has the integer `startValue` on its display initially. In one operation, you can: * multiply the number on display by `2`, or * subtract `1` from the number on display. Given two integers `startValue` and `target`, return _the minimum number of operations needed to display_ `target` _on the calculator_. **Example 1:** **Input:** startValue = 2, target = 3 **Output:** 2 **Explanation:** Use double operation and then decrement operation {2 -> 4 -> 3}. **Example 2:** **Input:** startValue = 5, target = 8 **Output:** 2 **Explanation:** Use decrement and then double {5 -> 4 -> 8}. **Example 3:** **Input:** startValue = 3, target = 10 **Output:** 3 **Explanation:** Use double, decrement and double {3 -> 6 -> 5 -> 10}. **Constraints:** * `1 <= startValue, target <= 109`
null
Array,Hash Table,Greedy,Sorting
Medium
2117
107
hey guys welcome back to my channel and i'm back again with another really interesting coding in today guys we are going to solve question number 107 binary tree level orders reversal part 2. before i start the video guys just want to request you that if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for notifications of more such programming related videos let's get started now with the problem statement so basically guys we are given a root of a binary tree and we want to return the bottom of level ordered reversal of its nodes so generally guys if you have seen a level or a reversal it is like you have the nodes by their levels so on the first level you have got note 3 second level we have got nodes nine and twenty the third level we have got nodes five fifteen and seven so we are traversing nodes by their level and we are printing their values by their level but in this case we have to print them bottom up order okay so basically if this is our tree then i have to print the last level first which is 15 and 7 then i have to print the second level which is 9 and 20 and finally the third level which is 3 okay uh another example here guys if the root is null you have to return a null list uh empty list if the root is only one single node you have to return only one single node constraints are pretty straightforward the number of nodes in are in the range of zero to two thousand value goes from minus one hundred to plus one sorry minus one thousand two plus one thousand so uh i hope the problem statement is cleared you guys now let's jump to the solution part of it so uh just a little bit of information about the solution approach so basically guys what we are going to do is we are going to do a classic level order traversal uh using our uh cube okay so we are not going to do any recursion here we are actually going to use a queue uh to actually uh do this sort of solution so what we are going to do guys at every level i'm going to maintain a queue and that queue is going to have all the nodes in that particular level so for example uh let's take if this is my tree and this is my queue so on the first level this queue is only going to have one node uh sorry one node which is going to have value three right then we'll go further up in the next step or in the next iteration i'm going to get three outside this queue so i'm just gonna pull three outside from this queue and in the next q value i'm going to put the uh children of the node three so the children of node 3 are 9 and 20 and what is going to happen with 3 is that my result set is going to have is going to be a linked list and i am going to append 3 value or the level which i picked up on the front of that list okay so if this is the list which i am going to return so let's say the result was empty uh on the first iteration in the second iteration i am going to put this uh q value this three value on the front of the result so three will become in the front okay now on the next iteration the q will have the children of 9 and 20 bones so because 9 doesn't have any children it is going to have the children of 20 so now the q is going to have 15 and 7 and i am going to append the previous 9 and 20 value to my result but this time i will append those results to the front so my results are going to be 9 comma 20 and then 3 is going to automatically shift uh back because i am just putting the results on the front okay just keep this in mind that this is going to be a result which is of type linked list because we have got a list here so uh you know appending any element on the front is not going to have problem it's just order of one in case of linked list okay so you're not uh doing anything which is heavy in time complexity fine now in the last iteration what's gonna happen is that your queue is just going to become empty and i'm just gonna uh append 15 comma seven node in the top of my result list and finally when there are no more nodes to process in my queue i'm just gonna return the result which is going to be the result that we expect okay so that is the classic level order traversal guys and the only difference is that we are appending the results uh in the result linked list at 0th position or at the front so that all the elements are shifted towards the back and that's how we get a bottom-up back and that's how we get a bottom-up back and that's how we get a bottom-up reversal okay so now that the solution is a bit clear to you let's jump into the implementation part of it so let's quickly create the variables which we need the most first variable is my result set so this is going to be result linked list and then the second variable is definitely the queue which i'm going to use to store my nodes tree node i'm gonna call this q and this is also going to be a linked list now the first thing i'm going to check if my root is equally personal because if my root is null then i can just simply return an empty list so i can simply return the result as it is if the root is not equal to null then obviously uh to start iterating from my q i have to first uh put some values into it so q dot add the root node now i am going to start reversing my queue while q dot is empty is false so until my queue is still having some nodes i'm gonna start hydrating them because i want to process uh all the nodes in the queue at that point of time uh i can only do that i don't wanna like i don't wanna uh take all the loads in the queue at one point of time i only want to take those nodes which are at a particular level and how do i determine the level by the size of the queue so at one level you can see that at one uh level my queue size is going to be the number of nodes on that level okay so because at this level the queue size is only uh one so three is the only node i'm going to have to process and at this level the queue size is two other and so on right so i'm going to create a variable called as integer size and this size variable is going to have the value of q dot size now i'm going to run a for loop for integer i equals to 0 to i less than size i plus and now i am going to keep start picking out elements or removing elements from the queue okay so tree node becomes equals to q dot pole remember i will only remove uh the elements which are in that particular size range right so now that i have picked up this one node so let's say uh on the first node i picked up was three because my queue was only having the first head node then what i'm gonna do i am uh going to put this uh thing in a temporary list called as result set okay so what i will do before i start this inner for loop i will also actually create a temporary integer list because you can see that my result list is a list of lists okay so this is a temporary integer list i need to create so let's create the temp result temporary result becomes equal to linked list so when my inner loop will go and start iterating on nodes from 0 to the size of the queue then i'm going to get the node outside the queue pull the node outside and then just add its value in my temporary result so temporary result dot add node dot valve okay so let's say now i have got three in my temp result right now i'm just going to check if node.left now i'm just going to check if node.left now i'm just going to check if node.left is not equal to null that means here you can see that 9 is not null then i'm just going to add this in my queue q dot and no dot left so next i'm just gonna do the same for node.write node.write node.write what's gonna happen this uh by this is now that i have added left and right nodes in my queue i have prepared my queue to be iterated for the next level right now you can see that my queue is having nine and twenty and three i have popped out okay because i did q dot poll so three hours for i have popped out three is now in my result set that means my temporary result is now having three value and now q is having nine and twenty so when i will go in this for loop again uh sorry now the for loop is over because it is only until 0 to size so now when i go to the outer loop again i will recalculate the queue size now q is having two values so q size will become equals to 2 and now i will again i trade these two values and put them in the result okay uh where do i put those in my result obviously i have calculated result right so once you have calculated the temporary result your duty is to actually add that temporary result in your main result list at the zeroth position okay so add this in your result set at the zeroth position so when you go into the next iteration now your temporary result is going to have 9 and 20 values and then you will add those 9 comma 20 values in the main result at the zeroth position okay so this is why you maintain a temporary list you gather all the nodes of the level and then use that list to simply add those values in your main result which is the list of list okay finally in the end return that's done now let's run this code guys let's see if this works for our uh our question and uh sorry there is an error here um what's the error okay let's try again oh yeah that's my bad because it's not a list of the different method of removing element but q has a method called as pole so i'm gonna declare it as q because q always removes the element from the uh from the first position okay you can see that now my solution is accepted and this is going to get submitted as well and there you go it works talking about the time complexity guys the time complexity for this solution is order of n because we are iterating each node only once we take one node we process it we put its children in our temporary list and then we move forward so that's why one node is only processed once that's why the time complexity is order of n where n is the total number of nodes in the tree uh space complexity here guys phase complexity is also order of n because we are using a queue of three nodes and at one point of time my queue is holding certain number of nodes uh at a particular level so that's why the space complexity here is also order of n okay uh so that was the video guys and that was the solution i hope you guys like the solution i hope it was clear to you if you have any questions comments regarding the solution please write down in the comment section below and definitely uh would answer them and if you have any further solutions to this particular question feel free to post them so others can benefit from that as well uh just like the fact if you do like this video guys if you did help me then please do not forget to like this video and share this video with your friends if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications thank you so much for watching guys i'll see you guys in the next video until then take care and bye
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
21
given two sorted linked list hulk' merge given two sorted linked list hulk' merge given two sorted linked list hulk' merge them into one sync result a linked list and return the new hat that's today's video let's get into it why my name is Steve today we are going through a little problem 21 merged two sorted lists let's take a look at the problem very classic merge two sorted linked list and retain as a new list the new list should be made by splicing together the notes of the first two lists so given these two lists once you've one two four one three four the merged new sought a linked list should be one two three four so it's still started first and we'll go through the iterative solution and in the next video we'll go through the recursive solution generative solution so just think about the problem suppose were given these two linked lists 1 2 3 5 X and the second linked list is 2 4 6 is the channel how can we merge these 2 sudden linked lists into your one such a linked list so this is the given input l1 and l2 is just a 2 linked list ok so we'll use that l1 and l2 these two linked lists and then four linked lists a very typical trick is that we'll initialize in Demi hat or a fake cat or whatever you want to call it so I'll just quite previous no and also well assign previous node to in the current node and we'll use the current no to iterate through the two linked lists so first step what we're going to do in the iterative solution is actually in both solutions iterative and recursive will always compare l1 and l2 you see which one is smaller right we always care we always want to splice the smaller one with the current node to be the current node next pointer pointing that right so what comparing l1 and l2 first in this case l1 is 1 l 2 is 2 L 1 is smaller than l2 so well used this the note that is pointed by l1 to be the current dot next that's this line next step will released after we do that so l1 is assigned to be current node and this point this note is sort of merged into the final result already so at this point what we'll do is that will move the l1 next pointer towards right assign l1 done next to l1 so l1 moved next step is that we'll move current caret dot next assign current our next two words current that means we'll keep moving current towards the right well current will always hold the position where it's next pointer should be merging wins whichever one is smaller in between l1 and l2 then next step well compare l1 and l2 again so this is the slice that we just went through and have just finished the first generation what we did is that we'll just keep comparing l1 and l2 you see which one is smaller and then we'll merge that one into the current node dot next and then we'll keep moving which everyone had gone merged in the last iteration towards the right and then we'll keep moving current as well this is the second one this is the second generation we'll keep comparing L 1 and L 2 u so l1 is now pointing and a note with the value 2 so 2 equals to 2 so in this case it doesn't matter whichever one we want to take right so we'll just take the second one coming down next is pointing to the node pointed by l2 next step we'll move out to since this note is merged into you in the final result we'll move out to towards the right and then move current as well so current will be moved here this is the second iteration now we're done third iteration what compare we're just keep can so you see at the end of each iteration in the l1 all out you will need to move towards the right so beginning this is the beginning of the third iteration l1 l2 they're pointing at these two notes would you comparison team and for two in smaller so then current our next will be pointing to the smaller one and then we'll move l1 and then we'll move current now this is done for the third iteration now we'll compare these and one and out to you again well just continue to go through in the end of it so that we can see how the code actually gets executed now come here l1 and l2 your game which one smaller l1 is smaller so well I sign this one coming down next to L 1 and then l1 moves towards the right current move towards right so this is the end of the fourth narration now let's see beginning of the fifth iteration will compare l1 and l2 again so in this case I don't use monitors so we'll assign this one coming down next to l2 now l2 is moved so we'll need to iterate well move l to towards the right now l2 is here this is done with the fifth iteration or I also move current to here and then we'll compare l1 and l2 again l1 is smaller in this case so we'll assign current down next this pointer pointing towards five that's it and then well keep moving so in this case we merged and the note pointed by l1 towards the final result so we'll move l1 to the right and now l1 is pointing at now that's the end of it so in this case whenever we get into the case when either l1 or l2 is pointing at a now note that means we have finished even if either l1 or l2 and then at that point we can just point current on next towards which everyone is still has some remaining notes but in that case were just assigned current on next tourists whichever one is remaining in this case in this example is Al to you so what just assign the current node that's pointed out by l2 toward to be in the current dot next that's it at this point we'll just return pre-done at this point we'll just return pre-done at this point we'll just return pre-done next remember we have created a fake dummy node called pre and pre dot next is pointing at the new hat right so we'll just return pre done next that's the end of the iterative solution we're done so let's see here 1 2 3 4 5 6 now this is the so after this generation we have merged the two sorted linked lists into one and written the new hat all right that's the idea the time complexity of this algorithm is o m+ o m+ o m+ in M and n beyond the two lengths of the two commandment list because anyway we have to go through the two singly linked to list time complexity is just oh one we are not using any actual memory or we're not using a recursive function so it doesn't have any call stack all right now let's put this idea into the actual code let's see how that is going to play out in the actual code let me copy this note 3 and there was just as initialize the dummy node and then we'll have another one called current and assign previous to be current so while the code will have a while and we why or l1 not equals to now and l2 not equals to now in both cases remember we need to check if both linked lists and not now if either one of them is now we can just assign whichever one is not now towards that current done next then we're done right so in the one what we were check is when the l1 and out both of these two and not now in that case what we'll do is if l1 done since both of them are not now we can safely assume we can safely access well we don't need to worry about it throws null point exception l1 smaller than L 2 well if this one is smaller what will do is that will assign so see what we did here is that this is the very beginning l1 is phone and then out you what we did is that we assign current dot next to l1 right that's the first time so assign current dot next to l1 this is the first step second is time origin is that we move l1 twist the right so in actual code that's going to be looking like this we assign l1 done next to BL 1 because we have merged l1 into the current node else so remember we can put smaller than all smaller than or equal to or you could put either way so that's fine because the same methods and could come from either linked list that's fine in other case that means if L 1 dot val is greater than or equal to L 2 dot well or who can do what I do is that well in that case what we should merge is out you into you next L 2 and then keep moving out to towards the right L 2 dot next all right this is what we did and then so back to you this example after we move L 1 towards the right what we need to do is that will also move current towards the right this is the point where we should merge in the one of the linked list node into right this one this current node will keep moving as well so what we'll do here is current dot next that's it and then we'll just keep doing all of these operations all of these iterations until when until either one of these linked lists the nodes are pointing at a now node at that point in this case it's this L 1 is pointing at now at this moment right what we would do is and that means if either l1 or l2 and now that means this wall condition will not hold then we were just to break out at that point what we will do is that will assign current dot next to what to whichever one is not now l1 equals 2 now if that is the case then we'll just assign l2 otherwise we were just assigned l1 right and then in the very end what we'll do is we'll just return premise but next that's it that's the final result that we're going to return right here predock next we just return print our next this is the final position of the current node and the final position of in the l1 or l2 is over here that's the idea now let's hit submit and see line 13 what is this our to not equal to now oh no space it's a minute game this is the iterative solution I hope this walkthrough will help you understand how the iterative solution how do you merge the tuning to sought a new place to work if you like this video just do me a favor and destroy the like button peace I really appreciate it and also don't forget to subscribe to my channel we're now going through a linked list series after this we'll go through three problems and then priority queue and then a different combination of data structures and algorithms to help people better understand and better prepare for their upcoming coding interviews really appreciate that and also hit the little bell notification so that when each time I publish a new video you're not going to miss out on anything see you guys in the next video
Merge Two Sorted Lists
merge-two-sorted-lists
You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. Return _the head of the merged linked list_. **Example 1:** **Input:** list1 = \[1,2,4\], list2 = \[1,3,4\] **Output:** \[1,1,2,3,4,4\] **Example 2:** **Input:** list1 = \[\], list2 = \[\] **Output:** \[\] **Example 3:** **Input:** list1 = \[\], list2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in both lists is in the range `[0, 50]`. * `-100 <= Node.val <= 100` * Both `list1` and `list2` are sorted in **non-decreasing** order.
null
Linked List,Recursion
Easy
23,88,148,244,1774,2071
318
welcome to mazelico challenge today's problem is maximum product of word lengths given a string array words return the maximum value of length words i times length words j where two words do not share common letters if no such two words exist return zero so this is the key here we need to figure out how do we figure out uh whether two words share common letters or not the rest i think we can just do straightforward and do a nested loop compare the two words together uh all the different combinations anyway and then if they don't share any characters together then we'll calculate the length times length of those two words and see if it's greater than the maximum that we calculated so far so one way that we could think about how to compare two letters is say we had abc and i don't know d f uh the simple way to do that is just make this to a set right if we make these into a set then we could just figure out if there's any overlap if we do an and for these two words that's going to tell us whether there's some sort of overlap and if there isn't any overlap then the resulting thing will just be an empty set so if it's an empty set that means there's no overlap then we should calculate the product of the length of both of these two and see if it's greater than maximum so to do this what i'll do is first create a lookup and i'm going to make this a default dict with set being the default key oops okay all right so now let's first calculate the sets for all these words 4w in words look up words it's just going to be a set of all the words or all the characters inside the word now all i have to do is say all right for i in word and for j in words uh let's figure out a way to compare if they don't share okay if they don't share any characters i and j then we're going to calculate uh the length of these two and see if it's greater than the maximum so we start with the maximum of zero and we'll say okay max equals max of max and the length of i times length of j okay finally we just return the max but the key thing is we want to figure out how do we write a function to compare these two so if they don't share let's see don't share we're passing two strings and what we'll do is we'll say if look up word and remember these are sets look up t if they share if something is inside there then it's going to return to false right otherwise return a true okay so this would be the easiest way let's see if this works w for j and words a lot of typos today must be feeling pretty tired all right so that looks like it's working so let's go and submit that and that works so time complexity is going to be n squared uh times the length of the character characters on the other side of words we'll call it m so n squared times m and we do use oven space because of this look up here now you could make it a little more efficient by using bitwise rather than using a set what we can do is say for like a b c for instance each one of these could represent an index number inside of our bits so if we had these three here like this would sit uh the first one would represent an a that would be like one uh set one works in the b c like this and we only have 26 characters so at the very most we'll have some sort of bitwise to like represent uh all whoops all the characters inside of that exist inside of our string and then we can just do an and um and compare it to another string and see if it equals a zero because if it goes zero that means nothing is shared right so we can also do that let's see how would i do that though um okay for that i would have to make this an int and i would get the word and say for each character inside of the word uh we are going to let's calculate our bitwise so let's start with zero and we'll say for what cnw do is bit w we'll do an or operator and we will get the ordinal of the character because each one of these characters represents some number and a equals 97 i believe so we want a to equal the zero index and b to equal the first index right so we can just subtract 97 here we'll subtract 97 and then we'll do a one operator to get the bitwise or i'm sorry one shift and then we at the end this bit wise should be the word so everything else should remain the same we can just do an and if this is uh if something exists here this would be not zero right otherwise if it's zero then we turn it true so this should also work let's see if it works oh what do i do here god i'm all over the place today i apologize let's see if it works okay so that works too and it's going to submit it accepted so time complexity and space is actually the same it's just that we actually i think we might save a little bit of space uh because it's not a set anymore it's going to be in just a bit right so we save some space but time complex is going to be the same so it just really depends on whether you're you know comfortable with using bitwise i personally am not so i'd rather just go with the set but it's up to you all right thanks for watching my channel remember do not trust me i know nothing
Maximum Product of Word Lengths
maximum-product-of-word-lengths
Given a string array `words`, return _the maximum value of_ `length(word[i]) * length(word[j])` _where the two words do not share common letters_. If no such two words exist, return `0`. **Example 1:** **Input:** words = \[ "abcw ", "baz ", "foo ", "bar ", "xtfn ", "abcdef "\] **Output:** 16 **Explanation:** The two words can be "abcw ", "xtfn ". **Example 2:** **Input:** words = \[ "a ", "ab ", "abc ", "d ", "cd ", "bcd ", "abcd "\] **Output:** 4 **Explanation:** The two words can be "ab ", "cd ". **Example 3:** **Input:** words = \[ "a ", "aa ", "aaa ", "aaaa "\] **Output:** 0 **Explanation:** No such pair of words. **Constraints:** * `2 <= words.length <= 1000` * `1 <= words[i].length <= 1000` * `words[i]` consists only of lowercase English letters.
null
Array,String,Bit Manipulation
Medium
null
48
hello everybody so in this video we will be looking at the lead code problem 48 that is rotate image so the problem statement states that we will be given a matrix 2d matrix of size n cross n so we'll have n cross n matrix and what we have to do is that is representing an image and we have to rotate this matrix by 90 degree so you have to rotate the image in place so we don't have to use any extra space and which means that we cannot modify so if i see we are given this example so what we have to do is we have to rotate it in such a way we have to rotate this matrix in such a way that we get this matrix so this is what we have to do so how we will do this if we observe the first row here that is one two three we can see it is the last column in our answer matrix then the second row here is the second last column in our answer matrix and the third row here is the first column in our constant matrix so what we can say is if i say this is my matrix a this is my matrix b so i can create another matrix b and what i'll do i'll traverse through this matrix and for each row i will insert the row in the last column of this matrix so for zeroth row i'll insert it into n minus one for first i'll insert it into n minus two for second i'll insert it into that will be zero here so this n minus one represent two this represents one and distribution zero that is how i will do and the time complexity for this will be of n square because we will be traversing this matrix and the space complexity will be also of n square because we will be using another matrix b to store this value so but the question states that we have to do this in place that is without using any extra space so how can we do this so if i take my example again so this is our example so how can we do this if i see this one is here so what if i transpose the matrix this let us just see what if i transpose the matrix so it is my matrix with three columns and three rows now let us just put in the values so if i transpose this will be one this will be four and this will be two this will be seven and this will be 3 this will be 5 this will be 6 this will be 8 and this will be 9 so now can we observe something now in this matrix the transposed matrix and this matrix the one which is our answer can we observe something yes we can what we observe is by this matrix in this matrix all the rows are in reverse from this matrix we can see it is one four seven here it is seven four one it is reverse it is two five eight it is eight five two it is reverse it is three six nine it is nine three six it is reverse so after transpose if we reverse each row we will get our answer matrix so that is how we can do this the first step is to traverse oh sorry to transpose the given matrix the second step is reverse each row so the time complexity will be o of n square for transposing the matrix plus another o of n square for reversing the rows so we will traverse for each row and reverse them and even if we use the stl reverse function it will take off and in the worst case so it will be of n square and the space complexity will be o of 1 that is a constant space because we are not using any extra space we are just modifying the array that is given to us so for the pseudo code if i write so my i will start from zero i will be less than n and i plus and my j will start from zero j will be less than i and j plus and what i'll do i'll swap my matrix of i j and my matrix of j i that is what we will do so this step is the transport step so let me write this so this is transposing so this is transpose then after that we will reverse so for reverse we will again traverse from i equals to 0 i less than n i plus we will do reverse this is hdl function in the c plus standard template library so what we will do mat of i dot begin and net of i dot and what this is saying is from the iterator this iterator will point to mat of i dot begin that is the first index it will be pointing to i of 0 and till the end of that row just reverse all these values so it will it is a reverse and it is also taking off n square and we will get our answer in the end so now if i code this so here we go i am given matrix i'll just take it as mac to save time now let us just get the size so size is mad dot size for end of i equals to zero i less than n i plus here what we are doing is first we will transpose the matrix and for inter of j equals to 0 j less than i j plus i'll swap mat of i j and mat of j i so i have done the transpose after that what i'll do now this step is reversing each row right so for end of i equals to 0 i less than and we will traverse for each row and we will reverse so our reverse mat of i dot begin not of i dot begin and net of i dot end we don't have to return anything so let us just run the code so it is working now submit it so as you can see it is submitted so thank you for watching the video and if you got it do hit the subscribe and like and see you all in the next video you
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
199
hey guys and welcome back to the cracking fang youtube channel today we're going to be solving lead code problem 199 binary tree right side view let's read the prompt given the root of a binary tree imagine yourself standing on the right side of it return the values of the nodes you can see ordered from top to bottom so we can see that if we have this tree here one two three four five we expect to get one three and four back so this unfortunately is the case of the leak code problem description being absolutely horrible which they have a very terrible habit of doing this they should really get someone to proofread these but um basically once you figure out what they actually want you realize that they basically just want you to return the value that is um right most in every single level so we can see one three four here and that's really all this problem um comes down to is simply finding the rightmost element in every single level as we can see here uh so once we know that basically you know we can just go level by level through the tree and if we're at the last element then we simply append it to our result so you know we would iterate um you know we'd use a q here because we want to use a level order traversal and typically use a cue with breadth first search to do that so you know we'd add one three and four so that's how you do it let's actually open the editor and i can show you how to implement that now that we're in the editor let's see how we're actually going to solve this problem so the first thing that we want to do with most of these tree based questions is actually check whether or not the root exists if it doesn't then there's nothing to process so we can simply return our base case here which is going to be an empty list because the problem asks for the values of the nodes right and it expects a list so if the root is empty so we're going to say if not root we can simply return an empty list right so like i said in the explanation portion what we want to do is a level order traversal and typically the way that we do this is going to be with a breath first search and to do a breath first search typically we use a q so let's define our q and we're going to initialize it originally uh with the value of root and what we want to do is we want to process the entirety of our tree so we're going to say while q so basically while there's still something to process what we want to do is actually oh and apologies we're actually going to need a result here to actually store the values of our notes when we do a level order traversal typically if we want to process only one level then we need to set a loop inside of our while loop to basically only process elements on that level so typically what we do is we're going to say level length is going to be whatever the length of the queue is when we entered this iteration of the while loop so we're going to say level length equals length of q and we're going to say 4i in range level length and the reason that we want to do this is that we only want to iterate over the current level and the reason that we're actually tracking i here is because when i equals to level length minus one then what we wanna do is actually append whatever that note is into our result because that represents the very last element in our um level here so we're going to say node equals q dot pop left and me personally i like to only put non null nodes into my queue so that way i don't really have to check whether or not the node that i just popped is uh null and then i'll just do the checks on the children you can do the other way around i just prefer to do it this way it doesn't really matter it won't affect your code uh that's just something to um think about so we're gonna say if i equals to level length uh minus one so basically this is when we're at the very end of our level we want to add that node's value to our result because that's the right most value on that level otherwise you know we don't do anything there because it's not the rightmost now what we need to do is add the left and the right children so we're going to say if node.left so basically if the current node.left so basically if the current node.left so basically if the current node has a left child then we want to append it to our queue so we're going to append node.left and we're going to do append node.left and we're going to do append node.left and we're going to do the same thing for the right so if no dot right we're going to say q dot append node.right append node.right append node.right and that's really it to be honest at the end all we need to do is return our result and we're done so let's submit that and make sure that it works and we see that it does cool so let's think about the time and space complexity of our algorithm so when you're performing a level order traversal you need to iterate over every single node in the tree which means that time complexity wise since we're touching every single node in the tree this is going to be an o of n solution right we're going to have to touch every single node and you know it's o n because we literally just go over every element uh so this is a linear solution space complexity wise um the maximum amount of elements that we're gonna store in our queue could potentially be the very last row of our binary tree if it's completely full that will be the most elements that we're ever going to have in our tree which is dependent on the size of our tree so this is just going to be an o of n solution um you know asymptotically so that's our time and space complexity if you enjoyed this video please like comment subscribe please check out my other videos if you're preparing for your on-site interview and have a nice your on-site interview and have a nice your on-site interview and have a nice day
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
1,942
so hello everyone welcome to this new video and in this video i will be solving the problem 1942 the number of the smallest unoccupied chair so this problem is not that difficult uh all you have to do is sorting so first we will just understand how to approach this problem and uh then we will quote it so one thing i hope you have already read this problem uh so one thing i always look for in problems whenever i solve the problem is that i see that the time complexity the value of n so here the value of n is with uh at boo can go up to 10 raised to power 4 so this gives me one hint that i can do it in n square time okay n square time complexity uh so let's get into the problem so let's understand the problem from this example so here i have been giving the arrival and departure time of friends so let's write it down here in sorted manner like the time of arrival i will tell you why you will understand yourself why that is necessary so let's write down so let me select the pen and then the first one will be one two three then another one will be i think what three one two five ten uh two to six one two just one two five then two six and then three to ten so we will also have to track that which friends are these after sorting uh so one two five is uh going to be the friend number zero this friend is going to be the friend number two and this friend is going to be the friend number one okay now you are given that there are infinite chairs so but how many chairs if there are 10 friends then at max the number of chairs that can be occupied is going to be 10 okay so let's make a array uh it can be more than 10 but you know only three chairs will be occupied like because we have only three friends are there so let's name these chairs zero one two three four and since initially all chairs are empty so i will just name them let's say minus one so let's continue naming them with -1 so let's continue naming them with -1 so let's continue naming them with -1 so initially all are unoccupied so they will be minus 1. now what happens is that friend 1 comes a friend number zero he will come at one second and what he will do is that he will occupy this chair and set that we will set the time that this chair will get empty at time five then we will move to this friend will come at two he will uh so now we will check can is the zeroth chair empty now so the answer will be no because uh it will get empty at five so i will occupy the chair number one uh at and i will set its departure time as six now i will come here at three i will see that okay all these shares are empty so i will mark my timing here as what uh 10 because it will the third friend the friend number one will occupy this chair and will this chair will get empty at 10 seconds so let's suppose if there was another friend who was going to come at let's say 8 and was going to leave it let's say 10 8 and 10 uh what have i written okay so what will happen is that uh we will check that we will see that this zeroth chair i will see that okay this five is less than eight so this person would have left by now so i can occupy this chair and this chairs uh will be occupied by this friend uh let's name it let it be the fourth friend and this will become what uh 10 because uh like it will get vacated at 10. so this is the approach so you know you are seeing that the time complexity is going to be n square uh n for this and n for this but you know this will get uh this will break in between because uh suppose the target friend is one then my loop will never go to this entry so now let's move to the coding part i hope you have understood the approach and if you have understood the approach please like the video and subscribe the channel because liking will help people identify that this video is useful so they will watch it so now let's uh so the first thing you have to do is do the sorting part so that is the main thing so for sorting what i will do is that just okay i will just sort using a pair vector i will make another vector and uh let's say let's name it mv and that vector will not be of int type it will be a pair of pairs you will understand why so pair of int comma uh okay so this is the let this vector be called mv so what this vector means is that i'm see i have to track this also 0 and 1 so i am creating a vector which is going to be going to look like this let this be one is going to be the arrival time and another pair will have the departure time and the friends number okay he is the zeroth friend so this will look like this so another will this be two and this will be the departure time and this will be the friends number okay so then when we will sort when we sort in pairs it sorts on the basis of the first entry so this can be a learning for you if you don't know uh it will sort on the basis of this number initially there will be some random let this will be 2 and this will be 1 and so on this will also be changed so this is going to be the structure of my vector now let's fill this vector so for int i is equal to 0 i less than what let me just make another variable in n is equal to times dot size and let this be n i plus and then we will go below and we will make a pair of int pair or just list let's just copy this one part okay this much copy and then i will paste it this is just so that i don't understand accidentally and for you to understand p is equal to what so p will have a structure like this times okay times i zero so this will be the arrival time and there will be another pair in this so this will be times i 1 this will be the departure time and this and now it will be i will be the friends number so now what i will do is that mv dot push underscore pack i will push this p into my vector so now i have push test now what i have to do is sort it so sort mv dot begin comma mv dot end so this will get sorted so now whatever initially it was in times array it will become sorted like this one okay now it is pretty simple so i will make another vector so it will be vector int chairs let it be chair okay chair uh n comma let's say minus 1 so minus 1 means that it is initially 0 and the total number of chairs are n that is equal to the number of friends so now i will write a for loop so for entire is equal to zero i less than n i plus and for the current friend that i am i will just write some variables let's say the friends arrival time will be what uh mvi dot first so how you choose in a pair is that f m v i dot first means this is the first p dot first this is the first okay now departure time will be int departure is equal to mvi dot uh second dot first so second means that in the pair this is the second element and in this does that second element is also appear so in that second element this is the first one so this is how it goes and it will be the friend so now it will be friend number so the friend number will be what exactly this thing copy paste and this will be what second copy paste so now i have all these things now i will write another for loop for int j is equal to 0 j less than n j plus so now i will be iterating the chairs so if chair j is less than equal to arrival okay so i am seeing a particular chair that uh the thing that happened here suppose a guy comes here at let's say 12 seconds he will see that this 10 is less than 12 so this chair is available actually so this is what i am actually checking so initially minus one it's with every share will be available so if share is less than arrival then i will set the chair j is equal to the departure time of the current guy departure and i will our story will end if the friend number is equal to target friend so the answer that the question is asking is our current friend number then i will just return the chair number that is j uh and that's it and one more thing well i mean if you ignore this let's say ignore this let's cut this so once you have set the chair you don't need to traverse into this for loop any further so you will just break once you come inside this loop now let's paste this ctrl v and in the end you have to just return something let's say return zero uh this is uh you will never come till this point you will always return here so that's the problem now let's test if everything is working fine i hope i don't do any mistake so this seems to work fine now let's submit it okay it got submitted you know it is a little bit so this can be a homework on your part so what uh where this problem can be optimized is that uh see i am just iterating this for loop okay so you can study on your own that this i am see i am just going on this all along okay so there may exist i'm not sure but there may exist a method there should exist that i won't have to iterate all the way up i will have some kind of tracking mechanism that will always point me to the next uh best chair that is available so you can read the discussion part i haven't read it so that's it that's the problem for you uh so if you have understood it please like the video and subscribe the channel so thank you and have a nice day bye
The Number of the Smallest Unoccupied Chair
primary-department-for-each-employee
There is a party where `n` friends numbered from `0` to `n - 1` are attending. There is an **infinite** number of chairs in this party that are numbered from `0` to `infinity`. When a friend arrives at the party, they sit on the unoccupied chair with the **smallest number**. * For example, if chairs `0`, `1`, and `5` are occupied when a friend comes, they will sit on chair number `2`. When a friend leaves the party, their chair becomes unoccupied at the moment they leave. If another friend arrives at that same moment, they can sit in that chair. You are given a **0-indexed** 2D integer array `times` where `times[i] = [arrivali, leavingi]`, indicating the arrival and leaving times of the `ith` friend respectively, and an integer `targetFriend`. All arrival times are **distinct**. Return _the **chair number** that the friend numbered_ `targetFriend` _will sit on_. **Example 1:** **Input:** times = \[\[1,4\],\[2,3\],\[4,6\]\], targetFriend = 1 **Output:** 1 **Explanation:** - Friend 0 arrives at time 1 and sits on chair 0. - Friend 1 arrives at time 2 and sits on chair 1. - Friend 1 leaves at time 3 and chair 1 becomes empty. - Friend 0 leaves at time 4 and chair 0 becomes empty. - Friend 2 arrives at time 4 and sits on chair 0. Since friend 1 sat on chair 1, we return 1. **Example 2:** **Input:** times = \[\[3,10\],\[1,5\],\[2,6\]\], targetFriend = 0 **Output:** 2 **Explanation:** - Friend 1 arrives at time 1 and sits on chair 0. - Friend 2 arrives at time 2 and sits on chair 1. - Friend 0 arrives at time 3 and sits on chair 2. - Friend 1 leaves at time 5 and chair 0 becomes empty. - Friend 2 leaves at time 6 and chair 1 becomes empty. - Friend 0 leaves at time 10 and chair 2 becomes empty. Since friend 0 sat on chair 2, we return 2. **Constraints:** * `n == times.length` * `2 <= n <= 104` * `times[i].length == 2` * `1 <= arrivali < leavingi <= 105` * `0 <= targetFriend <= n - 1` * Each `arrivali` time is **distinct**.
null
Database
Easy
null
1,021
hello guys in this video I will solve remove outermost parenthesis problem from weed code so in this problem we are given a string of balanced parentheses and we need to remove outermost parenthesis from the string so what does that mean we need to remove brackets whose level is one whose depth is one so what I mean by saying depth is let's look at this example here are some parenthesis so the level of the first 2 is 1 the level of the third is 1 and the level of the fourth is to level of these two parentheses is to I mean the their depth is 2 the depth of this one is to the depth of this 1 is 2 and the depth of these two parentheses is 3 so we need to remove all of the parentheses which have depth of 1 so we need to remove these 2 and these 2 we can let's start solving this problem we will need in depth which is 0 at first then we will also we need string result who I trade or our string and if as I is an opening bracket we will increment depth by one else will decrement it by one okay now Oh check that is greater than zero it's greater than one no than zero then we will add this character or string now in its non zero so it's when we add the first bracket the depths would be one but we don't need it so but when we removed the deaths would be zero so let's do it this way let's place this if here let's place another if here foreclosed upon if you check if it's greater than one and who are turn resulting string okay it was accepted please subscribe to my channel and thank you for watching
Remove Outermost Parentheses
distribute-coins-in-binary-tree
A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation. * For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings. A valid parentheses string `s` is primitive if it is nonempty, and there does not exist a way to split it into `s = A + B`, with `A` and `B` nonempty valid parentheses strings. Given a valid parentheses string `s`, consider its primitive decomposition: `s = P1 + P2 + ... + Pk`, where `Pi` are primitive valid parentheses strings. Return `s` _after removing the outermost parentheses of every primitive string in the primitive decomposition of_ `s`. **Example 1:** **Input:** s = "(()())(()) " **Output:** "()()() " **Explanation:** The input string is "(()())(()) ", with primitive decomposition "(()()) " + "(()) ". After removing outer parentheses of each part, this is "()() " + "() " = "()()() ". **Example 2:** **Input:** s = "(()())(())(()(())) " **Output:** "()()()()(()) " **Explanation:** The input string is "(()())(())(()(())) ", with primitive decomposition "(()()) " + "(()) " + "(()(())) ". After removing outer parentheses of each part, this is "()() " + "() " + "()(()) " = "()()()()(()) ". **Example 3:** **Input:** s = "()() " **Output:** " " **Explanation:** The input string is "()() ", with primitive decomposition "() " + "() ". After removing outer parentheses of each part, this is " " + " " = " ". **Constraints:** * `1 <= s.length <= 105` * `s[i]` is either `'('` or `')'`. * `s` is a valid parentheses string.
null
Tree,Depth-First Search,Binary Tree
Medium
863,1008
1,838
hi today we're going to be going over the Java solution for lead code 1838 frequency of the most frequent element the frequency of an element is the number of times it occurs in an array you are given an integer array norms and an integer K in one operation you can choose an index of nums and increment the element by at that index by one return the maximum possible frequency of any element after performing at most K operations so basically what this question entails is that we are given a limited number of K's and that can and we can use them to increment any of these elements um that amount and we can like distribute it off we could like if K is equal to five we can increment one element by three one element by one and another one by one as well or we could put it all into a single element but basically we're going to use that to try to find a way to get the most amount of elements to be the exact same and we're going to return how what is the maximum possible ones we can do so for in this one we are given this array and five k's I guess to increment and so if we look at this the output the answer should be three which makes sense if we want to optimize this really we're only we're not going to increment the largest element we're only going to increment the ones less than it trying to get it to it like it wouldn't make sense to make this four or five because then we would have to make all of these a five as well whereas if we just left as a floor we just have to increment these two to get it to be a four so you know we would increment one by three to get us four and then two by two to get us four and so we used up our five KS and all four elements all three elements would be K so that's basically how it works let's look at this second example in this one um K is equal to 5 again and the biggest one we can make apparently is of size two so if we look at let's say this one right here we could increment this one by three to get both of these to be four and that doesn't leave us any room to like increment them again to get them to be eight or thirteen so that's where our two comes in and notice that we didn't actually use up all our case we don't have to another one I guess would be this one right here so four and eight we would have to increment to four by four to get us eight so we would get two eights and that's our two as our output and then this one right here where we're going to increment the eight by five so the only trick that comes into this is that we can you have to use the idea that we can only use K to increment we cannot remove elements trying to balance them out we can only increment them so how are we going to actually go about doing this so this um seems like a sliding window problem so what we can do here is that we can actually sort our nums so if we sort them so these ones are already sorted except this one right here these two are already sorted and it says that like we don't know if it's going to be sorted um they never specify that it has to be but if we sort them we can treat them like a sliding window problem so let's go over this sliding window um if you don't notice basically we're going to look at a certain window so like maybe two elements and then that window can grow so now we could look at three and it could also shrink so now we would look at these two but it's not like we're looking at every single subset the end of the window will always be increasing and the back of the window will always be increasing as well they cannot like um go all the way back or something like that so here if we imagine like a sliding window we can see we can increase it when we still have K's remaining and then we could decrease and then we could increase our anchor or end of our sliding window when we run out of them to eventually get a valid substring so for example if we're looking at this one right here um again we only got to increment them to be the highest element in that sliding window so if they're already sorted it's pretty easy to find out which is the greatest element so in this one the greatest element is one and there's only one element we don't have to use up any of our case so we could increase our window to now be one and two so here two is our greatest element so we want to increase this one to B2 so we could increment it by one and now our K remaining is four so we got still increment it so we all increment it all the whole way and now we want all both of these elements to also before so we could increment the two by two and then increment the one by three so that's how we and that uses up all our case and that's how we can figure out that um the largest subarray or the largest number of elements is going to be three let's look at example two um again we have one on its own that's the largest elements only one we have don't have to use any of them up so now we're gonna increase them to be one and four so here um we're gonna use up three of our case to get both of these to be four and now we still have K's remaining so we um it's still valid so we're going to increase again now we're going to look at one four and eight and here we're gonna have to increment our one and four to be eight so that's going to use up seven plus four that's going to use up 11 Elements which 11 K's which we don't have we only have a limit of five so that means we're gonna decrease our window so now it's only gonna be four and eight so with four and eight we can increment the four by four to get us eight um so that's valid and we still have K's remaining so now let's increase it to four eight and third teen and now we have to increment the eight and four to get us 13. so we're going to have to increment the eight by five and the four by nine and that's going to use up more than the amount of K's we have so we're going to decrease our sliding windows so we have it with 8 and 13 and then that we will use up five to make the eight into thirteen and so keeping track of the maximum length of the window between this whole thing the maximum length was only ever two so that's why we return two there were multiple valid uh windows but again the maximum length was only two so let's try with this one if we were to sort this we would get three six and nine and here our K is 2 so we would look at this one three we don't have to increment anything else since three is the greatest element and there's only one and then we'll look at three and six we have to increment the three by uh three to get a six and that's going to use up all our K so we have to decrease it and now we're only our Windows only six which means we don't have to increment anything we could start increasing our window so now we're looking at six and nine we have to increment the six by three to get us nine which is more than how much K's we have and so we will decrease our window so to just be nine and then by that time we've reached the end of the array so our maximum we've ever really got was only ever one so that's how we got the output of one so that's basically so let's go to coding it um so again I said that we're gonna first sort the array so arrays dot sort nums and this is gonna make it uh very easy for us to keep track of like okay what's the maximum element in this uh window sequence and then we could in increase the other ones accordingly and also we're not actually physically increasing these we're just going to calculate what it would be so and also since it's a sliding window we're going to have an INT Max that we're going to keep track of which Max is at most at the very least going to be one and also an eight anchor which is going to be zero and then a four and uh and I is equal to zero I is less than numbers dot length I plus let me make this a bit neater there we go and here how are we actually going to keep track of how many K's we've used up because here's the thing if we let's look at let's say this one if we have this we've used up three of our case but then when we increase it to this and you know we have to decrease our sliding window we have to figure out how many K's we have uh how many K's do we have to remove from that one because we can't just do one minus eight so what we can do is that we could keep track of it into sum and this sum is going to be basically the sum of all the elements inside this array so as we're going through it we're gonna basically see one we're going to increase that to our sum we're going to see a four we're going to increase that to our sum and then when we look at eight and everything like that we're going to increase that to our sum so at this point our sum is going to be 8 plus 4 which is 12 plus 1 which is 13. and then when we have to decrease it we can just subtract this one from our sum so Y is this useful well because we can figure out our case by doing the greatest element times the length of the array minus the sum since you could imagine if we do the greatest elements times the length of the array that is basically the amount um the sum if all of the elements in that array were equal to the greatest element so if one was an eight if four was an 8 and 8 is an eight so in that would 8 times 3 that would get us 24. and then what we can do is subtract that 24 we could take that 24 and subtract it from our current sum of keeping track of all these so that way we can figure out how much K's we have used up so as we're gonna go we're gonna increment our sum with the new elements as we as they come along and then we're also going to have a while loop that's going to decrease it's gonna first check to see is this window valid and then if it's not this while loop is going to start decreasing the window until it is valid so until nums of I times I minus anchor plus one since it's zero index minus sum is greater than K so this is exactly what I was just talking about so nums of I times anchor I minus anchor plus one so that's going to get basically how big how what would the sum be if all the elements were the greatest element in that sequence and then we're just subtracting our sum and so that should get us how many K's we need to use up and if that is greater than our available ones then that means we need to decrease our uh window and so what we can do is that we can now do some minus equals nums of anchor and then we're going to increase our anchor so we're going to increase it so it's shortening down the window and we're subtracting that from our sum and then after that um we have if it passes this while loop then we know that we have a valid subsequence or a sliding window so we could just update our maximum to be math.max between our current Max and math.max between our current Max and math.max between our current Max and also our I minus anchor plus one so this is just checking if it is greater if the current substring we have is greater then it will update our maximum and we're just going to return Max at the very end so let's see if this works okay great um now let's submit it oh great so that was uh frequency of the most frequent
Frequency of the Most Frequent Element
number-of-distinct-substrings-in-a-string
The **frequency** of an element is the number of times it occurs in an array. You are given an integer array `nums` and an integer `k`. In one operation, you can choose an index of `nums` and increment the element at that index by `1`. Return _the **maximum possible frequency** of an element after performing **at most**_ `k` _operations_. **Example 1:** **Input:** nums = \[1,2,4\], k = 5 **Output:** 3 **Explanation:** Increment the first element three times and the second element two times to make nums = \[4,4,4\]. 4 has a frequency of 3. **Example 2:** **Input:** nums = \[1,4,8,13\], k = 5 **Output:** 2 **Explanation:** There are multiple optimal solutions: - Increment the first element three times to make nums = \[4,4,8,13\]. 4 has a frequency of 2. - Increment the second element four times to make nums = \[1,8,8,13\]. 8 has a frequency of 2. - Increment the third element five times to make nums = \[1,4,13,13\]. 13 has a frequency of 2. **Example 3:** **Input:** nums = \[3,9,6\], k = 2 **Output:** 1 **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 105` * `1 <= k <= 105`
Calculate the prefix hashing array for s. Use the prefix hashing array to calculate the hashing value of each substring. Compare the hashing values to determine the unique substrings. There could be collisions if you use hashing, what about double hashing.
String,Trie,Rolling Hash,Suffix Array,Hash Function
Medium
null
746
so lead code problem of the day and here's the runtime error brings a solution for you just in case if you're new to our Channel I highly recommend you to subscribe the channel to get the daily updates on lead code Solutions so let's start with today's question that is minimum cost climbing stairs I'm going to solve this question in three different steps so I highly recommend you to watch the video till end so that you can come across a detailed solution for today's problem so what does the question says that we have given an integer array cost where cost of I is the cost of I step on this St one of the most important point to noce here that once we pay the cost we have the two option that is either we can climb one step or we can climb the two steps right for every step say for example I'm standing over here I have the two option either I can jump at one position or I can jump at two position and second important point that is I can start at index zero or I can start at index one there is no any bound that we have to start from the first index of my itself no I can start either from zero or I can start either from first index and at that what we need to return is we need to return the minimum cost to reach at the top floor so what does this top floor how to calculate the minimum cost let's check in detail now say for example this is my array and TF simply means a top floor so this is my top floor which is present after the end of my array right so this is not our top floor the top floor is present after the end of my array so what I will do is in the first scenario I will be starting from index zero right now since I'm starting from index Zer I have to pay that much amount of cost in order to jump so first of all I will pay the 10 Rupees to jump now I have two option that either I can jump at one position or I can jump at two position so what I will do is if I jump at one position again I need to pay 15 rupees so rather than jumping at one step I will try to jump at the two steps because at the end what we need to return is we need to return the minimum cost so what I will do is I will jump at the two steps over here so right now right from this position I came at this position so this we took a two jump right now still I'm not present in my top floor still I need one more jump so what I need to do is in order to jump one or two steps I have to pay this much amount of cost so again I'm going to pay 20 rupees and then I will jump One Step because I will reach on the top floor in just one step I don't need to jump two steps so what is the total cost required to reach the top floor that is I need 30 rupees right so what I did is I took the start from this position right I started from index zero now let me start from index one so we will check what will be the total cost to reach at the top floor if we start from index one so since I'm present at index one I need to pay 15 rupees in order to jump so I will pay 15 rupees now again I have two option either I can jump one step or I can jump two steps but here we can say that if I'm jumping One Step again I need to pay 20 rup in order to go at top flow so I will not choose to jump One Step because I need a minimum payment so what I will do is rather than jumping one step I can directly jump at two steps and reach at the top floor so I directly go over at this position so what is the total cost required to reach at the top floor 15 so here I took 30 rupees and here I took 15 rupees so what is the minimum of 15 and 30 of course it will be 15 so can I say that I need to start from index one in order to reach at the top floor in the minimum cost that is15 rupes so I hope so you understood the meaning of the question now let's try to analyze how we can derive or draft a solution for this problem now let's start with our analysis one so what does the question says that in our question we got two option that is either can I have jump one or I can have jump to say for example if I'm standing at this index I have the option either I can jump from this position to this position or I can jump from this to this position so I have the options or can I say I have the choices to jump and always remember that whenever we have the choice choices whenever we have the choices what com comes in our brain for sure the one thing that comes on our brain that is recursion because what we need to do is we need to car out both the choices in every single index from this position jump One and Two from this position jump one and two so we will carry out all possible choices on every single possible index so that at the end we can get the minimum answer right because we don't know from which position what jump I should take so that I can get the minimum answer so rather than searching for it what I will do is I will carry out all possible choices and I have two choices that is Jump one and jump two so from this position I will jump one and jump two again at this position I can jump one and jump two so all the possible choices whatever the minimum answer I get I will simply return that minimum answer so whenever we are dealing with the recursion always remember the three important steps so number first steps is Express in terms of index and the second important thing is carry out all possible stuff carry out all possible step and at the end what we need to return is we need to return the minimum answer right so these are the three important step that we need to follow in order to carry out the solution of this problem so let's try to check how we can derive the solution for this problem now as I told you that whenever we have the choices what comes in our brain for sure the one thing that comes on our brain that is recursion because what we need to do is we need to care out all possible choices at every single index that is Index this and this means at every index I'm trying to carry out all possible choices so one thing that came to know that I need a recursion to solve this question so how can I use recursion to solve this question the number one step is I need to express in terms of index what does it mean at every single index I will car out all possible choices right so I need to make use of indexes so here I need index second important thing is carry out all possible steps so we have two option that either I can jump one step or I can jump Two Step so what I will do is at every index I will jump one step I will jump Two Step again at this index I will jump one step I will jump two steps again at this index I will jump one step and I will jump two steps so at every single index I will carry out all possible choices and at the end whatever the answer I get from all possible choices I will simply return which is the minimum answer of it because in question they have asked the minimum cost to reach at the top floor of my array so I hope so you understood this now again we got the two option to start my questions with because what they have told us we can start either from my zero index or I can start from my first Index right so what we will do is we will get to two functions so function first this will contain my size of my array and I this will be my index and this is my function again this will be my size of my array and this is my index one so what we are doing here is we are starting from index0 and here we are starting from index one and then what we return is what then if you're calling these two functions simply what I will do is I will simply return the minimum of these two right minimum of these two so I will call the two function one is from index zero that is index zero and one is from index one so out of these two function whatever the answer I get from both the function I will simply written the minimum of it so I hope so you understood the little bit intuition of this question how we can solve this question now let's try to define the solution for this problem okay now let's try to define the solution so first of all we will be discussing of index Z because as it is mentioned in the question we have option that either I can start from index 0o or I can start from index one so for the first point we are discussing for index zero so what I will do is I will simply Define a function called as F this is my array this is my size of an array and this is my Index right and I'm starting from index zero so what I have two option right either I can jump one step or I can jump two steps which means I have the two choices so what we have decided is as it is mentioned over here at every single index we will carry out all possible choices so what we will do is since I'm standing at here I will carry out all possible choices that is Jump one and jump two again if I come over here I will have two choices jump one and jump two so at every possible index we will try to carry out all possible choices so simply what I will do is first of all I will declare a variable called as one where we will be taking one step and how much cost do we need to pay since we're staring at this index we know that in order to jump I need to pay this much amount of cost so simply what I will do is first of all I will pay the cost present at particular index and again I will be calling the function and how many jump I need taking first I'm taking first one jump right I'm moving from this to this which means I'm taking jump one so simply I will increase the index value by one again one more choices I have that is since I'm standing here I can take one jump or I can take second jump and since we to take the first jump now I have the option to take the second jump as well so I will declare the variable called as two right what does it two means this is two jump but the point is can we take this two directly say for example I'm standing at this position can I take the two index two jumps no because anyhow my top FL is present at this point let me show you as I told you that my top flow present at this position and say for example I'm standing at last index I'm trying to take two gems is it possible no because I'm trying to get beyond my top floor what does the question says that I need to reach at the top floor but from this position if I try to jump two steps I'm going beyond my top flow so I cannot jump two step if I'm standing at the last position so can I say if I'm standing at the second last position I can take directly second jump right so that's the reason why I need to mention a condition that my if my index is less than n minus one so what does it mean is I'm standing at this position because from this position I can directly go to the top floor right but from this position I'm trying to go beyond my top floow so then and then only I can take a second step and how many amount I need to pay index on which I'm standing so simply what I will do is I'll simply out AI again this is my size of array and now I'm taking the two steps so I simply increase the value by two because here we're taking the two steps and here we're taking the one steps and at end what they ask we need a minimum value so simply what we will return is we will return the minimum value right minimum of 1 and two now we will think about the base condition now say for example we are going Beyond this array right I'm standing at this do I need to calculate anything no because I'm already standing at the top floor of my therefore can I say if my index is greater than or equal to N I need to return zero because I don't need to pay any cost because I'm already standing at my top floor so this is the function that we calculated to carry out the answer from index zero can I say that for index one I need the same one just I place of zero I'm going to start from index one so this is the same function we will use to carry out from index one right simply in place of zero I will pass the index as one and I will carry out all the task because I'm starting from this position jump one and jump two similarly rather than starting from index zero I will start from index one so I have the option jump one and jump two and at the both the function when I get the both the function for index zero and index one I will return the minimum of it so I hope so you understood the basic solution of this question that is using the recursion now the problem is since I'm using the recursion there might be a possibilities of overlapping sub problems because what we are doing we are carrying out all possible choices and we are having more than one function call in the same function therefore there is high probability of getting the overlapping sub problem so once we are having the overlapping sub problems what comes in our brain the one thing that comes on our brain is for sure that is dynamic programming now let's try to implement this question using dynamic programming now this is the solution we discussed previously that is we will be having a same function but we will be calling it two times so first function is called for index zero and again I call the same function for index one and at then what we'll do is I will return the minimum of both to index so simply I will get the minimum of function that is a r i n and zero because this is starting from index 0 and again I will be calling the same function but only thing is I will be passing index as one so here I have passed the index one and here I passed the index zero because in the question it is mentioned that either we can start from index zero or we can start from index one so at the end whatever the answer we get from the both the function we will try to get return minimum answer of it so I hope so you understood the recursive solution for this problem but as I told you that it contains more than one function call therefore there's high probability of getting the overlapping sub problems right and there is one only one solution is present to get rid of overlapping sub problems that is dynamic programming so we will analyze how we can make use of dynamic programming over here from this function we can come to know that there are the three parameters I'm passing to the function which are those three parameters I'm passing AI which is my array this is my size of an array I'm passing the index and throughout these three parameters which is the parameter which is changing is my array changing no is my size of my array changing no but the point is my index is changing my index is increasing either by one or my index is increasing either by two which means can I say that my index is only a parameter which is changing which are the out of all three parameters because my array is not changing my size of aray is not changing only my index is changing right therefore how much DP we require 1 DP 2 DP or 3 DP how we will analysis this will analysis on the basis of number of parameters changing in my function so there is only one function parameter which is changing that is index therefore we will be having 1 DP right we will be having 1 DP now what is the maximum value my index can now since my index is starting minimum value from zero and it is getting to end at n minus one there therefore can I say that simply I need vector or DP of size n right I need size y or in Java you can simply declare this array of DP of size y right of size Y and what we will do is we will initialize all it by minus one so initialize all the value by minus1 and simply we need to add two sentences in our solution right so what I will do is I will copy out this same solution and I will add two new sentences just to make convert it into DP so let's check a DP solution for this problem so this is the DP solution so what I did is I you added one sentence if DP of n is not equal to minus one what does it mean is say for example I'm calling the function for index 3 and the value for this index 3 is already calculated and I have stored in my DP so why should I call the function once again and calculate the value for index 3 no because I have already calculated value so simply return that value I don't need to calculate it once again so I use this sentence and finally whatever the values I'm calculating I'm storting in the DP so that I don't need to get an extra function call and again calling the function for the value which is already been calculated so that's the reason why for every single calculated value I'm storing in the DP so that if in case we are getting the extra function call rather than calling it that function simply return the value for it so I hope so you understood the solution for this problems clearly I tried very well to explain you this today's lead code portion of the day now let's move on to the solution for this problem so this is the C++ and this is a problem so this is the C++ and this is a problem so this is the C++ and this is a Java code you can check according to the own convenience so what I did is first of all I calculated the size of my array right the same thing I did over here now what I did is as I told you that we need a DP that of size n and I have initialized to minus one the same thing I did in Java that I declared an array called as DP and I all initialized to minus one then see I have called this function two times one is for index zero and one is for index one and what I did is I simply return the minimum of it because what they told we have two option either we can start from index zero or either we can start from index one and at the end we need the minimum cost what I need is minimum cost so simply what I did I call the function for index zero again I call the function for index one and I checked which one gives me the minimum answer and I finally return the minimum of it so this is my base case as I told you that once I we reach beyond my array we have reached the top floor so I need to return zero because I don't need to return or pay any cost since I already reached to the top floor and again I here I checked is there any function whose value is already calculated and stored in my DP if it is I don't need to get a function call and again call or calculate the value for that function so I simply return the value which is present inside my DP then I took the first step and before taking the first step I paid the cost and I took the first step so since I'm taking jump one I have incremented my index one the same thing done over here similarly before taking the second jump I checked is it my index less than minus one because what I told you say for example this is my AR and I'm standing at index last and if I take the two steps I'm going beyond my top floor that's the reason why I need to make sure I'm present at second last index the same condition I checked over here and then I took the two steps ahead and at then what I did is I simply return the minimum of step one and minimum of steps two and before returning it I stored in my DP so that in future if in case I required that value once again rather than calling the function again and calculating its value we will simply return directly from the DP since it saves our function calls so this is the most easiest problem today we had in the lead quote problem of the day and I hope so you understood this question really well just in case if you're new to our Channel or you are liking the way I'm teaching you do hit the Subscribe button so that I can get motivated and give a much more better solution for you till then I'm signing off
Min Cost Climbing Stairs
prefix-and-suffix-search
You are given an integer array `cost` where `cost[i]` is the cost of `ith` step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index `0`, or the step with index `1`. Return _the minimum cost to reach the top of the floor_. **Example 1:** **Input:** cost = \[10,15,20\] **Output:** 15 **Explanation:** You will start at index 1. - Pay 15 and climb two steps to reach the top. The total cost is 15. **Example 2:** **Input:** cost = \[1,100,1,1,1,100,1,1,100,1\] **Output:** 6 **Explanation:** You will start at index 0. - Pay 1 and climb two steps to reach index 2. - Pay 1 and climb two steps to reach index 4. - Pay 1 and climb two steps to reach index 6. - Pay 1 and climb one step to reach index 7. - Pay 1 and climb two steps to reach index 9. - Pay 1 and climb one step to reach the top. The total cost is 6. **Constraints:** * `2 <= cost.length <= 1000` * `0 <= cost[i] <= 999`
For a word like "test", consider "#test", "t#test", "st#test", "est#test", "test#test". Then if we have a query like prefix = "te", suffix = "t", we can find it by searching for something we've inserted starting with "t#te".
String,Design,Trie
Hard
211
1,870
hey guys in today's video we are going to solve one more lead quote question that is minimum speed to arrive on time so in this question we are given a array with distance values and a variable r with the given time so let's see what I meant by this so let's say if I am standing here this is point d and I have to go to point B that is my office and this is my destination so a is my home and B is my office and I have to go from A to B and I am having in total 6 hours to travel this whole distance right I am having in total six hours now what I have to do is I have to travel using train so this distance array represent that only so I am saying I will be taking train 0 which can travel distance one that means the zeroth index representing train and that train can travel the distance equivalent to the value of this index so if I'm saying from a I will be taking first train 0 so it will travel up to distance 1 then I will be taking train one that will be traveling distance 3 then I will be taking train 2 that will be taking that will be traveling distance 2 and in this manner I will be reaching my destination so we are given time and distance and we have to find the speed with which we can travel this much distance in the given time and not only this much we have to find out the minimum time minimum speed with which we will be able to reach our destination but there are few conditions that are provided in this question let's see what are those conditions are they are really helpful to solve this question for the first condition is the r value is going to be up to two decimal places that is something like this at most it will be up to two decimal places second thing is the answer that we are calculating that is speed is not going to exceed 10 raised to the power 7. the answer is not going to be greater than 10 raised to the power 7 this is the second condition and the third thing that is provided in this question is suppose I have traveled with train 1 and now I have to switch the train to train 2. which is going to travel distance 3 so before switching this train what I have to do is I have to check the previous time that previous train had taken so if I am saying train 1 T1 had taken 1.5 hours then I have to 1 T1 had taken 1.5 hours then I have to 1 T1 had taken 1.5 hours then I have to wait for half an hour more so that the value will become 2 and when the value will become an integer value rather than a float value then only I will be able to switch the train again departure so that is what it has been given in this question that each strain can only depart at 10 integer R so we may have to wait in between each train right so this is the another condition now we are aware of all the conditions and what we are provided in this question and also what we have to find so let's see how we can solve this question or what methodology can we use to solve this question so the first thing is we have to find speed and we all know that speed is distance upon time right so if I'm saying I have already been given time and distance and I have to calculate the minimum speed with which I will be traveling this for distance then what I can do is I can simply manipulate this formula and what I will be doing I will be saying time is equal to distance upon speed so now what I am going to do is I already have time I have the max limit of time right this is the max limit 6 is the max limit and I have to calculate the time with any speed I can take any value for Speed supports if I am going to take 3 and then I have to check whether I am able to travel this whole distance within this range right so if I'm saying my value my speed is equivalent to 3 if I'm saying my speed is equivalent to 3 then let's try to see what will be the time we'll be taking to travel this whole disc so the first will be first T1 will be traveling in so T1 train will take how much time it will take distance that is 1 by 3 and that is equivalent to 0.33 but we know that we will be taking 0.33 but we know that we will be taking 0.33 but we know that we will be taking ceiling values so it will become 1 now what we will go to train 2 and for train to what we have distance 3 and our Speed 3 so value is one value is already in integer form so what we will do we will simply add this with the previous value and it will become 2 this is the total time we had taken till now we will go to frame 3 and train 3 is having distance as 2 and speed as 3 and the value is 0.66 and now speed as 3 and the value is 0.66 and now speed as 3 and the value is 0.66 and now when we are going to add it with the previous value it will become 2.6 for the last value we hadn't taken 2.6 for the last value we hadn't taken 2.6 for the last value we hadn't taken the ceiling because after this we don't have to switch the train this is the last train right so we won't be going to take ceiling value so now we got this value that is 2.66 value that is 2.66 value that is 2.66 so 2.66 is the overall time that we had so 2.66 is the overall time that we had so 2.66 is the overall time that we had taken to travel this whole distance with speed equivalent to 3. and this value that is 2.6s is and this value that is 2.6s is and this value that is 2.6s is lesser than the given hours right given as was six so now we know that we can travel this whole distance when speed is equivalent to 3. right but now the thing comes in is 3 the minimum value that is something you need to check right because if I'm saying I can travel this whole distance using 3 as a distance then that is pretty obvious that if I'm going to make value of speed as 4 or 5 or 6 then to I will be capable of traveling these distances within the given R and even the values are going to get lesser and lesser with the increase in speed as the speed will increase the time will be reduced to reach our destination right so what I realized is I have to calculate a speed and that is even in such a manner that after a point like we calculated with 3 we know that the right side of the three is always going to have the increasing values and the left side of the three was having the decreasing values so we realized we are trying to calculate some sort of pivotal threshold and we know that when we are trying to find a threshold value in a given range these types of question are being solved by binary search we are going to solve this question using binary search now you must be thinking like we don't have any range that how we are going to solve it using binary research but if you remember in the starting of the explanation I already discussed those conditions which are given in this question that is the answer should not be greater than 10 raised to the power 7. so this is the max limit so we can say that our right value or the right pointer is equivalent to 10 raised per 7 our right pointer is going to be 10 raised by 7 and our left pointer is going to be equivalent to 1 because if speed is going to be less than 1 then we won't be able to travel right at least we have to keep this speed equivalent to 1 then only we will be able to move so our left value will be one so now what I am saying now find out the value between these two ranges in such a way that speed has to be the minimum value with which we can reach our office right so now we know that we are having two ranges and we have to apply binary search in order to calculate our answer so this question was this simple but to understand like with what approach we really need to solve this we need to go through the whole drawing explanation try to dry around the whole distance and what all are the values with which we can come up with those conditions and then we can finally reach to the conclusion that we need to calculate a pivot or a threshold and whenever we have to calculate a threshold when there are two sides to opposing sides that is the left and the right side and we have to move in One Direction depending on our requirement in such a case we will be using binary search always so let's try to solve this question using binary search and I'll type straight into coding part so let's firstly add one condition that is The Edge case an edge case can be if the distance that is the array length is going to be greater than or equivalent to R if this is the case then we won't be able to ever travel if the distance is already greater than the r plus 1 then you won't be able to travel like if I am going to tell you in this example if my R was given as 2 suppose my R was given as 2. and if I am going to travel this whole array with the minimum value of speed that is one so if I am going to travel this whole array with speed equivalent to 1 so for first strain what will be my answer what will be my time taken to travel with per strain so total time will be Distance by speed and that will be 1 by 1 is 1 right then I will be taking second train that is three by one that will be 3 and then I will be taking third frame that is two by one and that will be 2 and when I am going to add up these three values what I am going to get I will be getting 6 and my R is 2. now I was having two wires to travel the whole distance but even with the minimum speed I am going to travel it in 6 hours then I won't be able to reach my office on time that's why in these kind of scenarios what we have to do we have to return minus one this is simply going to check if we do have sufficient time to travel the distance the whole distance uh with the minimum speed so that's the condition with which we will be checking this Edge case and after this what we will do simply do the usual steps of our binary search that is defining our left and right pointer in this case we know that left is going to be 1 right is going to be 10 raised per 7 and then we will be having a loop which will run third line left is less than right and we will calculate mid will be left Plus right divided by 2 and after this what we have to check if the ceiling of what ceiling of I by minute what is I so we are doing for I in distance array but we are not taking the last one as we already saw in the example that we will be because we are taking ceiling values and we don't want to take the ceiling value of the last one because after last train we are not going to switch any train that is our last one so we will take the time to travel the distance with that train as it is so that's why we hadn't included it in our for Loop and after this what we will be checking after this I am going to check whether this is less than or equivalent to the given R so that we will be able to travel this in the given error not that is what we are checking in this if condition and if we are able to do that then what I am saying try to get the minimum value that's why I will make our right pointer equivalent to Mid and if this is not true then what we do we will search on the right side else we are going to search on the left side by making our right pointer equivalent to Mid and after stepping out of this we can return that's it this was the whole code hopefully I hadn't made any mistake type or syntax error oh I forgot to add one in this if we are making left equivalent to math then we have to increase it by one so yeah we can see that this function works fine and this was the whole approach and time complexity of this approach will be equal into the usual binary search time complexity that is login we are traversing the whole range of speed and returning the minimum speed in login time so I hope this video was helpful and if you really find this video helpful then you can like this video subscribe my channel and I will soon come up with few more questions till then you can keep watching and keep going and thanks for watching
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
100
foreign q and we have to 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 so in example one here we have the root of one so this is our p and this are q and for the left and right children we have basically the same values so these two these threes are equal and we just return true now for the second example the roots are the same but the first three has a left node of a value two and the second three has the right node of value two so the structure is not the same the second three is missing the left node and the first three is missing the right node so they are not uh they're not the same three and we just return uh false the third example is um uh pointing us to the same structure for the three but difference value so in this case we have the same Roots but for the left node of the first tree we have the number value two but the that's value doesn't match the value of the left node for the second three so we just have to return it false the number of nodes in both three cylinders is in the range 0 to 100 and the node values are from minus 10 to the four to the ten to the fourth so how do we actually uh so how do we check the uh if the trees are the same uh because it's three and the most handy algorithm is DFS that first search and the recursive approach how do we Define our recursive relation so three star you can think of it as threes are the same if they have the same root so let's PL P the note the root of the third three and Q the node the root of the second three if they are the same uh and we also checked before that the left subtree of the p is equal to the right sub three so it's equal to the left substitute of the Q so P left is equal to cooler two left and also the right sub 3 of p is equal to the right substrate of the queue uh then um basically the three's are the same so if we call the recursive function on the left sub 3 and we get the information that the left substitution posts are the same and we do the same uh for the right sub tree the only thing that we have to check is if the roots are the same so basically if the roots is the same and the left and the right sub three are the Same by calling the helper function uh we know that by three those three conditions the trees are also the same now for the time and space complexity we will have uh we will return early um because we will be checking the smaller of those if they are not identical smaller of the series so let's denote end to be the number of nodes in this model three and that's the type of what's because we will visit all the nodes from that three and uh the space complexities um uh related to the stack recursion stack that we are using uh and if the tree is skewed so we have something like this all the nodes on the left side or something like this on those on the right sides we will have basically the depth the size of the stack will be and so both time and space complexity are linear to the number of nodes of the smaller tree the result of the main function in the same three will be also the result of our helper function that will be closing cursive we will just pass the pnq nodes uh note that we could also reuse this entry function to call it recursively but I find this more readable too uh creates a new helper function so our helper function will get the uh the roots of the P the first three and the roots of the secondary then because we will be calling inter casual we have to have a base case and for three smallest most cases the base case is basically checking if the either of the roots or one root is um equal to null and if it is we check for the equality uh basically they have to be all both now for us to say that okay they are the same three and if they are defined we will check their value so basically the roots value has to be the same and also the left sub three has to be on the same uh for both on the first and second three and the right sub three has to be the same so we will just call the helper function recursively
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
540
hey yo what's up my little coders let's solve the delete called question 540 single element in assorted array basically we just need to find a single element inside the input array and the conditions are every element appears exactly twice inside this array with exception for one element which is single and appears only once let's do that we are going to have two pointers one will point to the left side of the array and another one will point to the right side of the array while left pointer is not equal to the right pointer the first thing which we want to do is to calculate the mid index is the index of the element in the middle of the array now let's consider the following case as an example imagine this is our input array we have calculated the mid index which is index 4 because that's our middle element and let's calculate 0 1 2 3 4 yeah the mid index is equal to 4 if this mid index is even number like we have if that's the case let's see what we have on the left side from the middle element here we have that the integer on the left side is the same as the middle element so they're equal right if they're equal it will mean for us that our single element is somewhere on our website starting from the midpoint and we don't want to consider the right part of the array anymore makes sense right if they're the same it means that single element is somewhere there and to not consider the right side anymore let's just change our pointers and the right pointer will become mid index minus two so we already checked we already know the mid element and we already know that the mid element is the same as the element on the left side so we are not we already know that these two elements are not single elements so we are changing our right pointer and right now we will consider only this part of the array we already reduced a lot of steps all right after that we will go on the next iteration of our value again the mid index will be equal to 1 so we are not going inside this if state statement anymore we are going inside the else statement now let's check the element on the left side again if the element on the left side is the same as element as the mid element what we want to do i will tell you what we want to do we want to change our left pointer again because it will mean that our single element is somewhere on the right side of the array so the left pointer becomes the mid index plus one because you don't want to consider this part of the array anymore you just want to consider this part and here's the answer the left will become the same as the right so we are not going to the while loop anymore we need to return something in this case both left and right pointers are pointing right now to this element which we need and we can return the index and we can just return the nums and left or right in the brackets and we will get the answer however it's not the end of the problem we also might have another case imagine that's the input array all right we're going inside the loop that's the mid element right we're going inside this if statement however the element on the left side from the mid element they're not the same and this condition doesn't apply anymore let's think a bit if they're not the same it will mean that the single element for which we are looking is somewhere on the right side of the array we want to move to change our pointers again the left pointer just becomes a mid index and we want and now we are cons we'll consider only this part of the array okay next iteration of the while loop we are having this array calculating the mid index which is equal to 2 right now so going again inside this first if statement these two elements are not the same this l statement applies we are changing our left pointer again we are getting the following array 588 and we are going to the next iteration of while loop again calculating the mid index here's the mid index it's equal to one is not even we're going inside the else statement our first if condition doesn't apply because the element on the left side from the mid element they're not the same what to do in this case let's think again if they're not the same it means that we can change our pointer and we want to consider only this part of array now because we know that these two will be the same for example to do that let's change our right pointer to b mid index minus one and we are getting the following array and the left pointer is pointing right now to the same place as the right pointer so we are going outside the while loop and we can just return left to right pointer let's test it if it actually works perfect it did let's submit perfect it was the lethal question 514 please subscribe to this channel guys a lot of interesting stuff is going to come soon enjoy
Single Element in a Sorted Array
single-element-in-a-sorted-array
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once. Return _the single element that appears only once_. Your solution must run in `O(log n)` time and `O(1)` space. **Example 1:** **Input:** nums = \[1,1,2,3,3,4,4,8,8\] **Output:** 2 **Example 2:** **Input:** nums = \[3,3,7,7,10,11,11\] **Output:** 10 **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 105`
null
Array,Binary Search
Medium
null
1,696
so hello everyone today we will solve today's daily challenge problem jump game six problem statement is you are given zero index to integer array nums and an integer k you are initially standing at index 0 in one move you can jump at most k steps forward without going outside the boundaries of the array that is you can jump from index i to any index in the range i plus 1 and minimum between n minus 1 and i plus k inclusive you want to reach the last index of the array index n minus 1 your score is the sum of all numbers of j for each index j you visited in the array and we need to return the maximum score you can get to solve this problem i have take different example and my array consists of 15 minus 2 minus 1 minus 3 1 2 and the value of k is 2 so we can jump maximum k step forward from our current index so let's discuss how we can solve this problem so to solve this problem i have created one array and in this array we will store the maximum score till the current indexes so this three in this array will represent maximum score till this third index similarly this five will represent maximum score till this fifth index and we will simply return the score of this fifth index so instead of going forward in the jump what we will do we will jump in backward direction because this will more intuitive for us let me show how we will solve this problem first of all we are on this zeroth index so we can't jump backward because we are on zeroth index so maximum scold the score till this zeroth index is 15 we will add this 15 in our array after that we will come to this first index so we will jump 1 minus 2 that is till -1 but minus 1 is out of boundary till -1 but minus 1 is out of boundary till -1 but minus 1 is out of boundary so we will jump till this 0th index and till this 0 the maximum score is 15 so we will add this 15 with minus 2 15 plus minus 2 is 13 till this first index maximum score is 13 after that we come to this second index now the range of this second index is still this zeroth index we will find maximum between this 0 0th and first index so maximum value is 15 we will add this 15 with our minus 1 so 15 plus minus 1 is 14 after that we will come to this third index now we can jump two step backward till this one now we need to find the maximum between 1 and 2 so the maximum is 14 we will add this 14 with minus 3 and so 14 plus minus 3 is 11 after that we come to this fourth index and our range is till this second index so we will add maximum between the second and third so the maximum value is 14 plus 1 is 15 after that we come to this fifth index and the range of this fifth index is still this third index so we will find the maximum between third and fourth index so the maximum value between third and fourth is 15 so we will add this 15 in our fifth index value so 15 plus 2 is 17 this is how we can find the maximum value so our 17 is the maximum value till this last index let's analyze the problem time complexity to solve this problem is order of n to travel through this array and to find the maximum value between our range of jump is order of k because we can jump k step backward and we need to find the maximum between this k step k backward steps so to find the maximum we require total order of k so the overall time complexity required is order of n cross k and space complexity to solve this problem is order of n because we have make order of a yen size array to solve this problem this is not the optimal way to solve this problem we can further optimize this solution like here just to find the maximum element between past k jumps we require total order of k time but if we store past k jump score in maxim data structure then we can easily find maximum value in log k time so if we use heap data structure here then we can solve this problem in order of n log k time but this is not the optimal solution we can solve this problem in order of n that is in linear time and if you talk if we talk about space then we can solve this problem with problem in order of k space complexity so we will optimize our time complexity to order of n and our space complexity to order of k so let's discuss how we can solve this so we know that about q data structure in q data structure we can pop value from left side or right side similarly we can add value in left or right so to solve this problem i will create q data structure and in this queue data structure we will add the values in descending order like our q will contain 15 13 10 and always the first index will represent the maximum value among the q so this is how we can obtain the maximum value in order of 1 so let's see how we can solve this problem by using q so to solve this problem i have created q of size k now we will add the score obtained in descending order in this queue so first of all we are on this zeroth index so till this zeroth index maximum score is 15 we will add 15 and its index that is zero here after that we come to this first index from this first index maximum we can jump till this zeroth index and till the 0th index maximum score is 15 so we will add this 15 with our minus 2 so 15 plus minus 2 is 13 and the index of 13 is 1 after that we come to this second index now our range is till this 0th index our 15 and 13 both are line this range so we will add this 15 with our minus 1 so 15 plus minus 1 is 14 now we will check 14 with this 13 so 14 is greater than 13 and 14 is less than this 15 so we will remove this 13 and add 14 here so we will add 14 here by removing this 13 and now our 14 instead of this 13 and the index of 14 is 2 after that we come to this third index and the range of this third index is still this first index but we can observe that in our queue 0th index is occupied by 15 and which is present in present on 0th index which is outside the range of this 3 because 3 is go till this first index so we need to remove this 15 because this 15 we can't add with our third index value so we will remove this 15 from the queue now this 14 will come to 0th index now we can add this 14 with minus 3 so 14 plus minus 3 is 11 and index is three after that we come to this fourth index and from this fourth index we can jump till this second index so this 14 is lie inside our range we can add this 14 plus this one so 14 plus 1 is 15 now we will compare this 15 with 11 15 is greater than 11 so 15 will remove this 11 after that we will compare 15 14 so 15 is greater than 14 so this 15 will remove 14 now our 15 will come to the zeroth index we will add 15 with it with its index in our zeroth index after that we come to this fifth index and the range of this fifth index is till this third index so 15 is lie inside the range we can add this 15 with 2 so 15 plus 2 is 17 and index is 5 so we have find our answer with just order of yen time complexity by using this queue data structure to solve these types of problem i want to give some suggestion like in this problem they have asked ask us to find the maximum score which we can obtain from the given array when we read about maximum or minimum in our problem we always think about dynamic programming and constrain our brain in that particular direction because of that we are not able to find the other ways to solve this problem like in this problem we can easily solve this problem by using sliding window technique so my suggestion to you is that don't constrain your mind in any particular direction by just simply reading some keywords in the problem like maximum minimum or some words like optimization try to think in every possible direction and after that come to the solution now let's see how we can code this problem my suggestion to you before watching my coding first of all try by yourself and after that come to my solution so my n equal to lene of nums and to solve this problem we required q equal to dq and we will add nums of 0 in this queue q dot append num sub 0 as we have discussed we are not only appending the score but also its index so the index is zero for summation we will make one variable summation and initially the value of summation is equal to nums of 0 it is very important that we need to initialize the summation with value numbers of 0. if we initialize the summation with 0 like i had did in the past then if our nums contain only one value then this will return zero instead of returning that value so it is very important to initialize our summation with zero now we will start traversing through our nums for i in range n our summation is nums of i plus first in first value in our queue which is the maximum value that is q of 0 this 0 will represent score and here we have to start from first index because we have already added this num sub 0 in our queue so we will start from this first index so now this step come where we are comparing our summation with previous value in our queue if our previous value is less than summation then we will remove that previous value until our summation is less than some previous value so while q and our summation is greater than or equal to our q minus 1 of 0 this is the la this represent last value in our queue and if it is less than our summation we will simply pop this from our queue and at the end we will append current summation in our queue so q dot append summation and the current index which is i we have discussed that we need to check whether our maximum value is lying inside our range or not if it is not lying inside our range then we need to pop it from the queue so if i minus k is greater than or equal to our q of 0 of 1 here first index represent the index and q of 0 represent maximum value stored in the q so we will remove this maximum value from our cube by using q dot pop left the reason behind we have used here q instead of using any array is that we can remove from the first from the starting of q with just order of n time complexity if we remove any element from the first of array then we require total order of vn time and at the end we simply return our summation so first of all we store the length of our nums array in yen after that we will created we have created one queue and initially we add nums of 0 in that queue and our summation we have initialized with num sub 0 and after that we start traversing through our nums array for summation we have add our current value with the maximum value in our queue after that we check whether our com summation is lie inside the queue and if our summation value is greater than last value in our queue then we will simply then we are simply popping it from the queue and at the end we are appending our summation inside the queue and here we are checking whether our maximum score is lie inside our queue or not if it is not lying inside the queue then we are popping this value from the queue and at the end we are returning the summation so let's check code will run or not summation is not defined so here i have misspelled summation so our solution got accepted let's submit it as we can see our solution get accepted successfully if you have any doubt regarding this solution then let me know in the comment section
Jump Game VI
strange-printer-ii
You are given a **0-indexed** integer array `nums` and an integer `k`. You are initially standing at index `0`. In one move, you can jump at most `k` steps forward without going outside the boundaries of the array. That is, you can jump from index `i` to any index in the range `[i + 1, min(n - 1, i + k)]` **inclusive**. You want to reach the last index of the array (index `n - 1`). Your **score** is the **sum** of all `nums[j]` for each index `j` you visited in the array. Return _the **maximum score** you can get_. **Example 1:** **Input:** nums = \[1,\-1,-2,4,-7,3\], k = 2 **Output:** 7 **Explanation:** You can choose your jumps forming the subsequence \[1,-1,4,3\] (underlined above). The sum is 7. **Example 2:** **Input:** nums = \[10,-5,-2,4,0,3\], k = 3 **Output:** 17 **Explanation:** You can choose your jumps forming the subsequence \[10,4,3\] (underlined above). The sum is 17. **Example 3:** **Input:** nums = \[1,-5,-20,4,-1,3,-6,-3\], k = 2 **Output:** 0 **Constraints:** * `1 <= nums.length, k <= 105` * `-104 <= nums[i] <= 104`
Try thinking in reverse. Given the grid, how can you tell if a colour was painted last?
Array,Graph,Topological Sort,Matrix
Hard
664
35
hey everybody this is Larry this is day 20 of the leeco daily challenge I didn't I did a weekly ones right hit the like button hit the Subscribe button join me on Discord let me know oh let me know what you think about today's Farm but as you can see on my screen maybe on the upper left side is unbox surprise you click for 10 extra coins yay uh what is going on why is there like so many things that anyway uh yeah today's bomb is 35 search insert position um as you can see I've done it at some point recently so I'm going to do a bonus uh extra prompt that I haven't done yet today uh after this so definitely hit the Subscribe button if that's what you're into uh okay so yeah there are a couple of ways you can do this uh really only a couple which is binary search either using the library not using the library I think not using the library well using the library you can you know do a binary search and then see if you know that looks up otherwise you know you could just use this as an opportunity to practice your um your search so you can cut kind of face this in a couple of ways you can say this is a uh get the index that is um or maybe even another way of saying is get the first number that is um that is equal to or greater than Target right yeah so let's do that so we say left is equal to zero R is equal to uh right is equal to n where um yeah energy got a length of nums uh and then basically while left is next so let me talk about binary search a little bit I might have a video on this anyway but just that um the way that I always do it and I need to kind of get this video out at some point is that I use inclusive bounds meaning that basically you know you have a range and we're searching both left and right and both numbers are inclusive that they're possible in the range the reason why I have n in here is so that it can go that means that Target is bigger than the biggest number so that's basically why um technically even though this is an inclusive balance it you know has something that drops off in theory the reason why I like inclusive balance because then now the search criteria is way more straightforward in that um in that when left is you go to right then you have uh a window or a range of one number and that number is your answer right um yeah so that's basically the idea and of course there's some stuff uh well um I also find it easier to um to move the barrels because then because you're always using inclusive then you know which point that you're moving and the other point that would be okay you don't have to worry about anything like that so yeah so basically if num submit is um greater than or equal to Target what does this mean right if this is great and you go to Target then damage that mid is a possible answer but we're trying to get um we're trying to get a smaller number right so that means that write is equal to Mid and then else left is equal to Mid plus one probably right because we're trying to get smaller or bigger but then it is too small so yeah and then now we just have to just uh you know something in my head if left and left so in this case when the while loop ends left is equal to right so you can say use idle one right so maybe answers you go to left or right it doesn't really matter um if num sub answer is you go to Target then we return answer otherwise we turn negative one is it or does it always exist oh well wait if not insert the index where it would I misread this one slash I was thinking of another one um so it doesn't ex so it exists then we return the index that's fine otherwise we return so maybe this is a little bit off because I didn't read it uh where it would be inserted now this is okay because this is the num the index in which it is greater than Target so actually we can just return enter we don't really need that done um yeah okay give us a quick submit and there you go um 10 56 day streak um hopefully I don't have to explain this one too much hopefully you've been practicing binary search if not this is essentially my template if you want to call it that usually I change this into a function but basically that's how I always kind of um Do It um and obviously this is going to be log uh o of log n for time because we're binary searching and for spaces it's just over one we have like five variables um cool that's what I have for this one let me know what you think uh let me know in the comments and yeah stay good stay healthy to good mental health I'll see y'all later and take care bye
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
810
And Hear That Shahrukh Mode Game Surya Given Udayveer Business High Pay And Square Pieces Airplane And So Will Have To Race The State Of The Game Of Tennis Players At Seervi Recommended For The Element Switch To Editor Mode Loda Player Beans OK White Plane I'm Starting Cream And Its Values Already 0 Mein Roke The A Painting And Only Ajnabee List Play List Role I Back Tell Someone Does So Let's Look Into This The First Player Celebs Per Have One Choice Aisi Can Relieve And 2002 Vansh That Death Yudhishthir One Or Two You serious one the number victims want to join is not giloy sonth game continues sunao box remove any element suppose e salute him officer to that dam one will be left sunavai lakshmi force to remove vansh and norms and comes and tales no element subah points and Isro for no element and sahabuddin na hua tha jab case hai love letters to first features to first one is left and join this is actually jo hai to bob against vikas the overalls and is already zero two 220c vaseline use no matter what seems basically Vighn This Cream Or Not And Where Given Its Value Is And Right Any Question We Problem Read More That Your Problems Petty Player Is Deep Too Tune Up Thought About When You Solve This Problem Just From Intuition Side Of Things And Trying To Learn Something From Where While sleeping masking tape a back tracking camp reminder switch have to go deep into game back android here option not right back tracking despite 127 lions want to for example of 202 players water celebs pop up video that and the thing SSC 2011 Scored1 Listened 021 And the state is defined by joining this thing solid Minutes York is on number if possible today with talking laut awards and click what was story alert samudra invest laddu one thing sweater puneet is talking about voodoo school annual day fruit situation so let me give this thank you have two three four most active in positive But Is Controlled Credit Which Folds Nao That Can Someone Just Tell Me What Is The Answer Hai Jhal That Choose And Cheese And 4020 For Kids 383 Me Your Only 300 You Know About Such A Good Doctor Meeting Ka Puneet Voice Of Maintaining Bread To Came In prayer for vote scam in fear no matter where you are Indore please the sense objects of its properties of this or this cream is actually a description 3 Shubhendu 100 Vinod This property of words and they want to solve this for a specific we use BP Gautam use backtracking and answer this problem that this drug Yuvakulp a voice of the country for MS in imitation loot-loot days on for MS in imitation loot-loot days on for MS in imitation loot-loot days on 209 Danny use backpacking and your DP or any other thing like that Tamil audio challenge with in this are you have displayed in the 2nd Edition More Comments You'll Like On James Augustus FZ Have Like You Can Get Support From Both Sides Inside A Guy Song Chori Questions A Few People Couple Of The States Which Can Result After Changing Damaged Hair Articles Change In This Need Into To Make Any Possible States That And Not Needed You Can't Even Just You Know And Fixed For Doctors You Can Be From Any Place One That Is Very Easier Not To Forget To Like Recurrence Relation For A Particular Case Subah Tours In The Time You Can Start Thinking He Can Do something better spaceships and to you have to information some properties and vision apply to girave solution and include hai to par sumtime but still only 10 minutes fast and set this sm continue and generate your back and will talk to check how sad song please Wait and the best in the time, it seems to be happening, yes or no, 21000 start, to aap lakt paun inch to aisi video free of the percentage remove and not give free play list number 109 that it is wet with tears Chal Gorakhdham Express Witch Place in the year baba subha dhundh condition and used to be som mistakes loop condition ki me lut spoon play isi mein egg bhurji paun inch tak yeh thing not make the first two elements which does not make 10 2012 through this channel status please like Subscribe button to play win or loose that nodi state agro b option 211 to 239 to remove this place in these two three letters two in one two three liye nihrib remotes 123 ki a chandra vihar me 123 main one aa ki minister and 100 difficult hai 1234 Uppal And One To Environment Google Play List Sunna Handsfree Letter Right Down The Number One To 218 Comments Subscribe And Waheguru Ga This Side Reaction Had Happened To This Point Kahin Vinod Subscribe Digit Pin Adh Ki X Y In This Ad Nasruddin More That X Price Rate Samsung Active Find The Results For This Tractor Aur Dushman Ye Rahasya Same Hair System For Spain Purposes How To Reduce Computer Tips Subscribe To Main Office WhatsApp Anshul Yadav SMS Kar Do Ki Abhi A Phone Number Details You Can Check The Rate Boys order in the lowest level of days only one and support and splendor pro not only that light sirvi sundha single element will use the selected example to tree and tried to be seen its this 232 remote to m1 airplane mode switch to two performance Option for any one to play the way two three to one election commission jobs play list play a question goal which I have one player name is back and law minister for play and rest everything including even last in condition torch light as notification you use Pacific 10 number elements of his thoughts with even number appointment is my favorite being always in the no that Bigg Boss 1817 support this less joint 12054 and number remove vaikunth that in the international market many intimate always and number balance come to address a are yes Adi Shuaib White Being Player Tenth Class 9 Obscene Dancing Coming Back To The Number 90 Number That It's Amazing In Open That Civil And Game Condition Start With Abs 21 2012 That A 12314 That If It Came To Acid's Number Plate Before Name Akshar remove vid oo loot mein 90 subhendu hai to any time ko more aloo serving hai the beaver number parliament speech can't pimples no possibility of killing a next ki Bigg Boss kisi remove saini manoj elements compound m0vie benefits of all the best all odds with A who is the to pilaao hai f4 that from next year they set number limit tay tu explain already episode 120 a sudhen change in the 10th edition 10 Aug 02 341 more cigarettes 14% and special Ravi Singh 341 more cigarettes 14% and special Ravi Singh 341 more cigarettes 14% and special Ravi Singh for any number of elements after no matter what The elements on the honey and number and will never give up the job will ever video 400 jaswant lekin meghwal understand solid some example neck na ek chooj mein b0l ek chooj 120 10th torch light or what is the value of 120 rate hai main par use Write in the representation petrol 70 join that this one ok now 102 that what nav support only I'm looking adding one element to make a Dr0 channels and with me to make add0 phone 's cutting back Android a man pipe loot quite understand but I Think for using this logic prithvi panstars figure things from polythene gas switch to look at things at but off but admit level and which can drive same solution so airtel network anything right one to three is only already mode any one which can remove any thing and Let's know this box in not remove anything because this is new Hindi teacher only this forget everything for you will tower 2004 or ₹100 note scientist ok ki unus luta specific but you will work in the same way e the queen you love me yes Ya know that we have the most endearing among our allies I am soft Puneet bani aur mention in u also make a condition that the next job student v0 light Ranveer and Sussanne in that case will not distract were deleted for Bigg Boss season 10 min Choose WhatsApp App Hai To Customer Body Ko Extra Oil 100 Vighnon Disawar Number Thank You Back To Things For Lips Best SSC Head-Dress Things For Lips Best SSC Head-Dress Things For Lips Best SSC Head-Dress Even Number Of Elements Ki And Jij Aur Eight Dec07 Sprite Test Problem Novel The Thing Khubi Is Daur Is Not Equal To Zero Last Second Class Turn Flash Light to Singh and 10 Numbers And Is Not Equal to Zero Do Hai Ya Dan Can Keep Doing Anything to Make Sure Set Next Remedy Is Not Equal to Zero Weird Possibilities Hai What is the Worst Position Hair Tension Select From element S a that boat what is st louis select something tax act 202 researchers can always select something tax truth that 19 races without a twenty-20 flight fair of and minus one twenty-20 flight fair of and minus one twenty-20 flight fair of and minus one number proven tax nuvve this note shabbir white youtube channel subscribe not that message Listen everything depends on which date the site appears sonic ten but next question cancel does it or not this year sayings and don't know that daily what they are saying debit the is note secretary these helicopter value that are equal previous two are tight yes security person Quality That Is You Have Equal Values ​​Anti Values ​​That You Have Equal Values ​​Anti Values ​​That You Have Equal Values ​​Anti Values ​​That Will Give You Already No Matter What Value Is That Is As Given At Least Not Equal Weird Cigarette HP Slate Coming Even Number And Bank Just A System In And Number Of Science And You Can Always Studied is but effective lack one number times in the VC chamber of measure but for best that 89 is living decided with this situation square skills and is not equal to zero I Sunil so this is not going to be no matter what is payment directly and this 90 next but pickup this and picket element increase female in animal element navya the same question quite trying to solve the and now they are trying to solve and - 2nd already and now they are trying to solve and - 2nd already and now they are trying to solve and - 2nd already set any sequence administrative and half cup 100 and question is coming record from That Navakundiya Solving a Small State of the Problem and Eventually You Can Always Be Something to Match Your Data Dargah Judgment in That Is and Will Never Comes to Behave Travels and Subscribe Acts Where - 90 Will Always Be Know What Position at This - 90 Will Always Be Know What Position at This - 90 Will Always Be Know What Position at This Point of Time And Subscribe Problem Is Length Of The Amazing Hey Man 10:00 Sequence That Hey Man 10:00 Sequence That Hey Man 10:00 Sequence That Such People - 2 Main Online To Parhaps Even In This Will Win Only cod4 Number It Is And This Less Some First Question 123 Should Remove Reversible Optimized subscribe The Channel Please subscribe and subscribe the Channel for More Understanding That Suggests You Can Get Example But Wise Manner And What Will He Does Not Mean That You Have To Values And Sears Tower At Least One Which Will Be One Quarters Definitely 1212 With Other Telescopes Have Gone On Which That all the people of China send some water and use this point to always decibel often to make share datas I will always be you review on the question Kuch hai zero do ki validator Ajay ko apne Peeth Siwan to make for the disturbance get destroyed and Always Have The Option To Civil Measures Everyone In This Year Will Protect Are Agansya Upcoming 39 Examples Which Is Died Due Mein Bhi Mirchi Selected Date Will Help You To Understand That But That Is Aam Ka Beech Police For Watching The Only Thing Is And Next 9 Science Notes Honey Singh At Random But Will Always Have A Choice To Do Something Which Will Make Sure That Next Saffron Producers And Swiss Roll Subscribe And Even Number 10 Number Length Is Lots Of 10000 Singh Right It's Difficult To That Including Lips Cracked And Length Like Ireland This Award Number Six And This Video Not Long Day It's Something For Bob Know Who Can Play The Same Trick And Sees Planning To Win It Will Always Been Seen Chapter-16 Pradesh Will Always Been Seen Chapter-16 Pradesh Will Always Been Seen Chapter-16 Pradesh MP Subscribe Log In Handsets 90 Number Hai 220 Lord When In Case If as number length life is about gram palak 123 folk key and five remove first number from where should always one more thing 123 subscribe now to receive new updates question middle aged person returning 1234 bluetooth ki haddi expect the district up which man economic thank you Please update your links on Wed 20 Nov 10 2011 Cotton Fabric and Sure Always Subscribe to 209 Ten Benefits Height Increase Words Today's Back with a Palindrome Question Happy That Number Oriented Yesterday I Team The Thing Which Was Going Like This Website Spiral Scientist David This Point Hard Category Saag Pushpi Ek What is Very Easier Sports Activities to Enter in the Noted Question Hai Don't and All the Hard Questions in Lakhon Daal Dein Toh Ye Mostly Police Time Vighna Question Next Question On Key Problem Ko Do Hai So Actually I Like This Up Sanam Will Stop Recording And Vision Hanging For Sometime We Got Positive
Chalkboard XOR Game
valid-tic-tac-toe-state
You are given an array of integers `nums` represents the numbers written on a chalkboard. Alice and Bob take turns erasing exactly one number from the chalkboard, with Alice starting first. If erasing a number causes the bitwise XOR of all the elements of the chalkboard to become `0`, then that player loses. The bitwise XOR of one element is that element itself, and the bitwise XOR of no elements is `0`. Also, if any player starts their turn with the bitwise XOR of all the elements of the chalkboard equal to `0`, then that player wins. Return `true` _if and only if Alice wins the game, assuming both players play optimally_. **Example 1:** **Input:** nums = \[1,1,2\] **Output:** false **Explanation:** Alice has two choices: erase 1 or erase 2. If she erases 1, the nums array becomes \[1, 2\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he wants, because Alice will be the one to erase the last element and she will lose. If Alice erases 2 first, now nums become \[1, 1\]. The bitwise XOR of all the elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. **Example 2:** **Input:** nums = \[0,1\] **Output:** true **Example 3:** **Input:** nums = \[1,2,3\] **Output:** true **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] < 216`
null
Array,String
Medium
348
923
Hello Hi Guys Welcome To Your Decisions Made Easy In This Video Will See The Question Sambalpur City Governor John Is The Number Of subscribe to the Page if you liked The Video then subscribe to the Page A Drama Entries and 10 Questions Lord Saturn in Numbers Dreams from 0210 and tagged between more than firing from country to country in due time complexity of using pointers subscribe my channel subscribe solution take solution of class result were elected long in order to prevent from Indian Roller Floor And will need to follow that on the hindus for loop state in interior decorators andar food we target - I - know this is the volume to find the value of length 0202 and over all need to the number of plus to equal this unrest and Is the account of this great 20 mins of value result mode of the students who did all this combination in result and finally I can just born in the result since long been converted into all strive to withdraw from to do the giver between 1000 Add From Most Important Part Subscribe To Petrol 100 Na What Do We Need To Find The Combination Number Search Debit The Number Equivalent To Get Data Use This Number To Two Numbers And 512 MB Only This Particular Direct Oil Subscribe Now To Use If they are to find the combination then they can have this festive wear is equal to two to the giver divide * - * - * - giver divide * - * - * - giver divide * - * - * - divide Subscribe They Never Regret Not Bo Subject's Titu Ji Titu's Number Instead of being replaced with account for district due to give me to multiply by subscribe now to the number instead of having multiply multiplied to improve the solution so let's go ahead and write the co doctors for watching over all Settings inside the mode of result full hd girl long result in this country but also a long way to unmute then other so will try to where is interior in noida and any account that your data into it's vast country are so oil do it i Total 208 Sexual 1200 Plus J2 Se Z F The Insider Bilty's Semen Bill's Date of Birth The One that Refining Doobie Target - - Simhastha's 100 So Continue - - Simhastha's 100 So Continue - - Simhastha's 100 So Continue Next 9 News Room Se A Suddhen Is The Formula Of Measurement Remedies To Divide Otherwise If I will not give up then Sudhar Shakti I multiply I am just minus one divided into multiples and so on the other side I am loose a result A I am just multiplied by Shivam Jain Multiple increase in prices of goods Flu and finally turn on Bigg Boss mode ahmedabad test electronics code full here anwar and a gruesome acts and submitted for the time complexity are you can see women and 10000 subscribe this video that a
3Sum With Multiplicity
super-egg-drop
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** arr = \[1,1,2,2,3,3,4,4,5,5\], target = 8 **Output:** 20 **Explanation:** Enumerating by the values (arr\[i\], arr\[j\], arr\[k\]): (1, 2, 5) occurs 8 times; (1, 3, 4) occurs 8 times; (2, 2, 4) occurs 2 times; (2, 3, 3) occurs 2 times. **Example 2:** **Input:** arr = \[1,1,2,2,2,2\], target = 5 **Output:** 12 **Explanation:** arr\[i\] = 1, arr\[j\] = arr\[k\] = 2 occurs 12 times: We choose one 1 from \[1,1\] in 2 ways, and two 2s from \[2,2,2,2\] in 6 ways. **Example 3:** **Input:** arr = \[2,1,3\], target = 6 **Output:** 1 **Explanation:** (1, 2, 3) occured one time in the array so we return 1. **Constraints:** * `3 <= arr.length <= 3000` * `0 <= arr[i] <= 100` * `0 <= target <= 300`
null
Math,Binary Search,Dynamic Programming
Hard
2031
1,425
hello everyone welcome back here is vamson with another live cing session uh so today we have an exciting challenge that will test our problem solving skill and python uh expertise so let's Dive Right In uh today challenge is called uh constraint a subsequence sum uh 1,425 from daily lead coach challenges 1,425 from daily lead coach challenges 1,425 from daily lead coach challenges so we are given an integer R and an in key and our goal is to find the maximum sum of a nonempty subsequence of the r right with a Twist so for every two consecutive integer in the subsequence their indices uh difference must be less than or equal to uh key so uh let's look at simple example to understand this better imagine we have uh fallowing array so I will write it down so 10 uh 2 uh - 10 five and 20 and our key will be uh - 10 five and 20 and our key will be uh - 10 five and 20 and our key will be uh two so the optimal subsequence will be as F so 10 2 then we skip uh minus 10 uh 5 and 20 uh and we need to Output the sum so sum of this uh particular subsequence will be 30 uh seven okay so now as we understand the problem better uh how do we approach this so a naive solution might be to iterate through all subsequence but uh that will be too slow and inefficient so instead we will use a combination of dyamic programming and a sliding window approach and we will maintain a DQ which will help us keep track of the maximum sum within a window of size uh key so let's walk uh through this uh step by step so first uh initialize a DQ to track Marx some in the window of size key so DQ will be TQ and loop through each number in nums so four I in range L nums add Max sum from last key position or zero if theq is empty so now I will be nums dq0 if DQ Al zero and ensure the Q is in decreasing order and within window size so while DQ and I minus DQ greater than zero uh or n i greater than ndq minus one so last DQ pop if n greater than n DQ minus one Al DQ will pop left uh okay so uh now what we do is append positive numbers to the DQ so if num I greater than zero uh DQ append I and return the max value from modified num so return Max of nums so as simple or as this so without comments prob it will be quite a short code uh so all right uh first yeah we can run it to check if it's working so yeah working for uh given test cases so given our aray 10 uh 2 - 10 5 20 key2 given our aray 10 uh 2 - 10 5 20 key2 given our aray 10 uh 2 - 10 5 20 key2 output first7 so all good so uh we can dive uh yeah more deeply into this task so first we initialize our DQ and we will uh then uh we then Loop uh through the aray and for each number we check the DQ to find the maximum sum uh in the last key position and add it if it's positive and we also update our DQ to make sure it always in decreasing order uh of sums and yeah so now after uh Computing for each position the last step would be to return the maximum value from our modify uh n r and yep we got solution so let's submit it for unnus cases as well to verify if it's working so yeah all good uh it's working and we beat 71% with respect to memory and we beat 71% with respect to memory and we beat 71% with respect to memory and also 75 with respect to uh run time so really good and yeah everything's work perfectly uh so yeah the solution took run time of uh 1,321 milliseconds so if you prefer 1,321 milliseconds so if you prefer 1,321 milliseconds so if you prefer something faster uh yeah so the option might be Ras programming languages so I think nobody or maybe there is uh not so many statistics but runtime is 40 34 milliseconds and 3.2 megabytes so uh I milliseconds and 3.2 megabytes so uh I milliseconds and 3.2 megabytes so uh I really like rust and go and python but yeah rust is fast and python is quite uh readable but as you can see 1,321 milliseconds and almost 10 times 1,321 milliseconds and almost 10 times 1,321 milliseconds and almost 10 times yeah nine times more memory but yeah so uh those are cost and benefits so and that's wrap up for today life cing session H I hope you enjoyed this uh Deep dive into uh constraint subsequence uh some problem from L code so yeah it's hard one but uh with proper understanding it's not so hard and remember coding is as much about problem solving as it is about uh syntax and understanding so keep practicing and keep challenging uh yourself and if you found this session helpful don't forget to hit the like button and subscribe for more coding uh content tutorial challenges uh machine learning uh Tech yeah and much more and if you have any question drop your question or suggestion in the comment section below and uh I will do my best to uh respond and also I will provide in the link in the description below implementation in uh python yeah python uh with did but also rust go uh C++ and uh with did but also rust go uh C++ and uh with did but also rust go uh C++ and much more uh so yeah you can check it as well and until next time keep practicing stay motivated and happy coding
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
1,887
hey everybody this is larry this is me going with q2 of the weekly contest 244 reduction operators to make arrays element uh equal so the key thing to know about this is just observing that for each number and they don't have to be unique it goes to the next number and then now you effectively reduce this problem into that number or into a new problem where um every you know you just have a new problem right so their states keep changing so then now you know that this is a little bit of a simulation problem in that way and that you simulate what happens but of course you have to do it a little bit faster because the numbers you know there could be a lot of unique numbers and you do them one at a time it's going to be too slow so then the thing to notice is that okay well if i have a bunch of the same numbers we can move them all at the same time and this alone is fast enough to get the answer because then now you can do it with and log in time mostly on the sorting um yeah and that's basically my idea is that okay i put it in a frequency table um so you know this maps the num the each number with its frequency um i have all the keys in a sorted way from largest to the smallest and okay so now for each number i go okay um current is just the number of numbers at the current max number so whenever you go to the max you uh whenever you process a number you know now you have that many numbers that you have to move to the next number and then and that causes well current number of operations so then now uh and the next you know that just adds the total number of operations and that's pretty much it and you stop when you get to the largest number or you stop before you get to the largest number because oh sorry the smallest number because once you're in the smallest number you don't do any operation so that's why i chop off the last element um that's pretty much it's a little bit tricky i spent a couple of minutes on this one but yeah um yeah uh basically the idea is that okay you have you arrange them from large to smallest and then you just kind of move them all together from the largest to the you know to the next smallest and because of that you just you know go for the numbers one at a time at worst um but it's gonna be dominated by the sorting anyway so it's gonna be n log n time and of n space due to the frequency table um you actually put um you actually don't need the um i mean it makes it a lot easier to write but if you're a little bit careful um you know you don't actually need this frequency table which means that you can do it in constant space if you're careful but i don't want to be careful so i didn't linear space uh challenge yourself at home up solve it um that's all i have with this one you could watch me solve it live during the contest next hopefully this is good yup okay uh what a silly mistake on a typo people already finished q2 make all the elements equal it's gonna be one over the next largest number that is strictly smaller than next largest okay so five and ten okay so okay tie breaking doesn't even matter okay so this is a frequency table thing so this goes from two to two okay five goes to three and then two three goes to one so that's three right okay so that's easy okay so then just like a prefix sum almost uh i'm gonna reverse this let's see so that's the number of current numbers that we're moving and then now we move to current okay um if this is not the last key so yeah because we don't return the last key and then we just return total i think that's roughly right i want to be more careful in this one is this right what happens if i do this just to make sure that this should be wrong okay yup that should be wrong so okay 304 let's give it a go come on yep okay minimum number flips to make yeah i hope you enjoyed chilling and going through this problem with me uh stay good stay healthy uh to good mental health i'll see you later and
Reduction Operations to Make the Array Elements Equal
minimum-degree-of-a-connected-trio-in-a-graph
Given an integer array `nums`, your goal is to make all elements in `nums` equal. To complete one operation, follow these steps: 1. Find the **largest** value in `nums`. Let its index be `i` (**0-indexed**) and its value be `largest`. If there are multiple elements with the largest value, pick the smallest `i`. 2. Find the **next largest** value in `nums` **strictly smaller** than `largest`. Let its value be `nextLargest`. 3. Reduce `nums[i]` to `nextLargest`. Return _the number of operations to make all elements in_ `nums` _equal_. **Example 1:** **Input:** nums = \[5,1,3\] **Output:** 3 **Explanation:** It takes 3 operations to make all elements in nums equal: 1. largest = 5 at index 0. nextLargest = 3. Reduce nums\[0\] to 3. nums = \[3,1,3\]. 2. largest = 3 at index 0. nextLargest = 1. Reduce nums\[0\] to 1. nums = \[1,1,3\]. 3. largest = 3 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1\]. **Example 2:** **Input:** nums = \[1,1,1\] **Output:** 0 **Explanation:** All elements in nums are already equal. **Example 3:** **Input:** nums = \[1,1,2,2,3\] **Output:** 4 **Explanation:** It takes 4 operations to make all elements in nums equal: 1. largest = 3 at index 4. nextLargest = 2. Reduce nums\[4\] to 2. nums = \[1,1,2,2,2\]. 2. largest = 2 at index 2. nextLargest = 1. Reduce nums\[2\] to 1. nums = \[1,1,1,2,2\]. 3. largest = 2 at index 3. nextLargest = 1. Reduce nums\[3\] to 1. nums = \[1,1,1,1,2\]. 4. largest = 2 at index 4. nextLargest = 1. Reduce nums\[4\] to 1. nums = \[1,1,1,1,1\]. **Constraints:** * `1 <= nums.length <= 5 * 104` * `1 <= nums[i] <= 5 * 104`
Consider a trio with nodes u, v, and w. The degree of the trio is just degree(u) + degree(v) + degree(w) - 6. The -6 comes from subtracting the edges u-v, u-w, and v-w, which are counted twice each in the vertex degree calculation. To get the trios (u,v,w), you can iterate on u, then iterate on each w,v such that w and v are neighbors of u and are neighbors of each other.
Graph
Hard
null
1,675
Peace be upon you, my dear friend. How are you doing? O Lord, you will be fine and in the best condition. God willing, today we will solve it together. If you have not solved the issue, you must first go and solve the issue before you come to watch the video. We will try it once, twice, and three times, and God willing, you will know. Let’s get started, in the know. Let’s get started, in the know. Let’s get started, in the name of God. The first thing he tells you is that he will give you a name called Lamaz, in which you can perform one of the two operations. Here is the verse on the first operation and this is the second operation. The first operation he tells you that you can choose any number that will be the perfect Eiffel number and divide it by two, meaning you will take the number and divide it by two and remove the number. The old number and put a new number as is done here. Choose, for example, the four. This is the last number drawn by two. What is it? The second operation tells you that you can choose an odd number this time and multiply it by two. He chooses, for example, the first one by which is one, and they multiply by two. There remains two, one in two, and put the two, okay, that is the difference between or the max and between all the differences between all the numbers, meaning that you will take each number and get the difference between it and all the other numbers, and the differences that will come out to you are the max. Whatever is between them, then it remains this. He wants to remain. I mean, we know now. It means that you take all the differences between all the numbers and take this. He wants to reduce this as much as you can, of course, using the two operations that he gives you. Okay, okay. We can know in another way. He. What is the difference between the smallest number and the largest number? If you add and subtract from it will be fine. If you take the max and subtract from it, this will give you, for example, this X. You can answer a difference greater than the Greater than the difference between any two other numbers in the chart. Okay, okay, because this is the max. Certainly, a million percent. The difference between them will be greater than the difference between any two other numbers. What is we calling it here? Ok, let's see the first example. The first example with us is one, two, three. Four told you that the difference will be one. Okay, okay, how come the difference remains one? In principle, let's erase this recent talk of ours. One, two, three, four, this will be four, half a half, one is petals. He told you that I can get less than three. I can get one. How can you get it? He told you that I will take the two or the Syrians of these four and divide them by the two, so my relative will remain one, two, three, two. Now, there will be how many three, one half, how many two, ok. He told you, I can take this one, multiply it by two, and I will have two, three, two of mine, which will be three. It is the sum of the two, so the difference between them is the same. In fact, he was able to find a single difference. Okay, so what did we do? The first thing that was close to us was in this appearance. Mine was four with half a half of its petals. I found that this four is an even number, so I can divide it by two, so when I divided it by two, it gave me two, so if the max is Mine now is the three that is the one, so when I subtracted them from each other, it gave me two, I said that since the one is an odd number, multiply it by two acres, so the max remains is the three, that is, two of them, so I subtracted the three from half a two, and it gave me one, and this or the minium that I can get, meaning The most or the least thing I can answer is perfectly fine. After that, in the second example, he told you what. In the second example, he said to you, I can answer three things. How did he tell you that you can work on it at two, and at five, perfect? Meaning that you will take this one and multiply it by two, so that remains. This will give you how many in the largest line: four, one, five, twenty, in the largest line: four, one, five, twenty, in the largest line: four, one, five, twenty, three, so you will come to a single number and multiply it by two because it is an odd number, so you will get a two, and you will come to a number twenty and divide it by both, you will have how many tens, then you will divide it again by two, and you will have a perfect five because it is an even number, and in the end you will be left with How do you deal with it, there will be three, and this will be five, as this is two, and this is four, so in the other countryside, where are the five and the two minis? Subtract them from each other from your hands, three, all right, and so on, the same thing remains for the third example, and any other example. I understood the idea from the question or the question, what do I want to be able to do? I continue to apply this idea. The first thing that is important to me is that I answer and try to make them come closer to each other. Okay, so I came, for example, in this village and said that I have one, two, three, four. I have two operations. Correct, the first operation is to remain on the even numbers if I divide by two in the even numbers. And what do the odd numbers become by multiplying them by two? Okay, okay, so now I can say that I have something called sweet. We assumed that we want to bring them closer together. The first thing is, oh, let the minimum get closer like this. I mean, what does it get closer like that? I mean, it increases, as long as it gets closer to the gain, it definitely increases, for example. Seven, I want to bring them closer to each other. Either let this one be larger than one, two, three four, so I am close to seven. Either I take this seven and reduce it. Okay, okay. I took care that I am close, meaning I am increasing and decreasing, meaning I am decreasing. Nice, these are the two operations that I already have. The two operations that I have an operation. It is done on odd numbers and an operation is done on even numbers, a multiplication operation and a division operation. This multiplication operation increases this division operation, which reduces the correct. So now I can say that if my minimum is an odd number, then inside it is a blessing that I can multiply it by two closest to the max, so that the difference is what Between the minimum and the maximum, it is said to be true, or I have it. It is an even number, and then I divide it by both, so it is close to one hundred percent of the semen. And so I am trying to reduce the division. It is nice, but someone will tell me, “Okay, beautiful.” Maybe, for example, like the village I have, it has a number of six. I hundred percent of the semen. And so I am trying to reduce the division. It is nice, but someone will tell me, “Okay, beautiful.” Maybe, for example, like the village I have, it has a number of six. I hundred percent of the semen. And so I am trying to reduce the division. It is nice, but someone will tell me, “Okay, beautiful.” Maybe, for example, like the village I have, it has a number of six. I have six, so I have one. I have two jobs, but whether you take these six and divide them into two, so they remain three, you will tell me that. It is beautiful. I now have three, half a dozen left. I will tell you, wait. 31 What? You divided the three, so the maximum is variable. Perfectly, the maximum is variable by four. If yours is there, it remains four. Okay, then we need this. If we are bringing the minimom and the maxone closer together, we will show you that the minimum and my maxone are changing, so when they change, I need to do what I should do, take the new one and leave the old one. You will tell me that, maybe the topic will be ruined, and I will tell you that no, there are no topics that will be ruined, and there is no need for that, because now I have something like this. You said that I will take the six and divide them between the two, so three remain. Right, right. There is no problem. Whether it becomes three, or not three, or whatever. I mean, the max means there are six, or three remain, or four remain. I am like this, a million of my percent. Say, I mean, it is better for the max to be mine. There are six and my minamo is one. The difference between them is not five. And when I divide by two, I still have the maximum that is four and the minimum that is one. Of course, the maximum is four. Even if this is after I divided it into two, there is no difference. It is not a problem. Give me what I said from five for you to four, minus one of its petals, so I will ask for a job. I will repeat the same thing. I will keep repeating this same process until a certain time comes and I can no longer do this thing. Ok, an idea like this came to us. What should we do? If we take the whole couch and multiply it by two, why do you now have one option for the odd verse numbers because the odd number? The one that is the cat is multiplied by an even number. The one that is an even will give you the number of an even, one million percent. Correct. What I am saying here is the two. I mean, multiply the power by the even, and you will get an evil. This is a million percent. This will happen. Okay. You do not have an option with the odd numbers except one thing. You multiply it once but by two. This means that if you have a number, for example, in this one like three. The option in front of you is that you leave the three as it is. If you multiply it by two, what remains is six? You will tell me what six is. This is an even number. You divide it by two and it returns three to you again. Then you You only have three, meaning it is an odd number, and when you multiply it by two, you have an even number. You do not have any other options, but even numbers are not normal. It may remain 20, for example, 20. This was divided by two. Your hand is ten. You can divide it by two, so you have five until you arrive. For an odd number, then the matter stops. Okay, so we said what, by God, this is an idea. We can multiply from the beginning all the odd numbers by two. So, what did we do? Let us multiply all the odd numbers by two. Our options all became even numbers. I have one option left, but the one that is mine is this. Let's multiply it by two, so it remains one by two. Two by two by four. Two by three by six. Four by two. With a sweet wish. So, I am the option that I have now. What should I do? I am dividing by two, but it is correct. Yes, because all my numbers have become even, so I am the option that I have the second one. I swear by two. I don't have any other option, so I will say, by God, that my sleeper is mine. And I have something called what to do. I will take the subtraction between it. This subtraction will give me how much it will give me. Six. Sweet. After that, I brought the six. I swear, the remaining verse is the wish, so divide by these two. How many of your hands are four? It is four, sweet, but this time I change. There are six left. The six remains. That is the verse. Subtract them from each other. You have four sweets. Take the six, divide them by two, and you give you how many sixes divided by two. There are three sweets. Sweets. Then you have the four. Subtract them. Your hands are two sweets. Sweets. I swear. The four by the two, which is this four, divide it by the two, and you get two, and I will give you two. Remove the four and divide it by the two, and put two. So I am like this. What should I do? I will take the maximum. I will subtract them from it, and I will divide it by the two. But this is the option that I have. Even if an odd number appears, I will not see it. There is no problem in the first place. What are you going to do with the number? We said you multiply it by two, as this is the only one you have. There is no use for another two because it will give you an even number and the number is even. Either you divide it by two, or you will not do anything. Okay, so you already made these three for her in the first verse when you multiplied the ariyah. It's all in two. Fine. You can't even multiply the even numbers by two because it's even. Fine. But if you hit it and don't multiply it won't make any difference to you because just like that, you'll go back to drawing on the two again, but you don't have to multiply it by the even number. Fine. Now you have it. Yes, the three are your top verses, they are yours, two were thrown out by your hands, one here. You will tell me how I will tell you that we were playing on something. Either we bring the minimum closer to the maximum, which means we increase it, or we reduce the mixon. Ok, we said how to increase it. We said that it must be an odd number. And the odd number, in order to round it up, we multiplied it by two, which is my child. The first operation we did on the ariya in the first place is that we multiplied the entire ariya by two. Okay, when another odd number appears for me, and the operation that I am doing is that I reduce the factor that is divided by two. I divide by two. I meet an odd number. What is three, then these three, can I reduce them? No, you are the option that you make on the odd numbers. The operation that you make on the mouse is that you multiply it by two, then at that time the three will not be able to do anything. Someone will tell me, “Ok, we stopped. What do we continue?” I will do anything. Someone will tell me, “Ok, we stopped. What do we continue?” I will do anything. Someone will tell me, “Ok, we stopped. What do we continue?” I will tell him, “Be careful, remember that what we are looking tell him, “Be careful, remember that what we are looking tell him, “Be careful, remember that what we are looking for” It is the minus or the difference for” It is the minus or the difference for” It is the minus or the difference between your max and your maximum is three and your minimum has two, any two of them will not make any difference. The operation that we are currently working on is that we are reducing. Tell me how you will reduce this number of singles. Okay, then I will not be able to reduce the three. Ok, I will not be able to take a number other than three because it is the max. It is our turn now to reduce yours to an odd number. That's it, you won't be able to do anything else, and this will remain my answer. Yours will remain: What are all the things that you have identified? The six, the four, the two, and the one of them. You will actually find the answer to the remain: What are all the things that you have identified? The six, the four, the two, and the one of them. You will actually find the answer to the remain: What are all the things that you have identified? The six, the four, the two, and the one of them. You will actually find the answer to the question, it is one, and this is the solution to the question very simple. Okay. Let's try the verse in the second example. The second example is four. We said the even number, we do not have to multiply it by two, so we will leave it as it is, two times one, two times five, two tens, two times twenty, as two times three sixes. Take the twenty and take the two. Subtract them from each other. How much? 18 So now you have the first number that comes out to you. It is sweet. 18 Sweet. You will take the twenty that is and divide it between the two. Your hands are how many. Your hands are a sweet ten. Give me a ten. Subtract the ten from the two. Your hands are a wish or a no. 18 No. The wish remains what you remove. 18 And leave the wish and divide it by the two. You will be given five, exactly, and then ten. This is the same thing. She will give you a wish and take the ten and divide it between the two. She will give you five, exactly, okay. What six? Subtract them from each other. How many sixes? With four, you will then remove the wish and put the four because the four is less than the wish. Give the four good. You will remove the remaining six and divide it among the two, and it will be yours. How many sixes do you have on the two of them? Okay, okay, give the maximum, which is the five, that is, five of them. I will not subtract them from each other. Threes. If the threes, we say four, then you remove the four and put the threes. Divide the five by the two. No, you actually have the rest of your maxes individually. So, that’s it, you have finished with your answer. So, that’s it, you have finished with your answer. So, that’s it, you have finished with your answer. Threes. Like the question, he didn't tell you, okay. The last example is the last example, which is the example of the number three, two, ten wishes. There is no odd number. There is no problem. So, divide by two. The first thing is to give the difference. Your hands are two wishes. Divide by two of your hands. How many hands are you? Five okay. Give the maxion wishes. Subtract the difference. Your hands are 6. Divide by two. Your hands are four. Give the maximum. Your hands are five. Five two. How many petals are there and your actual maxis? This is the end. Your answer is the least one of the three. These are the three. And this is the same. Do something like this. How did it remain in the code? The first thing you have is a variable whose name is like this. All your work in life. If he answers you with his long hands for you, there is nothing else, but of course in less time, meaning he and the top that is a phone, then you are fine, there is no problem. I mean, the first thing you will be blamed for is that you will take the number and say, by God, this number if it is one and one, but this is what you say. Two is equal to one. This is what is meant by the lock. Okay, so what is the end and one? If you, for example, have the number of numbers that are one, two, three, four, then you will find his one, how many one, zero, her two, one, like this, three, like this, four like this. If you notice that the first house is in the odd numbers. With a one in the even numbers with a zero, I tell him I have one. I mean, give me the first girl in my number. If it comes out with a one, it will be broken. If it comes out with a zero, it will be broken. This is what I am doing. I mean, you can look for something called, if you don't understand, consider it from this perspective, the two are equal, okay. After that, you have one. This means that I am multiplying by two. Okay. If you also have a number in the view, this is a number, for example, three, that will be one, zero. I saw what the turnip is doing that makes it put a zero at the beginning. You see the numbers towards the left. Okay, so you are one, zero. This remains it. The number six is ​​like this, so I multiply by two. I mean, if I six is ​​like this, so I multiply by two. I mean, if I six is ​​like this, so I multiply by two. I mean, if I don't understand it, then I can also say that what is written in the two columns is fine. After that, I take what is between the minimum and the ant. There is no problem. After I finish this instant, my arish remains all even numbers, because I multiply it by two with odd numbers. At the same time, I had the minimum, which is the lowest number on the chart, perfectly fine, and he looked at all the numbers and he gave me one by one. I told him that I had mine, which was supposed to be the lowest number on the table. So, I made it and made it the largest number on the list. It would still be an oil company until I made it here, under here. What? It was in this bad mood. I told him to give me the Maximum in the numbers that are available now, as it will be my top and I will make any pop for it. After that, as we used to do, we used to take the difference between them and the minis with my old one. Okay, if the Max that I am still making now is an odd number, then I will work. What should I do? Break it, so I'm done like this. Okay, if I don't want to do it individually, then I will continue. How will I say that the current minimum will be equal to the minimum? Between the minimum and the number that I am standing at is two. What does it mean, for example, that my relatives have five perfect wishes, so the max is one wish and the minimum is five, but when I did this, I was supposed to make him a bush, but after I divided it into two, then when I divided it into two, it would still be four and five, so the old one didn't have the new one left, so I would do that and tell him, maybe, this number, I divided it into two, would still be the new one, so what are you going to do? You're going to take the old one. And the maximum is on both, ok. After that, I start with the maximum on both. Okay, the one who saw the shift saw, ok, I saw the numbers. I mean, for example, if I have a number like six, for example, then this six’s pin will be example, then this six’s pin will be example, then this six’s pin will be one, zero. I saw what it means. She saw the numbers to the right, so they will remain one, and the zero comes here, so they will remain this. What number is it? Three times. I call it a name for both if it reverses the process. If you don't understand it, this is multiplying by two, and this is a name for both. I mean, but when I finish, what is considered to be what he said or ours, but if you don't understand, you can repeat the video again. If there is anything you can write in it. Comments, I will see you next time, God willing. Peace be upon you
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
54
hey guys welcome to one more video in this video we'll talk about spiral matrix problem uh actually in last six months this problem is asked by microsoft multiple times along with amazon and facebook so this is a quite a popular problem uh and this is an interesting problem because it doesn't require any complex data structures or any special trick to solve this problem all we need to do is just maintain some integer indexes and then we can solve the problem uh anyways let's not get into that let's first look at the problem description and then talk about the approaches okay so this is our problem description uh we have m by n matrix with numbers and all we have to do is spirally traverse that matrix so straightforward problem the diagram is self-explanatory self-explanatory self-explanatory so actually we should look at the rectangular matrix rather than the square matrix so rectangular matrix has some edge conditions so better to tackle those edge conditions while we write code or solve the problem right so we'll look at this rectangular matrix and we'll try to solve this problem so let's go to the whiteboard let's look at the approach and then as usual come back and run the code okay guys so this is our matrix m by n straight from the wrong description and we'll use the same matrix to understand the logic to solve this problem so as i said in my introduction that this problem doesn't require any complex data structure or any special technique like bfs dfs dynamic programming none of those we just need to take care of some simple integer indexes and then we'll be able to solve this problem okay so these are the four integers that we would be using to solve this problem start row start column n row n column so obviously start row and start column we start with them with zero and since android n column are zero base indexed uh we have three rows so we'll mark this as two and we have n columns four we'll mark this as three so now what we need to do is this is our matrix and first we need to traverse horizontally right from left to right so we need one two three four then eight nine then ten eleven twelve then five six seven so what uh okay so this is our code which will implement this logic using these variables so first we move left to right in the first row right so we use matrix of start row which is zero and we loop from start column to end column from zero to three so from zero to three we access zeroth row and we access all the elements so we'll do one two three four so we have one two three four in our output and now we do sr plus so we'll say start row plus we have finished this row so nobody accesses this row so this becomes 1 now next we need to access this 8 and 9 which means we need to access this last column and we need to access the rows right so matrix of end column and we loop from start row to n row now notice that our start row is one and n row is two so we'll just access eight and nine in the end column and then we do end column minus so this is done so now end column becomes 2 now next what we need to do we need to access this 10 11 12 so last row but from end column to start column right so matrix of n row last row and our loop goes from end column to start column so we are going right to left so 10 11 12 and then we do n row minus saying that this row is done so n row becomes 1. so we have done 1 3 4 8 9 10 11 12. now we need to do this 5 right so this is my first column so what do we do matrix of start column and we loop from end row to start row now notice that n row and start row both are at one right we've done this so the only row that is left is this so this will access only one number in the start column which is this right and then we'll do start column plus so start column becomes one so we have done all this now the last thing that is left is this six and seven so once we do this we come back here right now we go to matrix of start row now start row is one this is the row and start column is one end column is two so we'll be just accessing six and seven so loop from start column to end column access the elements in the start row and do sr plus two and then we exit the code since we have finished the matrix so that's the complete logic to solve this problem so let's just write synthetical code and then submit it and run against all test cases okay guys so we are at the last part of this video and if the explanation on the whiteboard was easily understood then this is simply extension of that approach or extension of that pseudo code to actual java c sharp or whatever language you write so let's look at the code and then submit it so we have this uh variables that we discussed start row and row start column and then in while loop we have condition that start row should be less than in row and start column should be less than n column obviously and the only thing that is different or the thing that we didn't discuss on the whiteboard is this direction so this is a simple integer variable and we keep the direction between 0 to 3. so if direction is 0 then go from left to right direction is 1 down if direction is 2 left if direction is 3 then up and so basically what we do is in one iteration of while loop will be performing only one operation so this is what that switch case will do so initially direction is zero so we'll perform this and then we'll come here we'll increment direction by one obviously mod four so direction will never go more than three so now direction will one will come again in the while loop will perform the second operation direction will be two again in the while loop perform third operation again in the while loop from fourth operation so what this does is basically we only perform one operation and then we come at the while loop to check condition whether we're good or not and then we come to perform the second operation if we would have written all for loop sequentially then we had to write if condition before each for loop you can do that if you don't like this direction variable just simply remove that and whatever the condition is there in while loop put it as if condition before each for loop and the same code will work so that's it so let's submit the code uh let's see the output and there you go all the test cases pass everything looks good since we have done this problem i just wanted to show one similar problem not similar but exactly same problem uh and same logic or same approach will solve that problem so the problem is spiral matrix two so in this instead of traversing the matrix we need to create the matrix so basically it's a n by n matrix square matrix so let's say if n is 3 then we need to create a 3x3 matrix and we need to fill numbers from one to nine in a spiral manner if it's uh if n is four then it's a four by four matrix and we need to fill one to 16 numbers so just similar logic so instead of reading the matrix we need to put the values or put the numbers in the matrix so as you can see the code is right there it's very similar uh i'm sure you guys must have noticed that there's no direction variable or the switch case that we had in the previous problem so the reason for that is since this is a square matrix the row min and column men or row max and column max will have same values after all the four loops whereas in rectangular matrix they can have different values right so that's the difference uh anyways the complete code would be there in the description box you guys can take it and try it out and see for yourself that what difference that direction thing makes in rectangular matrix was a square matrix let's just submit this one and make sure that same code runs and then that'll be the end of it so that's it guys i hope this video was worth of your time and if that's the case then just crash that like button and all the usual stuff subscribe and then let me know if you have any suggestion any better approach in the comment and then i'll see you in the next one take care
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
502
hi guys today we'll talk about our next two heap coding pattern related question this question i don't go and read out all the description what was being said but i will go to the input and i will explain what it was asking about so we have some number of projects and to start any project we require capital at index 0 if we will complete that project we will get the profit f1 if you will complete project which is at index 1 we it requires capital 1 and it will give the profit of 2. to complete the project at index 2 it needs capital 1 and give the profit 3. they're asking that we can only complete k number of projects and initially they gave us some capital and to sum up they were asking pick a list of at most k distinct projects from given projects to maximize your final capital and output your final maximized capital so we have to maximize capital by completing k number of projects let's go further understand with example all right so we will follow the same flow what we mostly talk about that we will follow reactive where r is for repeat e for example a for approach c for code d for test o for optimize we already know about two heap coding pattern in two heap coding pattern we already talked and go through two questions where we get one maxi one min heap in case when there is some ordered number and we have to find something from the middle in that case median in previous two question now this question is about second rule in second rule what we were talking about that if some object or any entity that contains two property p1 and p2 they are p1 is directly proportional to p2 and in some question they were expecting p1 should be max and p2 should be minimum we this question about this is exactly the same now let's understand the this question with example so for this example we will pick the same example what was given they were saying that we can complete only two projects initially they have given us initial capital is zero and for project they are saying to start some project and it requires capital for a capital of zero and one it means that at index zero we have capital zero at index one we have capital one and the project that we can start which is at index two uh it has capital one also for those projects the profit that we can get one profit if we complete that project that starts with capital zero which is at index zero so we will get this profit and we will get the profit two of the project which is that index one we will get the profit of three at index two so we say that this is zero one two so i just give the color to make better understanding red for profit green for capital so now in the requirement they're saying that they want to project that we can distinct to project which could maximize our profit we will go with some project which require minimum capital to start working so any project that require minimum capital to start working we will pick them and we will try to get the maximum profit out of it let me rephrase what i'm talking about so if you observe that for the project these are two properties so most of the cases apparently it looks like the project capital is directly proportional to profit it doesn't always true but these are this looks like very close calculation like if some project has requires more capital so it will give them more profit now in this question they were expecting that we should get we will spend minimum capital so that we can get the maximum profit in this case at the end we will get a maximum available capital with us so it doesn't it looks like a balance problem so i can say that this is looks like a balance it should be maximum and the other part should be so if you pull one thing so for profit so that profit we want to maximize that and this capital that requires to start that project we want to minimize this in this case we can get maximum benefit maximum profit out of it do they want to maximize it and they want to use those projects that require minimum capital okay let's see that how we can implement this question using two heap coding pattern so we will use uh maxi and we will use a min heap for maxi i'm using this for profit and for min heap i'm using for capital so this is a max heap and this is a min heap i'm just telling you about the mental model how you're going to do that we have set ordering for these mean heap and maxi considering their values these this ordering is that when whenever we are going to save indices into these min heap and maxi so in that case before saving that indices he's going to evaluate from these values so ordering is with the values and we are saving their indices maybe first go and look for we are going to save zero it will come it will save zero index here this next pro next project and we will see that this is its value is one so we will save one for the next let's say one and uh for the third second one this one we will save its index here also at this stage we know that these are the capital of all the projects that we can use and at the top is the index of the project which could be started with minimum capital now we will see what capital we have right now so available capital is zero this is available capital and with this capital which project we can start what we will do we will dequeue all project that could be started with available capital and we will put this and we will put the index of profit into our maxi now in this case what will be the shape we will dq 0 from here for this index we will look into the profit and its index will be saved here so we'll save index 0 because that's the project who's which could be started and we will get the profit of one so we will dequeue that in this case we don't have here zero we have left with one and two and maxip with zero we get some project which could be started with our available capital and we can get some profit out of it so with this what we will do in the next step we will dequeue that and whatever the profit we can get so in the next step we can see that in our capital we will add profit of project at index zero so in this case we will dequeue maxie and the next shape will be like this so there is nothing and in the minhy we have two project for index one and two now we have available profit at this stage after completing the project at index zero we have now profit one that you can get from here when you complete that project you get the profit one so our available uh capital is now one now we will dequeue all those projects from our mean heap which could be started with our available capital one so and then we will save those indexes here in our available capital is one so you'll see one and one these two project could be started with our available capital one and we will save their indices in the maxi and when we are using maxi for sure it will put two at the top and one at the bottom we will get our max heap in this shape now there is nothing in min heap it is empty and in the max heap we have uh we have added actually two and one y2 is here at the max because uh this capital uh this profit is maximum and this is max in the next step what we should do we just use the project at the top and we will use it in our capital so we will say project profit at index 2 use it in this case so that will be the whole flow so you can see here we have uh our available capital zero we pick a project that could be started with this available capital and we get the prof profit out of it so it will become one at this stage then we use that capital and we dequeue all those project that could be started with this available capital we put them in the max heap and we pick the top one from the root that is going to give us maximum profit that's the way we can maximize our profit i think that makes absolute sense how we are going to use min ape and maxi to get the maximum profit now let's see how we can use the code all right welcome back so that's code and we already know that we are going to solve this question using to heap coding pattern first we will use min capital heap we will get a priority queue we will use odd ordering for this pretty queue in such a way from less than in such a way that it should maintain i mean he mean capital heap so it will look into capital array and whichever the minimum value that index will be added so from less than we were saying look into capital and the consider that it should be every new element should be less than so we are saying capital of this we can maintain a max cap max profit heap and we will use the same pretty queue and for ordering we can say that from less than and in this case we should look into profits and that profit should be make an order in such a way that we could create a max profit heap now we go about our flow what we were talking about the mental model how we can execute and complete this solution so first what we will do in the main capital heap we will add all the project so we will go for i you're just going to save indexes for unit until capital dot land for all of that we are i don't need that even so i can go and say in the mean capital heap dot enqueue index so in this case we will fill it with uh in case of example so at this stage we have filled our mean capital heap with zero one now we will get a variable with available capital and we have initial capital of w so in scala there is not a break and continue statement the way it is used in java so we have to define a block which is breakable so breakable and inside we can go and say this is just a scala block for breakable code we are going to complete k project from zero until k project because we can call we have to just complete k project maximum at most we will see we can say that while our mini capital heap is non-empty capital heap is non-empty capital heap is non-empty we have something there and whatever in the mean capital heap at the top its capital is less than our available capital we will consider that project and we will add it in the maxip so we will say in capital from min he mean capital heap dot hat look at the top element and from the array using this index we will get its capital and we will compare it with our available capital if that capital is less than or equal to our available capital we will go and enqueue that project into our max profit heap so we are going to consider that project that okay we can we with this capital we can complete this project so we'll enqueue and we will dequeue min capital heap dot dq we got all the list with our uh all the list of project that we can complete using this available capital and we add them in our max profit heap now we see that if our max profit he is empty it means that with our available capital there is no project that we can complete so we can start working so it means that we had a break we are done there is no more project that we can start with our available capital if it is not so what we will do we will say our available capital will grow and we are going to get the profit out of it so we will say profits whatever the profit will be from max profit heap dq we will dequeue that and that index we will get from profits array and we will add it in our available capital and then finally we can return our available capital so let's run it all right so it is complaining until our spelling was not correct that's it so hopefully that will make some sense really thanks bye
IPO
ipo
Suppose LeetCode will start its **IPO** soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the **IPO**. Since it has limited resources, it can only finish at most `k` distinct projects before the **IPO**. Help LeetCode design the best way to maximize its total capital after finishing at most `k` distinct projects. You are given `n` projects where the `ith` project has a pure profit `profits[i]` and a minimum capital of `capital[i]` is needed to start it. Initially, you have `w` capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital. Pick a list of **at most** `k` distinct projects from given projects to **maximize your final capital**, and return _the final maximized capital_. The answer is guaranteed to fit in a 32-bit signed integer. **Example 1:** **Input:** k = 2, w = 0, profits = \[1,2,3\], capital = \[0,1,1\] **Output:** 4 **Explanation:** Since your initial capital is 0, you can only start the project indexed 0. After finishing it you will obtain profit 1 and your capital becomes 1. With capital 1, you can either start the project indexed 1 or the project indexed 2. Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital. Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4. **Example 2:** **Input:** k = 3, w = 0, profits = \[1,2,3\], capital = \[0,1,2\] **Output:** 6 **Constraints:** * `1 <= k <= 105` * `0 <= w <= 109` * `n == profits.length` * `n == capital.length` * `1 <= n <= 105` * `0 <= profits[i] <= 104` * `0 <= capital[i] <= 109`
null
Array,Greedy,Sorting,Heap (Priority Queue)
Hard
null
843
alright I'll guess I'll start so this problem was suggested by somebody on the discord Channel so I figured I would take a stab at solving this so before I start I just want to let people know that there's no guarantee that I will be getting the perfect solution or the best solution I think the objective of doing these is to kind of show you the top the thought process that I have as I solve these questions so let's get started the problem is guess the word and I have been reading through the description for the last couple of minutes so let's just read it again so that we can follow this so this is kind of an interesting problem because it seems like this is one of those lead code problems that are like it's I don't think there is a perfect algorithm for this because if you're depending on your test case you could technically have something that you can never find the solution for because what if the Oh also if your guess is not enough okay alright so um I guess the idea is that will give the will given a list of words and then we have a secret but we don't know what the secret is and then we can call this function mastered guess and returns my negative one if there are no letter mapping matches so the index of the strings the letters need to match is that correct or is it just generic matches let's see here the function returns an integer type presenting the number of exact matches value and position right so if I'm drawing this out so ABC and if I have a zc then I guess Master dot guess would return two because these two match so yeah like you can see here they say there will be five test cases each of which have only hundred words so that's what I was thinking if there are more than like thousands and thousands of words and if they're all like these unique combinations I don't think we could do very well with at most ten guesses for the word so currently what I'm thinking is so this is what we have to implement let's go over here we'll have to implement def I'm gonna make this a little smaller so after implement find secret word and then this takes in a word list and master and then the master has that guess method so if I'm given a bunch of words and if I call master guess on all of them so chances are I can at least throw away the ones that have negative one I think that would be the knife solution where I have a for loop that goes from 1 to 10 right because I can unload it from 0 to 10 and because I'm allowed at most 10 guesses and then what I can do is in each iteration I can call negative 1 but wait how does the master don't guesswork it takes an award so what else so what I will have to do is I can pick I think I'm reading the question room you have 10 guesses to guess the word oh ok so what I can do is I can pick a word randomly from the list and I can call guess against that so say that word is ABC and I get the score - so what does ABC and I get the score - so what does ABC and I get the score - so what does that tell me that tells me I need to remove all the guesses in the word list oh I need to remove all the words in the word list that I'm thinking are still candidates of to be my secret if they don't have at least two value positions in common with the string right and then that will reduce the size of my list and then I can pick another word randomly and call guess mastered guess on it again yeah I think that's gonna be my way of doing it so that means I will need a helper function that checks how many value positions two words have in common right and I'll implement that later I will write down the main logic first so let's say I'll use this I'll do this using a while loop because I get 10 guesses right so I'll even put in this function later but for now let's assume that they I have written a function called random word that gets a random word from the word list and what else do I need oops I should have put my phone on Do Not Disturb okay so now I will need to get some matched count equals two I'm gonna call master dot guess word so if this is let's think about it this way if this is negative one what does that mean so if this is negative one it would mean so if my this is ABC and say this is my word this is the thing I've gotten from my random word call and say my secret is de F if the value of Master guess is negative one it means that none of these are in common right so even then I can use this data point to my advantage so if this was a positive number then I would look for okay does this do these two words have at least one letter in common if so then they say but if it is negative one then I can say do these words have any position in common if so then this is not the secret right so if I was comparing ABC another word in the list that is a EF just because even one of them are in common I would be able to say confidently that a EF is not the secret right so negative one is also a helpful data point so then I can say word list close to remove candidates and this is another helper function that I will implement later and then I can say this takes in word and then the matched count because these will both me and then actually I shouldn't write this first because what I should account for is if matched count equals to 6 that would mean I found my word right so what am I supposed to return oh I'm supposed to return none so it should it'll just automatically work I assume if mastered guests is 6 it automatically just breaks the program so what I had written before is correct let's see if I can undo this yeah there you go ok and then this so this is gonna be my main program okay so now let's write the helper functions so the random word part to be honest now that I'm thinking does it matter if I pick something random or not I could literally just pick the first thing and that would be good enough I guess randomness does give me I don't know depending on how the area is arranged I'll just implement it anyway but I don't think it would give me any advantage like picking the first one or picking something in random I don't know if it gives me any advantage but then for random I'm going to import I think in Python it's called R and I don't quite remember and then I can just say return a word list I want to say it's Rand int and then I can just put in the word let's assume this is how it works so that's another thing I've done in during interviews is when I can't remember like exactly how these functions behave I just tell them what my assumption is on how they do behave because these are things you can just look up online you can just google them and figure out okay this is what the random behavior is it picks anything randomly between 1 and the number that you're passing or 0 and the number that you pass in so for our cases what I would tell the interviewer is hey you know what I'm just gonna assume randon return something between 0 and less than the length of the word list and I have never had a situation where any interviewer has stopped me they'll either say okay that's fine or they'll usually just clarify that oh you know I don't think random behaves that way I think it picks from 1 to length of worthless in which case I would just do random lengths of worthless minus one so it's a very short conversation that you can just have right away with your interviewer but yeah don't be afraid to list your assumptions as you go through actually it's very important to do so and then and this is gonna be our main this is the meat of this problem I think which is to remove candidates because we need a very smart way of removing candidates so that we can make our list of new candidates way smaller than the last one so I'm saying this takes in a word and you know what I'm tired of writing match counts so I'm just gonna write comment over here okay so I feel like if it's negative one then it is very easy so I'm thinking I'm guessing I need to make this some sort of like if-else loop because if it's of like if-else loop because if it's of like if-else loop because if it's negative one no here's what I'm gonna do oh but this also needs to take in word list right because I need to iterate through all the words so comma they should also take in the word list right because that's how I'm gonna be weeding out candidates so the new word list is gonna be an empty list to begin with and now I'm gonna say forward in word list right I'm gonna say well okay before we move on the other thing I wanted to think about so negative one we already described what happens like if you have even one character in common you'd say that you know what this is not a viable candidate what happens when you get ABC and your master dog gets value is two and then you're comparing against say some phantom string let's just call it XS x where or this is confusing let's just call it well control we don't know what these are and you get to and when you're comparing these you get the value that all of these are equal so there are three characters that are matching that also means that this is not a viable candidate right because what you want is if it in if and only if it's the exact value then it's still a viable candidate right so I think that's I'm glad I went back there because I think that's gonna be important so now so basically it's not at least two it is exactly two so whatever the count for the word we got in master guess for each word that I'm comparing in the word list I want to make sure it's exactly that and only then do I keep it as a viable candidate in my next iteration so I will come now I'll compare the two words and I know for a fact I think they've mentioned that all these are at most six character lengths why is this moving there you go I think yeah each word is six letters long so I can just write it for I in X range dogs yawning and then I can say six you need to go to the bathroom god dammit alright my wife will take him for I in exchange if over here I'll need to keep a variable matched that tells me and matched should be zero at first so for I in X range six if word I equals to W which is the word that I had guessed this time randomly which I had randomly picked then I'm gonna say matched plus equals to 1 right so now I need to check now if count okay I'll just it's only six I was thinking I should I could cleverly break early in the loop because if I even get one match and my count is negative one that I know this is not a candidate but that could introduce a little bit of messy code so I'm just gonna have void that from now maybe I can come back to that later and do this so I'm just gonna keep track of matched okay so this counts how many are master so now I can say if matched equals to count only then do I have this word to my list of viable candidates right so let's think about what happens here if my count is negative 1 and even if none of them match then this is 0 right so that's not what I want so I want the matched to be negative 1 and then I can say if matched wait ok we're getting into a weird territory here why does this thing have to return negative 1 why couldn't it just returns 0 it's so stupid all right whatever I can do if masked equals 2 count then or massed equals to zero and count equals to negative one right because even then it's a viable candidate I can't help but feel there's a clever way of doing this too but whatever and then in the end I can return new wordlist so because this is such an entry I have never seen a problem like this in an interview before where it just doesn't feel like there's an obvious amazing solution like all I can do is a heuristic not necessarily a deterministic algorithm beyond this I can't really think of any ways that yeah I can't really think of another way that I would solve this problem I mean at this point the classic things I would do so here's the thing these are this is one of those problems that's difficult to solve without having somebody to talk to without having a you know an interviewer or somebody who can talk to oh i Speights as KD tree what do you mean by that do you mean a KD tree could be used maybe but how exactly I don't all right well yeah like I was saying at this point what I would do is I would just unit test each of the functions that I have the functions to be honest the functions involved right now are fairly simple so I don't want to kind of I don't really construct a KD tree over the word list when you say Katie tree do you mean something like I try how should you determine who the parent is going to be of the KD tree start with the random word then check the character diff between secret and that word move to neighbors with that much character difference that is that would be a smart way of doing it well actually let me see let me think about it so if I had ABC and I picked this as a random word then I would compare this with all the words and I would know that okay these are all the ones that I don't have a match with these are I have one match what these are two match with but how is that alright maybe I need to read up on how KT tree works but I don't understand how that would give up give me yeah I guess I need to read up on territory to see how it would give me an advantage in terms of runtime okay well like I said I don't always come up with the best solution but I think this is one of those cases where it seems like ice by it has a pretty intuitive data structure that would apply for a problem like this oh I think KD tree I will read up on that and figure out how that could help reduce the wrong time in this case all right so that's it for today
Guess the Word
binary-trees-with-factors
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: * `-1` if `word` is not from `words`, or * an integer representing the number of exact matches (value and position) of your guess to the secret word. There is a parameter `allowedGuesses` for each test case where `allowedGuesses` is the maximum number of times you can call `Master.guess(word)`. For each test case, you should call `Master.guess` with the secret word without exceeding the maximum number of allowed guesses. You will get: * **`"Either you took too many guesses, or you did not find the secret word. "`** if you called `Master.guess` more than `allowedGuesses` times or if you did not call `Master.guess` with the secret word, or * **`"You guessed the secret word correctly. "`** if you called `Master.guess` with the secret word with the number of calls to `Master.guess` less than or equal to `allowedGuesses`. The test cases are generated such that you can guess the secret word with a reasonable strategy (other than using the bruteforce method). **Example 1:** **Input:** secret = "acckzz ", words = \[ "acckzz ", "ccbazz ", "eiowzz ", "abcczz "\], allowedGuesses = 10 **Output:** You guessed the secret word correctly. **Explanation:** master.guess( "aaaaaa ") returns -1, because "aaaaaa " is not in wordlist. master.guess( "acckzz ") returns 6, because "acckzz " is secret and has all 6 matches. master.guess( "ccbazz ") returns 3, because "ccbazz " has 3 matches. master.guess( "eiowzz ") returns 2, because "eiowzz " has 2 matches. master.guess( "abcczz ") returns 4, because "abcczz " has 4 matches. We made 5 calls to master.guess, and one of them was the secret, so we pass the test case. **Example 2:** **Input:** secret = "hamada ", words = \[ "hamada ", "khaled "\], allowedGuesses = 10 **Output:** You guessed the secret word correctly. **Explanation:** Since there are two words, you can guess both. **Constraints:** * `1 <= words.length <= 100` * `words[i].length == 6` * `words[i]` consist of lowercase English letters. * All the strings of `wordlist` are **unique**. * `secret` exists in `words`. * `10 <= allowedGuesses <= 30`
null
Array,Hash Table,Dynamic Programming
Medium
null
1,046
lead code problem number 10,46 last stone weight so this problem 10,46 last stone weight so this problem 10,46 last stone weight so this problem gives us an array of integers Stones where the stones ey is the weight of the stone all right okay so on each Turn You will choose the heaviest two stones smash them together and here you have a scenario right where if x is lesser than y lesser or equals to y and if x is equals to Y both stones are destroyed If X is not equals to Y the X stone is destroyed right because in this case X can only be uh lighter than y right and the stone of weight y has a new weight which is basically y - has a new weight which is basically y - has a new weight which is basically y - x okay so at the end of the game there's at most one stone left right so we have to do this process ESS repeatedly until we have only one stone left or none which this case if there are no Stones we just return zero right okay a fairly straightforward problem can be a bit confusing here but overall it's basically comparing two heavy Stone and if they are not the same we just take the difference right and if they are the same then we just uh destroy both of them right so knowing that we have to use a priority Q so this parity c will be used to store the weights of the stone in softed order right so when we compare we can just instantly take the top two heaviest two stones right heaviest two stones okay let's start with some examples so let's say the stones is this just going to use the example given in the example section here but let's say our stones are so okay and then we put it inside the priority so right now our prior will look something like this right so we8 8 7 4 2 1 okay in sorted order that's how a priority Q works okay so while the Q size is more and one we pop both pop uh the pop two heavy Stone which is case X is 8 Y is 7 the difference in this case would be the x - be would be the x - be would be the x - y x - y x - y x - Y and then since the difference is not zero minus y so this will give us seven this will give us one since it's not zero we will push one into our partic right remember this two are top and then we push one in here right then the next loop again we take the top two stones right pop these two compare them 4 minus 2 in this case we will get two the difference is two and since it's not zero then we push into our priority C again right this all right then again we pop one and two we pop two and one the difference now is one right because 2 - 1 is 1 difference is not because 2 - 1 is 1 difference is not because 2 - 1 is 1 difference is not equals to zero we push the difference push one into it and then repeat the process pop these two and now the difference becomes 1 - one which is the difference becomes 1 - one which is the difference becomes 1 - one which is zero since it's zero we don't do anything we do not need to push zero into our stones into our priority q and since now the size of our particu is not more than one anymore it is one so here I have a Turner basically this checks whether or not the priority is empty if it's not empty I will return it the top of the parior cube which in this case will be one right so you see here the output is one let's say if all stones are smashed then this will return false and then this will give us the zero right you'll return zero just like how the problem asks okay pretty straightforward and pretty simple while look can get this done that's all I have to share thanks
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
645
hey guys welcome to a new video in today's video we're going to look at a lead code problem and the problem's name is set mismatch so the question says that we have a set of integers s which originally contains all the numbers starting from the range 1 through n so n is the length of the array and unfortunately due to some error one of the numbers in s got duplicated to another number in the set which results in a repetition of one of the number and loss of another number so in this question we given an inte AR nums representing the data status of the set after this error has occurred now our task is to find the number which occurs twice and also the number which is missing and we have to return them in the form of an array so our output array is going to have size two so this is going to be the number which is appearing twice and this is going to be the number which is missing so this will be our output format which is an integer array which will be of size two so let's take this example and see how we can solve this question so we have the input are nums of the example one now since we have to find out the number which is appearing F we have to deal with frequencies right so let me create a hashmap which will store the array element as a key and the value is going to be the frequency of that array element so we start iterating through the input array from left to right we pick the first element we check if it is present inside the map no it's not present so insert it as key and set its frequency to one in the next iteration we take element two check if it is present inside the map as key no it's not present insert it and set its frequency to one next r at two again check if it is present inside the map yes it is present so get its current frequency and increment it by one so the total frequency of two is updated to two next element is four check if it is present inside the map as key no it is not present so insert it as key and set its value as one now we filled all the elements now we have the hashmap ready since they mentioned this condition that originally the array consists of all the numbers from range 1 to n so I'll use a for Loop where I will start from one and it will iterate till I is equal to n and here n is the length of the AR length of the array is equal to 4 so we start from range 1 through 4 so I will be initially 1 we check if one is present inside the key yes it is present if it is present get its frequency is one so it means it has repeated only once but we need the element which has occurred twice so it is present inside the map so it does not fit here and it does not fit here so we move to the next equal to two now we check if two is present inside the map yes two is present so get its frequency 2's frequency is 2 so it means two is appearing two times inside the array so we found the first number which is appearing five we insert it at result of zero so result of 0 is two and now we go to the next iteration I will be updated to three we check if three is present inside the map as key no three is not present inside the map as key so that is the missing number right so insert that number I which is three into the result at result of one you repeated is at result of zero and missing is at result of one and this is the required output which is matching here now let's implement the same steps in a Java program so here I'm creating the output of length two because we need output of length two and this is the input given to us which is an integer AR nums and I'm creating the map and now I iterate through the input ARR nums and fill the map so I'm using the get or default method if num is already present inside the map it will get its current uh frequency else it will get its default frequency zero and each time you find that element you increment plus one so let's take the same example 1 2 4 so first we start with 1 check if it is present inside the map no so add it and set its frequency to one next element is two is already present so add one to it so two's frequency is two now next element is four it is not present so set his frequency to one now we fill the map now we use a for Loop to iterate from the range I is equal to 1 and less than or equal to n because we are given the range of the original numbers present inside the array now I'm checking if I will start from 1 until I is equal to nums do length is equal to 4 so I should be equal to 1 2 3 4 because we are using I is less than or equal to so four will also be included now we start with first iteration I is equal to 1 now I is equal to 1 is present inside the map yes one is present so get one's frequency is one we check if 1 is equal to 2 no so it is not a duplicate and now we go to the next iteration because we entered the if block this won't be executed and now I is equal to 2 we check if two is present inside the map yes two is present so get two's frequency is 2 we check if 2 is equal to 2 yes so assign two as the duplicate two will be assigned as duplicate so 2 is here since we insert the if statement lse block will be scripped and now I is equal to 3 we check if 3 is present inside the map No 3 is not present inside the map as key so if statement will be skipped and else block will be executed and we assign I three to missing so missing will be assigned three and now in the next iteration I is equal to 4 we check if four is present inside the map yes four is present get its frequency here for frequency is one we check if it is equal to two no so this won't be executed and since we entered the if statement else block will be skipped the next iteration I is equal to 5 and we are going out of bounds of this condition so we come out of the for Loop and we assign result of zero as duplicate so this is 0 and one right result of 0 is duplicate and result of one is missing and 2 and three will be assigned there and finally we'll return the result 2A 3 which is the expected output here so the time complexity of this approach is O of n where n is the length of the nums array and the space complexity is also often because we're using a hashmap to solve this question that's it guys thank you for watching and I'll see you in the next video
Set Mismatch
set-mismatch
You have a set of integers `s`, which originally contains all the numbers from `1` to `n`. Unfortunately, due to some error, one of the numbers in `s` got duplicated to another number in the set, which results in **repetition of one** number and **loss of another** number. You are given an integer array `nums` representing the data status of this set after the error. Find the number that occurs twice and the number that is missing and return _them in the form of an array_. **Example 1:** **Input:** nums = \[1,2,2,4\] **Output:** \[2,3\] **Example 2:** **Input:** nums = \[1,1\] **Output:** \[1,2\] **Constraints:** * `2 <= nums.length <= 104` * `1 <= nums[i] <= 104`
null
Array,Hash Table,Bit Manipulation,Sorting
Easy
287
146
hi this is kevin and you're watching google engineer explains uh today we're going to be talking about leak code 146 lru cache let's dive in all right first off before we talk about this problem too much let's talk about what a cache is okay and i thought of a good uh example that can help illustrate what is a cache so let's say you have you know like written an essay in english but you're in a spanish class you have to translate your english essay into spanish and so each time you look at a word you're like okay i don't like you know you look at a word then you get your english and spanish dictionary out and you translate that english word into spanish you have to look it up but the dictionary is so gigantic it just takes forever to look up each let's say it takes like 30 seconds to look up a word so every word in your essay you got to spend 30 seconds go to the dictionary look up the new spanish word and you know put it down it's really slow so what would you actually end up doing you'd probably like get a little note card and write down some of the words that um you use a lot so let's say um you know maybe the note card fits like 10 words and you just start putting on the note card some of the words you start seeing a lot and um each time let's say that word has already happened the second time you don't need to like go into the dictionary because you already put it on your note card so you just look at your note card really fast and like maybe that takes five seconds to just glance at it and put that down as you're translating this essay so that's essentially a good analogy of what a cache is the cache is like your note card it doesn't have all of the words in the spanish-english dictionary but it has spanish-english dictionary but it has spanish-english dictionary but it has just it has enough to store some of the most commonly used words and it's a lot faster to look at the note card than looking up in the dictionary so yeah basically this analogy you know it can be applied to computer stuff like computer data and you know maybe you're looking up instead of english spanish words you're looking up data in memory then essentially the note card is your cash and it's just a smaller subset of the full thing but it's just faster to get to so what is a cache by definition it's its behavior is allows faster access to specific data but it has limited capacity right you can't you can only write so many words in the note card cool so let's talk about the problem a little bit then what is this whole lru business well extending off that note card analogy let's say your note card can fit 10 items um but as you're writing your essay you see that oh the first 10 words that i put on here aren't actually the most commonly used and they're not like the best words maybe like you know as you read more you can get rid of the items in your note card that aren't really being used that much or like weren't used very recently and put them with more words that were used more recently and this way maybe you're going to like in the note card see more items that you know actually are in your essay as you're going through because you only can let's say you can only start 10 items you want those 10 items to be you know stuff that would actually be in your essay so you don't have to keep looking it up so one way of doing that is you can just go by lru which just means like okay the item that was most that was least recently used we're going to get rid of it and replace that item with a new item for the cache and each time you look at your note card instead of looking at your dictionary that's awesome that's called a cache hit and it makes things faster and if we're going with lru this is one way to try to like maximize the amount of cash hits versus cash misses lru isn't the only way to do it but it is the way that we're implementing for this problem and again it just means like the item out of all the words you wrote in the note card the one you used last if you need to put a new word into the note card then the one that you use like longest time ago will be taken out and the new word will take its place cool so um let's see here there's a couple functions in here right there's going to be the get function which is basically looking it up from your note card and that's explained right here you look at the key maybe it's the english word and you get the spanish word out so um that's gonna be need to be implemented in constant time and then you also have put which is putting something into the note card which again has to be done in constant time um cool and then one other thing is we have a capacity this is how much like you know items you can put in your note card for example so maybe capacity would be you know we just have to um let's just say like there's a has a finite capacity so basically um pretty simple it's like very similar to like the note card analogy and this right here this is um so this problem actually is a you know different from a lot of other leak code problems and that a lot of them problems are actually you implement some function and the function is just like within the class so but it's really just implementing some function data goes in data comes out for this you're actually implementing an object so you're um you can see here how it's called right like you create an object the lru cache which has a capacity set up and um you can put in a key you can um and you can also put in you can get the key and you can put you can call the get function on the object and put in the get a key get the value out and you can also call the put method on this object as well and put in a key value pair so basically it's like we're making this lru cache object we're not like just running some function data through so this is a something like it's more closely related to object oriented programming so basically what we're going to do is going to be implementing a class more like om right instead of like i guess you could say functional programming for some of the other stuff that um is only code and so um since we're creating a class the class has some of its own state and specifically when we're instantiating right the lru cache we're saying we're giving its capacity so it's like each cache has its own specific capacity so that's just what this is here uh yeah anyways that's what we're doing it's very similar to like a hash map with getting and putting but like um we also keep track of capacity cool so how will we build this cache well you know we see this constant time get put we're talking about key value pairs like you should immediately think of hash map data structure right dictionary in python this is a data structure that you put in key value pairs and you can get the value out by you can reference the key you can give the key and you'll get the value out and both of these operations happen in constant time so basically it would cover all this now the twist here is we also need to keep track of what was used more recently so we need to basically keep track of some type of ordering unfortunately the hash map does not have any ordering associated with it's just kind of like a jumble of key value pairs that are you know there's no ordering but we do know some data structures that have ordering so a few that pop into my mind arrays and link lists um and specifically for this problem there really is only like one like really simple and clean solution that i've seen so far and this one uses a doubly linked list and we'll talk a little bit about why in a second in the solutions here there's actually two solutions that they described i'm going to go through the one with the doubly linked list and the hashmap which i think is the solution that you will definitely want to use on the interview they also come up with they also describe a solution which is about using an ordered dictionary and i would definitely not want to do that you can mention that in an interview but i would not recommend using that as your primary solution in an interview because it's just gonna you know that's at the point of the problem it's not to say like hey i know this data structure that does everything the interviewer is going to want to see how you like reasoned how you know all the stuff i'm talking about right here about this constant time gets input ordering all the stuff they want to see you reason all that so the solution we're going to go with is not going to be like the order dictionary one it's going to be we're going to use a python dictionary with a doubly linked list together cool let's talk about how we do that we would do this so let's we'll have our dictionary and let's say we have some key keys in here let's say that we have three keys and each of these key value pairs corresponds to a value alright so this is my um crappy uh drawing um character drawing but basically like k1 corresponds to v1 k2 corresponds to v2 k3 corresponds to v3 so in the dictionary we're going to have the key which is the like k1 k2 k3 and the value is actually going to be a node in the doubly linked list so um it's hard to illustrate here but basically this k1 and then it points to v1 k2 points of v2 k3 points to v3 and because we have this doubly linked list here we can keep track of the order so let's say we um you know do something with the cache and we decide to use v3 well this is so this is like let's say the order is like this is the most recently used this is the least recently used so if we do something with v3 it has to move to the front right now it's at the back of the list so then we would you know do something like this so this becomes three this becomes one this becomes two and um and that's essentially it like each time we touch something in the dictionary we update the order in our um in our linked list and we can delete items um from our link list and dictionary together and we can add things in and that's basically how we're gonna implement this um how we're gonna build this cache so what would happen basically actually talk about that in a second um this is our going to be our data structure and let's talk about like why we chose this data structure so first like why these data structures the doubly okay so first off we need the dictionary because this gives us the constant time get input and then secondly we would need the doubly linked list because why would we because a doubly linked list allows us to remove insert nodes in constant time so what does that mean like we can remove a node from anywhere inside this doubly linked list like v2 for example just pop it out and now it's going to be v1 to point to v3 we can do that in constant time and we can also insert a node somewhere in here also done in constant time so that's why we're choosing these two data structures why not array i mean let's say you had an array of like one two three four five right and you want to put something right here in the middle like a six that would essentially require you to move all these other items over by one so there's going to be three um operations to do so and essentially like it just comes out to being like anytime you need to like reorder the array like insert something in it basically becomes um an end time operation for reordering the array so it's really it's a lot slower than doubly linked list or just a link list in general why would we not want to use a singly link list um that's has it's a little bit more of an implementation detail but basically like with doubly linked list how it works is let's say you're pointing to v2 and you want to remove this node since it's pointing to v1 and v3 you can remove v2 by only having access to that node and do that in constant time whereas if you had a singly linked list you actually cannot so let's say you have like a pointing at b right pointing at c and let's say you have access to b and you want to delete b well how do you do that what you would do is have a's pointer point to c instead but you can't update a's pointer because from b you can't get to a so like it's actually not really that ideal for doing so basically cannot delete in constant time without access to the previous node so that's why i would not use simply linked list i would not use an array we need to use a doubly linked list to do all these operations if this comes up in the interview i feel like these are going to be important points so try to remember this stuff try to like understand what's happening here cool so let's um let's talk about a little bit about how we would do this let's get more into the nitty gritty of detail so let's talk about the implementation overview so there's two things we need to implement the get in the put right we have this data structure like the let's start with the gap first this is the easier of the two so let's say we have get what would you want to do well first you check if the item is in the cache right and that's basically if the item is in this key value pair section if it's in the cache um let's just get a little cluttered what's in the cache update your list so you're basically saying all right i want to get k3 i want to get k2 i want to get the v2 out you seem to update your list to say like well since i'm touching that item and now it should move to the front meaning it's gonna like let's say i'm touching v3 i want to get kv3 out then v3 moves to the front like this because it's the most recently used and we need to keep track of the order here of how things were used so we'll first we'll update the list and two we're going to return the item pretty straightforward and if it's not in the cache then we're just going to return minus one so i think that's pretty straightforward second part we would want to do the put operation um sounds a little slightly uh more complicated but not that much more complicated um so we're yeah we're gonna figure it out so first again if the item is in the cache then you would want to again every time you touch an item that's in the cache you need to update the list and this time instead of returning the item you're actually putting something in you're not like taking it out so we're going to update the value this just means like the key value pair already exists in the cache but your um let's say the key value pair was like um the key was 2 and the value is 2. now you're saying like okay i'm going to update it like now key of 2 should point to a value of three so we need to update the value as well and if it's not in the cache we need to first check if like we're at the max capacity and that's because like we're gonna basically be putting something in but if we're at the max capacity we also have to delete something so in this previous part if we're if the item is already in the cache we're not going to delete anything so we don't really need to check the capacity but if we um are going to delete something if the cache is already full we have to delete something then we have to check if we're at the point where we have to delete something so we'll do that if we're at max capacity we're going to remove the last item and we're going to update our hashmap update our list right remove the last item from the list and we'll take the last item off here and we're going to add some a new item to the front of the list and we're going to also update our hashmap to point to it our dictionary actually let's call it dictionary let's be consistent um and if it's not at max capacity we're basically just going to be adding the item in so again we would just update our list so actually these two are going to happen regardless so it's going to be like this we'll remove the last item and then we're going to update dictionary update our list regardless uh let me move last item from our dictionary as well so this would be with new item that cool um all right so that's basically it why don't we um do the implementation so i'm just going to paste some of these notes down into the bottom part there and let's talk through it as we go through i know this might still be kind of high level so um let's talk through it as we do the implementation hopefully it will become more clear all right first off we only have the lru cache object right now so we also need to define our node object so let's start with that this is going to be our doubly linked list node so it's just basically going to be storing a few different data points first we're going to have a key i'm going to give a default value left node and write node and this is just saying like i'm giving it these default values just means like if you create this node but don't give it a key or value or whatever it's going to default to this none value so self.key that value equals value self.left why do we need um both left and right pointers for the node um because it's doubly linked list you need to point to the node that's the left of it and also the note to the right of it or like so in this example right like each node points the one to the left the previous node and to the right which is the next node in the list and we're just keeping track of the key value pair here um earlier we showed that like the key is going to be in the dictionary and the value is going to be the node itself and the value is actually going to be so do we actually need the key in the node we actually do and that's later when we delete items out from um let's say we're removing the last item we need to know what the key is so we can not only delete it from the link list but we'll also delete it from the dictionary and i'll talk about that a little bit as we do the implementation cool so we've got our node and let's go ahead and let's define some of the state we're going to use in here as well um well first we're definitely going to have capacity and then we're going to have our dictionary let's call it like let's call it a short thing a library we're gonna have um this is gonna be the head of our doubly linked list which is gonna use a node i'm not gonna put anything in it self dot head and tail are going to be our node kind of like the ends which um this is going to help us later when we uh i'll explain later but basically we're going to this is going to be like a data structure to hold all of our other nodes in it basically since these are right now our linked list has nothing in it besides the head and the tail need to point to each other so self.head.right the node to the self.head.right the node to the self.head.right the node to the right of the head should equal self.tail right of the head should equal self.tail right of the head should equal self.tail and self.tail dot left and self.tail dot left and self.tail dot left the node to the left of the tail should be the head whoops so just uh connecting up this initial uh initial things there cool next um let's move on to the get oh actually before we dive into that we need to implement a few helper functions that are going to be used right here i just kind of said like very high level update the list return the item remove the item from the list remove item from dictionary whatever insert item update our list right there's going to be two methods what we really need so i'm just going to go ahead and put these down the first one is going to be remove node and just given a node and this is the great thing about doubly linked list you just need to give it the node and you can remove itself from the node so let me just do the implementation um node well actually let's do an example so just show real quick a b c okay so let's say we want to remove node b a has a pointer into b so what if you can remove node b basically what you need to do is the a's right pointer needs to point to c and c's left pointer needs to point to a and since b has a pointer to both a and c it's very easy to do this and this is also why we need to use a doubly linked list because we can remove a node just by giving the node itself whereas a singly linked list you would need access to node a in order to remove node b all right so i'll just show let's let me do the implementation maybe it'll become more clear like that so given the node dot right which is node c right dot left the pointer from c to the previous node to the left node should be equal to node a which is no dot left and very similarly node.left dot right and very similarly node.left dot right and very similarly node.left dot right which is the node that left is a and the right pointer of that should point to node c which is node.right node.right node.right okay so that's how it should be this also explains why we need to have the head and the tail because in order for this to work uh we basically need to have this node cannot be at the end because if we say no dot right and node.right is like say no dot right and node.right is like say no dot right and node.right is like you know empty an empty pointer then dot left is going to give us an error so basically if we have head and tail on the ends then we know that we're only going to be removing nodes in the middle and you know we're never going to run into this error because there's always going to be a head and tail buffers on both sides that's why we maintain that all right and then now we're going to do this is our first helper method remove node and then we're also going to insert after and this is going to be basically inserting our node after its previous node okay um and this is basically going to be used for like um getting a new node and inserting it after the head essentially right whenever we um have to reorder our list we're going to be putting things from anywhere in it to the front of the list so we're just going to be inserting it after the head so this will be implemented as such if you're inserting a node somewhere inside of a linked list what you need to do is first you need to connect the node so let's say it's like this a okay a and it's already pointing to c um if you want to put a new node b to go in between these then you would say node.left you first you would say node.left you first you would say node.left you first you need to connect the pointers on the node you're inserting so node.left equals previous inserting so node.left equals previous inserting so node.left equals previous right so to the left of the node it should be a and then node.right and then node.right and then node.right should equal previous dot right so previous is a previous that right is c you're just connecting up the nodes the pointers for the node itself and then right now a is still pointing to c and c is still pointing to a so we also just need to update those so you can just say node.left which is a now dot right node.left which is a now dot right node.left which is a now dot right which is pointing to c it should now point to the node itself and then note the same node.right which is c dot left the same node.right which is c dot left the same node.right which is c dot left it should point to the node all right so that's basically remove node and insert node um when you talk to the interviewer about this these are pre-fundamental functions pre-fundamental functions pre-fundamental functions um you know you want to get these right even if you miss something though usually in the interview they're not going to like run the code so it doesn't really matter it's more about your explanation make sure you get the explanation right the remove node allows you to remove a node somewhere in the middle of a link double-click list it middle of a link double-click list it middle of a link double-click list it can't be at the end and that's why we have the head and tail nodes and then for this one inserting after again allows you to insert somewhere in the middle of this the list in constant time and with doubly linked lists we're just connecting up all the different pointers cool so we have these two helper functions that we're going to use in the rest of our method here and also i just um started each of these methods with an underscore i just saw online that the convention for python is uh starting with an underscored means like a private method uh that just means like from the perspective of like you know if you're calling this lru cache object you're not gonna call dot remove node this is only gonna be accessible to other methods like the put and get methods that are within this object so that's why i created this underscore thing all right and you could talk about that in the interview as well this basically allows you to do something called encapsulation which is a big part of big benefit of using oom uh sorry oh oop object origin programming um uh yeah basically it just means like these like implementation details are abstracted away and you know the methods that are exposed um do not have access to these private methods all right cool so we're getting there we have these two helper methods we've got um our initializer um set up so we seem to set up our get and our put which is uh we've already written some pseudo code as well uh if you got this far in the interview i feel like you're gonna be doing pretty well here's the tricky part is now we have to do this implementation and just get it right it's very easy to make a mistake in this part but i think understanding and capturing the conceptually what's happening and showing this interviewer is already like doing pretty good but let's try to do the full implementation here and see if it works but i think like again like even using the pseudo code and like kind of replacing it line by line could help i just as i've done this problem to prepare for this video i've found that it's very easy to make like a small mistake um while you're doing the implementation so just be careful all right let's do it um i already written the pseudo code let's just start updating the pseudo code with real code all right so let's start with the get we're just gonna um so if the key is in your what's it called um self.lib just saying like you know if the key is in lid that means that this key is already in our cache if that's the case all we need to do is um first we're going to update the list so um first we're going to grab that node then right so node equals self.lib self.lib self.lib of key and it's going to be somewhere in the um in our linked list we don't know exactly where but we basically need to move it to the front because it's most recently being touched so first we're gonna remove that node and then we're gonna move it to the front all right we're inserting the node right after the head node um and then we're going to return the node's value okay simple and if our key is not in our cache already then we just return -1 that's just like part we just return -1 that's just like part we just return -1 that's just like part of the definition of the problem all right cool so we basically just implemented this part that's pretty straightforward pretty easy nice all right next we're going to do the put part so again if items in the cache then we're going to first update the list so that's pretty much the same right we're gonna get the node uh which is the key value pair in our library the node is the value we get that node we remove it from wherever it is we insert it to the front and then now instead of returning the node's value we're just going to be updating the value so we'll just say node.value the value so we'll just say node.value the value so we'll just say node.value equals value right that's basically like saying we already have some key value pair in our cache but we're writing in a new value into it so we have this oops node dot value is this new value okay and we can return here if this is the case otherwise uh if the key is not in the library then we have to now becomes we get a little bit a few more corner cases um first we have to check if we're at max capacity so like if so how do we do that how do we know how many items are in our cache right now we don't have a variable for it but that's okay because the library only contains key value pairs of items that are in our cache and we can in constant time get the length of our library that's one thing that the actually the doubly linked list is not that great for you can't really tell how many items are in the list but the live python dictionary has this we can just do if length um this is our how many items we have is equal to the capacity that means we're at full capacity right so if we're in this case we have to first remove the last item from the list so we'll first grab that last item which is a good thing we have this tail thing right so it's the one to the left of the tail is the last item and i'm just going to call it the remove node or the remove and we're going to remove this guy so we'll do self remove node remove and then we're gonna also just delete it from the dictionary so delete remove dot key and this is why we also need to store the key in our node right we also need the key here because we wanted to delete the last item but we don't know what the key is for that last item if we only had stored the value so it's important to have also stored the key here all right so basically what this does is removes that last item from the end of the doubly link list and um removes it from the python dictionary all right and now we just need to implement this last part update our dictionary with a new item so basically add our new item in so it's actually um we need to like create a new entry now for this so basically we'll say our new node is equal to node with key and value and then we're going to um insert this right after the head node right so basically the front of our doubly linked list so insert after head and we're gonna take that node we just made and put it after the head and then we're also just going to update our um dictionary so uh key oops equals node all right let me just delete all this stuff all right so basically this is this bottom part i'm just implementing this last part update dictionary with new item right that's right here we added it in uh update our list we inserted the item to the second item of the list so just delete all this stuff right here and that should be it um cool at this point of the interview you probably want to go through some corner cases and just walk through the code a little bit more and i will and do that in a second but i think we did explain pretty clearly what was going on as we were going through so i'm just going to go ahead and just try running this and see if we get this to work all right cool it worked alright so at this point let's talk about some corner cases um i think it's um let's start with capacity equals one i think might be interesting um yeah i was just taking a look at the constraints here um you can't have capacity of zero which would be actually a very interesting corner case but that's not part of this so you could definitely say like okay what is the minimum capacity if the capacity was zero we would probably just need to up so what would happen if capacity was zero actually let's start with that the interviewer could you know definitely pose that question i was basically we wouldn't want to maintain um uh any linked list nodes besides head and tail wouldn't ever have anything in our python in our lib either so um this one key in self.lib is always so um this one key in self.lib is always so um this one key in self.lib is always going to return false it's always going to return minus one and that's correct and then here um if we had zero capacity key would never be in here uh if lengths of the lip equals self.capacity i think we just need to have one more conditional statement here that says like oh capacity equals zero then like basically do nothing um yeah i guess it's not a perfect solution but yeah some it would probably just be conditional right in here for that uh and let's just check if capacity one works um capacity one would have one at most if uh would have at most one item in our doubly linked list so we can we these both would be valid use cases um if there was one item in there then we would um basically just return the value would remove the node from exactly where it is and then insert it right back where it was and that's still those would work fine um if we're putting something in if it's in there that just means that again we're moving from where it is inserting it right back where it is and it's updating its value so that's fine and then um for this one if it's at capacity it's basically you're putting in the new item you're going to remove the one item uh from and then remove it from the um the dictionary as well and then um insert this new item after the head so that also looks fine so yeah basically works for those two capacity cases if you wanted to if you had time in interview i know you've done a long a lot of talking for this problem so you might not have time but if you do have time also what couldn't hurt to like hey like illustrate you know what the link list and key value mappings might look like over time as you give them different values like you'd actually try some of this stuff out and show what that looks like i'm not going to do it because this video is getting really long let's quickly just also talk about time and space so time well it's really part of the definition of the problem we're going to have a constant time get and put and space this is a little more interesting uh well so and the reason why this is the case is like we're basically doing a bunch of constant operations the remove node and insert after node insert after helper functions are also you know have a finite amount of things that don't depend on the number of items in the list or anything like that they're um so they're constant time operations which is the huge benefit of the doubly linked list in terms of space we are going to have um it's basically n uh and that's basically because we have one key value pair for each item in the cache we're gonna have one key value pair in the python dictionary and one node in the doubly linked list so it's gonna just basically scale with however many items you have so yeah that's pretty also more straightforward item there cool so that's basically how you do this problem i think the meat of it really is like how you're picking these data structures i mean definitely talk about why not to use singly linked list why not to use arrays and just also knowing how these data structures work together um that's a big part of it hopefully you got some value out of this video and uh yeah good luck on those interviews thanks so much
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
1,721
hello everyone welcome back so today we are going to solve the problem of lead code after a gap of one week i guess so the problem we are going to solve today is related to a linked list so the common name is wrapping nodes in a linked list let's go through the problem once you are given the head of a linked list and integer k return the head of the linked list after swiping the values of the kth note from the beginning and the kth note from the end the list is one index all right so we need to swap the values present at the kth node from the beginning and the key from node from the end and we would be given a value called k so this is one linked list one two three four five and the k value is given as 2 so the node present at the second index from the beginning which is this node and the second node from the end which is this 4 we need to swap these two values and after swapping the linked list would look like this one thing to note here is that we don't need to swap the nodes all together we can just swap the values present at those nodes right and the list is one index it means that the first node of the linked list would be called as uh would be would have an index of one instead of zero which is usually happens in arrays here as well one example is given so this is the linked list k is equal to five so first we reach the kth note from the beginning which is this seven and the kth one from the end one two three four five here note from the end is this 8 so 7 and 8 are the fifth note from the beginning and end respectively so we can just swap their values so after stepping the values the linked list would look like this so let's take an example and see how we can approach this problem so i will take one linked list for reference so let's take this link is one two three four five six and uh let's take k is equal to two all right so it's a very simple english and we need to swap the kth node from the beginning which is this two and the ks node from the end which is this five so we need to swap these two values two has to come here and five has to go there we don't need to swap the complete nodes we can just have the values so what is a brute force approach that we can use over here so the first approach that comes to the mind is like somehow if we are able to reach this node and this node we will strap the values at those particular nodes so how are we going to reach these particular nodes so it's very easy so how do we reach this particular node the kth from the starting so suppose we have one variable called count which is initialized to one and we can create one variable called temp one which is pointing to the head of the linked list right so we can keep on incrementing count till the value of count reaches this k and simultaneously we will keep on incrementing m1 variable as well so after that our temp one variable would have reached over here and count value would be incremented to two so count and uh k are equal which means we have found the key node from the beginning which is this two now how are we going to find the kth node from the end right so we don't know how much we have to go from the beginning of the array one thing we obviously know is like if this is a linked list and if it is has a length of n right and so how first of all how are we going to find the length n so we can basically write a function and we can have one variable which is pointing to the first node or the head of the linked list and we will keep on incrementing that head variable till we reach null so in that way we can find the length end of the linked list so how we're going to find that this kth note from the end so this length obviously has to be k and the total length is n so how much is this length then and minus k right because n minus k from the beginning plus the kth length would be equal to n only like total length so we have to find the kth node from the end we have to iterate over n minus k nodes from the beginning of the linked list so we can have one variable called temp2 and we will keep on incrementing the stem2 variable till our count variable reaches n minus k in the similar fashion that we had found m1 so once we have tampon pointing over here and temp two pointing over here we can simply write one swap function in which we can swap the values present at temper and temp2 we don't need to swap the nodes we can just swap the values present over there right so it was a simple brute force method and uh if we look at the time complexity of this brute force method it would be so first of all we have to find tampon variable so in the worst case the time complexity of finding type 1 variable would be of n then we have to find the length of the linked list so for that of n as well then we have to find temp 2 for finding temp 2 variable we have to hydrate over n minus k uh linked list nodes right so for that as well the time complexity is of n so overall the time complexity comes out to be o three of n which is nothing but off and only but we are doing three iterations over this linked list right so this is the time complexity what is the space complexity is one because we are not using any extra space apart from some constant nodes variable like temp one temp two and count so this approach is also fine like the time complexity is of three and which is nothing but off and only but we are doing three iterations over this linked list so the interviewer may ask can we solve this question using by doing just a single iteration over this linked list so let's see if we have a better algorithm in place in which if we just do a single pass over this linked list we are able to solve it so let me create one more linked list one two three four five six and seven let's take k value as 3 right so we need to find this node and this node basically right how are we going to find these in the most optimized manner so temp one variable that we the approach we had used earlier we can use that approach here as well like we can increment temp until our count variable reaches the value k so in that way we are able to reach temp one variable one thing we can note over here is that this length is k so the remaining length would be n minus k right so the distance between this node and this node would always be k so it's kind of a window which has a length of k right so somehow we need to find this node right and also one thing to note over here is the window between this node and the last node is also of length gain right so here we can we are using a concept of maybe you can call it sliding window that distance between this m1 node and the first node is k similarly the distance between the kth node from the end and the last node would also be k right so we just need to find that window so one uh and also one observation is like we had already found that window when we had found this stamp for node right so what we can do now is we can create one more variable which is starting from the first node let's call it m2 so at this particular point the distance between or the window between m1 and m2 is of length k right so what we can do is we can increment temper in time 2 simultaneously till m1 reaches the end of the linked list so let me redraw it again 4 5 6 7 so temp 1 is pointing over here m2 is pointing over here right so what we will do is we will increment temp one so temp t1 let's call it t1 and d2 will reach here then t1 will reach over here t2 over here then t1 will reach over here and d2 at this fourth node p1 reaches here and d2 reaches here so we can have a check that we will keep on incrementing these time one and temp2 till next pointer of t1 is not equal to null at this particular time whatever the value of t2 is that is the ks1 from the end because the distance between these two t1 d2 would always be length k because we started from that particular window only and we are implementing both these variables by value one so right so if the temp two value m2 variable has a value of may be called uh value s1 and m1 would have a value of four right so we are kind of incrementing these values uh three at a time like the difference between them would always be three it's like that only right so in this manner we are able to find temp one and temp two in a single pass over this linked list so the time complexity of this algorithm would be of n like we are not doing any additions over here apart from this on time complexity i hope this algo is clear so let's jump into the code implementation of this course i will code the optimized solution for this yeah so first we need to find tampon variable for that i am creating one variable called count which is initialized to one and a variable which is nothing but pointing to head only right and we will implement this count variable till it reaches the value of k so while count is not equal to k we will keep on incrementing not head sorry similarly we will be incrementing count variable value as well right so in this way we are able to find this particular node in this case this third node but we have to increment the stamp one variable for finding temp two right then k3 from the end so we need to place this value into some other variable so let's create one more variable called this node also equal to m just for holding that value right so now we need to find uh m2 so how are we going to find temp2 and creating one more variable m2a which is initialized to the head of the array so now i will uh keep on incrementing both of these m1 and m2 till next pointer of time 1 is not equal to null right so now we need to do what we need to do is we need to implement both tempo and time to that's it nothing else after we have done that m1 and table 2 would be placed at exactly those places so temp 2 would have reached this kth note from the end and m1 would be somewhere over here right so there is no like it doesn't have any relevance now but we had uh copied the value of m1 in an answer variable so we have at this particular time the answer variable and temp2 variable so we can just swap the values presented this these particular nodes we don't need to swap the nodes oh i guess we can write a strap function it's not returning anything we need to pass these values supposing so these are passed by reference and we can create a variable called uh dfb over here which is initialized to a and a value would be copied to b and b value can be taken by what whatever was present in temp so this way we are able to swap those values right b is equal to 10 correct so after swapping uh the nodes we can directly return head if i submit it let's see if there are any compilation issues over here no it's fine i'll submit this yeah solution looks fine runtime and memory usage are also fine so yeah like uh going by the problem it was a very easy problem we just have to find the kth one from the starting end from the end of the array and we the brute force method also worked in an on approach but sometimes the interviewer may ask instead of doing three uh iterations or passes over the link list can we do it in a single pass so here we had used the concept of sliding window in the linked list and this concept can be used as well in another problems as well so if you go over a similar question section so if you see reverse nodes in k groups right so here is when the concept of sliding window in the linked list would come into picture similarly remove and it's not from the end of the linked list here as well the concept of sliding window like in which we are able to solve the purpose using a single pass over the linked list instead of multiple passes so this concept is a general one and is also used in the arrays as well so this concept we have now implemented in linked list as well right so keep on practicing this problem like try to write your the code by yourself once and definitely solve these similar questions as well because it will make you know it will uh tell you like how to implement these this sliding window concept if a new problem comes up later right so i will see you next time with another problem of lead code and possibly of linked list as well and i will see you next time thank you
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
708
okay so lead code practice time so in this video two things first one is uh to see how to solve this problem and then we are going to put some solid code in and then another thing is to see how to solve this problem during interview so let's get started so the first step is to understand the problem and try to ask some clarification questions in case there is anything that is unclear to you and also at the same time think about the edge cases so let's see insert into a sorted circular linked list so given a node from a circular linked list which is sorted in ascending order where the function to insert the value is which is called insert value api into the list such that it remains a sorted circular list and the given node can be referenced to any single node in the list okay and may not necessarily be the smallest value in the circular list and if there are multiple suitable places for insertion you may choose any place to insert the new value and after the insertion the circular list should remain and if the list is empty you should create a new single circular list and return the reference to that single node otherwise it should return the original given node so if the list is empty we just create a new node and return it otherwise we return the original given node okay yeah i think we're pretty clear and let's take a look at this example for this one we insert two then we are going to insert it between one and three and then finally we return original node which is three all right so i think we are mostly um we mostly understand what the problem is asking us to do um so i would say one edge case definitely is suppose the in the list is empty then we need to create a new node and return it and the other thing i think suppose so for example suppose a list is something like it contains one three five and seven and it is pointing to three suppose it is pointing to three which is this one and we are going to call let's say we call in 32 then uh what are we going to do so car so we can get the current car the current pointer and the next pointer and keep moving uh until we hit the one three so the suppose we have two pointers so the previous pointer and the current pointer so we keep moving until we find a suitable place to insert the two and then next time we are going to current pointer is pointing to this and the previous pointer it pointed this and let me insert the two so what if we uh insert we are going to insert eight so if we insert eight we see that the previous pointer is going to be c seven and the current point three is going to be one so of course eight is larger than seven but is eight is also larger than one so i would say that is a place that comes to the end of this linked list so we are going to insert it here let's see if there is any other okay so there are two cases one is to insert the node in the middle and the other one is to insert the node at the end or at the beginning which is the same which is of the same concept uh so okay so i think we kind of get it and uh and the other thing so if it is so suppose i insert let's take another look let's say suppose we insert a zero here and when previous pointer is this and the current pointer is this then we are going to let me say okay uh we are going to insert you here okay um okay and let's see suppose there is only one node let's say suppose there is only one node which is called one and uh we are going to insert two what are we going to do so if we insert two we will see that the previous pointer and the current pointer both pointing to the same thing um so i would say okay so i will say that the time we are okay so we need to have a limitation about when to stop iterating like because if we encounter the current pointer again it means we have already visited the circuit thus the circular linked list once so that's the time we need to pretty much stop and just insert the two so in this way uh we don't need to we will not select just dab we will we are not getting that loop here okay so uh several different cases one is to insert in the middle the other one is the insert at the very beginning or the end and the last one is if the if we hit the current pointer the head pointer again then uh we need to just insert the note there okay so that's the plan so that's pretty much about the solution and after that we are going to do some coding work on top of this so in here you care about your speed and also the readability and of course the correctness of the code so let's get started and do some coding work here and of course after the coding part we are going to do some testing um so first of all if uh if which is one ash case if had is equal to a num pointer what we are going to do is we are going to say okay node we are going to create a new node which is node is equal to new uh node okay and um you're going to insert okay the insert value okay and now do not crave that next is equal to node and we just return a node okay that's the ash case and the other one is uh we will try to see uh with we will iterate through this uh link a circuit the circular link list to see the to find the position to insert the node okay so let's see um if it is in 1382 then so okay so um first of all here we need to define two pointers the current so the first one is the current pointer pointing to uh the head let's say okay so let's see it is let's say call it this preview point let's call okay the current pointer and the next pointer is equal to head dot next okay so well um we need to set a stop condition so suppose we encounter the we the current is equal to head again then that's the time that it so that is uh so that's the condition we need to stop so how so let's say if car so car if we set current it's equal to head as a condition then there might be some issue because we cannot really start it what about next is equal to is not equal to head so if it is nice it could not equal to head uh if it is equal to head again uh oh sorry so let's say okay so let's see i so what we could do is um like something like this okay so if uh so if inserts value is larger or equal to is smaller is larger or equal to head dot value and the insert value is smaller or equal to head the next dial value then it is a time it is time we are going to do the insertion so we are going to say okay head okay so head dot next is equal to new node uh so i had done next is that one and it is inserts value okay and we just need to return okay and then current let's say current is equal to head down next and next is equal to next dot next and in this way we can succeed we can successfully jump into this well branch okay so like this one um if um so let's say because there are several conditions let's say we call it we have boolean to insert is equal to false so let's say if um like the condition below if insert value is larger or equal to current dot value and uh the inserts uh value is smaller equal to uh next dot value then it is the time we need to uh do the insertion so we are going to say okay 2 insert is equal to true so if um had so okay so if current the value is larger than uh it's if it's uh if this one is larger than uh next dot value then it means uh it is a place which is uh the beginning of the beginning or the like the edge among the beginning uh is its edge between the beginning and the end so what we need to do is we need to take special care about this so if uh the if insert value is uh larger or equal to the current dot value or the insert value is smaller or equal to next double value so we can also do the insertion so you'll see the two insert is zero true so if we need to insert between the current uh the current node and the next node if this is true what we would do is we would just say okay so current uh dot next is equal to new node um insert value and then it is next okay all right so and then if we already done and we have if we have already done the insertion we just returned the hat here and uh like we said suppose there is only one node or maybe everything in the list is the same then that's one we encountered had node again and we just insert it at whatever the place it is uh and it's just fine so current.next is your new current.next is your new current.next is your new node insert uh value next and we are going to return all right so uh let's do let's double check which is the testing part so the testing part we are going to do some sanity check by going through this code using some example and i design at the same time we will explain it and the next one is to set up some different test cases to have good enough text coverage about different cases so let's take this example let's say we have the one three four one and then it is pointing to three so let's say at the very beginning uh okay so let's give it so we have one three and four and this is uh the current pointer and this is sorry this is the current pointer which is three next pointer is four and we do the and we see okay the if he inserts two is it is not going to fall into this if branch so we are jumping into this else so we are going to set current as equal to this one and next as equal to one and then well we are going to jump into this well loop okay and make sure that the head node is three okay and uh so insert while it's since uh this is so the current value uh it does well um it is going to be larger than next wall because four is larger than one so it is an edge between the end node and the one and the begin node so um because the insert value is not larger than the largest one and it's not smaller than smallest one then we are not going to set to insert as true so instead we are going to uh move the pointers so we are going to move the next pointer we are going to move this the current pointer and now we see it is jump it's going to jump into this french and we set to insert as true and we are going to insert it properly uh and set the linking relationship okay so this one it should work let's say if we insert a five here so if it is a five uh similarly uh once the c with the current pointer is this and the next pointer is pointing to the beginning uh we see that the insert value is larger than uh the max the ending number so it is we are going to insert it there and let's say if there is only one node let's say if it is one and we are going to insert uh two so this one of course is not going to work uh and then we jump into this well loop and since the current is equal to head then we directly jump out of this while loop and we are going to uh do the proper thing inserting the this node the new node with value s2 okay so i think it should work let's give it a shot okay so it's the typo okay and then we return oh where okay so it should be returning head some typo so next is equal to current.next okay all right so question typos um let's see oh time exceeded so actually we didn't move the pointers so it should be currently is equal to the next and next is equal to the next style next okay so ah it should work okay now i should work um and i think it should be good okay so it's accepted so like i said definitely set up some test cases um like the example one and example two and also for example one we can insert five and insert zero which is like inserting uh after the and after the ending point or before the beginning pointer and also think about uh if there's only one integer then how it is going to work like it is jumping it is going to touch this branch all right so that's it for this uh code this coding practice i hope you like this video and uh i'll see you next time thanks for watching you
Insert into a Sorted Circular Linked List
insert-into-a-sorted-circular-linked-list
Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value `insertVal` into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list. If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted. If the list is empty (i.e., the given node is `null`), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node. **Example 1:** **Input:** head = \[3,4,1\], insertVal = 2 **Output:** \[3,4,1,2\] **Explanation:** In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3. **Example 2:** **Input:** head = \[\], insertVal = 1 **Output:** \[1\] **Explanation:** The list is empty (given head is `null`). We create a new single circular list and return the reference to that single node. **Example 3:** **Input:** head = \[1\], insertVal = 0 **Output:** \[1,0\] **Constraints:** * The number of nodes in the list is in the range `[0, 5 * 104]`. * `-106 <= Node.val, insertVal <= 106`
null
null
Medium
null
1,380
hello everyone it's really good to see you here so today we are going to solve a leaked good problem which is lucky number in a matrix so the problem statement goes like a lucky number is an element of the matrix such that it is a it is the minimum element in its row and maximum in its column so basically let's see it like this so let's say we have given a matrix m which has element 3 7 8 9 11 13 15 16 and 17. so in a row what is the uh maximum element we can see here so 3 is the minimum element right and in the second row 9 is the minimum element and in the third row 15 is the minimum element and if we talk about the column then here 15 is the maximum 16 is the maximum and 17 is the maximum element so what logic we have to put it here is like we have to actually um choose that element which is let's say 15 which is minimum in the uh in the row and maximum in the column so this is a lucky number so this is what we have to actually uh give as an answer so there can be different or so many lucky numbers so we have to store all those in the form of vector so what we can do is we can first iterate our matrix like this so let's say i is the row and j is the column so we have to firstly iterate it like this and what we have to do is we have to store the element what is the minimum element of that row in let's say a map and b so what i'm doing is just initializing three with one and then in the same way in the second row what we got nine is the minimum element so we append nine here and then fifteen here so one is basically the count initially of 15 now after that what we have to do is we have to go column wise so we have to use this one so uh in column the maximum element is 15 so we have to add this so i am just incrementing the counter of 15 and again 16 is the next element and again 17 is the next maximum element so we can append all those in the map now what we can what we have to see is if the count of that particular element in a map is greater than 1 it means that it is present in the column as well as in the row both because it's given in the problem statement that the element of the matrix is distinct so it the repetition in a map is possible only when that particular element is a minimum in the row and maximum in the column then only we can got a lucky number so basically we have to check the condition that if our map element has any element whose counter is greater than 1 then that is a lucky number so at the end we have to just append this inside a vector so 15 is got appended and we have to return this so this is the whole approach which we are going to follow so now let's see the code so here firstly n is the size of the matrix that is row size and then column and then we i am using a map in command and what we are doing here is this we are iterating the map like this and we are basically appending all those element inside a map which is minimum among that row so if the matrix ij element is less than d then we just initialize t with that element and here t here by doing this we got the minimum t value for that particular row and then at the end we are appending it inside a map in the same way we can go through column wise so here firstly we initialize j equal to 0 and then we are um what we are checking is if the element is greater than t if the element is greater than d because we have to find the max element in a particular column so what we can do is we can just increment the count uh of that element by appending it inside the map after that in the map we are just checking if the value of the element is greater than 1 that is the if for any key the value of map is greater than 1 then we have to actually push it in the answer vector because uh this is a lucky number and then we are returning it so let's try to submit this so yes it got accepted uh so this is the uh this is the a simple approach for solving the problem lucky number in a matrix and i hope you like it and you can access the code directly from the github link given in the description and this is it for this video thanks for watching you
Lucky Numbers in a Matrix
number-of-closed-islands
Given an `m x n` matrix of **distinct** numbers, return _all **lucky numbers** in the matrix in **any** order_. A **lucky number** is an element of the matrix such that it is the minimum element in its row and maximum in its column. **Example 1:** **Input:** matrix = \[\[3,7,8\],\[9,11,13\],\[15,16,17\]\] **Output:** \[15\] **Explanation:** 15 is the only lucky number since it is the minimum in its row and the maximum in its column. **Example 2:** **Input:** matrix = \[\[1,10,4,2\],\[9,3,8,7\],\[15,16,17,12\]\] **Output:** \[12\] **Explanation:** 12 is the only lucky number since it is the minimum in its row and the maximum in its column. **Example 3:** **Input:** matrix = \[\[7,8\],\[1,2\]\] **Output:** \[7\] **Explanation:** 7 is the only lucky number since it is the minimum in its row and the maximum in its column. **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= n, m <= 50` * `1 <= matrix[i][j] <= 105`. * All elements in the matrix are distinct.
Exclude connected group of 0s on the corners because they are not closed island. Return number of connected component of 0s on the grid.
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
Medium
null
1,970
hello guys welcome back to the channel today we are solving another leadport problem that is 1970 last day where you can still cross before jumping into the solution I would highly recommend you should read the problem statement on your own and give at least 15 to 30 minutes to this problem so let's get right into it what problem is asking that we are given a 2D metrics in which zero specify land and one specify water so what we have to do we have to move from top to bottom robot there is a catch that at ith day r i comma CI cell will be filled with water then we cannot cross that self so what we have to return is what was the last day when we were able to reach from top to bottom row this is we have to return which was the last step so let's take a test case for example two cross two D Matrix is given and it is specified in the question it is specified in the problem that on zeroth day everything is land and also it is one based indexing mentioned in the problem today not if one is a day what happens on Wednesday one comma one cell is filled can we reach from top row to bottom row yeah we can now we transition to second day and at second day two comma one is filled one two comma one is filled we can still reach Now we move to Third Day on third day one comma two is filled these three are filled now we cannot go to last row because top row is filled so what was the last day I would say second this we have to return now there are two things that are needed to handle to solve this problem first one is B have to do it for each day why we have to do it for each day because after every day you can see any cell is filled and after every day we have to check so this after every we have to do it for every day what we have to do check can we reach this is second then we reach that bottom row this is we know how to do it is quite trivial if you have done questions of grade kind of questions we can move both all the four directions and how can we Traverse a matrix or a grid we know two traversal DFS and BFS you can use both so this is clear you can do this very much easy but this is something this is easy we have to do it for every day we will check for every day we linearly search what we search for the day we linearly search for the day which was the last day when we were able to reach from top to bottom row but if we do this linear search it will give tle it will give daily you can see the constraint for yours for yourself so what is the solution for this so when I was doing the problem and basically it was linear search and the best thing that can appear to a normal brain is binary search we do binary search How We Do binary search let's see this much is clear we will be doing binary search so in binary search there are two not two three things the left the right condition in the mid we can find left by two major concern is for left and right we know zeroth days we can always travel from top to bottom because at zeroth day everything is land so we will start from one also why search binary search will also be clear so keep on listening and what will be the maximum condition if you have read the problem in this we have to return the last day and the last day will happen before this length or at this length why because if it doesn't happen then we can print any number then there is no answer or there is then no problem so the problem is that we have to find a day on which sorry the last day on which we were able to travel from top to bottom because the day will be in between this because then it will not be a problem because if it doesn't fall in this day and we have to return the last day and then last day will never happen getting my point if this is a valid problem then it has to be happen between the bound and what is the bound this sales Vector which denotes which cell will be filled I hope this much is clear so what will be the right bound I would say cells dot size this would be the right bound okay this much is clear now but how we gonna decide that if something happens left is equals to Mid plus one this is basic binary search else right mid minus 1 but how are we gonna decide that we will be moving left or right I would say this can we reach if we can reach let's push forward if he cannot reach let's move backward last day will be present somewhere here if we can reach here last day may be present over here so the reach if we are able to reach from this block to this block from any block present in the top row to bottom block any bottom block then we will move further and see if is there any last day or we can say to find the next last day basically we are just finding the maximum day up to which we were able to move from top row to bottom row I hope this much is clear what is our elbow we will be doing a binary search and where our left will be one already discussed by if still not clear please watch this video again the right will be cells size minus 1 and what we will be doing this check what check it is if this is true what we will be doing is mid plus one if it is not true what we will be doing is right mid minus one this we will be doing and how this check is implemented check how is check this check is implemented check is basically in the cell we can move in all the four Direction so it is quite easy if you have done enough grid question it is basically a traversal and how we can do a traversal on a grid using BFS or DFS both can be used it is quite easy the only thing was to conclude that we need binary search and we need a traversal I hope this much is clear let's see the code so let's see this is the direction Left Right top bottom very trivial thing and what we are doing DFS over here you can do with BFS also so this condition shows if you can reach the last row then it's true we are marking visit we are moving in all the Direction all the four Direction and what we are taking care over here is that we don't get out of bound and also it is a land new cell is a land and if it is then again search for that and if we are able to reach the last row return true if we were not able to reach the last row after all the paths we will return first so this much is clear now the main part the binary search this was the check that I was discussing it is kind of trivial very basic now the binary search the low will be starting from 1 why not 0 because at the zeroth day it is always a line and high is cell minus not minus cells dot size because we need an answer and answer will be the maximum length of the cell size because this is a valid question if answer doesn't lie in this range then it will be a valid invalid question so answer will be in this range basic binary search mid that's what not that's what that's how we calculate mid to prevent overflow making visited and what we are doing over here marking the day and that day any cell will be filled so we are marking the cell which will be filled on that particular day for example mid is 2. so when it is day two this is what the zero day is zero day this is the Wednesday one is a day this was filled and 12th day this was filled so we have to fill both of these that's why we are looping over there that's why we are looping till mid and filling everyone killing everyone and why we are doing minus one because it is one based indexing in the problem so and we did zero kind of indexing you can do plus one over here to convert it into one based indexing it's your choice then again what we are doing over here let's discuss if we can visit if it is a land and if we can do a DFS if it is a land then we will do a DFS and if you if after doing the DFS we can reach the bottom row then what we will do the result true and break out of it why we are doing this because we don't know on the top layer which one is filled so we will check for everyone if there is a case there here is a land but we cannot reach bottom but using this cell we can reach bottom so that's why we are checking for everyone over here checking for everyone and E and if it is formed no need to check further just break out of it and what we will do if we found that yeah we can reach so what we will do we will just increase our day how we get increase our day low is mid plus 1 and we store this answer and if it is not reachable we have to decrease this much is clear and after doing that when I research we will get the answer I hope this much is clear and dry run of this problem is not feasible it the video will get long quite long so let's submit it and see if it is running or not you can do with BFS also there are many approaches with VFS you can find easily in the discuss section but I did with DFS so I hope this much is clear it is submitting and you have to do what you have to do so keep grinding you guys are awesome see you in the next one bye and also consider subscribing to the channel liking this video and sharing with others bye
Last Day Where You Can Still Cross
sorting-the-sentence
There is a **1-based** binary matrix where `0` represents land and `1` represents water. You are given integers `row` and `col` representing the number of rows and columns in the matrix, respectively. Initially on day `0`, the **entire** matrix is **land**. However, each day a new cell becomes flooded with **water**. You are given a **1-based** 2D array `cells`, where `cells[i] = [ri, ci]` represents that on the `ith` day, the cell on the `rith` row and `cith` column (**1-based** coordinates) will be covered with **water** (i.e., changed to `1`). You want to find the **last** day that it is possible to walk from the **top** to the **bottom** by only walking on land cells. You can start from **any** cell in the top row and end at **any** cell in the bottom row. You can only travel in the **four** cardinal directions (left, right, up, and down). Return _the **last** day where it is possible to walk from the **top** to the **bottom** by only walking on land cells_. **Example 1:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[2,1\],\[1,2\],\[2,2\]\] **Output:** 2 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 2. **Example 2:** **Input:** row = 2, col = 2, cells = \[\[1,1\],\[1,2\],\[2,1\],\[2,2\]\] **Output:** 1 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 1. **Example 3:** **Input:** row = 3, col = 3, cells = \[\[1,2\],\[2,1\],\[3,3\],\[2,2\],\[1,1\],\[1,3\],\[2,3\],\[3,2\],\[3,1\]\] **Output:** 3 **Explanation:** The above image depicts how the matrix changes each day starting from day 0. The last day where it is possible to cross from top to bottom is on day 3. **Constraints:** * `2 <= row, col <= 2 * 104` * `4 <= row * col <= 2 * 104` * `cells.length == row * col` * `1 <= ri <= row` * `1 <= ci <= col` * All the values of `cells` are **unique**.
Divide the string into the words as an array of strings Sort the words by removing the last character from each word and sorting according to it
String,Sorting
Easy
2168
952
Hello friends, today's discussion about liquid problem is 952, it is the largest computer science like commenting problem. First of all, you are given equity in which Vyas and Notes only made the application which also has mushrooms in the. The value of notification is fine, what is it? Know that you have the graph and if you will be like this now late public conducted s between Navsari this Namastesye can get girl meets number two between the two when the quantity account statement of these two will come okay now This decision is disconnected complaint in the graph is ok you side of the largest complete will keep example 46033 face note more than point among Mukesh after's two dead one is in the middle of his porn Yogi ji's encounter is three that Bigg Boss has 1535 Which is in the middle, so if you subscribe 6 quantity, you get the benefit of four sizes by mixing its test, so now what we will do is first of all practice it, its most basic worship, on top of managing you, we first subscribe and between them, David. Let us do, let us subscribe and subscribe so that then what will you do, you will stop that status, you will complicate it and all the members of it, if it is expert then receive it, friend, press the account and take it, okay, then of interest. Or where will you get it from? Me Sama Ek Harbir Awal Difficult, We will mix all the notes that come from village Bahman with our hands. How many Tatas, how many notes are there in one packet of camphor? 4. Okay, so we will start it in the account or is it the footer, sir? This is a very simple proof of the whole process, you know the time complexity to wish a birthday, the time to reduce the face, send a message, after and you can say number plate, but when we do this, which remains a program, then this refill, everything is very heavy. It used to be said that TRP will be taken to you or her WhatsApp. Okay, here I will talk about the space bomb explosion of girls, there is a doubt about it, half of it means you are also requesting me, neither can you work and share. You are okay at the time of the year so you meanwhile this will be in chemistry okay so you can see it is developed from here is very last value so you are typing director Dr question how to optimize it so that it can be operated This is a very good concept for you to check. Deposit Union DJ Tune. If you have read then it is very good. If you have not then today is the chance to read it before going further. If you just keep leaving it, I will not talk, then you are a good professional. It will happen and you will never be able to read what should I do and depression, I will give you the Shivalinga given in the description box, you must read it is very important, whereas you can do it for how to liter a happy life cycle for dad, okay so this is very important. If it is on only then you have definitely used it will be useful in many places and that means it is a very good thing, it is used in such problems, so if not then it is definitely fine. So if you have DSP, then what will we do, how will we do it by using the most difficult one. The biggest thing in this is that you know that parents are not there, what do you miss, every note has its definition, this note is made into your paste, Delhi's first two three's perth test is done and every vote is painted, that number is to itself. Okay, so first of all, we will approach you with question number four 1635, so you know this is the largest number of science. Read the question. Okay, I care a great. Okay, so this is suitable for you. 1234 Third year, all these numbers are city, after that, the color of doing this is red, which has the smell or f-35, then your is red, which has the smell or f-35, then your is red, which has the smell or f-35, then your whole hey, which is a copy of the saliva register, will not be registered for the 35th test. Okay, let me do the last one for the organization. There will be no one even the biggest, so here you select means the latest 29 test matches of the week among them, so I have attached it, okay and let's move ahead, okay and what is Agra leadership, so what is that liquid? How to liner the printhead, the parents of each note are clearly defined as 1.12. By doing this, parents of each note are clearly defined as 1.12. By doing this, parents of each note are clearly defined as 1.12. By doing this, I have selected India as the parent of 91. What does it mean that the parents will be India of 122, but we will do this, it is okay, after that let's move ahead. Now you have caught the numbers of yours, as if firstly it is completely correct, then it is fair, then in which direction of the chapter and have you looked at the tree, then you are under the root of and if any number remains in it. You can finalize all the subjects in the end, all your tiredness was in the roof end, from IS GOING TO to Aaya Into Alleged Middleman, you guys, you will get all the subjects, now quarter corn flour filter K TO is okay. That kittu, now what will you have to do here, you know, HUDA is Sector-2, so do here, you know, HUDA is Sector-2, so do here, you know, HUDA is Sector-2, so what we will do here, see here there is a tattoo of obstacles and 4.4, so what do you is a tattoo of obstacles and 4.4, so what do you is a tattoo of obstacles and 4.4, so what do you do, which is your note, update it with the factor of the parents of the note. Two, what will we do and now it will be okay, what do we mean by saying that he is a number which has a sector-2, he is a number which has a sector-2, he is a number which has a sector-2, so we will update the festival from his tractor, in a strong pot, someone updated his Parents, others are okay, so updated this and told my mother, we benefited from this, we follow you from the first day, now let's turn to your six, okay, if we are educated then we will be teachers, if the teacher comes and takes entry, what will we do? This one has a number, after that you are here, okay, so let me move ahead, now what will we do, subscribe to Gas Ka Flame, two Ghaghare who are ours, don't subscribe, let's go, okay, Saurabh Streel and his murder, check that ace parrot. Who are you, whenever you say such a thing for your gentle because of a considerate reason, then your like this is fine, second is your body, today I will earn and pay you first, but pay for education, at this time, he is two and who is this method, who is this 3.73 This is yours While updating the note which will be on method, who is this 3.73 This is yours While updating the note which will be on method, who is this 3.73 This is yours While updating the note which will be on its feet, look at it from its factor, its bank and to talk to, which side means to, update it in this way, it has the rights like education, parents, guava food, teacher, it is still there, so what you Do it, which means it is at 60%, so before upgrading, do some update, 60%, so before upgrading, do some update, 60%, so before upgrading, do some update, then you have to do this with this updater, which means what were you doing with the apk file, like when you had it farka 10th floor end. Lord Vishnu's paint condo, so what will you do, you were updating it from the banner of his parents, that you had updated something, then other than that, his training is famous, then his foot is a slip of paint, then you put the coin on the coin with your feet. You have updated it, you will ask about the seat belt, if it is your assistant, then there should be a point of 123 on that rickshaw, so what will you do, not only the parents, it is okay, if you update the parents, then education is welcome, so what did we do with the paste of 1622? This has been updated from Means which is yours, which parents stop, those who benefit from it, okay, how do you know this, a parent of six, wants to listen to mother, difficult, welcome to Ghaghra, to melt it also, this 6622 entry means score, then you have A note was made, how is this phone, then subscribe to Meghnad, you melt this, subscribe to this, it is okay, tiger also has two packets of cheese, which twenty is yours, then you are getting some kind of taste, okay, Furkan was that and education printer. Take a galley, put some amount like this again, then when the barfi is till cash withdrawal, then friends, if you get the key and five, you suspended them, then first of all, work, phone's paint, who is the paint of 153, then Rafiq Pan. If there is no leave for Ad Africa legs, then what will you do here? Note note means that if your note is updated to the patient of the note and you have updated the parents of his tractor, then the note has failed and his factor is well in which and good then your parents. Please update it, I will tell you now, after that what will happen, first we click, so now see, you have this 5815 like friend, you have made this, if it is okay, then the factor of this thing is ₹ 50, you need half of it. factor of this thing is ₹ 50, you need half of it. factor of this thing is ₹ 50, you need half of it. I am half, what do you have next, your five is okay, so unfaithful, what is this also, 5ghz factor is okay, so now what do you have to write, meaning like here we have become ice on one side, when our skin is anti-oxidant, then what is it to your parents? is anti-oxidant, then what is it to your parents? is anti-oxidant, then what is it to your parents? Updates and if I move ahead then what is 2025 now, then who was the test, empowerment and the payment of Rs 500 note, you can make the fans of the note go ahead, update the parents of the factor, the note is banned that the economy is economic, you will get this update. Do the most two-three steps of the parents. You Do the most two-three steps of the parents. You Do the most two-three steps of the parents. You will update the two-three steps of the parents. will update the two-three steps of the parents. will update the two-three steps of the parents. Parents means the parents of the sector, then on the footer, 1.5 inches from the FD account, the footer, 1.5 inches from the FD account, the footer, 1.5 inches from the FD account, the parents of the earth will be preferred. Okay, so what do you care about that? That brother, this which is your free, is in the middle of 3.5, which is your free, is in the middle of 3.5, you have made your hair on the scientific magazine, what should you do with the value of the parents of the note, either you should update the rally of the parents of the note with the value of the parents of the tractor, it is okay means. What you have to do is update the value of the paint of the note's parents, the value of the tractor's parents, put the tarka parents on the side of the note from the rally of your parents, okay then I will go here, the next day most of them are 3500. What will happen if you have consumed five sector-51 actors, consumed five sector-51 actors, consumed five sector-51 actors, so first I will do 500, okay now see, 35.1 is 35mm 519 f5, so I have 35.1 is 35mm 519 f5, so I have 35.1 is 35mm 519 f5, so I have told you what to do, update the parents of the note with the stomach of the factor. It is okay to give that our front is okay so the paste of the note is 3535 and you have to update the back also. Parents of the tractor and friends, I have the file in red cloth, so update it from 33.5, what have you done with this update it from 33.5, what have you done with this update it from 33.5, what have you done with this 35.5. In between our and brothers, what is this but even 35.5. In between our and brothers, what is this but even 35.5. In between our and brothers, what is this but even a little bit of Pfizer factor is fine and I can now this in the middle of seven etc. like here, are you the 35th benefit, now what is it 5800, then as soon as possible, it is 81770, this is what to do but from To the parents of the note, you had to update the director's parents that if the note paint is F5 then you have to click on the like button or reach the chapter and will consume it. Assemble it in it. This is on your profile. Let me update it with the intake that tomato. If it is okay to add the paste, then we will decide that what has happened to you, make your soldiers on the hair, then on this channel, take every note, every turn, whatever the condition, parents etc., they will be the comment on it. parents etc., they will be the comment on it. parents etc., they will be the comment on it. Okay, now see now comes the real thing that you will get the benefit of doing this. You will get the benefit of doing this. Tell me, now you withdraw all your notes to cash, take six and what else and then you have 6 and 1550 and all your notifications on the side. It is 1530 so now first of all what do you have to do then if you want to do the paint point then first of all we mean leg statement to our man then first remind you of the two now look at the whole parents two so what did you know that this factor Of want to see the factors of food, but when your parents set it, there was no two cup ad, then I will tell you its full story. If you are parents, then what is the problem? Note something other than two. Comment Share. It is true that now that note. Apart from this photo, if we take anything more special, then who knows what introduction? Four cups, four cups, parents want two, then Mitthu is the writer of, but if the shop parrot is someone else, then what creation do you have, Kittu, who is there in your mind, there is no note other than four. Must have also been a pendant of that's why and someone else's Pendra There must have been more than one expense of that note One face in the sectors That's why it was set on its parents Okay Means like two is the factors for any specific Hague And tourist and good tightening a kiya to ko 332's legs are ok backem it's which is a mean stuart mother's phone and is fixed between both of them and there is pea so what happened to you what is that apart from that one more note through ahirwal American History Limit Here Pimple is exaggerated in the middle of the whole tips so mixture you mean this you need to write but it shows you that a mean this here it is necessary but that is why keeping a mistress you mean this see this need But tutor for any specific and taking six wickets as soon as possible means share the service or just come in the middle but you need me, so what to do, first of all it is okay for your parents, then who is the pendent heart patient. Okay, now what should we do, we started riding on our bicycle. Four cups of coffee are enough for the tree. So now I will tell you who is the trick paint. Now whatever method you will go, file the penal code and take part in Meerut on five. Okay, parents, it is five, okay. Who is the part of NDA? Seventh, okay, you have it there, that SMS of 650, you can see that see the damage to the paste of the clear one, whenever you get a note whose painter has got a note which has a benefit, then what should you do? Have you got the return bent? Vitamin A time, what should we do? Tell us, we will celebrate the bank statement of the account of the seven. Okay, update the feet with the seven and remember your parents, we will set it. Okay, and 679 and two mean problem. Test Totke channel will be brought here and set to two. Okay, you know its trend. You know all this is the note of all these decades ago. Tech Money Parrot. So you came to know that where did you go from to-do. Atishay that where did you go from to-do. Atishay that where did you go from to-do. Atishay 5707 used to get silent comment, see this style has been done in the angle of my friend's channel. * Thermal is done, up to two is done, it is in the angle of my friend's channel. * Thermal is done, up to two is done, it is in the angle of my friend's channel. * Thermal is done, up to two is done, it is fried, it is consumed, what is 06018, so now we move ahead, now see the whole loot. Do what Mian is ok then you have this time means that she and America got you agree ok then send it close the account ok this is a child near the city now let's move ahead Satya got you got something but But yes, this monk, what did we do before going? Reverse these attacks are totally optional. Everyone's parody accounts for the meaning of who was the festival of Jaipur will go here like this. 4.2 who was the festival of Jaipur will go here like this. 4.2 who was the festival of Jaipur will go here like this. 4.2 like this, here Kishanpur's paint was the ancestral business of 282 but After this, I had updated everyone that fiber makes a human being have a balance, the festival of Jaipur is also a problem, seven has been made, okay, so you update all this here, okay, who is the paint of 282, seven? Who is Six Penalty 786 4.12 Who is Six Penalty 786 4.12 Who is Six Penalty 786 4.12 Famous set of cannons, two are the seven, this is the whole of this updater, its ok, everyone's Edison is more and if you go ahead here then write Six Mila Se Ghira Shiksha Now Next Shiksha Prince Who Is 1622 Alto's 2.1 A intake so set your legs to Alto's 2.1 A intake so set your legs to Alto's 2.1 A intake so set your legs to maximum Okay so I mean this juice ad and celebs E4 diameter was former Court Pyun Seventh you only make education festival or festivals either you by which they note her children work You will follow brother friends, both CHL are fine and your routine of making Africa paste was difficult earlier and making thick paste by Rachika parents and then making your tablet made of clay is fine or the whole left like Yogi government is fine. BDO told that they Safi sometimes turn around and from the other side they update children for this Dubai 370's End Adventures Okay then you got medicine as a guest 33.57 Which thing is first then subscribe 33.57 Which thing is first then subscribe 33.57 Which thing is first then subscribe button is seventh so what did you do 70% button is seventh so what did you do 70% button is seventh so what did you do 70% Meaning 70% you did it and you have the certificate, Meaning 70% you did it and you have the certificate, Meaning 70% you did it and you have the certificate, so now what do you do, what do we do as your painter who was ours, we separate him, what should we do, we will create a separate account, parents will make yours ours, what should we do in that, one slate pencil, all the MS Word, the biggest rally that I am most significant to all of you, it is okay that in this till today, I keep increasing the open circuit in the chile of Jyoti note, what is the children's cases account of all 1200 10 notes and TVS Apache 200 is the trick, okay, if it is a servant, then brother, it is useless. This means there will be a photo of Scarlett Apollo Hospital. Okay, you want this. Okay, so far this is our approach. Whatever we said right now, if we look back at it, we will not get the credit. I want to tell you again, you will have to read DJ Tune because you will have to read it. There is no interest, okay, and here I just remind you of one more thing, look at this, it is the parent of 282, so what is prevalent, is there any other note other than Toofan, it can also be worn, okay, that is why it is after Vaastu. And there is any note, his parents are staying here and like it's okay, other than the benefit, any okay, it's okay, other than the benefit, any thickness is viral, it's okay on Africa, 1.5 and who is he, where is he from, 1615 more 1.5 and who is he, where is he from, 1615 more 1.5 and who is he, where is he from, 1615 more files, he is your pattern, who is 5.75 shopping files, he is your pattern, who is 5.75 shopping files, he is your pattern, who is 5.75 shopping and someone And note is ever a factor then and 135 that's why what should people do is we have a graph meeting okay and after that we update this entry you see its aa but more it means a lot to the stand its destroyed during you see so that Point your mind capable Rajeev Kakriya parents, there is any note like you see, you have to decide at home, certificate, who was their balance, only pregnant and five, only you are left, seventh chapter is 10 minutes, this is here, welcome Eterno to you. When the payment becomes physical, then you keep making returns and keep updating the find piece to the parents, okay, you see, first take the super hit where happiness returned in the guise of fairies, updated the dead cells of your face, okay by taking it as a prank. Hot SMS to kidney or legs like this, health is fine, so what should we do, pants off white legs, I will update behind, this is Nakul, what will we do if it is implemented properly, this is our saliva, so first of all send the paper to Maximum, okay who is your Wally to you to the maximum, what will you do to him, you parents, pressure of parents is painter, you recharge with MS Word, we recharged the payment, after that let's go ahead, it is good, worship is a drama, initially only parents, who will be the commission? Today what we used to do was 1812 but we have done this, then do it on your phone, your number is on the track, you do this, I, then always do this, pick up the meaning of square root of rhombus, any number is difficult, join all the weeks of it, ok. If the expertise is zero then it has come while doing its account, next is 9, like see it does the calendar, there is an apk file, if it is free on Africa, then Africa If you divide the lead character with someone else, then you will cry, first update the balance of one person on ISI and update all on the parents of Yadav or 21, it's okay. Festival A, like I told you have updated the parents of the note to 0.1, so sister, but updated the parents of the note to 0.1, so sister, but updated the parents of the note to 0.1, so sister, but what is Tata, then you will update the parents of this note, you will update the parents of the factor which we have updated the cheese cigarette, what will you do with Tatya's foot. Will we give okay the sum or what will we do with it, even after doing all this work, do the amount of environment like we should give the value mutton curry on the account, okay for his rights note but on his parents point and on the side of his feet children's account. Will do a plus, okay as you are here, back to the side note, cross, okay, so the first point, then if you meet, then to point the parents of solitary office, this group is on puberty, then come to Harikishan, see the first one better. Clothes got happiness, your ignorance salary account, then you fit one, seventh account happened first, again there is one, then one side was seized from who was Twitter's, it should have become more dirty, Indore should set that you will cross your account first. Whatever is the biggest rally you will get quiz through that paint which is the answer to the biggest collecting beau ok so you have updated your tears maximum fine chowk counterpart parts app ok check return of these amount which this one What happened from our post graduate union is fine and its time needs message legs useful and week machine on time because that one is added is fine and * machine on time because that one is added is fine and * machine on time because that one is added is fine and * under square root of what are you doing this cutoff According to this, you send it, please, what happened, this will be its time complexity, okay, you should ignore the ABS and we should mix it by Andrew Strauss, according to this, cross all these of yours, okay and whatever is in your The maximum element is not the one which as per the arrest here, whatever is the maximum limit of album sugar, all of that is the 12 most hair that will run, debiting directly here, the type feels the touch of the wart, that is Max Pro m1, what is this time? You are doing this, you parents should make a paste, okay, if you have any concern about the friend network hsn code of both the societies, then do tell in the comment section that this can be a little problem and for you, one and a half year old Ramesh, if you have not read then If I ask you these days in the description box, you will get a little pause here, okay thank you for watching, there are small hangings in it, Papa, happy thank you like this sir.
Largest Component Size by Common Factor
word-subsets
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return _the size of the largest connected component in the graph_. **Example 1:** **Input:** nums = \[4,6,15,35\] **Output:** 4 **Example 2:** **Input:** nums = \[20,50,9,63\] **Output:** 2 **Example 3:** **Input:** nums = \[2,3,6,7,4,12,21,39\] **Output:** 8 **Constraints:** * `1 <= nums.length <= 2 * 104` * `1 <= nums[i] <= 105` * All the values of `nums` are **unique**.
null
Array,Hash Table,String
Medium
null
30
hello everyone welcome to coding decoded my name is anthony today i'm working as technical architect at adobe and first of all i would like to congratulate all the subscribers of coding decoded that we have reached a big milestone of 10 000 subscribers a special video is in process i'll be sharing a thank you note with all of you guys very soon and i'm extremely super excited about this achievement why because there are no clickboard blades on coding decoded no fake promises no uh fake road maps nothing at all it's all honesty genuinely and the love and support that you guys have shown the association that we have built together as a community is truly commendable a telegram group of coding decoded it all talks about purity and genuinity when it comes to preparation and getting through these top notches and i would like to thank all of you for the love and support that you guys have shown and uh without further ado i think we should focus on today's lead good problem which is uh substring with concatenation of all words august 13th here in this question you are given an input string s and along with that input string you are also given an array of words that have same length that means all the words in your input array have same lengths in it what do we need to identify all static index of substring of s such that each of that substring is equal to the concatenation of each word in the words array and it is also told that you can only count each element of the word only once it this also brings us to a very important point that duplication can be allowed in this words array so let's try and understand the question by an example so here you are given an input string as how many possibilities of words are that can be generated there are only two possibilities one is foobar another one is barfu so what do we need to identify whether these two instances does it occur in my input string or not it does occur the first one is bar foo and it occurs at the zeroth index the other one is foo bar it occurs at the ninth index and this is what we need to return so if you see the output then these are the indexes starting indexes of these two strings barfu and fubar that exist in my input string s and here they have provided us with few more examples so i'll be taking a slightly longer example it's not very difficult question although one lead code it is hard but i would say we can read this question in a medium category so without further ado let's quickly walk through the presentation which i usually do and let's get started with the solution substring with concatenation of all words lead good 30 and as i told it's a medium level question as per me and in case if you have any doubt understanding this question but if you want to ask anything from me in general with respect to interview preparation adobe placement strategies or reference please feel free to drop a message on the telegram group or the discord server accordingly quoted both the links are stated below also with respect to solving yesterday's liquid problem that was find the lowest common ancestor in the binary tree we have already solved that question although i couldn't create a shorter video yesterday but we have already solved it in the past so for all those who have been looking for the solution on coding decoded must have got the solution right so i would urge you guys whenever you doubt that this question is slightly difficult one or you're not able to solve do give a shot on the coding decoded youtube channel and i promise most of the times you'll definitely solve find that question because they've already solved more than 800 problems in the past which is truly commendable the consistency level is at its peak we have solved more than 17 months of daily lead code monthly challenges and the credit again goes to all of you because you guys are my real strength now without further ado let's quickly go back to the same example that was specified in the question we have the input string as so there are two important things let us specified in the question the first one is all the words have the same length that means each and every element that is present in my bird's array would have same length in it for example here the length is three duplicates are also allowed so that makes the question slightly complicated and we have to hand gracefully handle the case of duplication so in the first go what i'm gonna do i'm gonna create a map of all the words that i need to look out for and in that map the first the key would be the string of type string and which actually stored the input word and the value would be the frequency so this represents the word so let me just write word over here and this represents the frequency so let's like flick over here and this is of type integer so let's do that and here what we will store bar has a frequency one who has a frequency one and though has a frequency one now what i'm going to do i'm going to start the iteration over my input string so let's start the iteration right now i'm at index 0 at the starting index 0 the first thing that i'm going to do is to create a copy of my entire map so i'll tell you in some time why are we creating a copy of it but let's remember for now that we are creating a copy so we have the bar frequency as one full frequency as one and the frequency as one again so let's write that up and let's start the iteration uh what i'm gonna do i'll create a substring of length three by three because the words are of length three so we'll do that and what word do we extract we extracted bar the first word turns out to be bar what do we check whether this bar is part of this map or not yes it's part of the map and what is its frequency the frequency is one so we will simply reduce the frequency to zero and delete this element up because we have successfully identified this entire word in our in input string so this is gone now let's proceed ahead and we update the pointer to this position f and at f we do the same thing again we create a new word of length three starting from f so what is that word this is that is true so we check again whether foo is part of our map or not yes who is again part of the map we reduce this frequency to zero and delete that element up because the frequency has been reduced to zero let's proceed ahead next we see let's next we update the pointer to this particular position and again we extract a new word of length 3 we get food we again check if that this foo word is part of my map or not no it's not part of the map therefore we can say that we haven't found a substring starting from the zeroth index which is which contains all the elements of words that exist in my input array because we still have an element remaining which is though therefore 0 can't be the one of the possible answer so what do we do now we simply restart the process starting from the first index so everything is gone and we again create a duplicate map out of the frequency map that we have created so bar has a frequency one who has the frequency one and we will do the same thing again and this time we'll start from the first index instead of zero so let's do that and when we are at the first index which is a we again extract the first word which is of length three we get a r f and we check whether this word is part of the map it's not part of the map since it's not part of the map there can never be a substring starting from this index that has the concatenation of all the words present in my input array therefore we simply abort the process let's proceed ahead next we have r and at r again we do the same kind of thing we create a word of length 3 what do we get rfo we check whether rfo is part of my map or not rfo is not part of the map we abort the process next let's proceed ahead to the next string and this time we are at the pointer f which is this one let's extract uh the word of length three what do we get foo who is part of the map therefore a free food frequency gets reduced to zero and since it has been reduced to zero we simply delete that element up let's proceed ahead and this time we update the pointer to this particular position and we again check what is the next word in queue is again foo who doesn't exist in my map anymore as a result of which this starting index which is starting at this particular f can't be part of the answer we have to restart again so let's proceed ahead and let's create the map again so this is gone we'll have bar with frequency one foo with frequency one and d with frequency one and right now we are at zeroth index which is this one we extract three characters what do we get oof is not part of the map let's skip let's move to the next index we get f o f is not part of the mac let's scale let's move to this particular index we are at this particular left now we extract the new word of length three and what do we get foo we reduce the frequency of foo to zero so we'll update it to zero and let's proceed ahead and right now the index under consideration is this one since we have found a word what do we update the pointer to this particular position at b we are looking for more words starting with b that could be part of the words map so we again do the same thing we create a new word of lengthy we get bar what is the frequency of bar in my words map yes it has a frequency one as a result of which we update the frequency to zero and we again do the same thing because there could be more words present and we update the pointer along with it to t and we recreate a new word which is though we check whether it's part of the map or not yes though is part of the map and we update its frequency to zero at this particular instance what do you see that all the words that are part of the map has a frequency zero that means with respect to f starting index which is this one starting from this point till over here we have successfully identified all the words that are part of my input words array this means we have successfully identified the first answer index and this index happens to be six so six index would be part of our answer and let's continue the process again we create a map where wherein the map will have bar frequency as one frequency full frequency as one and the starting index would be seven under consideration we'll recreate a new string oob is not part of our map so we'll skip this let's proceed ahead again we create a new substring of lengthy oba is not part of our map we skip this next we have b and at b we d do the same thing and the first uh word that we create is bar of length three we check bar is part of the map or not yes it is part of the map we update the frequency to zero we again do the same thing starting from this particular index which is b for this bar we update the index under consideration to t because we are successfully identified bar and from over here we recreate a new word uh the word length would be three we get the we update the frequency of the two zero because previously it was one and we redo the same thing the pointer gets updated to f and starting from here we recreate a new string the length is three we update its frequency to zero if you carefully observe then you will see that all the words that are present in my words map have frequency zero at this particular instance that means we have successfully identified the second possibility of answer and the starting index for this possibility starts at this particular b which i'm just highlighting the index happens to be 9 that means 9 becomes part of our answer set and you can do the same thing again for the remaining elements that will be acting as a starting indexes and you can manipulate them as i have just done and you can check whether there are more possibilities of answer or not to conclude it further let's quickly walk through the coding section and i'll exactly do the same things as i have just talked over here for each index you will consider it whether it can be part of the onset or not that's right it's simple mathematics the first thing that i have done here is to create an answer array that will actually store the in the starting indexes moving ahead i have checked the length of each word that exists in my words array and followed by i have created a frequency map this frequency map will store the frequency of each word that exists in my words array and this is what has been done here over here now comes the core algorithm i'll treat each and every index tends to be the starting index of our final substring and what do we do the first thing that i did in the presentation as well was to create a copy map so we basically copy the frequency map and then we look create new substrings and we check whether those substrings are part of the copy map or not if it is part of the copy map we reduce the frequency by one and in case the frequency of uh the substring that we have just created happens to be one that means it is to be removed from the map and in case if at any instance we check whether the size of the copy map has become equal to 0 that means it is empty we found out the first instance of our starting index and we add that instance to our ans array and once we iterate over all possibilities we simply return that up in case uh the substring that we have just extracted is not part of our copy map that means uh the possibility really doesn't exist for that particular instance of i and we break from there and then itself and we redo the same thing the same logic by creating a new copy map so let's try this out accepted 25 faster which is pretty fine with this let's wrap up today's session i hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for watching it and your subscription really means a lot to me thank you you
Substring with Concatenation of All Words
substring-with-concatenation-of-all-words
You are given a string `s` and an array of strings `words`. All the strings of `words` are of **the same length**. A **concatenated substring** in `s` is a substring that contains all the strings of any permutation of `words` concatenated. * For example, if `words = [ "ab ", "cd ", "ef "]`, then `"abcdef "`, `"abefcd "`, `"cdabef "`, `"cdefab "`, `"efabcd "`, and `"efcdab "` are all concatenated strings. `"acdbef "` is not a concatenated substring because it is not the concatenation of any permutation of `words`. Return _the starting indices of all the concatenated substrings in_ `s`. You can return the answer in **any order**. **Example 1:** **Input:** s = "barfoothefoobarman ", words = \[ "foo ", "bar "\] **Output:** \[0,9\] **Explanation:** Since words.length == 2 and words\[i\].length == 3, the concatenated substring has to be of length 6. The substring starting at 0 is "barfoo ". It is the concatenation of \[ "bar ", "foo "\] which is a permutation of words. The substring starting at 9 is "foobar ". It is the concatenation of \[ "foo ", "bar "\] which is a permutation of words. The output order does not matter. Returning \[9,0\] is fine too. **Example 2:** **Input:** s = "wordgoodgoodgoodbestword ", words = \[ "word ", "good ", "best ", "word "\] **Output:** \[\] **Explanation:** Since words.length == 4 and words\[i\].length == 4, the concatenated substring has to be of length 16. There is no substring of length 16 is s that is equal to the concatenation of any permutation of words. We return an empty array. **Example 3:** **Input:** s = "barfoofoobarthefoobarman ", words = \[ "bar ", "foo ", "the "\] **Output:** \[6,9,12\] **Explanation:** Since words.length == 3 and words\[i\].length == 3, the concatenated substring has to be of length 9. The substring starting at 6 is "foobarthe ". It is the concatenation of \[ "foo ", "bar ", "the "\] which is a permutation of words. The substring starting at 9 is "barthefoo ". It is the concatenation of \[ "bar ", "the ", "foo "\] which is a permutation of words. The substring starting at 12 is "thefoobar ". It is the concatenation of \[ "the ", "foo ", "bar "\] which is a permutation of words. **Constraints:** * `1 <= s.length <= 104` * `1 <= words.length <= 5000` * `1 <= words[i].length <= 30` * `s` and `words[i]` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Hard
76
264
hello everyone and welcome to my channel this channel is all about Cody here you will see detailed explanations on data structures and algorithms you will also learn how to solve coding interview questions by diving deep into the logic and intuition behind it and before moving further you might also want to click on the I button to see more liquid solutions so let's get started today's question is from July lead coding challenge day 4 and it's called ugly number 2 in this video we will discuss a method which is better than the DP solution in terms of both time and space so the problem here is we are given an integer n and we need to find the NS ugly number now what is an ugly number so a number whose prime factors only include 2 3 &amp; 5 is an agree number only include 2 3 &amp; 5 is an agree number only include 2 3 &amp; 5 is an agree number for example 1 2 3 4 5 or 12 or 10 etc a straightforward solution you might think is to find prime factors of every number and if we see a prime factor other than two three or five then we can skip this number as it would not be an ugly one but this method would be very time-consuming and you will end up time-consuming and you will end up time-consuming and you will end up exceeding that time limit as most of the numbers are not ugly so most of our time will be gone while checking the prime factors of non ugly numbers so is there any better way the answer is yes according to question an ugly number would look like this to raise to power I times 3 raised to power J times 5 raised to power K where I J and K are non-negative integers now what we can do non-negative integers now what we can do non-negative integers now what we can do is we can generate ugly numbers by putting values of IJ and K in this equation we can do this simply by using three nested loops each for 2 raised to power I 3 days 2 power J and 5 raised to power K now because most of the elements are not ugly the magnitude of an ugly number could be more than 1 billion but the total ugly number generated would be less than 16 hundred and ninty as mentioned in the question so what we are going to do is we are going to generate ugly numbers till 10 billion just by putting values of IJ and K in this equation we stored them in a list after that we can sort the list and return the NS element the magic will happen when we perform all this computation at a global level and inside the main function we just return the NS element from the list the beauty of this solution is we perform one-time computation whose time perform one-time computation whose time perform one-time computation whose time complexity is on your screen after that for every N we just return NS element former list which is a constant time operation so we have a list in which we are going to store our ugly numbers then we define a variable called M which is initialized to 10 billion and we are going to generate all the early numbers which are less than or equal to M then you see we have three nested loops I would be varying from 1 to M and after each iteration we update I by multiplying it by 2 J Woodberry from i2m and after each iteration J would be multiplied by 3 K is wearing from J to M and after each iteration we update K by multiplying it by 5 let us now see how these three nested loops are working so initially I is 1 therefore J would be 1 and as a result K would be initialized to 1 now what we are going to do is we are going to add K into our list and then we are going to update K by multiplying it by 5 so 1 would be added to the list K would now become 5 would be added to the list K would now become 25 so 25 would be added to the list K would now become 125 so we had 125 to the list and so on and so forth till K is less than or equal to M after this innermost loop we update J so J now becomes 3 because previously J was 1 so now K would vary from 3 to M again we will repeat the same process we add 3 to the list K now becomes 15 so we had 15 to the list then we will add 75 to the list and so on and so forth till 10 billion now again we update j29 because previously J was 3 times 3 is 9 K would now vary from J to M it means K would go from 9 till 10 billion then we are going to repeat the same steps again 9 will be added to the list K would now become 9 times 5 which means 45 so we add 45 to the list and so on and so forth so I hope it's clear how these 3 loops are working at the end what we are going to do is we are going to sort the list of ugly numbers and inside our main function we are just going to return the NFL iment from our list this code would run very fast because we have done main computations or pre-computation outside computations or pre-computation outside computations or pre-computation outside the class at the global level it means that these lines of code will get executed only when the program is loaded after that we can just call the method and a ugly number multiple times to know the answer let us now look at the time complexity of this solution for this innermost loop the time complexity would be Big O of log base 5 M similarly the time complexity for this loop would be Big O of log base 3 M times log base 5 M similarly for the outermost loop the time complexity would be Big O of log base 2 M times log base 3 M times log base 5 M and we all know the time complexity required to sort a list it is n log n in our case n would not be more than sixteen hundred and ninety so the time complexity would be sixteen hundred and ninety times log sixteen hundred and ninety now whenever we call this method we are just returning the NS element from the list which is a constant time operation so the total time complexity of this entire code is on your screen if you liked this video please hit the like button and subscribe to my channel
Ugly Number II
ugly-number-ii
An **ugly number** is a positive integer whose prime factors are limited to `2`, `3`, and `5`. Given an integer `n`, return _the_ `nth` _**ugly number**_. **Example 1:** **Input:** n = 10 **Output:** 12 **Explanation:** \[1, 2, 3, 4, 5, 6, 8, 9, 10, 12\] is the sequence of the first 10 ugly numbers. **Example 2:** **Input:** n = 1 **Output:** 1 **Explanation:** 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5. **Constraints:** * `1 <= n <= 1690`
The naive approach is to call isUgly for every number until you reach the nth one. Most numbers are not ugly. Try to focus your effort on generating only the ugly ones. An ugly number must be multiplied by either 2, 3, or 5 from a smaller ugly number. The key is how to maintain the order of the ugly numbers. Try a similar approach of merging from three sorted lists: L1, L2, and L3. Assume you have Uk, the kth ugly number. Then Uk+1 must be Min(L1 * 2, L2 * 3, L3 * 5).
Hash Table,Math,Dynamic Programming,Heap (Priority Queue)
Medium
23,204,263,279,313,1307
200
all right so let's take a look at this problem this one is called number of islands given an m by n 2d binary grid which represents a map of ones which are the land and zeros which are 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 meaning that the space outside are water so we don't have to think about like if there was an island touching outside of the grill we actually have additionally it's important to know that they're saying horizontally or vertically because this tells us that if there is a one diagonally it does not count it would be a separate island all right so then looking at our example here uh you see uh these ones and there's this one touching vertically and then otherwise you have these ones touching vertically so you can see just looking at it there's only one island because you have horizontally touching or vertically touching all the ones and then the rest are zeros this second example is a good example of what i was just mentioning that we need to consider is does diagonal count it does not so you see there's an island here in this little pocket of four and then this is an island and then these two are an island so you have three islands so seeing these essential assumptions uh m is our first grid length which would be our row and n is our column and we know that m is at least one so we don't have to worry about having an index out of bounds because uh you know we're going to at least have one row so the reason why i say that is uh you'll see here in a minute when i make a convenience function to essentially store the rows and columns so we're going to want to figure out what we want to return which is our count so we'll just go ahead and initialize our account zero let's make our convenient function convenience function for our rows and our columns so our rows would equal the grid dot length and now here is the part i was talking about where this is good to know if there's at least one row which there is so we can just automatically say uh the first row let's get the length of that and that will give us our column and you know the other thing here now to consider is all right now how do i handle a grid problem in a lot of these grid problems you're probably going to do a breath first search or depth first search while you're uh looking for something and the other thing to consider is when you look at these problems do you need to reset the values after are you expected to like return a grid with some original values or are you just looking through it for certain results and in this case we're just looking to count our ones and we also want to make sure that we don't end up counting ones we've already counted so the best strategy for something like this is to just replace the values with some value you don't need and we also know that zeros are water and we're not going to count those we're just using those as like boundary case so what we can do instead is just change our ones to zeros after we've counted them so uh you know typically when you're looking through a grid you're going to have a couple loops one to go left to right and the other one to go uh vertically so let's go ahead and start writing that function so four and i equals zero i is less than your row count and then i plus so that's our first iteration and then our inner loop we'll use j just because this is bothering me i'll line it up all right and then j is less than columns and j plus all right so now we are iterating uh all the way left to right top to bottom for our grid now what is our condition where we need to actually do something special well uh that would be if we find a one so if grid of i j equals one we've found something that we need to work with so now we know we found an island so let's just say count equals count plus one or you could even do uh just count plus and now that we've found that we also want to then remove or you know update our neighbors so that way we don't count these again so if we were at this one right here we don't want to then iterate to the next one and start counting that as an island so here's the special logic where we need to start doing some sort of search uh in this case i'll just probably do a depth first search where i'll go all the way right all the way left all the way up all the way down until i don't hit any other ones so once i hit this one i can go over and start marking these as zeros so forth so let's also say that we will then end up creating a depth first search function and after that depth first uh search function is done in this whole top to bottom at the very end we will return our account so now let's write our depth first search function so what are we going to want to pass it uh typically we're probably going to want to pass it the grid that we're working with so let's just go ahead and make that same uh grid that character grid that we have uh being passed into the starter function we're also going to likely want to know what is our current i what is our current j uh work and b so we're not constantly recalculating our rows and columns let's also pass in our row and our column and that should be it so then we can basically start doing some recursive uh searching through our grid if we have all these values now we need to consider what are some cases where we could start having an index out of bounds where we don't want that because that would actually cause our program to you know throw an exception so if i is less than 0 or i is greater than or equal to our row because uh you know zero and our row is really the uh if our index started at one then it would just be row but otherwise that's why we'd say greater than or equal to the row being the problem so now the other one would be if j is less than zero or j is greater than or equal to our column and the last thing is that if we run into a zero then we would also want to stop okay so this is our exit for our uh recursion basically this gets us out of if we're going all the way the right or all the way to the left or up or down we need a way to exit our recursion and no longer keep searching like i said we don't want an index out of bounds so we don't want to count any numbers as islands if we've hit some water because once you hit water that's it you don't need to keep going because if you go down another value if you were to start going to the right keep going to the right you know if you were here then you could start end up recursing down we don't want that once you have water you're done so this will be our exit for our uh left right up down and now the other thing is that if we've gone in here and we've hit a value that uh is a one we want to then change that value that is a one to a zero so we don't count it anymore and now aside from that um here's where we want to do our depth first search so we will want to go in all the directions and you can you've seen uh there'll be solutions out there that you might find where they'll write like a convenience function for going left right uh for me personally i just prefer to do it this way because it's just more readable for me so you're going to need to pass in the i but then uh we're changing the i for this first direction then j and then row and column and now uh so for this particular iteration we're going to change i to go plus one and then we will also want to go i minus one and then do the same thing but for rj so j plus one and then j minus one all right so this goes uh you know right left up down all that so you're covered you've now covered all the different ways that you can traverse uh to do your depth first search to find ones and zeros so you're covered here as it keeps doing the recursion it's going to go as far i plus one as it can so let's do i plus one and i plus one high plus one as long as it'll as long as it is valid otherwise once it hits that invalid value it's going to return and then it will start going into the next recursion step it'll keep doing that i minus one until again it's hitting in valid value then j and plus one and the j minus one all right so we're good there and now the last step is we need to pass in our value here to start our recursion so we won't do i plus one or j plus one because what we're doing is we're passing in that one that we find that we want to start with and what will happen is we already found a one we're going to pass where that one is in our function we know it's valid uh because we're already basically in our valid range as per the two for loops here so really we know that it'll pass this uh but we're passing it in anyways and then this is the step that's important is that one that we found is going to get set to a zero and then start doing that recursive depth first search uh calls right here all the way to the bottom we've gone left right up down okay so that should be it we're just going to go ahead and run that and as you can see it has finished and uh our answer is the expected answer so let's go ahead and submit and it was accepted all right so then our big o um for the space complexity will just be m by n because we are going to essentially uh potentially iterate through every value like if we started all the way at the top left and everything was one then we could end up going all the way the right all the way down all the way right and so forth where you would end up looking at every single value so that's how you could end up really having m by n as your space complexity where on the stack itself there's m by n now additionally as far as time complexity and by end worst case because you would end up having to potentially look at every single value in order to find all of the ones that are an island so that should be it if you have any questions on this please let me know in the comments below and if there's any other problems you want to see or if you just want any further extra explanation on this problem please let me know please take a moment to like and subscribe thank you
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
92
hey everybody this is larry this is day 23 of the june eco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's one reverse linked list too so i usually solve this live so if it's a little bit slow on the explanation or whatever watch it on 2x whatever you need to do i will warn you that i am probably going to be pretty slow on linked list stuff because it's not something that i practice that much just because um just because it's just it's usually very contrived examples of things that you should do in place in a way that really happens and just doesn't really come up and also like for example like can you do in one pass i guess it becomes like a brain teaser more than a programming thing or competitive programming anyway or even just you know so i'm generally pretty bad about these uh because i don't care about them so i don't know we'll see okay so this one reverse the node of the list from left to right inverse to reverse or return to reverse list um okay hmm yeah i mean so you know you could do in two pass it yeah and you can do an oven space you know put on a stack or something like that and then just reverse it that pretty straightforward and trivial um i don't know if i could do in one pass though let's see right uh are we given the length of the list now so we're not giving the length so get though i guess it doesn't really matter because you only need to go to the right so you can grab one loop to the left one loop to the right or like the same loop and then that would right it's hmm very uninteresting to me um because also if this is an operation you need you would actually just choose the correct data structure which maybe is a doubly linked list right so in that case it's a little bit awkward uh okay so let's say we have a pointer to the right and the left and then it just becomes reversing the linked list which is also i'm trying to think if i can do it of all one i mean i think if you're able to do an oven then it's straight forward i don't know i could do in one pass per se because this definition of pass is a little bit awkward for sure as well um because the traditional reason why you would do things in one pass iterating for an array for example is for memory cash reasons uh meaning that you know you have a contiguous array and you know cashing used to be more expensive than it is now because or if you know you work on an embed system or something like that and therefore if you still if you're able to lower everything into cash uh because of memory locality you do get to do it um you know it's much faster than going in multiple time and kind of resetting that locality or whatever but for linked lists depending on when you allocate and also depending on how fragmented you get or how many times you change the linked list all the memory is not in the same place right so the one pass does not yield that much more um efficiency because you're still kind of jumping around memory location anyway right so it's a little bit i don't know and now i'm just complaining more than anything but i think that's what i'm gonna end up doing um i'm just gonna put in a stack and then just go for it um i think for me to solve this problem uh definitely draw it out if you're having trouble with these um i for me generally i've done it enough times that i can visualize this um but and also just have you know whatever though i say that and if you've been following me the last month or two i've been really bad on implementation so maybe i say that and i'm cashing a check i cannot write or i'm writing a check i cannot cash um but nonetheless uh yeah so the way that i think about it is you know just do it as stupid as possible that is still of n and then we can think about optimizations later i'm not going to but you can't think about it later um so one thing that i would also um for implementation's sake one thing that i would suggest in general is this idea of having a sentinel head um that would make things easier for example if left is zero then you don't have to worry about returning the right head and stuff like that it gets very awkward so that's basically what i'm going to do new head is equal 2 on this node of negative 1 and new dot nexus you go to head so this is basically you could think about it is this zero the negative one index if you want to go to that or whatever even on your zero index or one index um and then now let's get let's go further away um so current is to go to newhead.next current is to go to newhead.next current is to go to newhead.next and then how do i want to do it i guess we do it for a count right um yeah let's just do four index in range of all right and i assume that this is within bounds yep okay and then we just use a stack maybe that's a little bit awkward but and you can also do it recursively obviously if you do recursively you're using an implicit stack which is an explicit stack which has the same basic idea depending how you do it but the idea is roughly the same so if index if this is between left and right then we just append uh current maybe this is off by one but we will have to check and then now at the very end we just popped a stack um how do you do that in a good place so the top of the stack you want that to point to okay so well length of stack is greater than zero basically you want the next pointer so let's keep track of the next pointer or last pointer maybe is you go to the last element the next of the last element right um okay so there's at least one element in this i suppose and the reason why this is it is to be honest uh i would just draw it out um base and i don't really have a easy setup to draw it out because i would have to switch back and forth but you can think about it as just you know just draw it out right like now you have two pointers to the left and the right and your entire stack um you want the last pointers the next of the last pointer um you want to kind of save that state so that your first pointer goes to it or something like that after you reverse the stack right so let's save that um yeah i guess the two ways to do it actually one way to do is reverse the list and the other one is to reverse the number maybe we will think the number is easier in this case actually i was thinking about doing some reversing the list so then let me think about this for a second if we reverse the number can we do it a good way um i mean there's still i feel like you can still do it with the stack so let's actually do reversing the number and then i don't know can i do i'm just trying to think where i can do it with all one uh extra space after reversing the stack and a caveat here is that if you're if you watch me enough you know that i rant about in place changes and stuff like that because it's just usually not what the api would want you to do but in this case i think that it's a perfectly reasonable thing for the api to do because this is literally you know reversing something right like if you give it a link this and you reverse it like the function you're probably expecting them to modify your linked list and not giving a copy so i think in this case this is okay but yeah so basically now uh let's actually you instead of using a stack let's use a deck so that we can use and this is mostly me being lazy to be honest but and you'll see why in a second uh but and now while length q is greater than or equal to two um so now back as you go to deck dot pop this i think just pop bit yeah front dot value back that values you're gonna like that while you find that value uh and then just return newhead.next uh and then just return newhead.next uh and then just return newhead.next so you may wonder uh i think one thing that may scare you a little bit is well on an interview it would this be okay i think on an interview to be honest you just have to you know the big thing the biggest thing about an interview is just to keep an open communication i guess that's like in life in general but particularly for your question um and for that um and sometimes you know you talk about different solutions and then kind of just get a sense of what they're asking right because on an interview it's very rarely maybe online is the case also clearly i have an off by one but maybe online it is more often no i mean this is i think online this is more often but oh because this is one index that's why so i should have just okay fine um i'm still wrong because i yeah i just messed up on the one index but yeah just ask a lot of questions uh keep the communication well um because you know very rarely they're just gonna be like hey here's a problem with all the statements and all the constraints given you right um that's basically what you know i mean obviously when you're doing lead code or other judges they cannot have this two-way they cannot have this two-way they cannot have this two-way communication so they kind of try to anticipate your questions by having all these constraints and so forth but in a real interview they don't generally given you in that title maybe always online assessments but in general so i think what i would urge is just you know communicate if you don't understand something make sure you ask questions don't you know don't also don't waste time don't stop people are generally smart they could tell better but yeah uh i still have some issues too two and a four uh hmm okay um but yeah so definitely sorry i'm just writing some test cases because i'm not super common about this but yeah so you think this is a little sketch maybe you're right but make sure you communicate if you see something like this on an interview and this is going to be linear space linear time though i guess we'll be doing two passes um can i do it in one pass um let's see i mean the answer is kind of yes but it depends on how you define a pass because if you use memory in it like if you do it recursively does that you know and then you pop off the stack does that count and then you could have some like no counting tricks that way which i'm not a fan of but um yeah so this is linear time linear space uh maybe two passive if you want to call it that uh maybe we could take a look at the solutions then maybe i'm here to learn as well and then cut let me see loading screen recursion yeah i don't know that's the thing with recursion is that uh that's what i was trying to get at right like you can definitely do it that way i did it with an explicit stack instead of recursion right um you know it does stuff before and after that's kind of what i did but because i have an input oh no well i end up using a deck because i got lazy i mean you actually didn't need this deck i was just kind of going for cleanup code because you could have just written you know you could have done a for loop of two pointers here right that's fine uh because we just use a deck anyway but and i think the recursive func uh solution kind of implicitly builds that away you're just not explicitly so i don't know maybe that's a couple ends on my part but for me when you did when you look at the complexity and the time and stuff like that it feels awkward to be like oh you're doing everything exactly right but semantically you didn't do it one pass is a little bit of an awkward argument against me it but that's my opinion feel free to you do your own thing feel free to uh do limitations that you feel will give you creativity uh like you know prompt you for a more creative control uh decision right uh yeah what is it a little bit of language so uh what am i doing let's see that's kind of cute actually so basically that's a weird bubble up type thing um oh yeah i mean i was talking about that as well you could change the links but i don't know like i said on an interview you would ask about it to confirm because that's a little bit weird but um yeah i don't know i guess this is okay but yeah uh let me go back to my solution i don't know why this doesn't get in the cookie but well yeah that's all i have for today let me know what you think let me know how you did it which of the way did you work on this farm uh i would talk i mean this also feels a little cheating because i feel like you could just put it in a way instead of the way that i did it but and that would i don't know anyway uh have a great night have a great rest of the week hump day happy wednesday uh stay good stay cool i will see you later and to good mental health bye
Reverse Linked List II
reverse-linked-list-ii
Given the `head` of a singly linked list and two integers `left` and `right` where `left <= right`, reverse the nodes of the list from position `left` to position `right`, and return _the reversed list_. **Example 1:** **Input:** head = \[1,2,3,4,5\], left = 2, right = 4 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[5\], left = 1, right = 1 **Output:** \[5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= n <= 500` * `-500 <= Node.val <= 500` * `1 <= left <= right <= n` **Follow up:** Could you do it in one pass?
null
Linked List
Medium
206
1,750
hey there everyone welcome back to lead coding so this is the contest bi-weekly coding so this is the contest bi-weekly coding so this is the contest bi-weekly contest 45 and this is the problem number three of the contest so let us see what the problem statement is saying we are given a string consisting of a b and c and we have to apply the following algorithm so the first thing is we have to take a prefix consisting of similar characters from the string s and we can pick a suffix of similar characters from the string s and the prefix in the suffix should not intersect the characters from the prefix and the suffix must be same and we can delete those prefix and suffix return the minimum length of the string after repeating the above algorithm and number of times so basically we have to select a prefix and the suffix and the characters must be same so can we do anything in the case when we have ca we cannot do because the c the thing that is at the front c and the thing that is at the end a are not same so we cannot do anything here what about this one so we have c here and we have c at the end as well so these two are same and we can remove them so we will be left with this much okay now we have a at both the ends so we can remove a as well and now we have b at both the ends we can remove b as well and we have a we can remove a and b so the minimum size that is left is zero so we can empty the entire string repeating all these steps of the algorithm what about this one so in this we can remove this double a and this a from the end so this is the suffix this is the prefix now the characters in the suffix and the prefix are same that's why we can remove them now we will be left with this much so b and this double b we can remove this b from the front and double b from the end we'll be left with cca now the c and this a are not same that's why we cannot do anything so the size that is left is uh this much three so now let me take some example here yeah so let me take this a b c a and b and let me just um add few more a and then a b all right so what i can do is i can look at the front part i can look at the back part so i'm keeping two pointers here start pointer and the end pointer or maybe the left or the right pointer whatever you consider so we will compare are the same are these two values same if they are same so i will simply pick up the entire part from the starting so let us just add one more b here we will be picking up the starting part where all the characters are equal to b so i will be picking up this part from here and similarly i will be picking up the end part where all the characters are b and i will simply remove them okay i'll simply remove this part so basically i shifted the start i shifted the star to this place and end to this place i'm going to do the same thing again i will see if these two characters are same so they both are same so in the case when these two characters are not same i will show you what will happen in that case so they both are same then what i'm going to do the same thing again i will be picking up the starting part with all the characters as a and the end part with all the characters and b as b and i will simply remove them so instead of saying like this what i can say is i will keep shifting s till the time i am having a as the character so i will keep incrementing s till i have a b or c so i will be here so that means i deleted this part okay the same thing i will keep decrementing my end till the part i either strike with c or b so my end will come here so basically this part is also removed now these characters are not same that's why we cannot perform these steps of our algorithm and we cannot reduce the string size further so that is why we will be returning and minus start plus one from here so this is the size that we are left with and we cannot further reduce it that's why we'll simply return here so this is what you can do i think the code is fairly simple i'm i don't want to code this i want you guys to code it out yourself so the main thing is uh you should be you should think it in a greedy way you should try to remove as many elements as you want from the start and as many elements as you can from the end so yeah you can code this and the time complexity of the solution is going to be big o of n the extra space we haven't used any extra space here so the space complexity is constant so this is it for the video you can solve this and you can also check the solution to the problem number two which i have explained in very detailed for those who don't know what cadiz algorithm is i have explained everything in detail so you can go and check that video out as well thank you
Minimum Length of String After Deleting Similar Ends
check-if-two-expression-trees-are-equivalent
Given a string `s` consisting only of characters `'a'`, `'b'`, and `'c'`. You are asked to apply the following algorithm on the string any number of times: 1. Pick a **non-empty** prefix from the string `s` where all the characters in the prefix are equal. 2. Pick a **non-empty** suffix from the string `s` where all the characters in this suffix are equal. 3. The prefix and the suffix should not intersect at any index. 4. The characters from the prefix and suffix must be the same. 5. Delete both the prefix and the suffix. Return _the **minimum length** of_ `s` _after performing the above operation any number of times (possibly zero times)_. **Example 1:** **Input:** s = "ca " **Output:** 2 **Explanation:** You can't remove any characters, so the string stays as is. **Example 2:** **Input:** s = "cabaabac " **Output:** 0 **Explanation:** An optimal sequence of operations is: - Take prefix = "c " and suffix = "c " and remove them, s = "abaaba ". - Take prefix = "a " and suffix = "a " and remove them, s = "baab ". - Take prefix = "b " and suffix = "b " and remove them, s = "aa ". - Take prefix = "a " and suffix = "a " and remove them, s = " ". **Example 3:** **Input:** s = "aabccabba " **Output:** 3 **Explanation:** An optimal sequence of operations is: - Take prefix = "aa " and suffix = "a " and remove them, s = "bccabb ". - Take prefix = "b " and suffix = "bb " and remove them, s = "cca ". **Constraints:** * `1 <= s.length <= 105` * `s` only consists of characters `'a'`, `'b'`, and `'c'`.
Count for each variable how many times it appeared in the first tree. Do the same for the second tree and check if the count is the same for both tree.
Tree,Depth-First Search,Binary Tree
Medium
1736
153
hello everyone it's really good to see you here so today we are going to solve a liquid problem which is find minimum in rotated sorted array so what we have given here we have given an array which is actually rotated and is it in a sorted order form and what we have to do is we have to find the minimum element inside it so how we can approach this problem is that let's suppose we have this particular given area so here the very simple approach which we can use is that you we can simply traverse throughout the array and find out which one is the minimum using an integer value initializing it with into max and then iterating over the array and just changing the value of our initialize integer answer which is initially in max and we change it to the minimum one and at the end of our traversal we find the minimum value but what we have to do is we have to don't uh use oauth and time but instead of that we can do it in of and in over log and time by using binary search so how we can do is suppose we have two pointers left and right and a midpoint so you can see that mid is basically l plus r by two so in this case our mid element is five so now here we have to check three conditions so the base case for our traversal is that let's suppose here you can see that 1 is the required answer right and if you check that 1 is less than 5 and 1 is also less than 2 and one is the single element which has these properties if we talk about 4 then 4 is obviously greater than 3 but it is less than 5 but in this case for 1 it's always the case that whichever is the minimum element it is always smaller than all the elements or all the neighbor elements so we can use this condition to check the base case so the base case is this one so we are using a previous is basically representing the index m minus 1 and next is representing m plus 1 but in this case we have to keep in mind that our previous maybe let's suppose our m is here so previous may go out of bound so what we do we just make it as m plus n so what we do we just make it m plus n minus 1 whole modulo l so by this we get an index of our previous one and similarly for the next since next is m plus one so we just take the model of it because there may be possibility that in this case this m goes here so our m plus one goes out and down so that's why we are keeping that in mind and we are making uh just taking modulo of it with n so by this we got our previous index so if this condition satisfies that our minimum value our previous is also greater than it and our next is also greater than it so what we do we just simply return and so this is the base case but if this is not the case then what we have to check firstly if our value at index m is less than value at index r then what we do we just make r is equal to m minus one so what i mean here is that let's suppose uh in this case m is here l is here and r is here so the value of at m is obviously greater than the value at r that means this is not a sorted um that means you can see that uh that this is not a sorted uh array or a sub array of the given array so here we uh what we have to do we have to check the second condition that is if our left is less than the value at um let's suppose numbers of l is less than value at nums of m then this means that the whole array is sorted so in this case what we do we just make rls m plus one so now our m goes from here to here that means our m is now here so uh sorry our l is now so l is firstly here now l goes from this position to m plus one position now since l is here r is here so we can say that m also is at this position so in this case if we check the condition that m is at this place previous is at this place next is at this place so it satisfies the condition that is our base condition that is the value at previous is greater than m as well as the value at next is also greater than that's why we return the index m and simply we have to return the numbers of m as our answer so this is the overall approach now in this case uh we have to consider this when our left array is sorted or we can say that from it to our the sub array sorted and this condition is to use when we can find that our array sub array which is starting from l and goes to till m is in the sorted form so whenever we found a sorted array then we just make our uh pointers or in this case let's suppose if left arrow is sorted then we make l goes to this position and in the same way if our right array is sorted then in this case we just make our write as m minus 1 so this is not possible in this case that's why we are not doing it and by this way we get a required answer so now let's dive into the coding part of it so here i had a slice another function naming index and it takes a vector integer as a input so what we firstly do we just take n which is the size of the nums and l is basically representing the zeroth index and r is n minus one then what we do we just iterate through a while loop for the condition till the point l is less than equal to r and our mid is l plus r by 2 so as i told you earlier that our previous is m minus 1 plus n so we are doing this plus n here just because the case when let's suppose m is 0 so we got this value minus 1 but this is not a case because we cannot do modulo then that's why we are adding n to be on the safer side in the same way m plus 1 modulo n gives her next now what we do we just check our base condition that is if our nums m is less than numbers previous and at the same time num is also less than equal to nums next then we simply return m as our answer index and if this is not the case then we check that if our writes are various sorted so if our evaluate nums m that is mid is less than value of num's end that is right then we change our right as m minus one and if this is not the case then we check the other condition that is if our nums l is less than numbers m then we just make our left as m plus 1 and if this whole doesn't give our any return value m then we simply return 0 so what we do we just call this function here so i am initializing int i which is equal to index numbers so this keeps the index of the smallest value and then we have to simply returns the numbers i so let's try to submit this up it got accepted so this is the approach to solve the problem find a minimum and rotated sorted array and if you want to assess the code then you can check the github link given the description and this is it for this video thanks for watching
Find Minimum in Rotated Sorted Array
find-minimum-in-rotated-sorted-array
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: * `[4,5,6,7,0,1,2]` if it was rotated `4` times. * `[0,1,2,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_. You must write an algorithm that runs in `O(log n) time.` **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** 1 **Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times. **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\] **Output:** 0 **Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times. **Example 3:** **Input:** nums = \[11,13,15,17\] **Output:** 11 **Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times. **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * All the integers of `nums` are **unique**. * `nums` is sorted and rotated between `1` and `n` times.
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go. Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array. All the elements to the right of inflection point < first element of the array.
Array,Binary Search
Medium
33,154
70
hey what's up everyone in this video we are going to solve a very easy to understand problem that is available on lead code the simplicity of this problem makes it a very good candidate for anybody who wants to learn dynamic programming and is just getting started and because it is a beginner friendly problem i have chosen this as a first problem in our dynamic programming series hey vavish here and on this channel we learn and apply various data structures algorithms to solve interesting programming questions so if this is your first time on this channel consider subscribing so let's take a look at the problem statement first you are climbing a staircase and it has n steps you want to reach from the bottom to the top and every time you can make one or two steps we want to find how many distinct ways are there to reach the top from the bottom we will see a few examples and that should make this problem even clearer so let's say this is the staircase you are at step number zero and you want to reach the step number one so how many ways are there to reach from zeroth step to first step using only one or two steps at a time the answer is fairly straightforward there is just one way of reaching from zero to one and that is by taking one step if you take two steps you directly reach two you are never going to be able to reach the step one so there is only one way of reaching from zero to 1. we can make a note of this so for reaching the step number 1 there is only one way now let's say we want to reach the step number 2 as we are allowed to take one or two steps at a time if we take directly 2 steps we are going to reach the step number two and hence this certainly counts as one way of reaching the two from zero is there any other way of course there is you can go from zero to one which is one step away and from there we can again take one more step to reach two so all in all there are only two ways of reaching two from zero and those are either take directly two steps at a time or take one step from zero and reach the step number one and take one more step from one to reach the step number two we can note it down for reaching two there are two ways now let's say we want to reach from zeroth step to the third step this time we cannot take directly three steps because we are only allowed to take one or two steps at a time so if we begin with two steps we are going to reach the second step and then there is only one way we can reach the third step that is by taking one step hence taking two steps at a time and then taking one step at a time is a certain way of reaching the third step what else can we do from zero we can of course go to the first step by taking one step at a time how can we reach three from one we are allowed to take two steps at a time so from first step we can take two steps at a time and directly reach the third step and hence taking one step to begin with and then taking two steps is another way of reaching the third step from zeroth step we went to first step by taking one step at a time from one we directly took two steps but we also had the option to take only one step in that case we would have reached the second step by taking one step now from two we need to reach the three and of course there is only one way that is by taking one step at a time hence to reach three we can also take one step each time and that way we can reach the third step so we can note that for reaching the third state there are three ways while we are at it let's also take a look at reaching the fourth step from the zeroth step in all these ways that we discussed we try to go from zeroth step to the nth step but on the other hand we can also think of it in the opposite direction so for example we can say that to reach the step number four it is unavoidable to reach either the step number three or the step number four without reaching at least one of these two steps we cannot reach the step number four so now let's put it this way we want to reach the step number four and we are only allowed to take either one step before reaching the four or we can take two steps before reaching the four now if we want to take only one step before reaching the four then we must be at step number three to do that similarly if we want to take two steps and jump from the previous step to reach the four then we must be at step number two from here we are getting very close to the final solution we want to reach the step number four we are only allowed to take one or two steps at a time we are not sure about number of ways of reaching four but we are sure about the fact that all the ways in which four can be reached will have one as the last step or the two as the last step so if we can find the number of ways in which one is a last step and number of ways in which two is a last step then we can simply add these two numbers together and get the number of ways in which we can reach the state number four now how do we find number of ways in which one will be the last step and how many ways in which two will be the last step and this answer will be given by step number three and step number two will take care of finding how many ways in which those two steps can be reached and using those two answers we can find the answer for number of ways in which the set number 4 can be reached if we are to put this in a mathematical function we can say that f of n is a function that gives number of ways in which nth state can be reached and for that we will need answer to f of n minus 1 because from all those ways we can take one extra step and reach the nth state plus f of n minus 2 because from that state we can take two steps and directly jump to the nth step and as a base cases to this function we know that when n is equal to 1 the number of ways are 1 so we can say f of n equal to 1 when n equal to 1 and similarly f of n equal to 2 when n equal to 2 now we can easily implement this in our code if we implement it as is then this would be a top down approach of dynamic programming on the other hand we can also think about the bottom of solution we already know that when n is equal to 1 the answer is going to be 1 when n is equal to 2 the answer is going to be 2 and now when n is equal to 3 we will add f of n minus 1 that is f of 2 plus f of 1 that is going to be 2 plus 1 that is 3 so f of 3 will be 3 and if you want to find f of 4 then in that case f of 4 will be addition of f of 3 plus f of 2 which is nothing but 3 plus 2 it would be 5 and similarly if you want to find f of 5 will be f of 4 plus f of 3 and it would be 5 plus 3 that is 8. now before moving to the coding part let's also discuss why this problem is a dynamic programming problem it's just a function and how does dynamic programming come into picture in the previous video we discussed two properties of dynamic programming problems one is optimal substructure property suggests that optimal solution to a problem can be found out by optimal solution to the smaller sub problems and in this case we can see that when finding the answer to f of n we used f of n minus 1 which is certainly a smaller problem compared to f of n and also we used f of n minus 2 which is again a smaller sub problem than f of n so the optimal solution to f of n minus 1 and f of n minus 2 led to the optimal solution of f of n and hence this problem holds optimal substructure property now similarly let's also discuss overlapping sub problems let's say we want to find a number of ways in which fifth step can be reached for that we will need the answer to number of ways in which fourth step can be reached and third step can be reached that is f of n minus 1 and f of n minus 2 but for finding number of ways in which fourth step can be reached we need the answer to f of n minus 1 in that case it would be 3 and n minus 2 would be 2 and here we can clearly see the overlap f of 3 will get calculated multiple times and this is what the overlap is but from here we can say that this problem also holds overlapping sub problem property if we expand this further we can see f of three needs f of two and f of one similarly this f of three will need f of two and f of 1 and hence entire sub trees are going to get overlapped now let's move on to the coding part as this problem is fairly small in terms of code size we will implement it in both ways bottom up as well as top down for the top down we have already discussed a template in the previous video we will continue to use that and we will see how easy it is to also implement it in the bottom-up approach implement it in the bottom-up approach implement it in the bottom-up approach let's move on to the coding part as we know when n is equal to 1 or n is equal to 2 we can simply return it from here so we can just check that condition first so if n less than or equal to 2 return n otherwise we can say that return climb stairs of n minus 1 plus climb stairs of n minus 2. however as we discussed there are going to be overlapping sub problems and we want to be efficient about it so we will calculate the result and store it in a storage all this is already discussed in the previous video so if you haven't watched that video i would strongly encourage you to watch that so nothing is missed in between all right so we will use the storage let's say we will use a hash map so unordered map of int now key will be the end that we are trying to solve the problem for and another inked would be the answer that it will store let's call it storage and we will always check the storage whether it has the answer for the current end now in the beginning of the climbing stairs we checked whether n is less than or equal to 2 in that case we can simply written n if that is not the case we can consult the storage if storage dot find n if storage already has the answer then we can simply return the answer that is readily available in the storage so if answer storage dot find is not end then in that case the answer exists in the storage so we can say storage of n and if it does not exist then we are going to calculate the answer and we will store this answer in the storage for the future references so we can say storage of n is equal to climb status of n minus 1 plus n minus 2 and then return storage of n if you want to simplify this further we can say storage dot find if we don't find it in the storage then compute it and at the end return it from the storage and if you want to even reduce the code size further we can put answers for n equal to one and two in the storage at the beginning and then we don't even need this check in the beginning so in the beginning we can store in the storage key one and answer one similarly key two answer two you can try and run this code it works as expected for the given test case but it's always a good idea to add a few more test cases so far we already have the answer to n equal to 3 n equal to 4 and n equal to 5 so let's test with that great for n equal to 2 the answer is 2 in the output as well as in the expectations and for three five four three four five we already saw that the answers were three five eight and that's what we are returning so let's go ahead and submit this solution all right it works now this was the top down approach that we implemented let's also implement this in the bottom-up approach this in the bottom-up approach this in the bottom-up approach and you will find that both are fairly close to each other and none of these are difficult as such for the bottom-up are difficult as such for the bottom-up are difficult as such for the bottom-up approach we'll simply store the answers in a vector that is an array where ith index will hold the answer for number of ways in which eighth step can be reached so let's say vector of integers and we can call it storage again we already know that the number of ways in which zeroth state can be reached in one that is not do anything so we'll put one number of ways in which first step can be reached is one that is go from zero to one and number of ways in which second step can be reached is two because we can go from zero to one and one to two or directly from zero to so now that we have initial values in our storage let's run a loop for reaching the nth step so for int i equal to 3 i less than or equal to n i plus in the storage we can store storage dot push underscore back so append at the end sorry typo here append at the end the answer for i equal to 3 will be addition of answer for i equal to 2 plus i equal to 1 so that is storage of i minus 1 plus storage of i minus 2 and at the end because we want to return the answer for nth step we can simply return storage of n and we can again try and run this code and it again passes the test cases that we had provided if you observe carefully as you can see we only care about the previous two values and we don't need all values in that storage there is certainly a scope of optimization here in terms of space complexity i will leave it up to you whether you want to optimize it further or not for now we can just submit this code and see if it works great so let's quickly discuss the time complexity and space complexity of this solution let's start with the time complexity declaring the storage it would be a near constant time so you can just say constant time this loop is going to run in the proportion of n let's say n times precisely it's going to be n minus two times but anyways in the time complexity analysis we ignore the constant so we can just say this loop is going to run n times and this insertion at the end of the array is also going to be a constant time so we can say that n times we are going to run a constant time operation so the time complexity of this for loop is going to be big o n and plus we have this constant time operation at the beginning so overall time complexity of this solution is going to be big o n similarly for the space complexity at most there are going to be n numbers in this storage and hence the space complexity is going to be big o n as well now some of you might think about how to find the time complexity of the previous solution which was a top-down solution which was a top-down solution which was a top-down solution and it was a recursive solution in some of my other video i have mentioned that i am going to make a dedicated video to discuss how to find the time complexity of recursive solutions and hence i'm not going to discuss that here but in the meanwhile if you're really curious about it i have written a fairly easy to understand blog post about it and you can find that on my website i'll post the link to that blog post in the description below so do check that out i hope that you like this interesting problem that is not so difficult to understand and write the code of and still introduces you to the dynamic programming if you enjoyed learning something new today give this video a thumbs up and share it post any questions in the comments below so either i or someone from the community can respond i would also love to hear any suggestions and feedback that you may have don't forget to subscribe to interview recipes see you next time and bye for now
Climbing Stairs
climbing-stairs
You are climbing a staircase. It takes `n` steps to reach the top. Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top? **Example 1:** **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps **Example 2:** **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step **Constraints:** * `1 <= n <= 45`
To reach nth step, what could have been your previous steps? (Think about the step sizes)
Math,Dynamic Programming,Memoization
Easy
747,1013,1236
524
hello guys uh and welcome back to my channel so today we will be solving the lead code day 22 challenge uh which says the that is the longest word in the dictionary through deleting so we have been given a string and a string dictionary and we want to find the longest string in the dictionary that can be formed by deleting some characters from the given string okay so let us first understand the problem so this is the string which is given to us and these are the list of strings which we have so we want to find a string a longer string which can be formed by deleting few characters from this particular string so if there are more than one possible result resulted in the longest word with the smallest lexicographical order uh if there is no possible result then return an empty stride so let us first analyze the problem what the problem means so for this i have taken into consideration this particular string so what so basically we have been given this string and we have to somehow do some sort of deletion from this particular string so let's say these are the dictionary of the strings which we have so this particular string we can delete this particular four elements and now a l e is there in the dictionary so this is one of the possible solution then again we can do one more thing that is we can remove this b this c and apple so apple is also one of the string monkey cannot be created from this particular string so this is not a part of the answer and the next one is uh yeah the next one is p-l-e-a-p-l-e-a-e which is p-l-e-a-p-l-e-a-e which is p-l-e-a-p-l-e-a-e which is which can also be formed by deleting abc so out of this four apple is one with the largest limb so that would be the answer and let us take this as the example so here if you check we have p l e a which is also a string and also l e a p which is also a string which satisfies the condition but if you check uh both of them as the lengths are equal we will take the lexicographically uh string which comes before right lexicographically l comes before p so this will be the answer in that case so i hope you are able to understand the problem so let us look at the solution which we can use here so for the solution part what we would be doing is that we would take each and every string from the dictionary which we would have we have and we would check if that particular string is the largest like first we will check if it's a subsequence of this string and if it is a subsequence we will also check if that's the maximum subsequence or no so let me just explain you that so first we will take the first element from the dictionary that is ale okay so we will have maybe two pointers so we will the first thing which we will check if this particular string is a subsequence of this string or no so we will have two pointers we will go through it we will check if this a and this a are equal so we will increment the count uh then it would check this l and l are equal so we will increment both these pointers again e and e are equal so we will again increment both these pointers until this comes out of the index so here we found that a l e is a subsequence of this string right so initially we would have an empty string so the result is initially empty now we have found out that ale is a subsequence of this particular string right so ale has length 3 which is greater than the result which we have the result was of length 0 but ale is greater than that so now we will make ale as a result and we will move to the next element in the dictionary is apple app le apple okay so again we will do the same thing we will check if a and a are equal yes they are equal both the pointers will be moved then it would come p would be increase then at this point again it would be increase l and l are equal so we will increase e and e are also equal so we will increase it and it would come out of bounds so now if we check apple is also a subsequence of this particular string right and also apple is greater than the result which i have got until now so this word that is the apple is actually longest than the current result which i have so again i will increment i will change the result to apple okay so now i will go to the third item that is monkey so if you check monkey is not there in the subsequence so basically monkey is not a part of this so this won't be considered then we will go to the last item that is plea so again if we check a plea forms a subsequence so here if you check p l e a is not greater than the result which we have until now right the result is of length 5 but plea is a smaller sub sequence so we will not update our result and at the end we will get our result as apple okay so this is the overall logic which we have so let us come back to the code now so this is the code which we have so initially we have maintained a result as equal to zero maybe i can just so after that i am looping through each and every uh element in the dictionary and i am checking if that particular string is a subsequence or not so to check the subsequence i am using the same logic which i had just explained so here there is a pointer and at the end if the j pointer is equal to the substitute then i can say that it's a proper subsequence so once it's a proper subsequence i will go inside it and this is the part wherein i am checking if the string which i have is greater than the previous result which was there if that's the case i will just update my result the other case that is this one so i'll just explain you this one as well so let us consider this case here if you check both p l e a and l e a p both are equal and the length is equal right uh and both of them are a valid solution so here i am i will be checking if both of them are equal then if result which i have right if result is greater than the string which is there in the dictionary if that is the case i will again increment my i will again update my string so basically what this particular thing checks is the lexicographical ordering so whenever a result is greater than str it would result it would give you a positive value and in that case we have to update the result and then subsequently we will return the result from here so i think this is pretty much it about the code let me check if yeah it is accepted as well so yeah i think this that is it for the video i hope you guys are able to understand it if you have any doubts or any queries please do write it in the comments section thank you
Longest Word in Dictionary through Deleting
longest-word-in-dictionary-through-deleting
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. **Example 1:** **Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\] **Output:** "apple " **Example 2:** **Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\] **Output:** "a " **Constraints:** * `1 <= s.length <= 1000` * `1 <= dictionary.length <= 1000` * `1 <= dictionary[i].length <= 1000` * `s` and `dictionary[i]` consist of lowercase English letters.
null
Array,Two Pointers,String,Sorting
Medium
720
818
all right eight one eight race cars so we have a car that starts at position zero and it has a speed of one and it has we can give our car two instructions so the two instructions are accelerate if we give an accelerator instruction it will increase our position by our speed and then we'll double our speed here and if we get a reverse or if we give our car reverse instruction then we essentially reduce our speed to 1 and flip the sign so if our speed is positive we're going to change the speed to negative 1. if the speed is negative then we just change the speed to one okay and then we just have some target position we're trying to reach and we want to return the minimum number of instructions to reach that target all right so now for the algorithm so what we're going to do is we're going to breadth first search through all the possible instructions step by step until we hit our target and once we've hit our target we can just return the number of steps in our bfs that it took to reach that and that would be the number of instructions um but what's important is that we limit our range of where we let our car uh venture out to so when we give our car an instruction we're not going to go through any paths of our bfs that take our car outside of this bounds that we want so the bounds that we're going to set our car to is position 0 to 2 times the target minus one so we're not going to let our target go into negative numbers and we're not going to let our car go past two times the target minus one and now i'm gonna explain why all right so let's go over some basic intuition so let's say this is my starting point here this is my start and our speed is 1. now let's say that there's some target position out here all right so this is my target and let's say that i want to try going into my negatives first and then into my tar and then head towards my target and let's so let's just so first thing we're gonna do is we're gonna reverse so now our speed is negative one and we're going to accelerate in this direction some amount we're gonna stop and we're going to reverse again so now our speed here equals one and now let's say that we accelerate all the way to our target and we just magically land on our target by going this way and then this way well what we could have done instead is we could have started from this exact same point okay so we could have started from the exact same point and see this amount here so we had a speed of one here and right now we also have a speed of one let me make that one a little clearer so we have a speed of one here and we have a speed of one here well that means that this mount here this huge arc we could have done it right from the beginning so let's just do that and this takes us somewhere out here so whatever let's just call this distance d this is also distance d and this distance let's just call this i don't know d2 let's call it d2 all right well after we reverse here let's say let's put our target right here after we reverse here our speed is going to be negative one and this distance d2 notice our speed here was negative one our speed here is also negative one we can just repeat this acceleration so we're going to repeat d2's distance and now we're going to land on the target this is g2 and why is this better well notice here we had to do a reversal here i'm going to do a reversal here well here we only had oh sorry from here we only had to accelerate reverse once and then accelerate again versus here we had to reverse accelerate so going into the negatives when your speed is one isn't better so i just wanted to prove that we don't have to go into our negatives to wind back and then go and then shoot forward all right so for the next one let's get on to that all right so for this next point let's say again my start position is here and let's say i want to try um going into i want to try going for my negatives again so let's just say that i venture i accelerate all the way out here and let's say that i reverse and now i undo all that progress and go straight back to my start point and now but the only difference here is that my acceleration is going to be a little bit bigger so now it's or it could be a lot bigger depending on what this distance is but the point is i'm going to accelerate again so for one more instruction let's say i can accelerate all the way out here so what did we just do here we accelerated undid 100 of our progress that accelerated into our negatives and let's say that my target is somewhere out here and now let's say that this acceleration takes me we could say it takes you directly to the target a little bit before or a little bit after the target somewhere around the target right well i think if you just look at this visually it doesn't make sense like why would we go 100 why would we accelerate in some direction and then undo 100 over 100 of our progress just to get like way further away from the target and then accelerate and towards the target when we could have just done a straight shot and this won't necessarily take us to the exact same position as say where any of these three positions are located but i think it's easy to see how like we would have had to have done all these instructions here done a reversal instruction then redid all of those instructions plus one more and then repeat some more instructions so we did like one like a one huge loop and i think just visually you can see that can't there's just intuitively it shouldn't be better than just going say somewhere over here and then you know continuing to accelerate towards our target or say going from here to say some a little bit past our target and then accelerating backwards so um i don't have a solid like hard proof for this but i think visually you could see why just to undoing a hundred percent of our progress into our negative positions to do some huge loop just and it just doesn't make sense or just visually it doesn't make sense um but yeah so i'm just proving why we don't need to go into our negative positions all right so on to the next thing all right so for this next example i just want to show that we don't have to check past two times our target minus one so for example let's say that my start point well let's see my start points always a zero right and if i accelerate i'm gonna end up at one because my speed is starts at one and if i accelerate again i'll end up at three because two times one is two so two plus one is three if i accelerate again so if my speed here was two in between these two points my speed my next speed will be four because i doubled my speed so that means three plus four is seven so i'm gonna end up here all right so from here to here now if i were to double my speed again so my speed here was four if i double my speed again it'll be eight right so eight plus seven is fifteen so let's say i'll be all the way out here now notice how this relates to our target so our target is 8 what is 2 times our target that is 16. so 2t equals 16. 2t minus 1 is 15. so we the most we can ever overshoot in a single instruction the most we can ever overshoot our target so let's say we overshoot it in one instruction is we'll always the at most will always end up at two t minus one at most and you know we could just keep going right so we could just say go let's so it took us our speed here was 8. so we could increase our speed to 16 and then keep going out here to like say 31. uh but i don't i just it doesn't make sense to like you know if we're even twice as far from our target that's not going to decrease the number of instructions to get to the target because on top of that we'd have to do um actually no yeah i think that's good so like just being twice as far from the target so if we go past two times the target um it doesn't make sense it's not going to decrease the number of instructions so we don't so what i'm trying to prove here is that we don't need to check positions past two t minus one and it's let's say and it's not possible to reach two times t because if it was we would have already been at t because t would let's say our target was seven right if our target was seven we would have landed on it so it's not possible to reach uh two t um assuming we just bound our so yeah we're just trying to bound our the positions that we check to 2t minus 1. okay uh so next all right so let's code this out first we're going to do is create a queue of a pair of integers and let me explain i'll explain what this represents in a second let me just type this okay so all we're storing is the speed and the position in our queue so a pair of speed and positions in our queue and we need a set of visited nodes so set a pair of integers and just call this visited because we don't want to recheck the same positions over and over again right same positions and speeds okay so uh this will be a new hash set and we need to put something in our queue so what's the very first starting point which is just the problem said we start at position zero with the speed of one so we just do q to offer um new pair at position zero speed of one okay and then we need to mark this node as visited so visited dot add q dot peak so that'll just q dot people just grab this thing right here all right and yeah so let's just keep going to bfs so now all the q isn't empty then we can go ahead and pull something out of our cues or we can pull the node out of our queue so uh this will just be pair of integer dot integer node equals q dot poll and then we're gonna i'm just gonna store the things inside the pair into some variables so it's more readable so imposition equals node.getkey and speed equals node.getvalue speed equals node.getvalue speed equals node.getvalue okay um so okay so we need to return so the whole point of the problem is to return the minimum number of instructions right so we need to keep track of since we're going through our we're going to go through our bfs one level at a time and the level that we're on essentially represents the number of instructions that we've given our car so we need to keep track of the level that we are at in our bfs um so the way i like to do it i keep a size variable so i'm just going to initialize this to one because there's one thing in our queue right now and we're going to keep track of our number of instructions that we've given the card and it's zero in the beginning because we haven't given our car any instructions yet right okay so what i'm gonna do here is if the position equals so if this position here sorry here if the position out of our node is equal to our target just return the number of instructions oh return okay so in the beginning this will just be zero right because we initialize this to zero and if zero happens to equal our target then we just return zero because we haven't given our car any instructions okay and now we're going to go through all of our possibilities but we only have two possibilities right either we accelerate or we reverse so um i'm gonna write a little helper method in a second but what i'm gonna do is let's say let's i'm gonna call my helper method offer and what i'm going to do is i'm going to pass in the queue pass and visit it pass in our current i'm going to pass in our next position so this is going to be position plus speed and then we want to double our speed so you can think of this as the accelerate so this is gonna be speed times two or we could do two times three or whatever and i think that's it i think we're good there it might be if i'm missing something i'll figure it out later and then we need to do our reverse right so then we'll do offer q visited um our position will stay the same because all we're doing is we're reversing we're not actually moving the car anywhere so position then we do um if the speed is greater than zero then we're going to set it to negative one if the speed is positive just set it's negative one if speed is negative and set it to one okay and then oh and okay so now again we need to keep track of what level we are in the bfs because that represents the number of instructions that we are currently at so because we're only doing one instruction at a time like per layer if that kind of that makes sense i'm having trouble worrying it but anyway um we need to decrement our size so if size after we decrement our size if it equals zero that means we've gone through all the nodes or this set of instructions on this level so if it hits 0 we need to set our size to the number of nodes in the next level which would be q dot size and we increment our number of instructions by one so just increment the number of instructions okay um soon and then there's a couple i've seen other people sometimes they do like a nested while loop uh to go through all the nodes in the current level um you could do it like that way too i just like to do it like this because i don't i prefer not doing a nested while loop but anyway um we still so the last thing we need to do is we need to write this offer method to go through yeah we just have to implement off putting the stuff in their queue so let's do that here so public or private void offer so we need to pass in our queue which is just a queue of pairs of integers and just call it q and then we need to pass in our visited so set a pair of integers and just call it visited and then next we need to pass in the position we need to pass in the speed and it's speed okay and now we need to do some checks so one we need to check we've already visited this right but we also need to check if this position is outside of our range that we wanted to check so if it's in the negatives or if it's past two t minus one or two times the target minus one so let's just check is position greater or equal to zero and position is less than or equal to two times the target minus one oh i didn't pass in the target that's what i forgot or we could just do like two times less than the target that would be fine too a little bit shorter let me just pass that in really quick so i forgot to pass in this guy right here um let's do that really fast so target and target okay so as long as we're in the correct range then we can continue to add it to our being bfs through this path so uh and then we also need to check that it's not visited so and visited doesn't contain um this pair so we can just do a new pair of position and speed and that's a it's pretty long let me just put this on another line okay uh i think we're good here yeah so if it's so if we're in the right range and it's not visited then go ahead and add it to our visited uh oh you know what i should just create this new pair in a variable here just call this node okay and put spaces because i'm picky about my spacing okay node new visited dot add node okay phone if it contains a node okay yeah so if it's not visited if then go ahead and add it to the visited and then we can go ahead and do q.offer and then we can go ahead and do q.offer and then we can go ahead and do q.offer the node and this is just like the neighbor right i could have called this neighbor node doesn't matter um but anyway moving on so uh yeah i think this should work oh and i need to okay so we're never gonna get to this return statement um because so this return statement here should never be reached because eventually our position will hit our target and then we'll return the number of instructions uh so you could put like a thousand negative one whatever but we're never going to reach that point so anyway uh just run the code see if what happens cool and just use the example test cases make sure it's good submit okay cool all right so now let's talk about the time complexity so what are all so our breadth first search it's just visiting all the possible combinations of positions and speeds because we're holding pairs of positions and speeds right and we're just making sure we don't revisit those same positions and speeds so all we need to do is figure out how many different positions are what are all the different speeds we can hit those positions at and then multiply it together so we're just doing the number of positions times the number of speeds so the number of positions if you remember is just 0 to two t minus one so this boils down to two t and then because we drop the constant this is just big o of t let me just comment this out so the number of positions boils down to o of t and then the number of speeds that we can hit those positions at well what's our first speed so our first speed is going to be one right and then it's gonna double to two then it's gonna double again to four then eight and this will actually keep doubling to up to t and i'll explain why it goes to t but i just go with me for now so uh assuming that it goes from one to t uh this ends up because it's doubling this just comes out to uh log of t or big o of log of t i think it's log of t plus one but um when you do the big o you know you drop the constant so log so it just comes out to log of t for the uh number of speeds or big o of log of t and now why does it only go from one to t and i kind of went over this earlier but uh okay let's just go through an example let's say the target is um eight right well what's our starting position are starting position it's going to be zero sorry not one so starting position is zero our starting position our starting speed is one now uh what's our next position going to be it's gonna be one and our speed is gonna double right then our next position will be three speed doubles next position will be seven speed doubles and we so right now we're position seven and our target is eight so now let's uh add eight to seven so it takes the 15 and this is two t this is sorry this is two t minus 1 here and our speed doubles again i'm sorry that should be 16. now uh this 16 here so there's only one there's only two cases where we uh hit um or we ever have a speed of 16 or where we have a pair of where 16 is the speed in our pair uh and that's when we start from the very beginning and go and accelerate all the way to the end or when we start from the end and accelerate all the way to the beginning so we don't care about those two notes because only two nodes right out of like you know if we have like a million nodes who cares about two nodes but uh so we can just like ignore the 16 there the number of speeds here though is four and what is log of the target i'll go to the target so log of eight would be three so the number of speeds ends up come coming out the majority of the nodes can be hit by log of our target plus one uh number of speeds um so hopefully that makes sense so like yeah so log of eight would come out to three and notice that we have four digits here so it just ends up being uh three plus one equals the number of speeds on average that the number of nodes can be hit by so uh that means that our total time complexity if our number of speeds equals big o of log of t our total time complexity equals uh big o of t times because the number of positions times the number of speeds uh times log of t and now the space is going to be the exact same thing because uh this is the number of nodes that we are visiting and we're storing all these nodes this is the word in the worst case we're going to run through all these nodes right and then we're going to put all those nodes in our visited set so our visited set is what's uh growing our space so then um the space just ends up being the exact same thing it ends up being o of t times log of t okay um yeah if you like the video you can uh give it a thumbs up you can subscribe cool bye
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
383
hey guys let's take a look of uh liquid question number 383 ransom notes first of all we need to understand the concept of ransom note what is that what is ransom notes um let's take in take a look at this picture ransom note actually it's just like they're trying to make a note and using words or letters cutting randomly from a magazine or newspaper or something like that in order to like avoiding the handwriting if the handwriting is like can be recognized or something like that so we can see you can cut the alphabet through from a through z like this and then you can make a ransom note above here right and you can use the r here a like this and then the dab to e like this right and then that is called the ransom notes this part let's read the question together it's an easy question so all right they're giving two strings ransom note and magazine so is the boolean function your return true if the ransom note can be made using the maxim the um the magnin string or it cannot be made so you return false otherwise right so they have one more condition just like each letter in the magazine can only be used once in the ransom notes what does that mean that means it cannot be used repeatedly let's dive into the three examples very clear so like if the magazine gives you b and your note need a so it cannot be made right you return false the second example just like the condition mentioned it can only be used once so like if the magazine gives you a b two letters and you need to make ransom notes a so you cannot use the letter a two times it can only be used once in recent notes so you cannot be made that you cannot make the ransom notes output is false and the last example just like magazine give you aab three letters and resume you only need to make aa which are two letters right so you can do that apparently so the output will be true let's take a look of the code i'm using c plus and you can see this is the boolean function that gives you two string one name ransom notes the other y is the other one is string magazine and i'm using an older map the key is the character and i'm calculating the frequency of each like the element so i'm using two for loop the first one just like every time we see the element from the magazine we increment its count right so the second one just like every time we see an element from ransom notes the same element so if the frequency is bigger than zero then we decrement it why we have to do that means like if we can decrement it to zero that means the magazine the string can make the ransom note otherwise it cannot be made so we can see from this like if the frequency is bigger than zero decremented otherwise we just return false and after the for loop if it can decrement it to zero that means the ransom node can be made so we return true okay let's run the code to see how that works or we can see the input like random know we need a and actually the magazine only give us a b so it cannot be made the output and they expected their return false like they're the same the big o for this one if this one is m and this one's n it's going to be m plus n right and we can see the submission runtime 26 seconds and faster than 50 of online submission yep that's pretty much of it that's question 383 thanks for watching and hope you have a nice day
Ransom Note
ransom-note
Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_. Each letter in `magazine` can only be used once in `ransomNote`. **Example 1:** **Input:** ransomNote = "a", magazine = "b" **Output:** false **Example 2:** **Input:** ransomNote = "aa", magazine = "ab" **Output:** false **Example 3:** **Input:** ransomNote = "aa", magazine = "aab" **Output:** true **Constraints:** * `1 <= ransomNote.length, magazine.length <= 105` * `ransomNote` and `magazine` consist of lowercase English letters.
null
Hash Table,String,Counting
Easy
691
419
welcome back everyone we're gonna be solving Lee code 419 battleships and a board so this problem is pretty much the exact same as the number of islands problem except instead of ones and zeros we're dealing with x's and dots um so essentially same thing as number of islands if you've watched that video before if you haven't essentially what we're going to do is run either depth first search or breadth first search on this grid and count the number of battleships on this board and uh in the number of islands problem I ran depth first search so this problem we are going to do breath first so if you want to see the depth first version go check out that video all right so let's get started uh we are going to implement breath first so we are going to need our cue from our collections Library from collections import DQ we will set that up Q is going to be equal to a DQ of an empty array and we are going to have some sort of count to count the battleships right we are also going to have a visited set to keep track of the row column pairs we have already visited okay now we need to iterate through every row and column in our grid how do we do that we can say for Row in the range length of our grid and four column in range length of grid 0. what are we going to do we have to check and see if the Grid at our row column if that position is an X and it hasn't been visited before we can increment our account that means we've run into a new Battleship and then we can run breadth first search so let's say if Grid at what is this row what did I say row column if that is equal to an X right yep our battleships are represented by X's if that is equal to an X and the pair row column is not in our visited set what are we going to do we are going to increment our account by one and add this row column pair onto our Cube so we will say Q dot append the row column pair and then we can just run breadth first on this so we'll say while the length of our Q is not equal to zero we are going to grab the row column pair with Q dot pop left now we need to check and make sure that this row column pair is valid within our grid right so for example one zero is valid but negative one right that's off our board that's off the grid that would not be valid so we have to check and make sure that these two values are valid pairs on our grid how do we do that we can say if uh rho is greater than or equal to zero and less than the length of our grid and our column is less than or equal to zero and less than the length of our grid at the first row what are we going to do we also need to check if that row column pair is not in our visited set and the position at our row column pair within our grid is equal to an X then we can continue our depth or I mean our breath first traversal so we'll say visited dot add the row column pair and then we can add on the new row column pairs within our grid so if we're at zero we want to add in one or a zero one and we would want to add in one zero right we'd want to add in all of the adjacent uh boxes so we'll say Q dot append the row plus one at the current column we will add in the previous row queued out a panda the previous row with row minus 1 at our current column and we will append the current row at the next column and we will append the current row at our previous column and then at the end we can just return our count we should have the correct count of our battleships so let's get rid of some spaces and run this invalid syntax this should be not and not is not in perfect we pass up both test cases so let's submit awesome so we do pass the submission cases so this again this is the pretty much the exact same problem as the number of islands uh except in that problem we ran depth first traversal in this problem we ran breadth first and the time and space complexity is going to be the same as the last problem where it is R times C the time complexity is going to be o of the rows times The Columns right we have to Traverse every Row in every column and then the space complexity is going to be the same as well rho times columns we are adding in all of our visited row column pairs all right that'll do it for Lee code 419
Battleships in a Board
battleships-in-a-board
Given an `m x n` matrix `board` where each cell is a battleship `'X'` or empty `'.'`, return _the number of the **battleships** on_ `board`. **Battleships** can only be placed horizontally or vertically on `board`. In other words, they can only be made of the shape `1 x k` (`1` row, `k` columns) or `k x 1` (`k` rows, `1` column), where `k` can be of any size. At least one horizontal or vertical cell separates between two battleships (i.e., there are no adjacent battleships). **Example 1:** **Input:** board = \[\[ "X ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\],\[ ". ", ". ", ". ", "X "\]\] **Output:** 2 **Example 2:** **Input:** board = \[\[ ". "\]\] **Output:** 0 **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 200` * `board[i][j]` is either `'.'` or `'X'`. **Follow up:** Could you do it in one-pass, using only `O(1)` extra memory and without modifying the values `board`?
null
Array,Depth-First Search,Matrix
Medium
null
1,839
hi welcome I'd like to address leak code number 1839 longest substring of all vowels in order uh this problem essentially proposes a classification of substrings that it's calling beautiful and a substring is beautiful if uh basically two constraints are met the first is that all vowels are essentially contained in a substring of an even larger string and also those vowels actually have to be in alphabetical order so it's sort of a two-step order so it's sort of a two-step order so it's sort of a two-step process for verification all vowels must be present right but that isn't to say that they must all strictly be um of the same frequency right I mean we could have a beautiful string where there are multiple uh vowels as long as those uh as long as the substring has all vowels present regardless of how many times they're duplicated and in addition to that as long as they're in alphabetical order then that is a candidate for a that is a beautiful substring um but what we want to do is we want to find out okay well we have this classification right of being beautiful right all the vowels must be there and it must uh be in alphabetical order um but the idea here is that we want to return the length of the maximum or the we want to return uh basically the greatest length of one of these beautiful substrings right so of all the beautiful substrings that there are which one has the greatest length or the highest length or the longest length and then we would aim to return that um and so this is kind of what we have here so uh the approach is to actually use a uh is a I mean of course you could generate um all you know sort of a Brute Force ways to really generate all substrings um and then to um you know go uh like you know maybe make these a helper method right one helper method could verify if uh you know if all vowels are contained um uh one helper method could verify if all vowels are contained and the other could verify if it's sorted and then of course uh you could record the length um but this seems to be a taxing problem because you're generating all possible um substrings right so it's not necessarily uh optimal to do that I think that would either be quadratic or cubic uh in terms of time complexity um and so we usually uh revert to sliding window in those types of cases and so the idea here is actually to have a pointer into R and int L right and left or you could have um you know um and then um start right I mean that's also a popular one and the idea is to actually leverage a set data structure and we are going to move across the string and essentially add characters to this set now why I say it's important to add characters to the set is because this set will allow us to keep track of whether or not at least or yeah at least one occurrence of the vowel is present in the substring okay so I mean we have to have some way to uh sort of assure that at least one of every vowel is present and so the idea is if we add each of these vowels into the set as we move along um and they're all vowels by the way we don't have to verify whether or not it's a vowel they're all vowels and I think that's made very clear with the question is that you know it you know the um the word consists of AEI or U um so they're all vowels right verifying it isn't really the problem the real problem is simply verifying whether or not two things right whether or not all vowels are contained and whether or not all vowels are in alphabetical order and so what we do is we just we move forward and we constantly add each character one at a time into the set and then as soon as the set size hits five we will know that we have all five um we have all five uh vowels in the set because it's only gonna a set will only store uh unique entries it's not going to store duplicates so if I look at this string here a you know I have multiple A's I have one EF four eyes I have one o and three U's it will only store a e i o u so as soon as that set size hits five I will know that there are at least one entry of uh of each vowel in this particular substring and um and so that's what's that's what helps and as soon as I know that there are at least five right or as soon as I know the set size is five well then I can record the maximum right I can try to uh judge what the length is of that particular substring which gave me a set that had five entries in it um and then I'll record its length and I'll compare that to the length I had before and then I'll kind of go that way now there's also one other part to this problem that I think I'll address after it's coded so as I said I'm going to have a set of characters here I'll call it set equals new hash set and the basic idea here is we are going to um have our uh left and right pointer and while that right pointer is Le and I'm actually going to introduce another string here called s so that I can have a more concise way of referring to word I don't want to have to type out word too many times um so here I instead of saying word.length I'm just saying s dot length word.length I'm just saying s dot length word.length I'm just saying s dot length so it's more compact so while R is not essentially while so if you say R is less than s dot length and you keep incrementing R it allows you to touch every single element um within the array or not the array but really the string um and so R would actually have to be incremented right eventually for us to get the algorithm to move along the string and the idea is like I said before we'll say okay we'll set dot add the character that R is currently referring to right and um we know that if the set dot size is ever five then we can increment a counter right so it count is equal to zero we can increment a counter because the counter um like we have a string where all vowels are present right that's why the set is five right so we were adding them into the set as they came and then the set with the set being five meant that at least one entry in the set um or at least one vowel of every vowel was present in the set and so we increment count by one but um it actually you know what on second thought it doesn't make sense to increment count because we're actually not counting the substrings that have this property instead we're actually recording the maximum length so I'm going to set the max equal to zero and I'm just going to say okay well Max is either going to be what the max was before or the length of the current substring right so the length of the current substring whenever you find the length just in everyday life you always take the upper bound and you subtract off the lower bound and the difference is the length um and that's true even for our case right um we take the right one which is obviously going to hold a greater value we subtract off the left one and then um and that should give us the length but the problem is these indices are offset by one so they actually start from zero and them starting from zero means that we have to have um we have to take that into account so we add one to it so if I had indices 0 through 4 uh this would I mean this would give me you know four right and then I'd add one and so the length of that would be five and that makes sense because an indices of zero through four does have a length of five zero one two three four five right so this the length of this is five but the maximum indices actually um is actually Four right so um basic idea iterate through add each entry into the set if the set has ever reached five then we know that at least one vowel um of every vowel is within the substring in question which means we should probably record the length and see if it how it pairs up against the length we had before um and so that works and then of course we increment right by one and then we return uh we would basically return uh what the maximum was right now that's all fine um in the way that it works but um who's to say that like okay how do we address I mean we've in essence we've addressed this concern um that you know they must appear at least once um and so if I were to return this now it would give me basically the maximum of uh a substring within which each vowel returns at least or appears at least once but I want an even more carved out definition of these substrings I also want them to be in alphabetical order so how do I filter that out how do I filter it being an alphabetical order well what you can do is you can say okay well it being in alphabetical order right I mean these are fine right but let's take a look at where this takes a turn right so you have a and you have e this is in fact in alphabetical order but what is some property that encapsulates this relationship of it being in alphabetical order and you could say well perhaps it's the ASCII value right because the ASCII value for letters that get larger um are greater so a is going to have a lesser ASCII value than e so um basically if I say s dot Care at r right this would have to be greater than s dot Care at R minus 1. right so when I say s dot Care at R it's returning to me a character but in Java I can actually also compare their ASCII values using these logical operators so if I say s dot Care at r it would definitely be less than but it would definitely be greater than a Stat Care at R minus one and a good way to demonstrate this is um if we have a word right like a b c d e f if we say word.care at one so that's B if we say word.care at one so that's B if we say word.care at one so that's B right um is that less than word.care at two um is that less than word.care at two um is that less than word.care at two which is C and the end this gets printed out didn't know that was possible gets printed out because it is in fact the case that the ASCII value of C is greater than the ASCII value of B and so in the same way we can leverage that here right so we can say well if s dot here at R is greater so it must be this way right it must be this way but we can say if s dot Caron R is less than s dot current R minus one then what do we do well it would make sense to start a new window right so you're gonna we're gonna start a new window so um what I mean by that is okay so we're here um and then we're moving up and everything is fine right we're moving up and everything is fine um and I think eventually a e i o U um this basic substring contains every single character um but you know they're not an alphabetical order so uh basically we eliminate strings while we move that don't or that are not in alphabetical order so as soon as we figure that out we disregard that string and we and re-initialize re-initialize re-initialize um like we move L which would be pointing at the end we move L up to r that gives us a new starting point um but then we also reinitialize the set so start starting a new window would just mean that okay well that left pointer L is going to point to R and we're going to do set dot clear which would allow us to start a new set um now one glaring problem here is on the first iteration uh if you do s dot carat R which is zero in the first iteration and then s dot carrot R minus 1 which would be you know you're referencing an index which is zero minus one your effort you're referencing minus one so that is an edge case here and that wouldn't make sense um and so really what you can do is you can say okay well while our or if R is uh greater than zero now why I say R is greater than zero that means it will instantly be added to the set and that's actually okay because you know one letter on in its own um in its own self is in alphabetical order right so it's okay I don't need to make this judgment for um I don't need to make this judgment for the first character um so it's fine and there you go
Longest Substring Of All Vowels in Order
decode-xored-array
A string is considered **beautiful** if it satisfies the following conditions: * Each of the 5 English vowels (`'a'`, `'e'`, `'i'`, `'o'`, `'u'`) must appear **at least once** in it. * The letters must be sorted in **alphabetical order** (i.e. all `'a'`s before `'e'`s, all `'e'`s before `'i'`s, etc.). For example, strings `"aeiou "` and `"aaaaaaeiiiioou "` are considered **beautiful**, but `"uaeio "`, `"aeoiu "`, and `"aaaeeeooo "` are **not beautiful**. Given a string `word` consisting of English vowels, return _the **length of the longest beautiful substring** of_ `word`_. If no such substring exists, return_ `0`. A **substring** is a contiguous sequence of characters in a string. **Example 1:** **Input:** word = "aeiaaioaaaaeiiiiouuuooaauuaeiu " **Output:** 13 **Explanation:** The longest beautiful substring in word is "aaaaeiiiiouuu " of length 13. **Example 2:** **Input:** word = "aeeeiiiioooauuuaeiou " **Output:** 5 **Explanation:** The longest beautiful substring in word is "aeiou " of length 5. **Example 3:** **Input:** word = "a " **Output:** 0 **Explanation:** There is no beautiful substring, so return 0. **Constraints:** * `1 <= word.length <= 5 * 105` * `word` consists of characters `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`.
Since that encoded[i] = arr[i] XOR arr[i+1], then arr[i+1] = encoded[i] XOR arr[i]. Iterate on i from beginning to end, and set arr[i+1] = encoded[i] XOR arr[i].
Array,Bit Manipulation
Easy
null
1,929
in this video we will solve another simple problem from arrays and this is taken from our lead code and the problem number is 1929 and it's called concatenation of array so the problem says you are given an integer array and its name is in nums and its length is n and you want to create a resulting array let's say ans and its length will be twice the length of input array and how is it formed so in the result its iath element is num psi and i plus n so till n 0 to n minus 1 it will be same in both the arrays so this is nums and this is answer and this is twice the length so till n minus 1 all elements are same so this is what the statement says and for i plus n that is so i ranges from 0 to n minus 1 so i is 0 to n minus 1 so i plus n so 0 plus n that is nth index and then when i is 1 we have n plus 1 h index so this is n plus 1 and all the way up to n plus n minus 1 so this is the i the max value of i is n minus 1 and we are adding n to it so 2 n minus 1 and that is the last index in the resulting array and this will be same as num psi that is this value so when the value of i is 0 we place it here and here at 2 places when n is 1 we put this value at 1 and n plus 1 and so on all the way up to here so all the value occurred twice so in essence what is the result so either you can implement this way whatever is given here or if you see the result it's the same thing repeated twice so first if you divide the result into two halves the first element of both the halves are same second element of both the halves are same and so on so this is the original array so you have to concatenate that twice so that's why the problem statement is concatenation of arrays so this is one two one and this is the result now let us write the code for this so we will store the size and then the size of result is 2 times n and let's initialize to 0 and now we will run a loop so we are populating all the values of result so this will not work because this till n minus 1 it's fine but after n minus 1 this i will become n and this will give out of bounds so better to write modulo here and that should work we could have also run a loop from 0 to n minus 1 and then each in for each value of i we could have populated two values result i and result i plus n and we will see that also so first let's try this both are same things uh so the wrong answer uh it looks like the last value will not set and the reason is that since it's not less than equal to i can go to till 2 n minus 1 so this should be this is the mistake don't make this kind of mistakes and now it's correct so we can submit and the solution is accepted and again the time complexity here you can guess it's just one loop and in each loop we are doing a constant single operation so it's often and space again often for this result that we have to return now let's comment out this part so now what we will do we will run just a loop from 0 to n minus 1 this is the value of i and then result i is num psi and result i plus n that is also nums i both are same thing this loop and this loop here within each loop we are doing two operations and the loop runs for n units here the loop ran for 2 n units and within each loop we are doing one operation and let's see if this works or not so this also is correct and if we submit this solution is accepted so somehow this earlier solution was taking 8 milliseconds this one is taking 12 millisecond but this may be random also the time complexity of both are the same so i hope you understood this simple problem so we will gradually increase the difficulty level of further problems related to aries so see you in the next lesson
Concatenation of Array
maximum-value-at-a-given-index-in-a-bounded-array
Given an integer array `nums` of length `n`, you want to create an array `ans` of length `2n` where `ans[i] == nums[i]` and `ans[i + n] == nums[i]` for `0 <= i < n` (**0-indexed**). Specifically, `ans` is the **concatenation** of two `nums` arrays. Return _the array_ `ans`. **Example 1:** **Input:** nums = \[1,2,1\] **Output:** \[1,2,1,1,2,1\] **Explanation:** The array ans is formed as follows: - ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[0\],nums\[1\],nums\[2\]\] - ans = \[1,2,1,1,2,1\] **Example 2:** **Input:** nums = \[1,3,2,1\] **Output:** \[1,3,2,1,1,3,2,1\] **Explanation:** The array ans is formed as follows: - ans = \[nums\[0\],nums\[1\],nums\[2\],nums\[3\],nums\[0\],nums\[1\],nums\[2\],nums\[3\]\] - ans = \[1,3,2,1,1,3,2,1\] **Constraints:** * `n == nums.length` * `1 <= n <= 1000` * `1 <= nums[i] <= 1000`
What if the problem was instead determining if you could generate a valid array with nums[index] == target? To generate the array, set nums[index] to target, nums[index-i] to target-i, and nums[index+i] to target-i. Then, this will give the minimum possible sum, so check if the sum is less than or equal to maxSum. n is too large to actually generate the array, so you can use the formula 1 + 2 + ... + n = n * (n+1) / 2 to quickly find the sum of nums[0...index] and nums[index...n-1]. Binary search for the target. If it is possible, then move the lower bound up. Otherwise, move the upper bound down.
Binary Search,Greedy
Medium
null
443
So hey guys welcome back to our new video a this next video on strings to lead code 443 question is string compression and just we will read the question and just we will know how many approaches are there to solve this problem and just let's Read the question T is given an array of character compress it using following algorithm OK and being with the mt string for each group of consecutive repeating characters in a cas means how is given here in this question that we One array element must be given. Means just an example of an array. Some elements must be given in it and that too in repeated way. And just let's see what else is given in it. And if the group length is one append the character to s ha in. To go to two conditions, we need to take an example, what is actually like A B and C, actually it is an array example and just in this example and in this string compression we have to Do that if an array is repeated two times e if a is repeated two times t is the first index of an array and just we will see the element we have caught do that if we are catching the first element that is an and If we're catching the first element a we'll see there how many times it's repeated so we'll iterate we'll know that a's repeated twice so what we'll do is what's repeated a means What is repeated? The character is A. So we will write the character first in the output that will be the A and what will be the next. We have to write that is that. How many times has it repeated? What has been repeated two times? So V. Will just write that two means after a means in the output there will be a then two means what will be the a will be the character shown in the a shown in the array and of first index and the two will be that number of times repeated What is A means how many times is A repeated so less means here also it is given that A and next to is given that what is A is repeated two times and just iterate means when we iterate and move ahead then we will It will look like B and the same has to be done B and C Both of these are like same If we are taking B then B is repeated two times So Here in the output it is given that B is repeated two times and C is repeated three times. What is the end explanation in this that in the lead code it is given that the groups of there are the groups of A B and C and first. The first element of whatever is in the groups is to write that will be the a and if we are taking an example then we will just append a and then how many times is it repeated then we will write as a. Two after the after a after two we will write that how many times is it repeated same with this because ya pe to one same index me one element is given off index of for index zero so just we will return one and here there is no repeat. What is shown in the next element How A and B is repeated 12 times So what we will see will be the output of fur This will be the output for This is that A is A, how many times is A repeated, so what will we measure, we will append one after A and B, what will we do in that which is repeated 12 times, we will separate the one which is 12, we will write those 12 together and we will just Like it is written here that one means b after one and one after two the rest of the means is repeated 12 times but we will separate there so let's go on white board let's try to do and aa means hum mes hamara What will be the approach? Our approach to solve this problem will be that we will use two pointer approach and let's see how we approach this problem by taking an example from the end of this first apple n first test case. Given in the problem if taking this then what we will do to find out the output we will take two pointer approach What we will do in this two pointer is denoting the first pointer to a second pointer which is if the First Pointer What the first pointer will do Traverse through every element of an array It will traverse the entire element It will see which elements are repeated how many times The first element will traverse and what it will measure What the second pointer will do It will do The thing it will help in output array it will help in output and e and we will also use count will be equal to we will count how many times it is repeated and how many times which character and which element how many times What are we doing on Y? We will iterate through the whole loop up to A up to end A and count even and why did we buzz? We have caught what J is because we are starting from one end. A starting from zero and we are iterating j then the whole loop and what will be the condition after iterating our condition will be character j minus w equals to character of j miss tra to understand this statement what is this when we iterate from J to the n number of elements we will iterate over from the first index to the last index. What will we do with what we have got? What we have written on J is n and what will be the j my its first element t is one is equal than what we will do then we will do our we will do count plus measure just iterate forward we will iterate forward and aa psv plus this will be the Thing not both character j minus and minus which is the element before j and the j are equal then we will just iterate will move forward because equal so that condition will not fall and if it is not false then we will just iterate Forward and after that what we will do if this is not equal than what we will do cutter i end character S aa given aa e zero index we will anyway set that will be the first index t aa e 0 we will equal both and like this we will run the loop and the last condition will be I will explain in the code what will Be the last condition that we read here that if the group length one append the character to s that condition we will read now then let's go on to the code so s I said to y we will treat first Then we will iterate aa and j from the first index to the last index. We will iterate as many elements as there are in the array and let's see this in this a key a like I said that we Can write t i plus here also t e i ps no need here also means we can write here also but if we are giving a below then it is also quite good but to minimize the code a bit short For this I have given above only yes if the condition here is that if as I said that if whatever is j is not equal to j - 1 then what we will do is not equal to j - 1 then what we will do is not equal to j - 1 then what we will do that whatever character will be aa i will be set to The minus and so we've done this and just and will iterate come see like I said we're going to the next condition will be like if our count is greater than the two then we will Just iterate the character t is a plus ps and just move forward and this and after that if all goes false then we will just return to will be the first element we had equal to zero and just this is solution of The Compress String So Thank You Ga For Supporting
String Compression
string-compression
Given an array of characters `chars`, compress it using the following algorithm: Begin with an empty string `s`. For each group of **consecutive repeating characters** in `chars`: * If the group's length is `1`, append the character to `s`. * Otherwise, append the character followed by the group's length. The compressed string `s` **should not be returned separately**, but instead, be stored **in the input character array `chars`**. Note that group lengths that are `10` or longer will be split into multiple characters in `chars`. After you are done **modifying the input array,** return _the new length of the array_. You must write an algorithm that uses only constant extra space. **Example 1:** **Input:** chars = \[ "a ", "a ", "b ", "b ", "c ", "c ", "c "\] **Output:** Return 6, and the first 6 characters of the input array should be: \[ "a ", "2 ", "b ", "2 ", "c ", "3 "\] **Explanation:** The groups are "aa ", "bb ", and "ccc ". This compresses to "a2b2c3 ". **Example 2:** **Input:** chars = \[ "a "\] **Output:** Return 1, and the first character of the input array should be: \[ "a "\] **Explanation:** The only group is "a ", which remains uncompressed since it's a single character. **Example 3:** **Input:** chars = \[ "a ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b ", "b "\] **Output:** Return 4, and the first 4 characters of the input array should be: \[ "a ", "b ", "1 ", "2 "\]. **Explanation:** The groups are "a " and "bbbbbbbbbbbb ". This compresses to "ab12 ". **Constraints:** * `1 <= chars.length <= 2000` * `chars[i]` is a lowercase English letter, uppercase English letter, digit, or symbol.
How do you know if you are at the end of a consecutive group of characters?
Two Pointers,String
Medium
38,271,604,1241
589
this is lead code question 589 and re3 free order traversal so we have a tree like this and we need to run a pre-order traversal on that street and a pre-order traversal on that street and a pre-order traversal on that street and return the values in a vector of integers so this is not a binary trade if you look at the structure of the nodes here in the tree they have a vector of node pointers called children and that's because normally we have lefts and rights for node pointers in the binary tree but this is different each node can have an undefined number of child nodes so it could be 3 5 10 or even more than that when we run the pre-order traversal we need to print all pre-order traversal we need to print all pre-order traversal we need to print all the values and return them in the vector it's going to be a bit different from the usual code but you will see that there are many similarities so first I have the private access modifier and as inits and inside of this section I create a vector of integers that I'm calling values this is what I will return from this solution function and it's going to contain the values of the nodes in this n re3 whatever it is it could be this one or a different one from the test cases now I need to point out that every tree is going to have anywhere between 0 and 10 000 nodes and the values are going to range from 0 to 10 000 and the height of the tree is less than or equal to one thousand now we need to reserve some space in my Vector here to store all the nodes values so because they say that A3 will have a maximum of 10 000 nodes I'm reserving 10 000 spaces for my notes so this Vector will be able to store 10 000 values without having to reallocate for additional memory so now we can enter this function here and we need to check all the time if this node is a valid node if is now then we don't do anything otherwise if it's not null then we need to add this value the value of the nodes here inside of our Vector called values so I'm using the M please back methods on my vector and as the arguments I am passing it the value of the notes next up we need to verify if this node has child nodes so because all the nodes here have this Vector called the children storing the pointers of different nodes we can check here if that Vector has a size above zero meaning it's not null because it has child nodes if that's the case then we need to iterate through all the child nodes and at every iteration we're going to call the pre-order function which is to call the pre-order function which is to call the pre-order function which is this one on that child notes so this is where the recursion is taking place and then when we are done we can return the values from the vector so these values here is this Vector which is being updated at every step of our recursive algorithm that's pretty much it for the solution if I run these tests I think they have two or three test cases they have two and we've passed both of them now let's submit it and we pass all the test cases I hope this was simple for you in the next video we're going to look at different types of traversals for narratories
N-ary Tree Preorder Traversal
n-ary-tree-preorder-traversal
Given the `root` of an n-ary tree, return _the preorder traversal of its nodes' values_. Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples) **Example 1:** **Input:** root = \[1,null,3,2,4,null,5,6\] **Output:** \[1,3,5,6,2,4\] **Example 2:** **Input:** root = \[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14\] **Output:** \[1,2,3,6,7,11,14,4,8,12,5,9,13,10\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `0 <= Node.val <= 104` * The height of the n-ary tree is less than or equal to `1000`. **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
null
Easy
null
377
Hello everyone welcome to my channel court sorry with mike so today we are going to do video number 10 of our back tracking playlist ok lead code number 377 is medium market but is it not at all in medium it is quite easy with the family template of back tracking Will make this and will make it with two sends. Both are family templates. They will make the back tracking in two different ways. The combination is even four. The name of the question is similar questions. I have included pulses in the description. Do try it. People made this, so made all that too. People are ok it is min brother google snapchat question by looking at the question understand what the question is six then look let's understand the problem life is distinct integers ok you have been given another target interior the target is to tell you the total number of possible combinations of which The sum will be equal to the target, okay, so look here, 1 2 3 is the target, you have given it, so see how many possible possibilities have been sent, whose sum will be equal, look at 1, here it means you multiply any one number. You can also take times, took one once, took one twice and then took two, will make it an example through back tracking, here it was a little concerning for me due to which I made a mistake, pay attention to this here Pay attention, look, it is 211, what does it mean that 123 was my input, he might have rejected one in the starting, after that you would have come, he would have taken you, okay, he took you, after that look, he I have taken the forest back, after that look at this, I have taken the forest back, okay, after that, I have taken the forest again, what does it mean that brother, when you leave this and move ahead and as soon as you took the forest, you Tuk when you take tu then after that go back to 0 index and take one also, this is fine again and yes it is possible that again if you do not take one then take two again then you plus tu a jaata answer is fine, one is this method. It happened the second way, what happened that you took it, after that when you started again, it took 0 hours, this time it was 1, okay, after that, it was taken again for 09, one, the answer was done from here also, do it from here too. If there is multiple base then one thing, do you know what mistake I had made that as soon as I take you as mother, pay attention here, take two, take mother, here is you, take me, after that I do index plus one. I used to give, okay, after you, then I will have three in the option, so brother, where has one gone, then I could not take one, that is why I know that whenever you take an element, you get it back. You will have to start from zero thunder so that you can try this element as well. Again this is ok and this is clear from here from this example otherwise I was doing wrong. Look here also see 3 is 1 is ok three comma is one so its Meaning, what would have happened is that in the beginning you would not have taken one, the index went to one here, you must not have taken this also, then the index went to one here, okay then when you see this for yourself after that, the index has gone back to 0, right? After that look, you can take one, yes you can take it, you can also take it no, then you have taken one, three plus one four, the answer is A, okay, that means now whenever you take the element here, then from the beginning you can go back to the beginning. We will have to see whether we can take any other element or not and it is clear to me from here, look here 21131 Okay, so I understood this thing only after making a mistake and that's briefly fine, I am using simple back tracking. I will code it and show it to you using the template family method. Okay, like I always tell, the first question that comes to my mother's mind is, brother, why is this a question? I have told you long ago that all the questions in my bag tracking playlist. Everywhere I have told you that whenever a question is asked about which or the total possible permutation combination, then you must think about back tracking, today we will sleep in back tracking, that is, again our problem of wave tracking. We will make it from the same Khandani template, okay, so let's start and I always told you that remember the Khandani method, what it used to be was that take something, do something means take it, okay, explore it, after that make it a river. Revert the step that you took for one minute. Step three and then explore again. This is the traditional way of completing back tracking. Okay, you took it once, then explored, then undo the same technique that you did here. Till is clear, ok, good, now let's move ahead, friend, I told you, always make three diagrams wherever possible, it is very helpful, so see, here I make a train of it, here I also write the index number zero induction. Number one index number you are ok index ID If I take you late then remember I told you that if I take you then I will have to start from zero again right I told you here it is okay here look at these ratniks if I take you here Look, I have taken you here, after that, why did I go back to one, then my life must have gone back to zero, it is okay because now any possible combination should be your answer, whatever possible combination is okay, if I changed the index to one. If you have taken zero then it will start from 0 again, one comma two comma three means index, now my ID will remain here, okay and science, I have taken one, so in our target, I have given one to us, that's it. Three more are needed, okay, if I had rejected it, I have rejected it, that means we are not taking this index, so now the further flood which is one comma two comma 3 idiots has come here. Okay, now look, pay attention, this is the important thing here. What I was explaining to you above is that if you take this, you have taken this, if you have taken this, then look, pay attention, if it is 123 then index ID plus one will not be created here, I said that you will have to do the ID from the beginning again. Start in this number is right from zero and here you have taken 2, take care of it, so earlier your target was 4, now your target will be only two, do minus two, right 4*8, if you have taken two in this then do I. It has become two 4*8, if you have taken two in this then do I. It has become two 4*8, if you have taken two in this then do I. It has become two because here you have taken two, so here you just got two back. Now look here, the index has gone back to 0. So see, I will get that combination of mine also. If I take one then it is late. So I am late, one comma, you are comma three, I said, how will I take it, what will happen if I send it back, I will start from zero, then the index started again from zero and this time I have taken one, so remember the target. I had two children, now I have taken one more, so that's the target, I have one child, okay, here again you will have the possibility whether you will call this country people or not, if you take this one, then one comma 2 again. It will start from here and look, my target has become zero So as my target has become zero, I will say that one possible lesson has been found, what will I return from here, I will make one, that means one possible lesson has been found. Where my target has been achieved, look at the target, it has reached zero, that lesson was gone, first I took 1, then I took one, okay and here remember you had taken it, okay and there are many more things from here, right? Look mother, let's take the forest, isn't it history, you are here, look here, remember the forest, I have taken it, what happens if you don't take the forest, right, so I take this branch here, I write down, take note, okay here. I had come then, how could I get my ID here and still my target will be you only because I have taken note of him and not taken one, it is okay, now look, the ID is here, you are there, so if I take it then it is okay. So see what will happen one comma, you country history will start from 0 again, remember I am repeating to you again and again that if you take from back then you will start back from index zero. Okay, so now here I have told you. I have taken it and I wanted you only, so the target became zero. As soon as the target became slow, I said, brother, I have got it with another hand, I will return one, that I have got another lesson in which I can achieve the target. Given one, what was that target lesson, this is where I took two, okay, here I did not take anything and this thing here also took two, so two plus here, it is done by doing two, okay, so many like this Trees will be formed, meaning many trees can be formed. Okay, so here is DS, then further, if you had not taken this, if you had taken note, then what would have happened here, then 123 ID goes here, see how to take note. I do n't have to do ID Now see, even with three, you have two options, either you took it or you did not take it. Look, then I am saying that if you took it means if you took three, how much is the target, still the target is fine, here I write. I am giving you the target till now, if you have done it till now, then if you take your three then remember the index, it will start again from zero, I told you that the egg will start again from zero, okay and if you take three here, then child one. Now look here, you can take one here, you can take it or not, if people, otherwise you will get it from here, then here you will get another part, took one and took three, OnePlus 3 4, you will get the target from here also, so the same I am trying to tell you that you will get multiple lessons like this, okay you will get multiple lessons from where you will get your target but you have understood the crack, what did I say that there is take two option, no take. ID Again, it's okay and your target will be lost. If you have just taken RDX, then there is a vein of idea in the target, I am giving it away. Okay, that means I have taken notes. Okay, so it will be simple. And what if you don't take it, then it's an obvious thing, history. You will have to do plus one, it is okay and the target will remain the same because you have not taken the element yet, you should understand these two lines, what is this actually, this is the family template of back tracking, the code which is going to be made, see how simple it will be now. You will come to know in a simple way, here you will write the solve function, starting of target is fine, if my target is equal to zero, whose sum was equal to the target, then we will return one, then brother of the index, definitely check that it is out of band. If the index is greater, give it equal, you are done, okay, you will have to check the index, you are deporting me again, then it is okay, remember after this, there were only two things after this, brother, what were these two things, isn't it the index? And this was the case in the reject index take index kaise. This was the case in the reject index. Look, in the take kaise, the index was sent back to zero. This is the catch. Actually, this was not an important part of this question. It is fine, the rest is a template. It is exactly the same, now look at the number of ways you got by rejecting and the number of ways you got by taking, send us the total, then sum both of them, the number of ways to get the target from take ID X and the number of ways to get the target from reject idiot Reject Underscore Idiots, this will be mine, return was a very simple function, nothing is required here, it was a very simple format, now many people will say to me that brother, actually this is DP, then I will say yes, definitely look at DP. I too do the same thing, I have seen tech and non-tech, too do the same thing, I have seen tech and non-tech, but what is the difference here? Look, the index has gone back to zero. Okay, and definitely, if you make a complete tree diagram, then you will know that you will get many such repeating statuses. Which you can memoize, it is okay and this will not be accepted, no actually because this is an exponential solution and our constant is a little big. Look this time, you are giving two chances to every element, once and also taking it once. Even if you are not taking it, then it has exponential time complexity, isn't it? Every element on taking and non- complexity, isn't it? Every element on taking and non- complexity, isn't it? Every element on taking and non- taking will go to the expansion time group, so definitely we will have to memorize it, so it is obvious that it is clear cut, I am looking for two things to memorize it. One index is changing, the other target is also changing, so what will I do, it will be my DP, it will be of dimension, right n + this target of dimension, right n + this target of dimension, right n + this target plus one or n + 1, whatever we will take, okay plus one or n + 1, whatever we will take, okay plus one or n + 1, whatever we will take, okay two. If you have DP of Tu Di, then it is clear, it is okay, we will do it in memory, if we see, this is actually my family template only, it is the right of back tracking, so let's submit it quickly and see after that. We have one or two other methods, which reduces the family template, but the way of writing is different behind it and I have already told you that thing in the seventh video of this playlist. That's why I told you in the seventh video. It has been said that there are two ways of doing the family template, one is reject and take and reject and there is another way of take and reject but the loop continues where many people get confused and they say brother sometimes. People do back tracking with a loop, sometimes without any result, see this without looking, you can chip the camera, I will tell you after this, first let's quickly code this one, we will write exactly what was told, okay, first of all define the internet. Let's take n = define the internet. Let's take n = define the internet. Let's take n = size, it is ok, simple return, if you are going to write a function then start from index zero and sending the target till here is clear, after that see inter solve, you have to write vector of numbers and sending the target right till here is clear. Remember, I told you that if my target becomes equal to zero then return one because you have found one thing where your target has been achieved, you are fine and also check that if Id is your greater then equal. You have become N, meaning you are out of bounds, now you do not have the element, otherwise make the return zero. Well, think one more thing for yourself, mother, let's take the number in the target. You are keeping the number decreasing, right? The number is decreasing like this. Mother, let's take it, look here, Mother take it, there was one forest, you could have taken it one more time, look here, do the forest one more time for yourself, then the answer has been done for you, okay, but if you had taken it one more time, then you are seeing the answer. What would have happened had I gone five, my target would have gone negative, I would have been reducing the target by one, that is, even if the target had gone to zero, it would have been a mess, now there is no need to live further, you would still have zero returns. Do right after this, it is simple brother, take DS, solve it, if you have taken it then find more elements from zero again. Okay, Namas and you have taken science, if you have taken this element, then drop it in the target. Now all this and so much more is needed, right target, I got this vein of idea It did not happen because you have rejected the IDEX element. What should I do? In the end, as many answers as I got from it and as many answers as I got from it, if everything is fine, then submit it quickly and see how small and clean the code is. Right, I like such code. Which one should follow the template, which one should follow our understanding, if you submit it and see, then the time limit seat will definitely be there because this expansion has gone time complexity. Right, for every element, you try two things. Take ID is reject ID. There is one thing in time. Look, it is done and look, there is also a big value here and Ka is 200. Okay, so friend, it is an obvious thing, it will have to be memorized, then it will have to be written and then index will have to be taken. Two things are changing, what are the things that are changing, index and target. If it is changing then the value of the index is kept at 200, let us take 201 and if the value of the target is kept at 1000 then let us take 11, okay and here we initialize it, I set T - 1, the size of T is okay and set T - 1, the size of T is okay and set T - 1, the size of T is okay and Before calling here, check if t of comma target, note it is equal to minus one then it is ok to return t of idea and if it is not solved then it is ok to store it here before returning. After that, what we will do is submit it and see, solve this question using the template of family back tracking, it will be like the template from Jaldi Chalte Hain but the method will be different but we will solve it by continuing with the loop and I have already told you about this playlist in the seventh video. But still I am repeating it today so that your revision is done, so let's see it in this way too. Now see what we will do by using loop, we will solve it. Okay, see, the same thing will happen in this also the same thing is done in one take. There is an idea and there is also a rejection, but you know the rejection makes a loop for us, but less of a loop makes a rejection for us, we just have to do the take, okay because look now, I will show you here. But look at eat i = id, whatever I send, I eat i = id, whatever I send, I eat i = id, whatever I send, I will start from there, now it will just go on till i &lt; n, i plus will start from there, now it will just go on till i &lt; n, i plus will start from there, now it will just go on till i &lt; n, i plus, okay now tell me one thing, earlier what was the option of take this index i. take this index of take this index i. I have solved it and will bring the rest of the answer. Now, I had told you that whenever we do any tech, we start from index zero. Right here, there was a little fear. Earlier I had told you, what was index zero in tech id? Okay, and the target here was - Names of I because we have taken it. - Names of I because we have taken it. - Names of I because we have taken it. Okay, now look after this, here I had to write note take reject of ID What will happen to that i = When i plus becomes plus happen to that i = When i plus becomes plus happen to that i = When i plus becomes plus then it is obvious that the element will be rejected, so in the next time we will check for i+1, is element will be rejected, so in the next time we will check for i+1, is element will be rejected, so in the next time we will check for i+1, is n't it clear till now, so we do not need to do this, above is a result. We will take the variable result, this is equal to zero, okay, here we will just take the result plus this equal, take the underscore I, okay, so look, pay attention, again I am repeating, why here the reject less is happening by itself. I = ID is happening by itself. I = ID I question will be asked here again and it will be solved for I + 1. here again and it will be solved for I + 1. here again and it will be solved for I + 1. Okay, so take note take is done by both and you will see my seventh video in this playlist, there also I have used this loop method. It has been told in seconds and in both of them actually only one thing is happening which is the traditional way of take and reject take explore and reject and explore the same thing is happening here also but it is written in a loop so now What will we do? We will go into the code and replace it with a simple but loop. Ok, we will just write the code in it and replace so much text with just a for loop. So, those who finish quickly, their code is also okay, so look at it. We will modify the code and just replace it with a but loop. Look, I have removed this one. Tech History Reject Idea. Here is a simple result, this is equal, let's take zero variable. Here we will write the fruit loop, it will start with this = ID. I &lt; What was the underscore I? If we take it, then the solution will be fine, we will start from zero because I have taken it, we will add name and target and whatever result will come, we had to simply return the result, I had to do ID X + 1, that is, ID X + 1, that is, ID X + 1, that is, next. Had to go to the index, look, it will be done here, I is I +, if it is plus, then go to I+1, +, if it is plus, then go to I+1, +, if it is plus, then go to I+1, then the less of the rejects will also be done here, I have only one but in the loop, it is ok, so it is simple, you run it and see. let cipher able tu pass which d example is ok then submit it and see it should be able tu pass which d yes hd s they have solved this question using our second way of back tracking also ok any doubt is resident in d Mango Session At Variety Bill Be Your See You Gas Video Thank You
Combination Sum IV
combination-sum-iv
Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`. The test cases are generated so that the answer can fit in a **32-bit** integer. **Example 1:** **Input:** nums = \[1,2,3\], target = 4 **Output:** 7 **Explanation:** The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations. **Example 2:** **Input:** nums = \[9\], target = 3 **Output:** 0 **Constraints:** * `1 <= nums.length <= 200` * `1 <= nums[i] <= 1000` * All the elements of `nums` are **unique**. * `1 <= target <= 1000` **Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?
null
Array,Dynamic Programming
Medium
39
2,000
hello everyone welcome to my Channel today we have another problem to solve here um imagine we have a special word and a special letter our job is to flip the beginning of the word up to the first time we find our special letter let's look at some example to better understand the question so if our word is AB c d e f d and our spal letter is D we find D at position number three here so we flip AP part from the start to three inclusive and our new word is DCB a e FD and let's try another one if our is X YX z x e and our spectal letter is z so again we find Z at position number three so we're going to flip from the start to number three and our new word is z xyxx e but uh what if the spectral letter is isn't in our word like in ABCD and we're looking for Z which is not in the not in here so well in that Cas we don't do anything and I would stay the same ABC D so for our coding section we're going to have we're going to has two have two pointer left and right I'm call two variable left and right equal to zero and first we going to use the loop to find the position of our spe spectal letter in the word the loop going to keep going until it's find the character when and where is there is stop so I want to implement the loop here I'm going to call the variable I for example so I want to run from the beginning to the end of the word and let's move one step I'm going to use the if to check if actually the character actually the word or not so I want to check if the word at I is equal to the character and if it is we're going to break out of the loop and if it's not it's going to the right want to keep moving forward until it find it and next we need to check if we found character at all if it not we don't need to do anything because our specture letter isn't in the word and we just return the word without changing so if right equal to the size we going to return the word without changing anything this mean the right is can run through all the from the beginning to the end of the word so it cannot find the corrector so what if it what if the special letter is actually in the word we got to use one more Loop use y loop it's going to run from left to right and going to swap the position of the word at left and the word at right don't worry this is the complexity the time complexity of this uh swap function is O of n so it's not um it's not affect too much to our time complexity and left Plus+ and right complexity and left Plus+ and right complexity and left Plus+ and right minus so that's all we're going to return the well I forgot the yeah silly mistake yep and it's accepted try to submit it and accept it with Zer Ms beat 100% And and let's explain the quote one 100% And and let's explain the quote one 100% And and let's explain the quote one more time here this for Loop we used to writing the first occurrence of the special word I mean letter or character Y and this if statement it use to check if the spectal letter isn't in the world we don't do anything and this y Loop it just basically just to reversing or swap the uh the position so I want to say it's reversing segment from the start to the spectral letter position I think yeah that's it I hope this uh video going to help you thank you
Reverse Prefix of Word
minimum-speed-to-arrive-on-time
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`. Return _the resulting string_. **Example 1:** **Input:** word = "abcdefd ", ch = "d " **Output:** "dcbaefd " **Explanation:** The first occurrence of "d " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd ". **Example 2:** **Input:** word = "xyxzxe ", ch = "z " **Output:** "zxyxxe " **Explanation:** The first and only occurrence of "z " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe ". **Example 3:** **Input:** word = "abcd ", ch = "z " **Output:** "abcd " **Explanation:** "z " does not exist in word. You should not do any reverse operation, the resulting string is "abcd ". **Constraints:** * `1 <= word.length <= 250` * `word` consists of lowercase English letters. * `ch` is a lowercase English letter.
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Array,Binary Search
Medium
1335,2013,2294
859
welcome to october's leeco challenge today's problem is buddy strings given two strings of lower case letters return true if you can swap two letters in a so that the result is equal to b otherwise return false now swapping letters is defined as taking two indices such that i does not equal j and swapping the characters at a of i and a of j and they give you a few examples a b and b a is going to equal true because we just swap a and b and that's going to be ba so that equals b so that's true here a b this is false because if we swap the only possible swap here is make it b a and that's not going to equal a b so that's a false but a here and a equals true so keep that in mind here this edge case is gonna make you a little bit trickier so we might be tempted at first to write some sort of recursive function to like swap all possible letters and positions to check to see if we can recreate the string b but forget that step back for a second and think about what are the conditions of what will make the output true here so the very first thing the obvious thing is that all the letters the number of each character needs to be the same right so we can just create a counter object for string a and string b and make sure that they're the same because otherwise if we have an extra character like x and a no amount of swapping is ever going to make it b so that's one thing now as soon as we realize that yes all the counter objects are the same for a and b we might be tempted to think okay well then it's true like do some sort of sorting but that's not the case either because the positions here matter like we can have the same number of characters but if it's jumbled in a way that we can't swap just once and create the string b that's not going to work so not only do the counter objects need to be the same basically two positions on a and b need to be different exactly two now there is an exception to that what about a b and a here we can see that uh both of these are actually going to be the same but once is going to return false and one returns true so what's the difference well the difference here is that we have more than one character of a so we could have two a's three b's four c's doesn't matter if the strings are the same then we know yeah we can swap the same letter in some position and then we turn the same letter b it's only when we have only one of each character and nothing's different that's when we can't swap and create b okay so keep in mind those two cases and we'll go and start going this out so the first thing we want to do is create a counter object that's the number of each character and we can just use the counter to create both of this so the very first thing we do is check to see if these two are the same because if c1 does not equal c2 immediately we can return false maybe they're a different length maybe they have different characters doesn't matter just return or false now the next thing we need to do is count up how many positions between a and b are different so how can we do that well we already have uh we know that the lengths are going to be the same right because of the counts are the same here so why not just make a for loop say 4 i and range of length doesn't matter a or b what we're going to do is check to see if a of i does not equal a of b and let's just count these up so if a of i does not equal b of i then add here to a list and we'll just make this a list comprehension and we can just sum these up and this will be the number of differences right so this would be diff and now we should have if this is true it should either be two or zero okay so if diff equals two that meets all the conditions right we have the same number of characters and only two positions are different so that must mean if we swap this then it would return the same letter so we can just return true immediately there now otherwise if diff equals zero we need to check do we have more than one character of any of these like any of these characters do we have more than one and if we do then we can return it true right so we already have our counter object so let's go through those for uh character and number uh count in c1.items we'll say um count is greater than one and that's going to return a boolean so we'll make this a list and if any of these are true then it's going to return true otherwise it will turn false right so we just return that and that's going to take care of that weird edge case where it's basically the same string now we just need to see hey do we have more than one character otherwise these conditions aren't met there's more than uh there's like one difference or three differences doesn't matter we know that this is a false all right so let's do our test okay it looks like it returns true and submit and there we go accepted so there are some ways to optimize this a little bit we could try to use less memory and stuff but because there's only 24 characters 24 lowercase characters we know that the space is bounded to 24 so it's more or less constant space now um initially when i first saw this uh i was tempted to like keep track of the index numbers and like do some swapping and keep track of all that but the more you think about it the more you realize there's only a few conditions where we can return a true here and once we realize that we just need to write all those you know statements and then just return it true all right so thanks for watching my channel and remember do not trust me i know nothing
Buddy Strings
design-circular-deque
Given two strings `s` and `goal`, return `true` _if you can swap two letters in_ `s` _so the result is equal to_ `goal`_, otherwise, return_ `false`_._ Swapping letters is defined as taking two indices `i` and `j` (0-indexed) such that `i != j` and swapping the characters at `s[i]` and `s[j]`. * For example, swapping at indices `0` and `2` in `"abcd "` results in `"cbad "`. **Example 1:** **Input:** s = "ab ", goal = "ba " **Output:** true **Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'b' to get "ba ", which is equal to goal. **Example 2:** **Input:** s = "ab ", goal = "ab " **Output:** false **Explanation:** The only letters you can swap are s\[0\] = 'a' and s\[1\] = 'b', which results in "ba " != goal. **Example 3:** **Input:** s = "aa ", goal = "aa " **Output:** true **Explanation:** You can swap s\[0\] = 'a' and s\[1\] = 'a' to get "aa ", which is equal to goal. **Constraints:** * `1 <= s.length, goal.length <= 2 * 104` * `s` and `goal` consist of lowercase letters.
null
Array,Linked List,Design,Queue
Medium
860,1767
338
hello everyone welcome to the channel today's question is counting bits if you are new to the channel please consider subscribing we sold a lot of into question on this channel and that can definitely help you with your interview the question says given a non-negative the question says given a non-negative the question says given a non-negative integer number num for every number I in the range 0 less than equal to PI less than equal to now calculate the number of ones in their binary representation and written them as in and if you look at example number 1 we are green with 2 and we are returning 0 1 and if we look at example number 2 we are going with 5 and we're returning 0 1 2 1 so let's move to the coding part let's understand what these examples are saying and let's see how we can solve this portion after that we will see the code I have taken the example given in the question so let's first understand what exactly question is saying so when question is saying 2 and output should be this way that means starting from 0 it says when I am representing 0 in binary form I have 0 is the number of ones in binary representation of 0 and when I'm talking about 1 is the total number of ones in binary representation of 1 and when I talk about 2 1 is the number of ones in binary representation of 2 if I talk about number of ones in 0 is 0 if I talk about number of ones in 1 is 1 if I talk about number of ones in 2 that is also 1 if I talk about numbers of 1 in 3 so I have two ones if I talk about number of ones in 4 then I have 1 4 if I talk about number of once in 5 then you can see I have 2 words and this is what I am representing in n array so before we see how we can solve this question and what is the intuition behind it let's first talk about two things one is least significant bit is the rightmost bit of a binary representation it will define whether the given number is or even if the LSB is 0 that means the given number is even and if it is 1 that means the given number is odd and the another thing is right shift and if I say right shift by 1 that means suppose I say I took 7 if I make a right shift by 1 that means it will become 0 1 that means we will broke this one and we will add 0 in front of this in general when I'm making a right shift I am dividing the number by 2 so if I divide 7 by 2 it will come up to 3 and 0 1 is binary representation of 3 let's take 6 is equal to 0 1 2 and if I make a right shift it will become 0 1 again this was 6 and this is 3 so making a right shift is equivalent to dividing by 2 now we know both the things what is less significant bit and the right shift so let's see how we can solve this question now so let me raise this for you so if I say that I am given with any number and I need Britain the solution in this form that starting from 0 till the end I need to represent how many number of ones a particular number have at every single position so one way is I will take a for loop in and I'll come to zero I will count number of ones in zero then I will come to one then again I will count number of ones in one and so on then again for that I need to go in the binary representation of every single element and then I have to take two for loops and the question is asking us that can we solve this question it of n so we need to come up with solution which is o N and what is the solution for that let's see that so if I say if I write down the number of ones from starting from zero to twelve so I have written till five in six I have two in seven I have three in eight I have one in nine I have two in ten I had two in eleven I have three and in twelve I have to and if you see we can see a bit and what the pattern is let me show you in a second for Gio number of once is 0 for 1 the number is 1 for 2 again it's 1 for 3 it's 2 for 4 it's 1 for 5 it's 2 4 6 it's 2 for 7 it's 3 for 8 it's 1 for 9 it's 2 for n it's 2 for 11 it's 3 for 12 it's 2 if I take out any odd number let's say 7 and I divide 7 by 2 and I will add 1 to that divided by 2 is 3 and the value of threes - and if I will add 1 to that it threes - and if I will add 1 to that it threes - and if I will add 1 to that it will weaken 3 and the 3 is the value of 7 this is the case of port in case of even I just simply need to divide by 2 so if I take 6 I will divide it by 2 and after dividing I will get 3 so I will simply take the value of 3 which is 2 so if I take 6 divided by 2 which is 3 and I will take the value of 3 which is 2 so you can see 3 &amp; 6 have same values 4 &amp; 8 you can see 3 &amp; 6 have same values 4 &amp; 8 you can see 3 &amp; 6 have same values 4 &amp; 8 have same values 6 in 12 same values because 12 divided by 2 is 6 and the their same number of ones in there and if I talk about owed you take 11 divided by 2 is 5 the value of 5 is 2 plus 1 is 3 so we can see this pattern over here that if I have owed then I need to divide it by 2 and need to add 1 to its number of ones so that we're going to be my number of 1 and if it is even then I simply need to divide it by 2 and the number of ones in 8 and the number of ones in a divided by 2 that is 4 will going to be same alright so let's see how we can represent this pattern in our code so we are saying two things that one is we need to divide it by 2 and I told you whenever we make a right shift by 1 that is equivalent to divide by 2 and the second is we need to add either 0 or either one you can say in case of even we are adding zero and in case of code we are adding one so one is we need to divide and one is we need to figure out whether we are going to add zero or whether we are going to add one but again the question is how I can tell whether the given number is odd or even when I don't know what the number is so if I say that take any number let's take 11 and the binary representation of 11 is 1 0 1 if I take the end of 11 with 1 it will be equal to 1 0 if taking end with 1 and its end up equal to 1 that means the number is odd or you can say I will add this number to my and divide by 2 let me say it again rather than get confused between even on or I can simply say that I will going to add and with one of given number that if I'm green with 8 I will going to do 8 divided by 2 and I will going to add 8 + 1 this is and operation if I am in with 9 I'm going to divide 9 by 2 and I'm going to add 9 + 1 so let's see 8 &amp; 9 example to add 9 + 1 so let's see 8 &amp; 9 example to add 9 + 1 so let's see 8 &amp; 9 example above so it is represented by 1 0 I will going to divide 8 by 2 so which is 4 the number of ones or 4 is 1 then I will going to add 1 0 and with 1 and if I take a and of 1 zero with one it will come up to 0 because in end to get one I need to have 1 and 1 so it will do so 1 plus 0 is 1 and you can see the number of ones in 8 is 1 and let's see the example for 9 so 9 divided by 2 is again 4 and so I will take 1 and I will add 1 0 1 and with 1 and I fell to a end it will turn up to 1 0 which is equal to 1 so I will add 1 plus 1 that is equal to 2 and 2 is the value of my right so in this way whenever I'm green with the number I will start with 0 and every time we go back to divide by 2 and once I'm done with / - I will add then I will add with / - I will add then I will add with / - I will add then I will add number and with 1 and works well with the written either it will gonna be 0 right there it will gonna be 1 if the number is odd and whenever I will take an end with 1 I will going to get 1 if the number is even whenever I am going to take end with 1 I am going to get 0 so this is the way I can solve this question so let's move to the coding part and let's see what is the code for this problem so let's see that code at line number 3 I made an array cold result and I've initiated with 0 at index 0 then I'm taking a for loop and I am simply a pending result I write shift 1 when I'm saying I write shift 1 that means the value at I divide by 2 and I am adding either 0 or 1 and I'm adding integer of I and with one and this will tell us whether I need to add zero or I need to add one I end with one written zero in case of even and it will written one in case of old and at the end and simply returning the result so this was the code let's see whether it works or not so here I submitted my code and it could accept it so this was the solution for this video you can find the code in the description below if this video was helpful to you please give it a thumbs up thank you so much guys for watching the video please don't forget to subscribe
Counting Bits
counting-bits
Given an integer `n`, return _an array_ `ans` _of length_ `n + 1` _such that for each_ `i` (`0 <= i <= n`)_,_ `ans[i]` _is the **number of**_ `1`_**'s** in the binary representation of_ `i`. **Example 1:** **Input:** n = 2 **Output:** \[0,1,1\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 **Example 2:** **Input:** n = 5 **Output:** \[0,1,1,2,1,2\] **Explanation:** 0 --> 0 1 --> 1 2 --> 10 3 --> 11 4 --> 100 5 --> 101 **Constraints:** * `0 <= n <= 105` **Follow up:** * It is very easy to come up with a solution with a runtime of `O(n log n)`. Can you do it in linear time `O(n)` and possibly in a single pass? * Can you do it without using any built-in function (i.e., like `__builtin_popcount` in C++)?
You should make use of what you have produced already. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous. Or does the odd/even status of the number help you in calculating the number of 1s?
Dynamic Programming,Bit Manipulation
Easy
191
1,559
hey guys today we're going to solve lead code number 1559 detect cycles in 2d grid so we're given a grid of characters just like this and we need to find if there is a cycle where both these cells have the same value and the cycle length needs to be at least four so the way we're going to do this is recursively through a depth first traversal of the grid so first of all as you know i like to set up a variable tracking the directions in which we can move for example here we cannot move diagonally then we're going to set up the amount of rows and the amount of columns in our grid and you know if we don't find any cycle at the end we're just going to return a false just like this and also we're going to set up a visited set so this will keep track of the cells that we have already visited so that we won't visit them again with the depth first search because that would be wasteful okay so now we need to actually loop through all of our matrix cells and start the depth first the traversal from every cell so we look through all the rows we look through all the columns of the current row and if we haven't visited the cell yet so remember that in a set we can't just pass in the reference of the array we need to convert it to a native value such as a string so i do that here so if we haven't visited the current cell yet then we start the depth first search and if the depth first search will return true that will mean that there is a cycle involving this position so we will return true now what are the parameters of our depth first search function first of all the current row and column then the previews row and column because in our depth first search we don't want to go back to the previous row ever and so to represent here that we have no previous cell we just put minus one and minus one because that's impossible and the other parameter of our depth first search function is the current grid cell value so we just pass in the current value of the current cell because remember that the cycle needs to be all with the same value inside of the cells okay so now we are going to return true if this depth first search function returns true now we just need to implement it so the parameters as i was saying are the current x and y so row and column coordinates the previous coordinates and the current value so we call it here start character okay so now what we're going to do is we're going to add the current cell to our set and remember to call join here just like before or this won't work then we are going to say if we don't find any cycle just return false so this is going to be at the end of our computations now we look through all of the directions in our variable that we have set up previously and we get all of the neighbors by doing this we set up the new x coordinate new row coordinate and the new column coordinates by adding to the current the respective value here and then what we do is if the row the x-coordinate is greater or equal the x-coordinate is greater or equal the x-coordinate is greater or equal than zero and if it is less than the number of rows then it is a valid coordinate then we check as well for the y-coordinate check as well for the y-coordinate check as well for the y-coordinate it needs to be greater or equal than zero it needs to be in the bounds of the grid essentially and then we also check if the new grid value is equal to the start chart because if it's not then we don't have to do anything we can't traverse the grid in that direction because the values are different but if all of these conditions hold then we just need to check another thing which is the new or the new coordinates need to be different at least one of the two new coordinates need to be different from the previous coordinates and if all of these conditions hold then we can check if we had already visited the new coordinates and if we had then we could just return true because that would mean that we have indeed found a cycle because we aren't remember that we aren't going on the previous coordinates so the only way for this to happen is if we have looped through in some way so there would be a cycle and if there is if it isn't already visited so if these coordinates haven't already been visited then we can just visit them so-called just visit them so-called just visit them so-called adfs on them with the usual parameters so the new x and the current x and y become the previous last x and y and the same start character value and if it if this depth first search returns true then we can return true as well and that's it so i'm going to show you that this works and this solution is optimal because we go through all of the nodes of the matrix only once so i would say that this is a o of n space complexity and the time complexity where n is the amount of cells in the matrix and the space complexity comes from this visited set alright thank you and that's it for now bye
Detect Cycles in 2D Grid
cherry-pickup-ii
Given a 2D array of characters `grid` of size `m x n`, you need to find if there exists any cycle consisting of the **same value** in `grid`. A cycle is a path of **length 4 or more** in the grid that starts and ends at the same cell. From a given cell, you can move to one of the cells adjacent to it - in one of the four directions (up, down, left, or right), if it has the **same value** of the current cell. Also, you cannot move to the cell that you visited in your last move. For example, the cycle `(1, 1) -> (1, 2) -> (1, 1)` is invalid because from `(1, 2)` we visited `(1, 1)` which was the last visited cell. Return `true` if any cycle of the same value exists in `grid`, otherwise, return `false`. **Example 1:** **Input:** grid = \[\[ "a ", "a ", "a ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "b ", "b ", "a "\],\[ "a ", "a ", "a ", "a "\]\] **Output:** true **Explanation:** There are two valid cycles shown in different colors in the image below: **Example 2:** **Input:** grid = \[\[ "c ", "c ", "c ", "a "\],\[ "c ", "d ", "c ", "c "\],\[ "c ", "c ", "e ", "c "\],\[ "f ", "c ", "c ", "c "\]\] **Output:** true **Explanation:** There is only one valid cycle highlighted in the image below: **Example 3:** **Input:** grid = \[\[ "a ", "b ", "b "\],\[ "b ", "z ", "b "\],\[ "b ", "b ", "a "\]\] **Output:** false **Constraints:** * `m == grid.length` * `n == grid[i].length` * `1 <= m, n <= 500` * `grid` consists only of lowercase English letters.
Use dynammic programming, define DP[i][j][k]: The maximum cherries that both robots can take starting on the ith row, and column j and k of Robot 1 and 2 respectively.
Array,Dynamic Programming,Matrix
Hard
null
1,680
everyone welcome to the 27th of january's equal challenge and today's question is concatenation of consecutive binary numbers in this question you're given an integer n and you need to generate a new number uh by con that is formed by concatenating the binary representation of all the numbers starting from 1 up to n also you need to keep in mind while you're calculating this new number you need to do the modulus of 10 raised to the power 9 plus 1 during the generation of the new number from the new string that has been created by concatenation of the binary representation of numbers from 1 to n i quickly said that let's walk through one of those examples in this case n is specified as 3. what you do you start an i loop starting from 1 till n and generate the binary representation of all those numbers so for one is one for two is one zero four three is double one and you can cartonate uh all the all these strings so the new number that is formed uh the new string that is formed by the concatenation is double one zero and what you need to do you need to generate the new binary representation uh new number using this binary representation so first you are that this is the two word process first you are converting a number into a binary representation and the other way is the other part of the question is you need to convert the binary represented number into a decimal format which represents 27 and you have to do this so let's quickly walk through the algorithm that i have created let me just start the slide show and let me just take a pen here it looks fine so as the question stated n is three how many numbers do we need to incorporate one till three what is the binary representation of the numbers well one is one two is uh one zero and three is one uh if you concatenate all these numbers starting from one zero 1 this is what the new binary representation is and now do the reversal the first part is decimal to binary and the other part is from this binary representation you generate the number the decimal number how do you do that starting from the starting index 0 so 0 1 2 3 4 you keep on multiplying it with the power of two since that was a binary representation the power will be two here uh the power of two will be used so two it has to into two raised to the power zero plus one plus two decimal one plus 1 plus 2 in 2 raised to the power 2 plus into 0 so you keep on adding this so what you get 2 distribute 2 into 0 plus 1 is 1 or 2 raised to power 1 is into 1 is 2 disturbed 2 is 4 in into 0 is 0 2 raised to the power 3 is 8 into 1 is 8 and 2 raised to the power of 4 is 16 into 1 is 16. so if you add all these numbers uh 16 plus 8 is 24 plus 2 is 26 plus 1 is 27 so the new number is 27 and we will do exactly the same steps as i told so let's jump on to the coding part let's define a variable mod uh we need during the generation process from binary to decimal we need to every time when we are adding and multiplying it we need to perform the model operation two is the part 10 raised to the power nine plus seven so one two three four five six seven eight nine so this looks fine and let me just take a variable for my answer or new number let's say it's new number equals to zero and let's start with the iteration from i equals to 1 till i equals to n i plus what do we need to generate the binary representation of i so i'll be using a method here integer to binary and that will give me a string a binary string so you can write your own method for this i'm using an inbuilt java method so binary let's just call binaryrep of that number of i and also let's i need a multiplying factor of two so let's start with subtract it equal to zero and let's put each character in that binary depth two card array pretty simple and what i'm doing is i'm generating the number now how uh if integer value equals to if c equals to zero value will be zero otherwise value will be one pretty straightforward because there's only there are two only two possibilities and once you have this val what you'll do new number equals to new number into two modulo mod plus val and modulo and the end ideally we don't need this factor because we are every time we are multiplying it by two are ourselves so return the new number let's try this up looks good accept it the only tricky part in this algorithm is this logic where new numbers equals new numbers into two mod modulus plus and then a modulus again let's forget the modulo part for a second because that's in order to avoid the overflow condition of integer range uh let's assume the news number equals to new number into two plus one how is this working uh let's take the binary representation that we intended to uh through which we intended to generate a new decimal number and let's let me just iterate through uh this case where new number equals to zero initially so new num equals to zero and we'll be at the first index so this one this is what the current number has so let me just write it in a better way so this is the this is actual representation that we are intended to calculate let's start with the iteration where i equals to 1 and the binary representation is 1 and a new number is 0. so new num is 0. uh new num equals to new 0 into 2 plus 1 uh that gives us new num becomes what is the updated value of new num minimum becomes 1 now let's walk through the second iteration where i equals to 2. the binary representation is something like this and what is the value of new num equals 2 new number into 2 1 into 2 plus 1 it becomes 3 while we are iterating through over this index and then we have 0 at 0 again new num new nums equals to 3 into 2 plus 0 so that gives us 6 pretty simple and new numbers becomes 6 at this new number 6 when we have completed the iteration of i equal to 2 let's talk about i equal to 3 and newton's value is six new num is equal to six uh binary representation of three is double bond and let's start with uh the first index this index so what you are going to do six into two plus one because that's one in nature this gives us thirteen and if we do it again thirteen into two plus one so that gives us twenty seven this is how we generate our answer uh the modeling part is through the overall condition of integer maximum range and that's it hope i made this logic pretty clear to you if you want to write your own uh integer to binary conversion you can go for it uh no foundations to use in build method but it's always easy to use the inbuilt methods thanks for watching video hope you enjoyed it
Concatenation of Consecutive Binary Numbers
count-all-possible-routes
Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`. **Example 1:** **Input:** n = 1 **Output:** 1 **Explanation: ** "1 " in binary corresponds to the decimal value 1. **Example 2:** **Input:** n = 3 **Output:** 27 **Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ". After concatenating them, we have "11011 ", which corresponds to the decimal value 27. **Example 3:** **Input:** n = 12 **Output:** 505379714 **Explanation**: The concatenation results in "1101110010111011110001001101010111100 ". The decimal value of that is 118505380540. After modulo 109 + 7, the result is 505379714. **Constraints:** * `1 <= n <= 105`
Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles.
Array,Dynamic Programming,Memoization
Hard
null
1,603
hello everyone and welcome to another short video on solving uh a elite code problem with apl and i have to start by apologizing because the idea of these videos at least for me is to solve these problems for the first time in apl with you and hopefully that shows you a little bit of how thinking in apl might look like and for the first recording i did while solving this problem i actually ended up with a video that was way too long and that's just because the structure of this problem is fairly different from the other little problems we have been doing and it's not to say that this is a difficult problem it's just that the structure of the things they want us to do is very different so we've been solving some algorithmic problems and this is more of a problem where you have to structure a small program and this actually makes it a really interesting toy example for how namespaces and classes work in apl so i'm going to take this opportunity and show you a little bit of that and so yes the full disclosure i have read this problem and i solved it 10 minutes ago when i was recording and so this is a re-recording which so this is a re-recording which so this is a re-recording which hopefully is going to be a lot cleaner and clearer as well so the problem statement says that they want us to design a parking system and this parking system has or keeps track of three types of parking spots there's park parking spots for big cars parking spots for medium cars and parking spots for small cars and the idea is that a car can only park in a spot that corresponds to its specific size so a medium car can only park in medium parking spots it cannot park in bigger parking spots nor in smaller parking spots so the idea is that we need to implement a function that initializes that creates some parking system that is able to keep track of these parking spots and then there's another function which is the av car function that takes a type of car which corresponds to big medium or small cars and it tells me true if i was able to park the car or false if i was not and what is more the parking system should update itself and say that or reduce the count of available spots and they have an example here so they are creating a new parking system with one spot for a v car one spot for a medium current zero spots for small cars and so the first time we have a big car it gives true because it was able to park that car and then we have a medium car and it also returns true because we were able to park that car but then it adds a small car and it fails because there were no spots for small cars and then we have another big car and this time it fails because the only parking spot we have was occupied by the very first beaker and so we are going to tackle this problem in three different ways this is a really simple problem and so they do ask for a solution with object oriented programming but we will start in this video we will do something which is simpler and we will just keep track of the states in a simple vector with the parking spots and then i will link in the description to two other short videos one of them we solve this problem with namespaces and in the other one we use actual object-oriented programming in actual object-oriented programming in actual object-oriented programming in apl which is something apl can also do so yes on to the very first solution so the way we are going to do this is well first i should open an interpreter so that we can work with it sorry wrong thing give me seconds okay so we start with nothing and the idea here is that we will our parking system which won't be a class right now it's just going to be a vector is going to be composed of these numbers so it's a three element vector with the number of spots for each type of card so actually our function that initializes a parking system is a function that does nothing because if we want to initialize the system with these spots then what we want is to actually get that vector so this is our function to quote and quote initialize the parking system it's the right stack which takes this argument and returns it unchanged and now what we need is a function f car that will take the parking system on the left so let me save this parking system it's ps for parking system and now we take the parking system and we give it as a left argument to the function f car and in here we say the type of car that we want web and this is it doesn't work because i haven't defined the function and the idea here is that when i have this car this type of car to this parking system then the function returns the new parking system change the new value and returns the boolean saying if it worked or not and the way we could do this is by doing a multiple assignments so we can unpack the results by saying something beeps on my computer it's because i have it open sorry for that so the idea is when we call the function like this we actually assign the result like that okay and this will be the new parking system the new updated state and this is the boolean that says if it worked or not and so we need to define this function and how can we go about doing that well there's two things we need to figure out so we need to figure out if we can park the car or not and we need to return the new value and if this were some programming some classical programming language that you are some of those mainstream programming languages or a not array oriented one you will probably do you will probably use an if statement but let's not do that let's write this in an array oriented way or an attempt at that and so the first thing we are going to do is to take the card type and produce a boolean vector with a one in the place where that car will go so for a car type of two we would create this and this says to park this car our parking system needs to have zero big spots it needs to have one medium spot and it needs to have zero small spots or if we were having a small car we would generate boolean vector because it says okay my parking spot doesn't need any big or medium spots but it needs a small spot then we can take this and we can try to subtract it from the actual parking system and in this case well there's no spots for small cars and so when i subtract this one from this zero what happens is my parking system suddenly gets a negative value and that's something i can't have my parking system cannot have any negative number of spots available and with that i can see if i can park that car or not because doing the parking system minus this little vector over here gives me negative values and then i just need to be able to pick the correct parking system which is either the original one if i cannot park the car or the new one if i can park the car and as you'll see this is fairly simple to do so let me go ahead and open my editor to implement this function that adds the car and this is a it will be a short defense so the first thing we do is we try to create the new parking system and that should be the old one which is the left argument minus that vector we just described so it was something like um can i deal with this line yes delete this line so i have this and then i wanted to for this type of car i wanted to create this vector over here so what i'm going to do is i'm going to use iota 3 to create three integers and now i see that create to toggle or to turn on let's say that to turn on the first sorry to turn on the middle element there with the two what i need to do is have one to this and then compare with my car type so this works for a car type of two so if i wanted to park a small car then the car type would be three and if i wanted to park a v car my car type would be one so this creates the vector that i need and this is the car type so the car type here will be the right argument and i need to compare it with this vector so this gives me the new parking space and then i need to return the new parking space and the boolean value should be zero if there's a negative value in here in the in this new parking space so if there's a minus one in the new parking space then this gives me one and in that case i actually want to return zero so i need to use the tilde to negate this otherwise if there's no minus one then this gives me zero but i actually want to say that i was able to park the car and the negate turns that into a one now what i need to do is should i return the new parking space or the old one so which one should i return and the thing here is if the new parking space does not have negative values then i can just return it but if it does have a negative value if it has a minus one there then i need to revert that and i need to revert that minus one to a zero so what i can actually do is type something like new parking space max to zero because if all spots are fine then this does nothing and if one of the spots became negative then this will reset it back to zero so i can actually group this now let's press skype to fix the function and now i can use the function and you can see how it works so let's go ahead and create the parking system that's used in the example and let's do the let's take the parking space and to this parking space let's add the car of type one and i was able to park that car and now these are the spaces i have left now let's do the same thing again but now let's park a car of type two was i able to park it yes i was how many parking spots i have left or zero in for each type so now let's try to park a car of type three and let me press i think it's shift enter no it's not ctrl enter so we can trace through the function as we go along so we just enter the function this is the line that we are going to run now if you take a look here omega is the three there alpha is the parking system and so i can run this line and i see that the new parking system is this thing over here so what's the boolean value here well i can let me copy this and paste it here well this is zero why because there's a minus one in there and when i negate it becomes a zero now what is this if the new parking system has a minus one here when i max it out with zero then that minus one becomes a zero and this is basically me resetting the new parking system to what it was before it was zero then new parking system is zero minus one and then if i max it up with zero it resets and this would have worked if i had other available spots in here because if i have other available spots in here these would also be these would be positive and so maxing them with zero would do nothing because those other values would be greater so i can also run this and then we leave the function and you see that i did not park the car and the parking system stays like that and so just to show you this one more time i have available spots for big and medium cars but if i try to park a small car so let's take the parking system and add a car of type 3 notice that the parking system remains the same and the boolean is false because i was not able to park this car and so this is the the solution without any um fancy types of structures without namespaces without classes etc just as keeping track of the state in this vector and if you have another simple alternative well feel free to leave them in the comments below otherwise if you want to see how this could be solved with or in a more structured way with a namespace or with a class there's going to be two videos linked in the description and if not then i will see you in the next video bye
Design Parking System
running-sum-of-1d-array
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size. Implement the `ParkingSystem` class: * `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor. * `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`. **Example 1:** **Input** \[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\] \[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\] **Output** \[null, true, true, false, false\] **Explanation** ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0); parkingSystem.addCar(1); // return true because there is 1 available slot for a big car parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car parkingSystem.addCar(3); // return false because there is no available slot for a small car parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied. **Constraints:** * `0 <= big, medium, small <= 1000` * `carType` is `1`, `2`, or `3` * At most `1000` calls will be made to `addCar`
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
Array,Prefix Sum
Easy
null
23
Hello guys welcome back to take use this video will see the match shot at least problem Vismrit ko number-23 so in this problem will be doing problem Vismrit ko number-23 so in this problem will be doing problem Vismrit ko number-23 so in this problem will be doing good fiber process in order to solve this problem so let's posted key problem statement in this problem you R give energy of killing at least and liquid spilled in ascending order win mode on the language in to-do list order win mode on the language in to-do list order win mode on the language in to-do list mant example in order to give winners in ascending order to enter into a single shot at least three boys subscribe total number of modes turn on Do 228 In This Case Which Plus To Write Now Free Mode On This Thank You Into A Single Place You Will Find Written Notes In Ascending Order For This Is Not Want To Return To Returns The Video then subscribe to the Page if you Just 2 And This Point Two Three One Two Three Do It Is Subscribe Now To Receive New Updates List Play Complexity Will Go To Your Pan Right Choice Will Be Applied To All Dual Gautam Switch I Will Be Explained In This Video To A Different Than 200 This program is actually and off space display this simple to implement but if you implemented by road office doing better than what is simplest idea which comes to your mind senses at will give flu se 1000 notes required to this interesting than what we can do it is Not just a liquid 2125 voter list in to-do just a liquid 2125 voter list in to-do just a liquid 2125 voter list in to-do list and want to see the results channel so and use this point to chintu pimple because you can just point this upon you can easily drink list ok I hope you already know how to Make Two List So You Can Apply This Simple Approach And You Can Watch All The Number Of List Play List To Play List Element 12345 Elements And Elements Of Obscuritism The Ayodhya Total Number Of versus which you will be doing nothing but and of ok improve time complexity of this possible approach and now let's look at the second approach no this is or simple approach in this case letters udayveer and nurses and deserving elements which can incomplete point To the beginning that is the head of the list of all the point elements and minimum play list so let's users compare the value of the meaning of this point two three minimum 202 this point two three not three four subscribe se so you can THE CAN EVEN LESS ALIVE UP ENEMY SUNIL DUTT IN UPDATE THIS POINT ARE NOW AGAIN COMPARE 483 LIKE THAT YOU WILL BE INCLUDING ALL ELEMENTS OF THIS LIST GREAT SOULS WILL PERFORM IN THE INTELLECT WILL BE DURING SERVICE CENTERS THE GROWING HE ADD MEMBER NUDE VERY SIMPLE APPROACH For taking spirit will take water in the complexity other features I have plate this point Anadhe Gautra-1 Space and time point Anadhe Gautra-1 Space and time point Anadhe Gautra-1 Space and time complexity in this case will be for including one need into your earliest your traversing all the K list in this lineage element from which of the list On this topic this point to my this point a your comparing all the best on Saturday absolutely minimum element unadhe limit evening that operation fennel elements with twins' that operation fennel elements with twins' that operation fennel elements with twins' operation at this time will be heroine's I hope you understand were second simple approachable Latest New Look Next Approach World That One Is And Simple Approach Here You Will Be Joining All The List And Copy Then Values ​​And Will Be Applied And Copy Then Values ​​And Will Be Applied And Copy Then Values ​​And Will Be Applied Simple Sorting Algorithm Officer Very Simple Unbearable Give Three Let You Know What You Will Do Is Video give Tel Pointers Well You will just make point to 20 notes ride on revenue has not given the points you can just avoid it will just a quarter of and where is the total number of elements including all the least not given winners list hands free mode on single list min wait And Long Pending Okay So This Is Again Very Simple Approach Not Give Up Like This Place Between Adheen Express Channel Subscribe Button Click Here To The Number During Last Not Want To Give The What We Can Do It Is They Can Divide Somewhere In Between And Cancer Divide This problem into problems and difficulties in which can be just like 100 or 200 this problem you need to know how to do the volume to subscribe will just divided into problems Video then subscribe to the Page if you liked The link for detail view ok so while Moving from top to town and UK dividing the number of list 2 and when you reach problems size 20 this list of science one day with the list of science one day you will get the resultant list ok electronics then 49 give winners list and you will Get Se 14 Mother 14 And You Will Get K 224 This Is The Total Number Of Tourists And Definition Of Class 9th Chapter Ki Play List Resulting From Bottom To Top Subscribe From Top To Download Way From Bottom To Top Sources Hua Tha Bahen Divider Ko On Kar Technique in this case Middle East into pieces added into house you can see in two hearts and qualities due in what manner to be understood as a level will process and number of the total of history will be best to subscribe and divided by subscribe like It will have to subscribe let's compare level-3 subscribe three level-3 subscribe three level-3 subscribe three layer number of votes will be the true for all the total number of years including all the best spread logical ok so you have noticed this level and your processing all dost notes37 level Shoulder Total Time Will Be Number Of Levels With Lock Between Two Multiplied By Number Of Note Switzerland Total Time Complexity Will Be An Lock K Know What Happens If You Have And Number Of List You May Think About 100 In This Case Rehabilitation 1833 But They Can Take care number of list one side and they can take and number of list on the side soir left with just single list day you will just stop ok development is the topic condition you can not have a single east west and this is the topic condition hair oil to Can Be Divided Into Heaven And As To When You Must To Gather 12.22 Can Be Combined With Three To One To 12.22 Can Be Combined With Three To One To 12.22 Can Be Combined With Three To One To Three For This Is Well Known As Seek Approach Which By Using Hit Song How To Use Pair This Fold And Previous Problem Din You Might Figure And That we can solve watching this Video give least one to three to the difficult element of all turn on Thursday for this point elements 1234 subscribe channel like this is the meaning of the name of the smallest list play list 154 will be included INTO ANSWER LINK LIST 100 WILL JUST A HIT WICKET OUT AND WILL JUST OR REPLACED WITH THE LAST ELEMENT OK THIS IS BASICALLY BACKSTREET MEENAL GAUTAM QUALITAS AND ALL THE LINKS FROM THEM WILL BE PRESENTED BELOW YOU CAN GO THERE WAS THE PLAY LIST SUBSCRIBE NOW TO Receive New Updates Point 12.23 NOW TO Receive New Updates Point 12.23 NOW TO Receive New Updates Point 12.23 Loot in to-do list element and you will Loot in to-do list element and you will Loot in to-do list element and you will introduce element may change the property of that new This is the present element is lower side of doing we saw all this episode and you have included element not for the next element You will again repeat this process will just for this element in 10 answers an answer list 8 9 users liked this element you will reduce the size and you will apply subscribe and subscribe this Video like and subscirbe again play 9000 you can keep on repeating you can Just keep on repeating process of updating this point and then you will stop 220 Have Already Included Want To Know When You Stop This Next Element 1023 For Will Be Taken Out In Seventy Root This Point They Can Be Applied For This Is The 40 Days Will Be Mute the like this is not considered quite update this point to that is the day you will be updating this point to know the answer is not only single element must subscribe absolutely not this point internal decorate cannot be pushed Into the only busy single element they pop out will be including 7 This point will get updated with love for internal so they can not intervening into the only grind MP 20 percent day in which can be assured all the elements have been included into your answer this See Center Answer English So They Can Determine The Head Office List I Hope I Understand S E Approach In This What They Are Doing Well Placid Them All The First Elements Of Them Will Take Care Number Of Elements Of This Element Key Traversing Element And Subscribe Element Updating The lock's time because his eyes key is only ok and were doing for a number of elements of total time complexity and if you are able to understand the soldiers computer 's time complexity of algorithm subscribe like share and simple solution swift's time And space complexity of wave subscribe to the Page if you liked The Video then subscribe to the detention mode on me 108 bieber doing this will give one's number off list right and left widow's updates in pointer to nh -24 To A updates in pointer to nh -24 To A updates in pointer to nh -24 To A Few Of Having A Number Of Least You Will Be Divided Into Two Parts On To-Do Divided Into Two Parts On To-Do Divided Into Two Parts On To-Do List From Part Plus Minus One Number 100 Grams Service Return From Left Side Will Be Stored In The Answer Is Written From Right Hand Side Subscribe Click button this merge to this channel subscribe button to 9 this that this ayurveda limited like when you give in to-do list with her dead lineage do you want to in to-do list with her dead lineage do you want to in to-do list with her dead lineage do you want to gather ok no latest servi function on which hair Will Be Getting The Earliest As Well As Alert As Well As The Right Index Is 0123 45 Number Totally But In This Point You Just Need To Push And Subscribe Favorite Play List Which Are Already Giving Or Original But Not Giving Winners Will Be Divided Like Subscribe &amp; Share Subscribe Now To The Scene 98100 Given Any &amp; Share Subscribe Now To The Scene 98100 Given Any &amp; Share Subscribe Now To The Scene 98100 Given Any Relation Will Be Divided Into Two Parts Will Have Answers For The Life What Will Have Answers For The White Part Only Single English And Left As Well As Right Shoulder Fat Answer Will Be Appointed By Yashwant this point to the head of the black list festival also point to the lightning list so explain 920 820 morning very friend link listen to return head and finally it will be written in head ok Sudhir developed function for dividend by turning it on you can directly- Straight And Which Will Be you can directly- Straight And Which Will Be you can directly- Straight And Which Will Be Returning To Prevent Divide On Doing Latest Not Look At The Hero 16 This Is The He Notification In This Is The Structure For Watching This Is The Function Which Will Understand This Year Left Right And Will Be Taking He Practice Of Priority Q Will Take Over Had Jewelers Airtel Pointer Both Will Be Passed Into Leadership Okay Will Inside The First Notes Of Specified List L1 L2 L3 Lansdowne To Wealth Will Be Baking The First Notes Of All This List And Will Be Merging Into His Okay Will B building he player software apply he flower oil this care number of units which was the first step one British you day will be processing all the notes11 what will be doing so will just taking some will be the villagers who will you know the answer ok what We Will Be To-Do List Will We Will Be To-Do List Will We Will Be To-Do List Will Great The Point Up Because He Should Assure You That They Will Be Taking Any Point This Point * 2014 List and Withdraw pre-2005 Notes Subscribe This process in just two days will be the value of the list of All the States Subscribe Will Also Be Able to Understand You Can Be Possible to Donate Will Help Us Bring More Free Quality Content for Everyone You See in Next Video Send
Merge k Sorted Lists
merge-k-sorted-lists
You are given an array of `k` linked-lists `lists`, each linked-list is sorted in ascending order. _Merge all the linked-lists into one sorted linked-list and return it._ **Example 1:** **Input:** lists = \[\[1,4,5\],\[1,3,4\],\[2,6\]\] **Output:** \[1,1,2,3,4,4,5,6\] **Explanation:** The linked-lists are: \[ 1->4->5, 1->3->4, 2->6 \] merging them into one sorted list: 1->1->2->3->4->4->5->6 **Example 2:** **Input:** lists = \[\] **Output:** \[\] **Example 3:** **Input:** lists = \[\[\]\] **Output:** \[\] **Constraints:** * `k == lists.length` * `0 <= k <= 104` * `0 <= lists[i].length <= 500` * `-104 <= lists[i][j] <= 104` * `lists[i]` is sorted in **ascending order**. * The sum of `lists[i].length` will not exceed `104`.
null
Linked List,Divide and Conquer,Heap (Priority Queue),Merge Sort
Hard
21,264
1,758
hello and welcome to another video in this video we're going to be working on minimum changes to make alternating binary string and in the problem you're given a string and you want to figure out how many operations you need to make it alternating meaning you don't have zeros next to zeros and ones next to ones so in this first example you can just change this to one so that'll be one operation in the second one it's already alternating and in the third one this is where you kind of get the intuition for this problem you can either turn it into this or this and either way we'll take two operations and so this is basically the hint for this problem is whenever you have a string of n characters the alternating version of that string like let's say we have six characters the alternating version of that string will look like two it can only have two different versions it can only look like this or it can look like this so all we really have to do is just compare our string to both of these and figure out how many changes it takes to make our string to one of these and then the least is going to be our answer so for example let's say our string is like this we compare to this one so compared to this one and we can just basically see like how many characters are different so in this case there's one another one and another one all actually another two here right so different easier to see so we have four and then we compare it to the other version so we can compare it to the bottom one over here write actually 0 one01 one how many differences one two so we would have two so that would be our answer and that's pretty much all we have to do now we don't want to really uh for this alternating string like let's say we know our string is length 100 or something we don't really want to like make a string like this we can just have a starting character that will swap at every character so for example if we're comparing our string like this string to this we can just like Loop through this string have a character that we compare it to have it start at one and then every index it will alternate so like at the next index it will go to a zero then it will go to one then zero and so on so you can either have a conditional based on index or you can just have it alternate and that's pretty much it so we can go it so essentially we're going to have a result and we're going to have a total and we're going to have like a current character we'll start at zero for the first iteration and we'll say like four character in s if character doesn't equal Cur then add to the total so this is the first iteration is going to be like this one where it's 0 1 Z1 and so on and then we will um swap C to the opposite one so we'll say c equals one if per equals zero and if it's one then turn it into a zero yeah should be good so essentially we're swapping it now we do this exact same thing so we can make our result equal to the total at the end and we can make the total zero and basically run the same exact thing so we run this exact same except now we start the Cur at a one so now our string will be 1 0 now if you want you can also do this in one loop I guess we could do that so we can refactor this to have it take one Loop so we could say like total two total one and now we could have two of these so this would be in one Loop so we could have like curve one and curve two and we could have them like alternate so we could say like if character doesn't equal Cur one TOA 1 plus equals 1 L total 2 plus equal 1 we could just do it like this and then we could um we could move we could uh increment these both in the loop so this will just be swapped so one um actually I think the logic for changing the character should be the exact same right so if it's a zero it should turn into a one and if it's a one it should turn into a zero so actually this logic should be the same yeah this part should be the same they just start at a different character and finally we can return we don't need a result anymore now we can just return the minimum of total one and total two and that allows us to do it at one be like one two there we go now if this is a little bit confusing you could all always write this in one in two separate Loops but essentially we just have the two different alternating things it can be either ones followed by zeros or zeros followed by ones and we just flip our character every single time and add up the total difference okay and um for the time this is oven and for the space it's L1 because we just use this like one character that we alternate if that's a little confusing you can actually build out string so you can build out the string of ones and zeros first and then build out the string of zeros and ones if you want that's or this character is better though because you know it basically alternates stuff so hopefully this is helpful and if it was please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
Minimum Changes To Make Alternating Binary String
distribute-repeating-integers
You are given a string `s` consisting only of the characters `'0'` and `'1'`. In one operation, you can change any `'0'` to `'1'` or vice versa. The string is called alternating if no two adjacent characters are equal. For example, the string `"010 "` is alternating, while the string `"0100 "` is not. Return _the **minimum** number of operations needed to make_ `s` _alternating_. **Example 1:** **Input:** s = "0100 " **Output:** 1 **Explanation:** If you change the last character to '1', s will be "0101 ", which is alternating. **Example 2:** **Input:** s = "10 " **Output:** 0 **Explanation:** s is already alternating. **Example 3:** **Input:** s = "1111 " **Output:** 2 **Explanation:** You need two operations to reach "0101 " or "1010 ". **Constraints:** * `1 <= s.length <= 104` * `s[i]` is either `'0'` or `'1'`.
Count the frequencies of each number. For example, if nums = [4,4,5,5,5], frequencies = [2,3]. Each customer wants all of their numbers to be the same. This means that each customer will be assigned to one number. Use dynamic programming. Iterate through the numbers' frequencies, and choose some subset of customers to be assigned to this number.
Array,Dynamic Programming,Backtracking,Bit Manipulation,Bitmask
Hard
null
77
hi guys today let's discuss the lead code question 77 combinations given two integers n and K written all possible combinations of K numbers chosen from the range 1 to n you may return the answer in any order yeah let's go to the example one the input n is equal 4 and K is equal 2 so when n is equal to 4 and K is equal 2 we'll be getting 4 C2 combinations which is 4 factorial / 2 combinations which is 4 factorial / 2 combinations which is 4 factorial / 2 factorial into 2 factorial so it is going to be six combinations and the output is going to be 1 2 1 3 1 4 and 2 3 2 4 and 34 let's go to the example two in the example two n is equal to 1 and K is equal to 1 so we'll be getting only one combination so that is going to be one let's go to the constant section as well so the constant section is uh n value ranges from 1 to 20 and K value ranges from 1 to n so there won't be any Corner cases where uh K is equal to 0 or k is greater than n so there are no such uh cases here so we need not cover those Corner cases yeah I hope it is very clear from this question description let's go into the explanation part of it for the purpose of explanation let's consider n is equal 4 and K is = 2 so consider n is equal 4 and K is = 2 so consider n is equal 4 and K is = 2 so when n is equal 4 the input combination is going to be 1 2 3 4 and K is equal to 2 from this input we are going to get four descendant and descendants are going to look like this so we are going to split this input 1 2 3 4 as 1 and 2 3 4 so the how we use it this one for the recursion is we whatever the combinations that we get for 2 2A 3A 4 and K is equal to 1 we'll be adding 1 to that those combination and the second descendant from this input is going to be 2 and 3A 4 and K is equal to 2 and the third descendant is going to be 3 and 4 and K is equal to 2 and The Last Descendant is going to look like this four and it is going to be an empty list and K is equal to 2 so for this first 1 and 2 3 4 and K = 2 so for this first 1 and 2 3 4 and K = 2 so for this first 1 and 2 3 4 and K = to 2 for the next recursion we are going to send 2 3 4 and K is = to send 2 3 4 and K is = to send 2 3 4 and K is = 1 let's look at all the other descendants as well so the other descendants are going to look like this 3A 4 and k equal to 1 and 4 and K = 3A 4 and k equal to 1 and 4 and K = 3A 4 and k equal to 1 and 4 and K = to 1 and empty list and K is equal to 1 this is going to be our base case whenever K is equal to 1 our output should look like this for 2 3 4 and K is equal to 1 we are going to Output in this format and this is going to be our base case we are going to Output a list of 2 3 and four for the other descendant we are going to return something like this 3 and four and for the other descendant we are going to return four and for the Last Descendant we are going to return an empty list so now the control actually flows to the previous step so we are going to append 1 to the below obtained result then we are going to arrive at 1A 2 1A 3 and 1A 4 in the similar way we are going to arrive at 2A 3 and 2A 4 by appending 2 to the 3A 4 obtained from the below list then we are going to get three 3A 4 by appending 3 to 4 and the last one is going to be an empty list because we did not get any combinations from the below one so it is going to be an empty list finally we are going to add all these things into a list and we are going to return this list and this is going to be our output I hope it is very clear from this explanation let's quickly code this up let's create a helper function so that helper function is going to be Helper and it requires two arguments the first argument is going to be start and the second argument is going to be K so this K value will be updated in the successive recursive calls it will be updated and even the start will be updated if k equals 1 we are going to solve the base case in our base case we are going to return a list of for I in range of start to n + to n + to n + 1 and we are going to written a list of I and else if K is not equal to 1 we are going to iterate from for I in range of start to n + 1 and let's create an empty list so that we'll be returning this result at each uh recursive call and let's call the recursive function so the recursive function is going to be Helper and we are going to call it on I + 1 call it on I + 1 call it on I + 1 K minus 1 so we are going to decrement K at each recursive call and finally the K value will be reaching the base case of k equal to 1 and we'll be returning from that recursive call so this is going to be our partial result and we are going to app we are going to create a new list with all these combinations so it is going to be result Plus it is going to be I we are appending I to all the combinations so it is going to I plus partial for partial in partial result so for all the combinations We Are appending One to that combination so we are appending sorry we are appending I to that combination and finally we are going to return this is the list that we are creating so which means that it is a combinations that we are creating so finally we are going to return this helper of so our start initially is going to be from is going to be 1 and K is going to be K I hope we are done let's quickly run the code yeah it is accepted let's quickly submit as well yes it is submitted hope you like the explanation for more such videos please subscribe to my channel thank you
Combinations
combinations
Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers chosen from the range_ `[1, n]`. You may return the answer in **any order**. **Example 1:** **Input:** n = 4, k = 2 **Output:** \[\[1,2\],\[1,3\],\[1,4\],\[2,3\],\[2,4\],\[3,4\]\] **Explanation:** There are 4 choose 2 = 6 total combinations. Note that combinations are unordered, i.e., \[1,2\] and \[2,1\] are considered to be the same combination. **Example 2:** **Input:** n = 1, k = 1 **Output:** \[\[1\]\] **Explanation:** There is 1 choose 1 = 1 total combination. **Constraints:** * `1 <= n <= 20` * `1 <= k <= n`
null
Backtracking
Medium
39,46
1,455
Hai Hydro Suryavanshi Question Check It's Lord Curzon Chiffon Is This Sentence Subscribe Must Subscribe Sentence In this sentence you have to tell that if you do it in the beginning, get married Jiya Raghbir and share and subscribe If you were sending a text message, then I am giving the answer There were tumors, this is It is quite a simple problem, what are you doing sir? Good day, let's see once, how will we do it, as we have kept it separate for us, subscribe to it, if it will come together with the pimple position, then our position in it is ghee, subscribe, thank you. You that end is August friday so we have basically got the paste point subscribe this point thank you now what will I do to take the tempo for how many lunches from WhatsApp Singh Hero Blouse Amazing Temporary A I will have to check first the attempts of this great end If you subscribe, then basically what is happening is that first we have to check that if our subscribe is doing a perfect little bit then we have done it, after that if it is not doing then we will appoint this trick. This trick is done by police training. We will start EM Casio, our anger is over, what is the process and subsequent withdrawal, we will do it in a hilly village and after that, if we are not in India, we will go to the airport, let's see a poem, we will remove it by saying this. That we wrote this condition because and here with a happy stomach, so it can be done in the condition that on Monday this word is near grated 20.21 if cigarette will near grated 20.21 if cigarette will near grated 20.21 if cigarette will be favorable here because there will be complexity at that time because of power of fifth ODI because we The input string was a sentence, did a lesson on it and the space complexity is ordered.
Check If a Word Occurs As a Prefix of Any Word in a Sentence
filter-restaurants-by-vegan-friendly-price-and-distance
Given a `sentence` that consists of some words separated by a **single space**, and a `searchWord`, check if `searchWord` is a prefix of any word in `sentence`. Return _the index of the word in_ `sentence` _(**1-indexed**) where_ `searchWord` _is a prefix of this word_. If `searchWord` is a prefix of more than one word, return the index of the first word **(minimum index)**. If there is no such word return `-1`. A **prefix** of a string `s` is any leading contiguous substring of `s`. **Example 1:** **Input:** sentence = "i love eating burger ", searchWord = "burg " **Output:** 4 **Explanation:** "burg " is prefix of "burger " which is the 4th word in the sentence. **Example 2:** **Input:** sentence = "this problem is an easy problem ", searchWord = "pro " **Output:** 2 **Explanation:** "pro " is prefix of "problem " which is the 2nd and the 6th word in the sentence, but we return 2 as it's the minimal index. **Example 3:** **Input:** sentence = "i am tired ", searchWord = "you " **Output:** -1 **Explanation:** "you " is not a prefix of any word in the sentence. **Constraints:** * `1 <= sentence.length <= 100` * `1 <= searchWord.length <= 10` * `sentence` consists of lowercase English letters and spaces. * `searchWord` consists of lowercase English letters.
Do the filtering and sort as said. Note that the id may not be the index in the array.
Array,Sorting
Medium
null
120
hey so welcome back and this is another daily good problem so today it's called triangle it's a medium level dynamic programming problem and so let's get started here so essentially you're just given a two-dimensional Matrix two-dimensional Matrix two-dimensional Matrix um but it's actually interesting where the uh basically the length of the rows don't always match and they kind of perform this kind of triangular shape here and so basically like the length of the rows kind of go length of one then two three and so forth so they just increase by one uh with each kind of row and so basically what we're wanting to do is this is a minimization problem and so we're going to want to go from top to bottom and find basically the shortest path to get there or the kind of minimum cost to get there and so if you kind of view these numbers as like costs you can say that okay I want to kind of go down this path that has this minimum cost and in this case it ends up being so we go from two we start at two then we choose three and then we hop over to five and then we go to one and this path here lends itself to a total cost of one so you just take the sum of that path and that's basically uh what we're going to want to return here all right and so in this case well you can also have negative numbers and well if there's only one value here to get from top to bottom you just want to add that so it ends up being negative 10 here all right and so essentially the reason why this is kind of a dynamic frogging problem is you can kind of format it in a way so that you can reuse certain decisions that you've maybe made before and that's because well you'll end up doing a lot of repeated work here because there's multiple ways that you can get to five let's say and from five you maybe want to make that decision on how you want to move forward many different times and so you can get to Phi by either starting at 2 going to three and then choosing five or you can get to Five by saying let's start at two go to four and then go to five and the reason why this is a repeated work as once you go past five you'll constantly having to make this decision of okay do I want to go to one or eight so all the possible pass forward from five you'll have to do kind of that repeated work for each iteration getting to five all right so I hope that kind of makes sense um but essentially if we want to map out our decision tree basically what it's going to end up looking like is we start at 2 and then basically we have two different choices we can either go to the say two which is index zero you can either choose to go to index 0 again on the next level or on the next level let's go to index basically zero plus one or I plus 1 which is obviously just one here so that ends up being 2 or 4 in this case all right and so then once we get to these levels they also have decisions and so basically now we're at looking at the next level so this is level zero now this is a level one and now we're at level and this is like an L here level uh two and so now when we're looking at level two when we're at this step say if we chose two we can either look at I equals zero or I equals one and so I equals zero is six and then I equals one is five but we're not four since four is at index uh one here we can then look at once again index one which is five or at I plus 1 which is seven all right so basically at each iteration there's going to be two decisions or two deposit paths which is either the current index that we're at or the current index of plus one essentially all right and so it's very easy to convert this into a top-down convert this into a top-down convert this into a top-down memorization approach which yields itself to like o of N squared time and space complexity like so and so that's basically um this here so typically whenever you do a top-down approach and I'll show you do a top-down approach and I'll show you do a top-down approach and I'll show you after how to do the bottom up we will Define the DP such that we're at index I so we're going to return up here and so typically you want to Cache this so let's just throw this in a cache and so you want to look at okay what's the base case well the base case is once we reach the end here so that's okay if I is in greater or equal to the length of our triangle or let's just place this I like using array it's the length of the array um but once again this is a two-dimensional array so we'll also want two-dimensional array so we'll also want two-dimensional array so we'll also want to be keeping track of what the current level is as well so these will both be starting at zero and so if the index is out of the bounds for this particular level then we'll want to just kind of return zero and propagate that answer upwards but we'll also want to check okay and or we want to make sure that okay is our level out of bounds as well and so we just check okay if the level is greater or equal to the length or the number of rows in our array we also want to check that otherwise we're just going to return the two possible paths that we're going to do and naturally we want to do a minimization of it and so we want to go to the next level and we can either stay at the current index or we can choose to go down to the next level and increase being X by 1. and essentially we're just adding to our array um which is at index L and index I it says that this is just the current value that we have but this is okay moving forward which path we want to go down so that works and if it computes here success but you can see that it has very low time and space complexity so let's go ahead and we'll do the bottom-up go ahead and we'll do the bottom-up go ahead and we'll do the bottom-up approach to save on time and space actually and so what this looks like is generally you want to convert that kind of implicit memorization that we're doing to a very explicit array here and so that looks like this where it's basically the length of our array plus one here and so we're going to want to return the result of this at the index zero and so we're going to go from bottom up and so we're going to reach the very top and kind of propagate the shortest path upwards and so instead why don't we actually just set this to be equal to um n for n in our array for the last row so basically we're going to pre-fill our so basically we're going to pre-fill our so basically we're going to pre-fill our DP array with the bottommost row so that's what basically is so the bottomless row will be pre-filled bottomless row will be pre-filled bottomless row will be pre-filled um with those bottom values so from here we're just going to say okay why don't we iterate from bottom up so we want to go through for I or for every level in the range and we're going to start from not the bottom level but the level above the bottom and we're going to basically move level uh each level upwards and so once again we'll go like this and we'll say okay let's start at the end of our array minus 2 to get the level above the lowest level and we just iterate backwards and so from this point then we want to say okay well we also want to trigger Traverse through every single column and so this will be like for I in the range and we just want to go through column by column so just the length of the array and this is non-inclusive and this is non-inclusive and this is non-inclusive and so from this point we basically had those two decisions that we can go down and so that's okay do we want to look at the current index or the index over and so we just say okay the DP at this particular index will be equal to the minimization of well itself and basically the um path next to it that you can also go down so I plus one so I think this makes sense let me just think for a second but as you can see we aren't actually adding any numbers we're only propagating the bottom most row so we want to also be including these different numbers as we move path this past this point and so we want to be using numbers within our Matrix here and so we're just going to be adding at this particular level like so uh this particular value that we're currently at as well so let's go ahead and try running that oh and it's out of range so let's think for a second uh so at I oh so basically we want to only P so because every single row can have varying um number of columns we want to consider that so when we're at a particular level we only want to consider the columns within that rows kind of column range so we can do that by just saying okay let's grab the length of the or the number of columns at this particular level looks good and success so that's o of n time complexity and O of n space complexity uh using this bottom-up approach so I uh using this bottom-up approach so I uh using this bottom-up approach so I hope that helped and good luck with the rest your algorithms thanks for watching
Triangle
triangle
Given a `triangle` array, return _the minimum path sum from top to bottom_. For each step, you may move to an adjacent number of the row below. More formally, if you are on index `i` on the current row, you may move to either index `i` or index `i + 1` on the next row. **Example 1:** **Input:** triangle = \[\[2\],\[3,4\],\[6,5,7\],\[4,1,8,3\]\] **Output:** 11 **Explanation:** The triangle looks like: 2 3 4 6 5 7 4 1 8 3 The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above). **Example 2:** **Input:** triangle = \[\[-10\]\] **Output:** -10 **Constraints:** * `1 <= triangle.length <= 200` * `triangle[0].length == 1` * `triangle[i].length == triangle[i - 1].length + 1` * `-104 <= triangle[i][j] <= 104` **Follow up:** Could you do this using only `O(n)` extra space, where `n` is the total number of rows in the triangle?
null
Array,Dynamic Programming
Medium
null
1,701
so lead code 1701 average waiting time so you're the chef of a restaurant and you're given an array of customers in order of their arrival at the restaurant and as soon as the customer arrives they give you their order and you're given the time of arrival and the time that it takes to prepare the order of the current customer so you can only prepare the orders in the order that they are given to you as an input so like the customers are in a queue and you cannot decide to prepare a order before another if it was given to you in a certain order you need to prepare them in that order okay and what you want to return is you want to return the average waiting time of all of the customers okay so to do this we're going to basically have to simulate being the chef and determining what is the waiting time of every customer so to do that we're going to first of all keep track of the total waiting time of all customers and then we're going to divide that by the customer's length and that will give us the return the correct return value which is the average of the waiting time okay so we're going to have two variables which is first of all the result which is the total sum of all of the waiting times of all of the customers and we're going to have the now variable which keep track of the time so this is just the current time and now we're gonna have a loop that goes through all of the customers and takes their arrival and the time to prepare the order and what you do is first of all you need to wait like if now is less than arrival then it means that you cannot do anything in the time between now and arrival because if we are at the start of this iteration here it means that we have ended the previous iteration or it is the first iteration and if we have ended the previous iteration then it means that we've already prepared the order of the previous customer so if we've already prepared the order of the previous customer and now is less than arrival then we cannot do anything in the meantime we cannot like use the time between now and arrival to do something so if it is not arrival time yet then we just wait for that we don't do anything but wait but if it is already passed then we already have the order and we do not have to wait any time in fact the customer is already waiting if now is greater than arrival so might as well take their order immediately okay now so after doing this line now you are sure that you are ready you are actually ready to prepare the order of the customer because first of all as i've already said before you've already prepared the previous customers order and so you do not have to do that you can prepare the current customer's order and second of all the customer has arrived because of this line here okay and so now you are sure that you can prepare the current customer's order and how do you prepare it you just simulate doing something so you add to now the time that it takes to prepare the order and now you have the actual waiting time of the customer which is just the current time minus the arrival of the customer right so you add that to the result because remember that the result is the total sum of all of the waiting times of all of the customers and at the end you just return the result divided by the length of the customer's array and that's it right so i'll submit the solution to show you how it works and the time complexity is o of n because you just go through all of the customers once and the space complexity is o of one because you don't have any array or list or set or map or anything like that so that's it for me today thank you for watching and bye
Average Waiting Time
remove-max-number-of-edges-to-keep-graph-fully-traversable
There is a restaurant with a single chef. You are given an array `customers`, where `customers[i] = [arrivali, timei]:` * `arrivali` is the arrival time of the `ith` customer. The arrival times are sorted in **non-decreasing** order. * `timei` is the time needed to prepare the order of the `ith` customer. When a customer arrives, he gives the chef his order, and the chef starts preparing it once he is idle. The customer waits till the chef finishes preparing his order. The chef does not prepare food for more than one customer at a time. The chef prepares food for customers **in the order they were given in the input**. Return _the **average** waiting time of all customers_. Solutions within `10-5` from the actual answer are considered accepted. **Example 1:** **Input:** customers = \[\[1,2\],\[2,5\],\[4,3\]\] **Output:** 5.00000 **Explanation:** 1) The first customer arrives at time 1, the chef takes his order and starts preparing it immediately at time 1, and finishes at time 3, so the waiting time of the first customer is 3 - 1 = 2. 2) The second customer arrives at time 2, the chef takes his order and starts preparing it at time 3, and finishes at time 8, so the waiting time of the second customer is 8 - 2 = 6. 3) The third customer arrives at time 4, the chef takes his order and starts preparing it at time 8, and finishes at time 11, so the waiting time of the third customer is 11 - 4 = 7. So the average waiting time = (2 + 6 + 7) / 3 = 5. **Example 2:** **Input:** customers = \[\[5,2\],\[5,4\],\[10,3\],\[20,1\]\] **Output:** 3.25000 **Explanation:** 1) The first customer arrives at time 5, the chef takes his order and starts preparing it immediately at time 5, and finishes at time 7, so the waiting time of the first customer is 7 - 5 = 2. 2) The second customer arrives at time 5, the chef takes his order and starts preparing it at time 7, and finishes at time 11, so the waiting time of the second customer is 11 - 5 = 6. 3) The third customer arrives at time 10, the chef takes his order and starts preparing it at time 11, and finishes at time 14, so the waiting time of the third customer is 14 - 10 = 4. 4) The fourth customer arrives at time 20, the chef takes his order and starts preparing it immediately at time 20, and finishes at time 21, so the waiting time of the fourth customer is 21 - 20 = 1. So the average waiting time = (2 + 6 + 4 + 1) / 4 = 3.25. **Constraints:** * `1 <= customers.length <= 105` * `1 <= arrivali, timei <= 104` * `arrivali <= arrivali+1`
Build the network instead of removing extra edges. Suppose you have the final graph (after removing extra edges). Consider the subgraph with only the edges that Alice can traverse. What structure does this subgraph have? How many edges are there? Use disjoint set union data structure for both Alice and Bob. Always use Type 3 edges first, and connect the still isolated ones using other edges.
Union Find,Graph
Hard
null
225
um hello so today we are going to do this problem uh from heat code called implement stack using queues um so the problem says we need to implement elastin first out stack using only two queues um and it should support all the function of a normal stack so push tab pop and empty so these functions here um and some nodes here we must use standard operations of a queue so only in q and dq so nq basically pushes to the back of the queue and then uh we can peak or pop from the front that's what d2 does and we have size and empty operations so these are the operations of the queue that we should use um unless our dq so basically i think for python we have to use a dq python doesn't have just a q it has a but it has a double-ended queue but we should has a double-ended queue but we should has a double-ended queue but we should only use these operations that's the restriction that we have is to only use the queue operations of edq um or i think if you are using java you can also use the linked list here um yeah so that's pretty much it so here we add one and two to our stack so um if we add one and then add two um then top gets called so we need to return two pop gets called so we return to and remove it and then um we check if it's empty it's not because there is still one here so written false here um so that's pretty much it now let's see how we can solve it okay so let's see how we can solve this so let's say we have a so what we want is to implement the stack so let's just have our stack here i want to implement it using two cues um so the one thing to note is the difference between stack and queue is that a stack is last in first out right because if we add one we add two last added is three if we want to pop we'll pop three and then after that we have two so it's the last one added is the first one that gets out q is the reverse for q we it's first in first out right and one thing to note for a queue is that um there are two operations this is important to note is we have enqueue which pushes in to the front of the cube uh sorry pushes to the back of the queue and then we have dq which removes from the front so what this would mean basically is if i add one two so we push to the back so i add one we push to the back here then we add three but to pop we or tdq remove from the front so we remove this one first one and then after that two so you can see it's not the same order as the stack here so we added them in the same order but for the stack we'll get three two one right here one two three okay so you can see it's a little bit reversing there and so that's where the idea we can have here is that okay um when we are pushing what we want is each time we push we want the queue to have the same order as the stack so that when we pop we get the same order how do we do that so in this queue what we want is we want a queue to end up with three two 1 so that we can remove three first and then two and then one okay so how do we do that um it's actually pretty simple if we use two queues so what we can do is have two queues so we can have q1 and then q2 okay how would you accomplish this so first we have one so we add it to our q right and then we want to add two so we do is we move this one here we want two to be first so we want two one this is the end result we want so what we can do is move the content of q1 first to q2 so what we want is move this here and have q1 be empty and then we push the element that we want so this is push 2 and then we push 2 here and then we take the content of the q2 and then move it back to here and so now we have the order that we want now let's see how this will look like with multiple albums so now we have q1 has two and one and now we want to push three so push three how do we do this so we do the same sequence which is um move content of q1 to q2 and then empty q1 and then push to q1 and then move back content of q2 to q1 so basically we use q2 just as a placeholder of the elements until we push the new element so that it's at the front because um last in first out for the stack that's what we want and then we add the rest of the elements back um and so now uh what happens for push 3 we'll move the content of q1 to q2 and so what that would mean is we'll move two and one here and q1 is empty and then we'll push three to q1 and then we move back the content of q2 back to q1 so we have two and one and this is exactly the order we have in the stack three two one right three two one and so when we pop from the front of the queue or when we dequeue we'll get three first dq again we'll get two dq again we'll get one and that's exactly the order of the stack um so just so that you can really understand and the idea is clear let's do it more with push 4 okay so what we do first is we move the content of q1 to q2 completely so this is q1 this is q2 so we move 3 to 1 we empty q1 right and then we push 4 and then we move back the content of q2 three two one and this is exactly the order we'll have in the stack which is when we add four it's at the top so when we pop four first okay so by in so in the push operation we do this but in pop we just dq and so that makes it the that makes it um work like a stack so let's scoot this up and make sure it passes um okay so let's call it what we just saw so we need two queues we need the first one in python we will use dq but um just remember since dq in python is a double ended queue we should not use the operations that are not available in a simple queue so for a dq in python we'll use only um enqueue and dq operations and these basically are um the enqueue is adding from the back this is append and then dq is um removing from the front so it's a pop left so we only use two these two operations to and that's what the problem statement asked us to do okay so we need two cues first we need our first one and then the placeholder one we use um we can name these in a nicer way maybe we can call or yeah let's actually just have them q1 into q2 to match the explanation okay so for push what we said is that first we need to move the content of q1 over to q2 okay so what this would mean is basically just overriding right and then we want to empty out q1 uh we want to initialize it to nmt dq and then what we want is the second step is to push the element to q1 so that would mean append x and then we want to move back the content that we put temporarily in q2 back to q1 because now the element is uh that we want to push is in front last in first out the last input in the front so that it becomes the first out and so we then we need to put the rest of the content so then it would mean we would move the content of q2 over to q1 so we append the elements that we pop from the placeholder queue so q2 is our placeholder um and this basically will move content of q2 to q1 okay after x of course right um and that's pretty much it for this one now for pop we made this in a way where q1 always has our invariant that we respected is q1 always has last in element in the front of the queue so that means to get since this is a stack we want last in element um we can just return pop from the front of the queue and so to do that we just use pop left so we use our q1 and we pop left and we return that and then to get the top element we said that the top of the stack is the last in element and we maintained that element is in the front of the queue so it's in the first position that means we can just return it by returning the first element in q1 which is zero at position zero now to check in empty that's simple we just check the length of our queue that contains the element we check that it's equal to zero and that's pretty much it so if you're on this it should pass and it does best test cases um now in terms of time complexity here um what we have our pop operation is um since we do pop left from a queue it's a constant time or one um and then for push we traverse q2 that can be at most an element n being the number of calls to push um or the number of elements in the queue and so it's open time in terms of space we're using oven as well for the two cues um yeah so that's pretty much it for the solution the other one thing we can do actually is we don't need two queues we can simplify this and use just one queue so let's see how we can do that um okay so the main idea to think about here is we actually don't use need to cues so how can we do it we can do the same thing but instead of moving the elements to a second queue we can just kind of reverse the order so let me explain what i mean here so uh we need the same thing here for a stack we have these things one two three we want the last element to be the first out okay so for our q one q here we add first one and then we want to push two what should happen here so we can do here for pushing two we first push two at the end like this then the second thing we can do is what we want is moving this here out here okay but this here we can get it with just the front it's in the front so we can pop it so we'll pop this one and then we will push it again to the end and now we get exactly the order in the stack now when we want to push three what we do for push three is we um do a similar thing so we have one two and one already from this operation and so what we do here is we push the element uh three to the end uh normal q and q operation and then we keep popping for the size and minus one that's what we did here as well and so what we need or mean here is we take two we pop it we add it here so this is just uh in q operation and then we take one and then we add here so each time we take n minus one after we push the element and then we move it back and we cannot here we have the exact order for the for our stack and so yeah let's write down the exact operations we are doing here so the operation is first push x so for pushing x what do we do so in qx normally right then the second operation we want to do is for we repeat n minus 1 times we pop the front element um so pop front right and then add it and then enqueue it pretty much thank you okay and that way we will accomplish the same thing we did earlier with the two queues so here let's just um take another example to make sure this is clear so our queue currently has three to one right we're gonna push four so first we push four and then we take n minus one elements of the queue so and it's the size of the queue after appending the element and we'll keep popping and adding to the back so and then queueing so three we pop two and then pop one until we do that n minus one times and you can see here this is exactly um the format of the stack where we have one two three four now what happens if we tap here four here our queue will have three two one in the same order as the stack so this works pretty much correctly um yeah so the operations are just in qx and then do it n minus one will pop from the front at to the back that way we get the stack order um yeah so let's put this up um okay so let's adapt our solution here to match just using one queue so we remove this q2 um and we don't need to do this we just append first our q and then we want to move n minus 1 times so n is the length of the queue and then we want to repeat n minus one time so we can do that in the range of n and what we want is to pop from the front and then enqueue from the end of the queue so that would mean we take the q and this element is what we want to push so we push it here with a pen so we pop from the front and then add it in the back of the cube and then for uh pop we maintain that q1 always has the last element in the front of the queue so this is still we are still doing this with this um and same thing with tab and same thing with empty um yeah so pretty much that let's run it um this is just we just need to update the name here q instead of q1 uh here sorry it should be n minus one right because that way we want to move only the elements before the one that we just added um okay it looks like that is us so here we append and that works let's submit and that passes test cases as well um yeah in terms of time constitution this is the same as the previous solution uh push is of one because we do the slope and then other operations are of one um and then um our space complexity is also just one q so oven um yeah so that's pretty much it for this problem uh thanks for watching and see you on the next one bye
Implement Stack using Queues
implement-stack-using-queues
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`). Implement the `MyStack` class: * `void push(int x)` Pushes element x to the top of the stack. * `int pop()` Removes the element on the top of the stack and returns it. * `int top()` Returns the element on the top of the stack. * `boolean empty()` Returns `true` if the stack is empty, `false` otherwise. **Notes:** * You must use **only** standard operations of a queue, which means that only `push to back`, `peek/pop from front`, `size` and `is empty` operations are valid. * Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations. **Example 1:** **Input** \[ "MyStack ", "push ", "push ", "top ", "pop ", "empty "\] \[\[\], \[1\], \[2\], \[\], \[\], \[\]\] **Output** \[null, null, null, 2, 2, false\] **Explanation** MyStack myStack = new MyStack(); myStack.push(1); myStack.push(2); myStack.top(); // return 2 myStack.pop(); // return 2 myStack.empty(); // return False **Constraints:** * `1 <= x <= 9` * At most `100` calls will be made to `push`, `pop`, `top`, and `empty`. * All the calls to `pop` and `top` are valid. **Follow-up:** Can you implement the stack using only one queue?
null
Stack,Design,Queue
Easy
232
1,877
everyone and good afternoon to all of you today we have problem which name is minimize maximum pair some in Array lead code b877 problem so before going forward in this video please make sure that you have likeed and subscribed to this Channel and also it's my advice to all of you that please read the problem carefully and try to build up the intuition in your mind and also try to do the code also if you simply see this video and do the code it will not beneficial for you so please do the code so let's read the problem is saying that we have the pair sum of pair a comma B is equals to A plus b we have to maximum the maximum pair sum is the largest pair sum in the area list okay list of pairs for example if we have pairs 1 5 2 3 and 4 the maximum some pair sum of is six and8 then the answer will be eight so given an array of nums of even length and pair of the element of nums into ny2 okay so we finally what we have to do is we have to minimize the maximum pair sum so what the mean of minimize the maximum pair sum let's see so let's uh see this PDF yeah if you can see here what we are doing is if we this is a second example in lead code so we have given 35 42 and 46 yeah this is the whole PDF yeah 35 42 and 46 so we have to minimize the maximum pair sum so we can create a pair sum like 35 and 42 and 46 three can create a pair with anyone except three okay so it can create if the pair sum is 3 5 4 2 and 4 6 the maximum is 8 6 and 10 the maximum is 10 and now we can create like 62 44 and 35 the pair is now 8 and eight the maximum sum is reduced now so that we have to do the minimi the minimize the maximum PIR sum so we have minimized our maximum PIR sum so let's think about what can be the intuition for this so firstly we have to minimize the maximum P some so we have to sort this B we can simply see this we have to sort so it will be 2 3 4 and 5 6 now if we take last two elements five and six that will be 11 now but our answer is eight so 11 is greater than 8 so what we are doing is here we are taking the last elements but we have to take the minim we have to minimize the maximum pair we are taking the maximum pair six and five but we have to minimize that also so what we can do is we can take the last element or first element so it will be six or two that will be eight then three then five that will be eight then four that will be eight and we have to take the maximum of these three so that will be our answer so let's take the example uh this will be this is the example of lead code 3523 so if we sort this 2 3 5 now what we can do is we can take the last element of first element that for that will be three five or two 7 and three or three six so we can take the maximum so maximum of these two will be 7even so 7 will be our answer so let's do the code that is basically very simple code yeah let's open this so my headphone batter is very low so let's do this very fastly so firstly what will I do is I have to sort this so nums do V comma nums do end I have sort this now I have sorted now what I will do I have to create in nals to nums do size and I have to take the maximum of final these two or three elements so what will I do I will take the element int Max equals to int Min okay so because we have to take the maximum of final array or elements we can say so I have to create the int Maxi variable so what I will do now I'll create a loop for z i l than nums do size Y2 then I + 1 ++ what why I'm doing size Y2 then I + 1 ++ what why I'm doing size Y2 then I + 1 ++ what why I'm doing nums plus nums dot size divided by two why I'm taking the half element because what I am doing is I'm taking the first element and the last element and adding these two elements then again I equal to one so uh I will take the first element and the last element now I will add so it will be like the array is going from 0 to ny2 because the our final element why will be mid element so mid element plus mid element so it will be 0o to ny2 now what I do is I create int sum equals to nums of I in starting element plus nums of N - I in starting element plus nums of N - I in starting element plus nums of N - i- 1 I will explain it if I = to i- 1 I will explain it if I = to i- 1 I will explain it if I = to 0 so it will be nums of 0 or I = to 0 it 0 so it will be nums of 0 or I = to 0 it 0 so it will be nums of 0 or I = to 0 it will be nums of n minus one means last element so n equals to if we take the example this here the N equals to four so this will be nums of three and this will be nums of zero starting element is nums of zero and ending element is nums of three because we are starting from the zero index so this is perfect now what I'll do is I'll take Maxi equals to maximum element of Maxi comma sum this is done and finally I'll return it Maxi so let's run this code and see it will work or not what is the problem number do size here should be here is a syntax problem yeah now again run this problem run this code as you can see it is working perfect let's submit this what is the time right now 12:41 43 this what is the time right now 12:41 43 this what is the time right now 12:41 43 actually so it is working perfect so let's discuss about time and space complexity for this solution so as you can see we are just sorting this so the time complexity will be n log n and we are not taking any space so space complexity we go of one so if you there can be many appro to solve this problem you can solve this problem in less time complexity also I using big and log I'm sorting this if you can use better approach so please comment that approach so that other can see your approach okay so or if you find this helpful then please like share and subscribe okay bye
Minimize Maximum Pair Sum in Array
find-followers-count
The **pair sum** of a pair `(a,b)` is equal to `a + b`. The **maximum pair sum** is the largest **pair sum** in a list of pairs. * For example, if we have pairs `(1,5)`, `(2,3)`, and `(4,4)`, the **maximum pair sum** would be `max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8`. Given an array `nums` of **even** length `n`, pair up the elements of `nums` into `n / 2` pairs such that: * Each element of `nums` is in **exactly one** pair, and * The **maximum pair sum** is **minimized**. Return _the minimized **maximum pair sum** after optimally pairing up the elements_. **Example 1:** **Input:** nums = \[3,5,2,3\] **Output:** 7 **Explanation:** The elements can be paired up into pairs (3,3) and (5,2). The maximum pair sum is max(3+3, 5+2) = max(6, 7) = 7. **Example 2:** **Input:** nums = \[3,5,4,2,4,6\] **Output:** 8 **Explanation:** The elements can be paired up into pairs (3,5), (4,4), and (6,2). The maximum pair sum is max(3+5, 4+4, 6+2) = max(8, 8, 8) = 8. **Constraints:** * `n == nums.length` * `2 <= n <= 105` * `n` is **even**. * `1 <= nums[i] <= 105`
null
Database
Easy
null
1,611
hey everybody this is Larry this is day 30th of the Leo day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's far I'm here in naha in okanawa in Japan on my last day in Japan last full day anyway so uh yeah let me know what you think about the comment check out this Temple check out these beaches or Beach beaches uh and yeah and also check out the sunset I think and the highway all right I think you checked out everything so let's check out this problem let's go hey everybody this is Larry uh I actually did this live this is a long video because it took me an hour and change to South today anyway because I don't know maybe I'm just a little bit off I'm here in Farland in Taiwan uh a lot of traveling so I'm little really tired but I'll go with the explanation uh from this really smart guy I know from four years ago I'm just kidding but no it's my submission from four years ago and I think that code is actually more intuitive to learn so I'm going to go over that instead of the code that I did today which I kind of did a little bit of pattern matching and try to figure it out right okay so one of the key thing uh to understand is that this is also a gr code and what that means practically for this problem is that uh the minimal number of operations will go through every number in binary once right um You can think about it's just you know there's no uh branching out anything uh it deterministically goes from one to the other um kind of I'm hand wve a little bit do your own research on gr code uh because there's definitely a lot of new ones there but that is some part of understanding uh okay so basically one thing to kind of you know just play around with and if you play around you'll notice that okay well you have one it takes this number of moves to go to zero if you have 10 which is two this number you have 100 which is you know four8 so that's the number of moves it takes to go zero right uh and the reason why you can and this is kind of relating to Great code because it has to go through or I mean that's one way to prove it another way to prove it you just play around with it and kind of get an intuition of why that is the case uh and the reason is kind of like roughly let's say you have here you have to go with here first and to go to here you have to go to here and then I mean I'm skipping some of the steps and then to go to here you have to go to here and then basically dot and then eventually you have you hit every possible two to the uh all other the possible uh prefixes right until you get to a th and then you do it again so if you sum it all up you uh or the previous steps up you get 2 5th minus one for five digits okay so then now the problem is how do you change it to zero so given n uh the way that well first is that I can WR it to a binary string uh or a string containing the binary digits this is just for practical purposes uh or laziness purposes that's the Practical purpose of just having ones and zeros there are number of ways you can do it but that's how I did it and then here we just want to change to zero because that's the name of the problem change the things to zero right and what happens when you have zero so you hav change all X to or zero so then now if there are no digits you return zero if there's one digit then you have two moves right uh if it is a one then you make one move and turn it to zero otherwise it's zero if uh the first digit is zero then you can just do the suffix right because for example we have you don't have to worry about the prefixes so just you know chop it off and calculate the rest okay and then now if this is not true that means that now your prefix is a one right uh and you have some random I don't know I a but like it can be any number combination between and of course there only two cases which is that the next digit is a one if the next digit is a one then now to convert this prefix to from one to zero then you just have to convert the rest to zero so that's what this basically does right so you change this to zero change the suffix to zero change all these to zero and then now you have this number and then you do uh you make one move to remove this right uh I think I would a little bit weird but you make one move to remove the prefix of one so you get to here and then you uh do two to the X moves uh x minus one but you add one because you have to make that move um to get rid of this and that's your answer right a little bit recursive but that's fine and of course yeah okay uh otherwise you have something like this right from here then your goal is to get to here so then you can make these moves the same thing as before uh so here now you have changed to one of this prefix so now you take this prefix and you change it to the first digit to one to convert it to zero uh and then after this then now you can convert this to the end in 2 to the X moves again same idea and then now you have a change to one uh function which is the this is the thing that I couldn't get today even I got it four years ago is to change the one function so you basically you change the first digit to a one and then the rest do two zeros right so again if there's no string it's zero no moves you're done actually maybe that's an Infinity I don't know by the way that doesn't come up I think maybe I'm wrong uh if there length of one then you just have to do the one that change the moves if uh if the first step if the first character is a one then you just have to return the change to zero so this is very recursive very what I call exhaustive uh enumeration you just go for every possible case and now here you know you have zero uh because the first character is one you handle that case that mean the first character is zero and the rest is some random junk and then now this is basically the idea right so then now the random junk we convert them all to zero except for the first one we get this and then we get make one more move to get to this and then now wait what oh yeah this has changed to one so yeah you make one move to get to this and then now you make again two to the X moves or two to the K moves I will here to get rid of the these to go to the suffix of zero right uh and this is the same here if the second digit is zero then you want to change the first digit to a well you just change all these to a one and then now that you're here you make the same moves as here and that's what basically what this does so yeah um I think this is a cener way to understand this problem it's just recursion um and this is something that happens in Gray code as well so you basically just change one bit at a time the way that I wrote this is technically n squar because we keep on allocating space and stuff like this um it makes this function o of n instead of O of one but you can also just keep track of an index and that would be fine right because we only look at the suffix right so like in the same way they use dynamic programming uh but yeah uh but that's pretty much all I have for this one this is I think a better understanding of the problem or better understanding of the solution so let me know what you think uh if done slightly more probably this is linear time and yeah linear space linear because n has uh log n Bits And and we do this amount recursion note that every time we do a recursion we take we remove at least the first character uh right so yeah anyway uh that's all I have for this one let me know what you think and you can watch me in the live today in November duf the struggle that I did and try to figure out the pattern matching I am just out of it so uh yeah let me know what you think and definitely let me know if you have questions and please your question should not be you can explain better that's that doesn't help anybody and you should know that anyway uh I mean I'm trying to I'm trying all right look anyway that's all I have for this one though uh ask questions here this court and I'll see yall soon thank you byebye or you could watch me solve it during the whatever now hey everybody this is Larry uh oh yeah there's an intro but yeah uh day dir of the Delo day challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's po I hope you like the intro I'm here actually now in Fallen uh in Tai Taiwan so uh yeah let me know what you think uh I'll have to uh H so tired so many flying and traveling anyway today's Farm is 1611 minimum one bit operations to make integer zero given an integer n you can transform it to zero using any number of times change to right mod zero okay change the if bit in the binary representation of n if the if minus one is set to one and this and I minus 2 is zero oh okay let's think about what that means uh what are the operations so you have two operations though change the rightmost bit so here you have some number and the first one is just change the last one from one to Z or 0 to one okay and then the second one change the I bit in the binary representation if I minus one bit is set to one and so if you have suffix like this you can change it from one to zero or 0 to one right okay uh that's interesting okay so I mean I think the first thing I'm going to do is play with small numbers and see if we can come up with something just uh something to play around with nothing else so you have uh zero is zero one is just going to you change it to from one to zero so that's one two is going to be what do you do right so you have this you're going to change to zero to a one you going to change this one to a zero and then change this one to a zero so is that three right I forgot I didn't count so okay so like this one two three so that's three right so two is three and then three is actually going to be uh this and then you uh change I change do and then it's going to be z uh so that's actually going to be two right okay so those are all the two bit ones so what's four rep this um well you're not going to make this a one because that doesn't make any sense so or I don't know maybe it does for now so this you're going to go to 101 to um 111 change this and then change this back to a zero and then now you can remove this to 10 right or and this is of course a two or yeah and two we have an answer for which is three right so this is this plus three okay and is a big number I guess yeah um H what are we doing here well it seems like this is a whatam I call what is that thing where you go for all the sequence from zero to one once what is that guy's name H I don't remember it's been a long time but there is a there is um there's a thing where you always uh change one bit and you can go all the bits and with this way it seems like uh you know a naive first try or at least mentally is kind of what I did right except for now it's going to be like a breath first search thing can you do this in Reverse what would be the reverse of this right 01 out of one I don't know maybe there's a way to do it but it seems very confusing but okay but it seems like Okay so let's say 0 is zero say one is going to be one but then 10 is going to be three 100 is going to be 7even right because now in a way this is always the worst case right this is the worst Cas is because in order to remove this one bit you have to basically convert because um yeah so to get from here um you have to get to here right I mean yes but what's a better way of thinking about it well the way that you have to think about is that 100 goes to seven because it basically reaches all the other possible numbers before hitting the uh the two all right so this should be seven and a th it's going to take all the other numbers until I mean if I have to guess this is going to be 15 but okay so we have some pattern about this but then now how do you do the intermediate stuff right we have some powers of two things um which is fine so may I'm not off by one can we combine these like okay let's say ref I don't know 111 right what's another way to decompose this well we want to go to 110 which is actually the next one but it may not be I mean okay I have a feeling about it but I'm still trying to figure it out a little bit how to do it um I'm trying to figure out if there's a easy way to decompose it using the things that we know so we could kind of build recursively um can I go to one do I need to go to one what the is the well I think there's like some recursive thing right so okay so let's say you have this 111 what are we trying to do well we're trying to go first to one 100 and to go to 100 we have to first go to 110 right because to um so that we can make this into a zero and 110 first we have to go to 111 which doesn't make sense hang on this is really weird I don't mean like that so 111 we want to go to 01 0 or maybe 011 what is the next logical jump I think that's what I'm trying to figure out like okay let's say about 111 we want to get rid of this number right the leading Z one so that means that we have to go to least this number so that we could get 110 and then remove it right does that chiz let say we have to it I mean that it's a very particular example then what do we do then the next number that we're trying to do is of course 1 0 whatever it is matching and then now we can remove the one and then we know what this is in theory but before that how do we zero these out in what order do you zero these out um let's remove a zero for now in this case in order to remove this one I have to make this suffix zero is right and in order to make this a zero we have to make sure that all these are well just one0 0 right can we add them up okay so for example the first thing we're trying to do is get to I guess this is already good because then oh no now what am I doing so we have to try to get to here right then now no what am I doing this is a hard one I mean because I think the way that i' I thought about it is just figure i' I thought about it is just figure i' I thought about it is just figure pattern matching but I'm trying to figure out a more logical way other than pattern matching CU you know for explanation pattern matching like pattern is not very interesting but I think is something like this where you're like doing this inductive thing but I'm kind of dranking out on it today so to remove this one we have to get to right how do we get here well we get to Here by first getting to here right cuz if you get here well technically you get to here and once you get to here then now you can turn this off and then now you could recursively do this you know figure out the suffix is that it then it's just one bit at a time for example if it takes three what the suffix on this right so in one move you would do you don't do this do you no because then oh maybe you do in one move now you one move two move three move four move and then you do the smaller on wait what is the first move would be this is kind of hard right you actually want to do okay one and then now oh wait no do you no you do this and then now you have to change these two zeros somehow and you know how to change these to zeros this is uh a set number sequence now you do this and now you change this to a zero these two zero again we could figure that out it's like 2 to 5th minus one or something and then you have zero right and then now you have zero and then now you do this okay I think I get it maybe let me try again I mean I'm trying to like get it understand it enough to be able to code it right it's not enough to uh like okay so the first thing we want to do is and was that even minimum I don't know all right so and then now you have this what do you do well now you do this and then now you can turn the then and then now you can turn the suffix a lot of moves and now you have this thing and then you can remove the Zer now you have this thing well now you can remove this zero but is that true that I can always moove these zeros am I making that up now I mean it should be okay yeah it's the same as just this answer it now you do this and now you have this which then you do this and then now you this still don't have a good formulation of it though why don't you do this and then why don't you just do this oh no you can't I see so then now you have the suffix if it's this then now you can turn this off and then here you can turn these off so I think the special cases if you have ones in a row maybe I just maybe that's the part that I was confusing littleit let's say you have a lot of ones but happen uh well first you have to create a zero so only way to do it is going do the zeros and now you have this then now you can take this off then take this off well I'm trying to think which one makes sense like should I go I mean this also Logic the other way should I go here and then we move or is it just like remove right H that's interesting actually so let's say you have one one11 let's do a smaller example so I can kind of work it out what the best answer is maybe right is it to go to and then take can did I make that up I didn't make that up right cu well then you go one and then you go zero right and now you could do this but you don't want to because you actually should take the this for first you could take the zero and then this right h maybe I need to play around with the examples more I think I'm not my intuition is not very good okay so then now let's say you have thousand I just assume that you can go to do the one and then this is the sequence that we're talking about and then uh right and then now this goes to 100 which is this thing which is Plus 8 or plus seven maybe depend on how you want to count it is that right I skipped this step I think uh this goes to D and then now you and then that's okay that's why it was well it just looked weird um and then this is 100 so if we have something like this we definitely do not take this off CU if we take this off so basically we always want to take the biggest digit off first and the way to take the biggest digit off first is just by setting the second bit to IE and I feel I get it but I still don't know the this is kind of uh I think I understand the problem I don't think I missed anything but it's just a hard problem to reason CU let's say you start here right then now you want to get rid of this one so you're trying to get to well here how do you do the moves also I missed one missed some steps this actually goes to that's why I got confused here and then this okay wait did I get everything this time so let's say you're here you want to get to here to get rid of this one um well you that's not so bad well let's say you have some random number how do you do it well we want to go to here and you go to Here by zeroing this out first so that means that you want to go to this first man I feel like I have no idea what's going on what is that word I was thinking named after that guy who plays with these kind of sequences uh hemming oh I guess that was yesterday's thing right hemming distance and the hemming cycle or whatever it's called and of course it can get very big so given that n is very big we cannot just simulate even do well I mean simulator is not necessary we know how to do like here we just have to figure how to get here so prob R this one but here to get to here you have to go to right and you get to here but like what is the formal way of doing it or formal way of describing this is it just taking the last bit of one at a time like okay let's say we go here right that's not even true you can take this last bit up because that's actually the move before this you want actually to take this off and then here and then now you can take this out um H is still there's some stuff with consecutive ones that I think I'm not understanding I'm adding zeros and that makes it easier let's say have just ones what am I doing right well here uh you it goes to if nothing else this is one move and then now you can remove this and then now you can do this and then now you can remove the suffix right and then do this I guess that's okay but what if you have odd numbers right so let's say you have this instead of your input uh okay then now again you match I guess you just do this H is that right let me play around with this for with this idea of matching ones okay so what if you have something like a zero here or even just a zero here what do we do uh okay first we can even this out one operation and then okay fine now you have this you just take this out okay I guess that then you don't even okay fine okay I think I see the pattern but I feel like I don't have a good understanding of it so maybe we'll have to read up some an later so okay so okay so then now moves isal to zero right let's just say we strain made it into a strain no what that just make a bit thing right so uh okay fine bits you can write in a number of ways uh while n is greater than zero this is pretty hard I don't know if I can uh I don't know if I can explain this one to be honest if it's right if it's wrong then I definitely can't right uh okay so then now okay um for I in range of length of bits right if bits of I is equal to one and bits of I + 1 is equal to zero one and bits of I + 1 is equal to zero one and bits of I + 1 is equal to zero then we just remove this thing right let's just do this way if I + one is qu equal to n or this then now we just remove the Sur because we assume everything we seen before is Zer right so then now moves be added to um 2 to the power of IUS one maybe so one yeah two okay fine right uh and then else if it's a zero we just ignore right um but then there's an L of if this is a one then we take one move to set I + 1 is equal to zero one move to set I + 1 is equal to zero one move to set I + 1 is equal to zero oh and then maybe I should change this a little bit right so if bits of I + 1 is little bit right so if bits of I + 1 is little bit right so if bits of I + 1 is equal to one maybe this logic is a little bit easier right then we take one move we set it to zero and then else after that we zero this out too right all what so we make one move to uh so you have one you take one move okay and then two to the zero oh this is zero I forgot whoops uh okay fine the first digit should be plus one okay and this what no h I is zero oh I see no I mean do I see so for one you just make one move right isn't this two to the one I'm looking at the white case why is returning four let me double check some stuff okay now that's what I expect so okay if it's equal to one and the next one is a one which it is it moves equal to one I + 1 is equal is it moves equal to one I + 1 is equal is it moves equal to one I + 1 is equal to zero and then this never happens right what is going on H this is pretty hard I don't know if I can explain this to be honest even if this ends up being right uh even though I'm obviously still struggling but why is this uh I thought we set this to be zero oh this is not n this is link for pits and this weapons when I mix stuff okay um I'm just baging on the keyboard hope oh oops okay so we definitely have something wrong so that's good I guess I mean it's not great but at least it's something she might got this one right there why is this wall need smaller cases okay so I'm W for a lot of things so okay so 10 is going to be 10 and we have 18 we expect to 12 what is 10 uh 10 is this number so we have yeah we do expect 12 so what am I doing here so 10 first we try to get this to be a zero there yeah so then how many moves does that take that takes three moves so that now three moves later over here is that true yeah one two three right but then why do I have this thing is just like really weird then oh no one we wouldn't get from here to here and then subtract it off okay so this is very weird for me or maybe it's not weird but it's just okay now what now how did I get 12 from here was that and my logic was that here oh here we can maybe I missed this step I did miss a step I think I missed a little bit in the understanding because basically so we have something like this I was just saying that you can take off the end like first I take this and this right but here already you don't just do remove this let's say this is already zero then what right you remove this by well you have to set the next one to one and then remove this so yeah so now you set the next one to one and then you remove this and then now you can set this one to zero and then you will move this now that doesn't make sense how do you get rid of this suffix again do you get okay here you definitely want to get rid of the suffix but actually right and the formul is right but like for example here you wouldn't get rid of the suffix You' get rid of the prefix right suffix You' get rid of the prefix right suffix You' get rid of the prefix right so what happens if you have a so maybe my zero case as well if the next number is a zero you remove it set it to a one you set it to a one like okay from here you want to go to Here by making one move and then get rid of the 10 and then the suffix okay so that means that if you have a one but the next bit is a zero does that make sense so I was doing it the other way actually something like this I go oh I have something like this I go so and then now we have a thousand but that's not that's what I guess that's the odd number case that I was wrong about even number case I think it's fine it makes sense right so let's say you're 10 hey well I guess that's not even but uh but let's say we have um 14 right like 14 is that right like my is my test case right no because basically you have these ones you set this one to be a zero and you should be setting this one to be a zero I think I'm just trying too hard to pattern match I think I need to kind of go back to First principles and kind of restart the thinking a little bit um the idea should be that if we're doing first principle the idea should be that if okay let's you take the first two bits the most significant bits and they should be they should look like this so no matter what it is you should convert this to here and then remove the most bit and then here is just we have an answer for that one okay and if the first two bits stop like this then you still convert it to this right and then is the math just to kind of figure how to get to there here it is just um you know yeah if we go from left to right okay we look at it CL two bits fine and then now this what does that mean that means that we have to convert this to zero and we can R this to a zero by looking at the last two bits and I can rot these to zeros right and this we can do it the way that we've been doing and then now we go to do somehow by flipping this bit how much effort is there to get this one in okay let's about this and now how much effort is there to take this one and move it here what's the math on that the math is yeah I mean have obviously have to get to here and then now how do you get to here um by getting to so that we can so something like this and then now you have so this you FP how many is that like for example here you actually don't try to go to a th right trying to go to 1100 so basically the next thing makes sense okay so you trying to go here and you go to Here by I mean this is also just equivalent to converting this to zero right so then now we're solving for this one two zeros and in this one we're converting it to two to I mean we want to convert this to here but and here how do we zve this well we're trying to get to right and we get to Here by going to do and we get to Here by man I am just very lost today for I think I'm just trying to figure out how to get the math from here to say here even like how do you solve this in a structural way I mean we get to here okay fine or even here you how you want to say it fine but how what is the recursion right and is this right as always on day that you're trying to get a quick finish that uh I need plug in my power soon like okay let's say we have this right you have this right so what does this mean this means converting it to this and then going and then this to zero what does that mean that means that if we have this we're trying to basically subtract out we take moves to go to well let's do one at a time right maybe is it what which direction am I going so you okay so let's say recursively when we want to get to here well we want to get to here so that means I have to get to here and to get to here we have to go to here maybe and get to here have to go to there and then have to go here so there is some like prefix thing going right in that you're trying to go to here and so you're trying to go well this is just the initial so you're trying to go here and then here in a way you are taking like but then you getting to here not the not this which is what I guess I am well on what's 15 14 again 14 right and I'm trying to get to so then first I'm trying to get it here well I guess I'm already here so then now I'm trying to get to here and then I'm just one move from here right there is like a prefix e thing to do but I'm not quite a for to calculate where this lies maybe I just uh maybe I'm just going to have to figure out a pattern to it I mean I don't know whatever I'm doing isn't working right so yeah so this has four right and halfway this is this all right and this is going to be eight halfway is this is that right that actually is not what I would have expected maybe and here the two I guess just matches I guess I have to really Bo for it I also need to get a power supply soon so I may pause for a second what is the prefix that this goes I mean this is just this one and before right no that's not true has an extra zero so then now it's going to right so is dis of shifted by one on the most significant bit right and this goes to right well no this goes to here pilot yeah this pattern is less obvious to me right what am I adding stuff hang on oh no it's this and then now you're trying to get rid of the 100 so it's not okay I see but here you have to so then now this is in reverse trying to get rid of the 100 this is ridiculous okay fine uh going to pause for two seconds because I need to get my power supply to plug in I didn't expect this one to be the S to be frank sorry friend I don't even think I have a good explanation but right uh trying to not show you that I'm not wearing pants I'm just kidding but I'll be right back all right just have to get my power supply I was just charging my uh my phone was too lazy to break out two power supplies earlier okay I think now I see the pattern but wow that is a tough pattern right so the pattern isn't what I thought it would be but basically okay what is the pattern right so basically here we so there the Symmetry is that if you kind of draw it in a different way right um and then here if you kind of reverse this to right so that's basically the pattern is that and then now you go to the 1,00 that and then now you go to the 1,00 that and then now you go to the 1,00 which is here say and of course you can draw it in the other way if you like right and then now you do the same thing for hundreds okay and then you can kind of see that uh we can do one bit at a time and this takes you know 2 to the ey or whatever it is kot Tech right okay so then now the question is what happens okay so we if we're at 10,000 and we're at 11,000 if we're at 10,000 and we're at 11,000 if we're at 10,000 and we're at 11,000 or whatever in binary you know that's good and fine um how do you uh how do you go from here to um like let's say right here how do you solve it right like what's the answer for 10 like for that number I guess there a couple ways you could say it um you could go to the left to 10,000 it um you could go to the left to 10,000 it um you could go to the left to 10,000 like and then subtract the difference or whatever right so this number is just equal to there is some symmetry in here in the this and that so this is just equal to getting rid of 10 uh but from 10,000 right so like the 10 uh but from 10,000 right so like the 10 uh but from 10,000 right so like the number of moves to get rid of the 10 the binary 10 would get you to 10,000 and you just 10 would get you to 10,000 and you just 10 would get you to 10,000 and you just subract that from the number of moves to go forward from there okay but can I generalize it a little bit better what about this one same thing but so we're trying to get rid of the one which is I guess easy in this case but is there more generaliz way of doing it while thinking about it okay this one I guess maybe it's okay this one we want to get rid of the 111 maybe that is a easier way to think about it okay we're trying to get rid of the 111 and then the 111 if we already have to map which we don't I mean it's just this thing really okay we have to 11 then now we can yeah we go left to 10,000 fine when 11 10,000 fine when 11 10,000 fine when 11 we I don't know also go left so we get rid of a 11 from 100 so we add 100 and then we subtract to 11 okay someone like that right maybe that's a little bit easier okay let's think about what that would mean yeah let's do it the other way just reverse this just like Miss would say right then now okay not even we just count down and then now basically okay so now we're 10,000 so we add 10,000 so we add 10,000 so we add 10,000 um and then we subtract the rest right so that now almost like uh what's it in uh inclusive exclusive right that one yeah so now you FIP right and only if this is um this with GL hopefully I didn't I actually should have tested some edge cases I was just I'm a little tired how did I did it in previous years that lad is smart and that is not understandable okay so the prefix I get it okay oh man this is actually really cool wonder how long change the first P lar is smarter than I am I'm getting old oh gray code is the thing that I was thinking about I forgot the name I mean there's a Heming thing too and Dei deji thing but uhuh I mean I guess this was the logic I was trying to think but I don't know why I didn't just implement it like this is pretty cool though I think the way that I did it today is not very cool the first character is zero okay then just return that's fine the second character is one 10 we can change oh yeah that's basically what I was saying but I don't know today though I don't think I quite got to doing it like this maybe I should have uh do the enumeration I think that's what I was half going through but I just had trouble kind of making that one extra step yeah I don't know I don't like the way that I did it today to be honest and I think I just like I said pattern matched a little bit uh I think if I were to kind of explain it um yeah I think that's uh okay I'm going to end with this because I'm going to just do the explanation a little bit differently than what I just did so yeah uh but this is going to be linear time constant SPAC is or linear space Maybe dep you want to say uh because n is the size of the output and bit is the size of the input uh I don't know but yeah but I think the idea here is that okay I mean I think I basically have the same idea I don't know that this code really can raise that but basically here for whatever this is I just basically yeah try to get to the pre number and or the next number depending on where the thing is um but it's always going to be okay so this we go to the left by 111 so maybe another way to think about it maybe another way that I could rewrite this in a way that I think is more intuitive given what I had it's something like um yeah maybe I didn't want to do it this way I guess we you know um yeah okay so this is a string right so then no I mean I could I guess I couldn it but I think I'm just going to but this ends up being the same thing as my old my foury old solution anyway so uh so I think I'm going to explain this one and then um yeah I mean it's kind of what I was going for and that's what comes out that's what this reduces to but yeah anyway that's all I have for today let me know what you think stay good stay healthy to mental health I'll see youall later and take care bye
Minimum One Bit Operations to Make Integers Zero
making-file-names-unique
Given an integer `n`, you must transform it into `0` using the following operations any number of times: * Change the rightmost (`0th`) bit in the binary representation of `n`. * Change the `ith` bit in the binary representation of `n` if the `(i-1)th` bit is set to `1` and the `(i-2)th` through `0th` bits are set to `0`. Return _the minimum number of operations to transform_ `n` _into_ `0`_._ **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** The binary representation of 3 is "11 ". "11 " -> "01 " with the 2nd operation since the 0th bit is 1. "01 " -> "00 " with the 1st operation. **Example 2:** **Input:** n = 6 **Output:** 4 **Explanation:** The binary representation of 6 is "110 ". "110 " -> "010 " with the 2nd operation since the 1st bit is 1 and 0th through 0th bits are 0. "010 " -> "011 " with the 1st operation. "011 " -> "001 " with the 2nd operation since the 0th bit is 1. "001 " -> "000 " with the 1st operation. **Constraints:** * `0 <= n <= 109`
Keep a map of each name and the smallest valid integer that can be appended as a suffix to it. If the name is not present in the map, you can use it without adding any suffixes. If the name is present in the map, append the smallest proper suffix, and add the new name to the map.
Array,Hash Table,String
Medium
null
1,751
hey what's up guys this is john here so today uh let's take a look at this elite called problem number 1751 maximum number of events that can be attended number two so you're giving like an array event right where we have start day end day and the value so basically the ice events start at start day and end at end stage and if you attend this event and we can get this value and you're also given like an integer k right which means that the maximum number of events you can attend so one thing to be noticed here is that you can only attend one event at a time basically if you choose event to attend you have to wait until this event is finished and also the end date is inclusive so which means that let's say here's the example oh sorry and then you need to return the maximum sum of values you can receive by attending this event right so what does this one the end date is cl is inclusive mean right so basically separation we have three events here right so the first event starts from day one and ends at day two and this event start also starts at day two and ends at day three so it's it seems like you know the two and two the ending date and starting date is the same of these two events but that means that you know we cannot once we attend the first event we cannot attend the second event just like this one because it's so the first event it ends like this day right so we have to finish this day so basically if we attend uh the first event so the earliest day we can start another event is a day three here which is this one that's why uh we cannot attend this one anymore so yeah basically that's the idea right of this problem and then so for this one for example one here so we have the maximum we can attend is the values we can get seven by attending event zero and event one right so and here we have some other examples and here for this one the max value is 10. so all right cool so for this kind of like interval problems for the start and end it's always uh like we should always sort basically no but uh by what by which uh order right by start we either sort by start date or by the end date so for this problem uh we should sort by the start date so why is that because you know because the way we're solving this problem is that let's say we uh we want to uh let's say we attend this uh event zero right so this is the event that zero we're trying to attend and after attending this uh this event zero we need to find basically the first uh i mean after the event zero uh what's going to be the next event we can attend okay and to be able to find that you know basically we that's why we need to sort by the start time because after this uh the event we have ending date and then we can use that ending date to find the first available event that we want to attend that's why you know to be able to check that you know we need to sort by start time and for each of the event you know we have two options basically you know basically we can either choose to attend this event or we don't attend right so if we don't attend this event basically we can just uh throw the problems to the next state so which means that now and also we have this kind of k events limits here so now it's kind of obvious that we can define our dp functions here basically dp of i and k here and so this one means that you know the maximum values the maximum value we can get right we can get when at ice event right and has k events left sk events left so that's basically the definition of the dp here right and so how about the dp transition function right so basically two options right so i mean the first option is that we at ice event we choose not to attend this current event okay so which means that the answer right so we have the first answer will be the dp of i plus 1 right and then k because if we choose not to attend the current event which means that we can start the we can uh check the next event which is i plus one and then the k doesn't change because we didn't change that or right or we can the next one is what it will be the max of the answer right plus what if we choose to if we chose to uh to attend this event so first we can get the value for this event right and then like i said the knight the next ep the dp is what this should be the next i here right and then the k will be k minus one because uh we have k minus one events left that we can attend and this next ice is the thing we need to find because like i said depending on how long the current meeting will last right we might need to be we might need to skip some of the events down the road right basically the next i is the first event that we can attend and from there we just do the same thing we can either choose to attend this next uh event where we don't uh we don't attend it but the problem is that how can we find this next eye right i mean brutal fourth way is that we just simply loop through uh we simply loop through the uh the event starting from i here and then we just you know returned the first one whose uh who's the start time is greater than end time right remember it's a it's in inclusive so for example if it's two here n times two so we need to find the first uh event uh starting from i whose uh start time is greater than three which is starting from greater than two which means starting from three so that's the brutal fourth way and depending on if the this current event is so big right so i mean that i think it's going to be a of un square time complexity right because we are doing like a linear scan okay but we can do better right because obviously you know since the all the other events that they're sorted already right we can simply do a binary search right on that on top of that basically we just use the end time we use the current end time and then we do a binary search on the on this uh on this assorted event then we can quickly find the next available events after this event right cool i think that's it so that's everything and to do this and we're using a dp uh top-down dp right with a memorization top-down dp right with a memorization top-down dp right with a memorization and then let's do it so the code is pretty short actually so first we sort the events right so by start time and then by end time and then we have n it's going to be a length of okay and then we define the dp right so the dp like i said is the current event i and then we have a remaining k here so we'll do a lru to help us do the cache okay and then here we just return the dp of zero and k right because we start from the event zero and the at the beginning we have k events left so some like uh exit point so basically if i is equal to n right which means that uh which means that no uh there's no more events left then we simply return zero or like another one right so if k is equal to zero right we also return zero it means that there's no more uh available event that we can attend then basically not attend event i right so we have answer equals to dp of i plus 1k right so that's that and then the next one is a 10 right attend event i so to attend event i we need we first we need to find the next i of event so we do a binary search bisect left so the events right research on the event so one thing to be noticed that you know in python since event is like uh it's a list right you cannot search a integer against the list they have to be the same type so which means that you have to use you have to convert that end time to be the uh to the list basically this event i one is the end time of the current event right so you have to convert this one to a to an integer sorry to a list and then so that you can use this one to search but remember so the third the end time is two if we do a by bisect left okay but we cannot use this uh this two as a starting time because the start the ending time is inclusive which means that we have to do uh this one plus one which means that the first available event has to have this uh has to have the uh the start time greater than uh at least to be a two plus one which is three basically we're searching for the next event the first event whose start time right is at least three because this is how binary search works right so let's see if we have one two and three right so uh we have two here right so we wanna search the index for this for the first uh element who is greater than two right basically and how we do it so we do a binary search we do a bisect left on this two plus one which is three that's going to be the first uh item the first index whose value is greater than two right that's the how this by a bisector works that's why we do a two plus one then we'll get this index so and then after that i think the writes just like we still answer equals to the max of the answer dot uh so first you know we need to collect the current values right by attending the this current events it's gonna be event i dot 2 right that's going to be the value plus the dp of now we the starting time start index is i right and the k will be k minus 1 right so then we return the answer yeah so i think that's it right okay run the code yeah so it passed so for this like a binary search attempt right so basically the uh um the time complexity for this one what's going to be time complexity for this so we have k so we have like this how many states we have the total events the event lens okay so as you guys can see right so the k times event length is less than 10 to the power of six okay so which means that this one can guarantee that you know the total state of this dp will be uh will be less than uh so let's say the event length is its n right so and we have a k so the total state we have is n time times k and n times k is uh it's not will not be greater than 10 times 10 to the power of 6. so the event is fine now to find this binary search right so this one the obviously is the log n right basically so the total time complexity for this one is n times k times log n all right so we search the uh we use the login to search the next available i here yep so i think that's it right i mean um you know uh another like classic in interval a plus dp problem right so again right so if it's to solve this kind of problem we have to decide like if either we want to sort by the start time or end time so for this one since we're trying to use a top-down use a top-down use a top-down approach which means that you know uh if we and also the uh for this kind of interval problem you know uh we have some a common another common approach is that we also uh would have two options basically we either attend this event or we don't attend this event and so for this problem you know to not attend the event is simple and but to attend this current event we need to find the next available the next uh basically the next uh event that we can the first next the next event we can attend so to find that uh a brutal fourth wave will be a research we scan from the current eye and until we find the first event whose start time is greater than the current event and end time or even better we can do a binary search on that and then we just uh do another dp on this one right cool i think that's everything i want to talk about for this problem and thank you for watching this video guys stay tuned see you guys soon bye
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
56
Hello friends, welcome to the new video, question number 56 is a question of Amar Jain Travels medium level. This question has been given in basic clearance category. It has been asked on Facebook, Amazon, Google, Apple, Microsoft, Payl and big companies. Let's start with this. Basically, you have been given a number of intervals in the input and you have to match as many overlapping intervals as you can, so let us quickly understand what to do in this question and we have to return all the overlapping intervals as they are. Let us quickly understand how to do what we want, so this is an example, in this we have four intervals. First of all, I would like to tell you that this interval is written in 108 wards, why I wrote it in shot A so that we can see which central is starting first. Which one is starting later then it will help you to chill out so first of all if sorted in is not supported then you can start first interval second first is starting then to 6 then tab and how are these shots their starting Point you will see is 128. Keep this shot on the basis of the starting point of these four intervals so that we can see which one is starting first and which one is right after. So first is 113 and second is 226 so we can see clearly. That is, our two six started even before the end of 130, so basically these two intervals overlap and we have to match this. Now let's look at neck central 80 and 1519, so you saw that the second was 1226, after the end of that. Our one TAN has started and after the end of Airtel, our 1519 has started, so only the first two intervals are overlapping and the third and fourth intervals are not overlapping, okay, so after one UP, what? There will be 1342 tips, if you march, it will be converted into a family tree. The most extreme point is one. If there are subscribed points, then it will die. The rest of the intervals can be copied as is. Okay, the logic of marching is the logic of marching, they are discussed. Let's do the first interval, you see, take 123, then the end points of the first interval and the starting point of the second interval, we can compare them and check whether these two are overlapping or not, then basically you have to see that Is the starting point of the second interval less than the end point of the first interval? I would like to repeat again that the starting point of the second interval is our business. If it is less than the end point of the first interval, then you can search. Ok. And how will we march after that, once we understand, first of all you compare the interval and you have merged it, okay now after marching, both these converters become F-16, now again you have converters become F-16, now again you have converters become F-16, now again you have any interval at the back either Is it dead or was your last interval some winter, if you compare it with the new interval then somewhere you must be getting an idea as to which data structure you can use because we have picked our previous output. What we have to do is we have to see and then we have to either pepper these two or else we will not do the patient in the same way then we can check the next two intervals then we will use the step that if it is male then this test We will put it in our and the next interval will come then we can do it at less than the margin travel because in this pack such a date face which is dead last in food is the previous input in the strat which is very successful, for basic we can compare it with that. I will show you once and how the steps can help you in this way you will see that we can put the first interval in the set and we can start from the second interval. Now whatever we check in the central We will compare with what will be in the last intervals tag, either these two will be patients or they will not be men, so basically after spooning it and mixing it, we will put two in the set that our merge has been done, after that we will stock our next interval. We will compare it with our interval reading in whatever step. If it is not matching then we can directly put it as state topper because we know all these were in sweaters. Now the next interval which is going to come, we will directly put it from top ten. We can do it at less, so we are using the step that we will compare with whatever is there in the previous till and we will keep doing chili, so basically 1510 birds will not be there, then if you put the statement, then this is our final interval, we have four intervals. From and which in the output we will return three intervals 2 and travel yours are merged then you have seen that in the test it has gone to the bottom so when you print your answer then that will have to be printed first then 108 so it will be in the angle How to do Intuition Lighting Spoon If you are ahead, then once quickly put it, how to code it, so first of all we had discussed which are our intervals, so basically I will write this in the smartphone because if they are not in the opted for then our comparison will be wrong. It is possible that first of all we will have to use them from the starting point of all the intervals, so I will write a function according to that, we will start them. Interior does not compare, so we will compare all the intervals of both of them, starting from them. After comparing the points, we sort them out so that our comparison is not wrong and we had discussed that if we take the help of mixer one, then we make tags of good type or do you know how each interval is defined? You have an interval array which has two elements inside it, a starting point and point, so we are going to start the interval in it, so you can write something like this so that we write girl to new stock. Okay, so now you can tell us. What has to be done is that basically we can put the first interval in the stock, if there is something in the list in the tag to compare, then first of all we can query in the set. Now we can query the first interval, then we can query the first interval in the tag. Now we have to compare with the second interval, so let's start with tie 0910, copy all the intervals, whatever they are, i plus, okay, so how will we do the village, so basically now we have to find out the second interval of ours. What is its start point? So I write down the start point to that point. Why did I name it that it is basically the second interval and the one that I added in the set is the first interval, so its chart point will be so that it is of this type. Gaya I and Jo can be written and in the same manner, the second interval is this measurement. Let's write down its end points. Hello, we will take end point two because the second center line point is needed. We will name it in this manner. Okay, the first interval is that text. If it is inside then we will have to pop it, so you and I give a name, you write the fixed dots, okay, so now after this, let us write down the starting and ending points of this also once, so we give this 10.1 first. If so we give this 10.1 first. If we name the end point to endoid one of interpol, then from this plant we will take out the one from the power array which is at zero position, that will be the starting point one, so first of the interpol, I have defined the starting point and the end points of the first interpolation. Took so that you can compare, how to do it on less, now these intervals were like seventh, our second interval was our you six, so we have contacted this three with this two, so let me write again, what is the condition that we have to write which is first. You can take the end points of the interpolation if it is greater than the end points of the first interval or is equal to the starting point of the second interval, then here you will have to match the mails, you do not have to merge, okay, so in this way we will write. It is better if you die, if you don't do it yourself, then if you have done this Paul wrong, then first of all we will have to pause it again. If it has been done wrong, then it has not been given flower program numbers and we should also put the current interval in the tag so that it If the same interval can be compared in the next time, then we also put the interval which is the current interval, so that next time we can compare the next intervals with this current one. Well, if there is a march, then how will it march, then to merge, we will have to create more interior, it is Majumdar. I live in this, you will have two elements, 1 will be its extreme left wanderer, our starting point will be one, well, the extreme right boundary will be K. If I look at the example here and tell you, I will take 1213, your two will be six, then the extreme life will be interwoven. The extreme right boundary will be your end point two. What do we have to do whether it will happen or not Let's take WhatsApp control, we can take 213, it will become of patients, hit one, okay, in this case I wrote end point two which is wrong, in this case end point should be one, so we cannot see it by ourselves, here we have to You will have to calculate a max, you have to keep that the end point two is greater or you can write the end point of simple or if the input is made, then I mix the ends of both and make the maximum end, which one is greater, okay? We will have to compare this, 10.1 will be the lowest We will have to compare this, 10.1 will be the lowest We will have to compare this, 10.1 will be the lowest waste because we started first and it is clear, so you will do this chilli and after mixing, we will put it in the check so that next time we can compare this, I think. For animals, now we have to quickly create the output because till now we have filled in the stock, so this is all we have and after that we can return it, so quickly read the output week to see if something will be typed. So we will mix it later, I will write this as the output, now basically I have to blank the step and do nothing. Whatever is the side of the stock, we have that many intervals, that many rolls, okay and the columns will be our two because exciting than that can. Let's quickly write down the point, break it and feel it upside down, if it comes out upside down in the set, then in this also we will feel the element from behind, click on the last position that it will not be output, this loot don't length minus one is great think 1205 - - let's do it Now how we have to do it, 1205 - - let's do it Now how we have to do it, 1205 - - let's do it Now how we have to do it, you will have to poll, you will have to top the Acacia stock, so I am giving it a problem, so after popping that tag dot, what you have to do is output your, whatever is your output, put the starting point of 100 in it. Whatever else you are, we will put zero before or before this lot is being typed and in the same way we can do it that here we will fill one and return the one which was in the last, now quickly once. I compile this, there will be some typo errors, so we will mix it, once we see the mistake, Arya Stark dot size, I have to put the thing racket here and run it again, once I submit it and check it. If there is any mistake, we will fax it. Our fast is wrong, so let's take a quick look at what is wrong in the logic. A small mistake has happened. Basically, if the end point of the first interval is more than the starting point of the control, then the match will happen. If you want to do this then there should have been one here, I had written two by mistake, I will submit it once more and check it is not getting submitted, then you will see that this time our code is submitted more successfully, now let's talk. Complexity What can be the complexity of this code? First of all use your shopping function. At the top we can assume if we have end intervals and in each interval you have two elements one starting point and 1 end points. So end numbers are our Pass and your shot then you can directly say graph in log in the complexity of our function can be hello can and here we have processed the element what and travels and more than this you can see here But we have done macromax and internal process, so we can directly say overall complexity and law and if you use extra space, in the check also you can fold total intervals, then you can also say space complexity. Our Bigg Boss will be added if Our total number of if we have intervals Thank you very much for watching this video You can subscribe this channel You can share the video You can like Thank you very much E kar do MP3
Merge Intervals
merge-intervals
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. **Example 1:** **Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\] **Output:** \[\[1,6\],\[8,10\],\[15,18\]\] **Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\]. **Example 2:** **Input:** intervals = \[\[1,4\],\[4,5\]\] **Output:** \[\[1,5\]\] **Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping. **Constraints:** * `1 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 104`
null
Array,Sorting
Medium
57,252,253,495,616,715,761,768,1028,2297,2319
1,991
1991 find the middle index in array question so we are given a zero index integer array nums find the left most middle index that is the smallest amongst all the positive ones so a middle index uh it's also given about the definition of the middle index so what is this middle index mdl index is an index were numbers of zero numbers of one plus uh numbers of zero plus numbers of one plus etcetera plus numbers of middle index minus 1 will be equal to number numbers of middle index plus 1 plus numbers of middle index plus 2 plus etcetera plus numbers of nums dot length minus 1 so if we find uh the middle index at the very left end that is if middle index is equal to 0 then the left side sum is considered as 0 and the same thing is applicable for the right side that is if middle index is equal to num state length minus 1 the right side sum is considered to be 0 so return the left most middle index that satisfy the condition or minus 1 if there is no such index so let's check the example so first example uh the numbers is given as 2 3 minus 1 8 4 so here 8 the third index 0 1 2 three the third index eight is considered as a mid index because two plus three five plus minus one is four so uh the sum to the left of this middle index is four and right of the middle index that is four and those two sums that is the left part sum and the right part sum uh with respect to the middle index is same when we look at the second example uh here the 4 is considered as the middle index because to the left part of the 4 it is 1 plus minus 1 is equal to 0 and to the right part as it is already explained here if our middle index is num star length minus 1 then the right side sum is considered 0 so here the right side sum is considered as 0 and uh that's the 0 that's y of the index 2 that is this 4 is the middle one now uh 2 comma 5 so suppose if we are considered considering this 2 as the middle index that is 0 as the middle index then the sum to the left is 0 but sum to the right there is 5 so 0 is not equal to 5 so this index 0 cannot be the middle index now if we move to uh the next index that is 5 1 where nums of 1 is 5. sum to the left is 2 but sum to the right is 0 so there is no such middle index that satisfies our given condition in the question so the answer is going to be minus 1 s there is no valid middle index and the other special case is if we are having only single element we are having only a single element that the that single element will be the middle index because to the left uh it is 0 and to the right it is 0 so how we are going to uh do this problem so let's uh consider the first example a first example is nums is equal to 2 comma 3 comma minus 1 comma 8 comma 4 so uh here when we take uh the sum like 2 plus 3 plus minus 1 and 8 is the middle index and the right side is 4. so this is why this third index comes to be the middle index because here the total sum is 4 and here the total sum is 4 so lhs is equal to rhs that is left hand side is equal to right hand side suppose uh if we find uh what is the sum from this left to right like the cumulative sum from left to right let's say left cumulative so if we find such that we can check whether we will find any relation uh like uh whether we will uh find any induction to ah get the result so left some cumulative sum so the first value is 2 then it will be 2 plus 3 which is 5 then it is 5 plus minus 1 which is 4 then it is 4 plus 8 which is 12 and 12 plus 4 is 16. so this is uh when we consider the sum from left to right now same way let's also try a right to left so right cumulative sum which is equal to let's uh come from this right let's uh start from 4 and fill this array from right to left that is uh we start with 4 and then 4 plus 8 is 12 then 12 plus minus 1 is 11 then 11 plus 3 is 14 and 14 plus 2 is 16 that is what we are actually doing means we will be doing right sum of length that is uh actually we will be storing the right sum of length minus 1 is equal to nums of length minus 1 and we will be traversing from 4 i is equal to length minus 2 i greater than equal to 0 i minus and this right sum of i will be equal to right sum of i plus 1 plus num so 5 that is we are filling from right side to the left side so uh when we uh so this is the two uh values that we uh get after applying this so our left cumulative sum is 2 5 4 12 and 16 i write cumulative sum is 16 14 11 12 and 4. so if we check this the third index is uh we are getting as same value so it means that it's the equilibrium point that we are looking for so we just need to traverse again and just check uh for uh which of the index the left cumulative sum becomes equal to the right cumulative so after finding this we just need to find the index where left cumulative sum become equal to right cumulative sum so that's what we have to do in this problem so let's try this approach so uh let's uh deal with the uh single element case first itself if nums dot length is equal to one then it is just zero now what we are doing we need left uh part sum and right part sum so int let the length b nums dot length so this is a left part sum which is equal to new end of length and int row right part sum which is equal to new end of lines same as that of the input arrays length so now uh find the left part cumulative sum okay so left part sum of zero is equal to numbers of zero now we start traversing for in i is equal to 1 i less than length i plus and our left part sum of i will be left part sum of the previous element that is i minus 1 plus num so phi same way we are going to find the right part cumulative sum so right part some off uh as we told here we are filling from right to left at first the right most that is if this is our element so one two three four something like that uh we will be filling first from 4 then 4 plus 3 equal to 7 then 7 plus 2 equal to 9 then 9 plus 1 equal to 10 that is from right to left so right part some length minus 1 will be the very last element now go from right to left for in i is equal to length minus 2 i is greater than equal to 0 and i minus so right part sum of i will be equal to the sum of right part sum of i plus 1 the very first next element plus uh nums of i so now we filled both right part accumulated sum array and left part cumulative summary now we just need to find the index where we have equal value so for in i is equal to 0 i less than length i plus if left part sum of i becomes equal to right part sum of i we just return this i so if we are going to find any such uh index where left part sum of y equal to right part sum of i then that is our middle point our equilibrium point so we will just return this i otherwise we will not be going to find any middle index so we'll return minus one so let's check with other sample test cases let's submit so when we are talking about the time and space complexity here we are going through the array once here again we are traversing through the array once and here also it basically n plus n which is a big of 3 n which is a which is same as big o of n in case of space complexity here we are using extra space of size big of n and here also big o of n plus n it's big of n itself so space complexity is big of n and time complexity is big of n so this what this problem is
Find the Middle Index in Array
league-statistics
Given a **0-indexed** integer array `nums`, find the **leftmost** `middleIndex` (i.e., the smallest amongst all the possible ones). A `middleIndex` is an index where `nums[0] + nums[1] + ... + nums[middleIndex-1] == nums[middleIndex+1] + nums[middleIndex+2] + ... + nums[nums.length-1]`. If `middleIndex == 0`, the left side sum is considered to be `0`. Similarly, if `middleIndex == nums.length - 1`, the right side sum is considered to be `0`. Return _the **leftmost**_ `middleIndex` _that satisfies the condition, or_ `-1` _if there is no such index_. **Example 1:** **Input:** nums = \[2,3,-1,8,4\] **Output:** 3 **Explanation:** The sum of the numbers before index 3 is: 2 + 3 + -1 = 4 The sum of the numbers after index 3 is: 4 = 4 **Example 2:** **Input:** nums = \[1,-1,4\] **Output:** 2 **Explanation:** The sum of the numbers before index 2 is: 1 + -1 = 0 The sum of the numbers after index 2 is: 0 **Example 3:** **Input:** nums = \[2,5\] **Output:** -1 **Explanation:** There is no valid middleIndex. **Constraints:** * `1 <= nums.length <= 100` * `-1000 <= nums[i] <= 1000` **Note:** This question is the same as 724: [https://leetcode.com/problems/find-pivot-index/](https://leetcode.com/problems/find-pivot-index/)
null
Database
Medium
null
1,894
Scientist A Hello Hi Guys How Are You Commission Always Doing Good Welcome To Land Co Disney Today Will Drowned Medium Able To Send A Text Festival Replace The Channel And Dont's First D' Replace The Channel And Dont's First D' Replace The Channel And Dont's First D' Souza After Alarm Is Preserved Quickly Subscribe Believe Me It's Various Issues In This Win 10 I Don't Know It Is In The Media Person But One Thing Which Makes This Question On A Gay So Let's First Read Na Modya Ruh Aur Oil Earn So I Will Tell If Already Riots Will Tell You What They Do The Question Singh Find Out But divide also to subtractive brigade square 5257 more 6 - subtractive brigade square 5257 more 6 - subtractive brigade square 5257 more 6 - 5 16 - 511 but and over again started from 16 - 511 but and over again started from 16 - 511 but and over again started from the first saw Altendorf very he life of detail but also to separate discount reduce chop here again and again should behave 1111 my favorite 6 - 1st feb - should behave 1111 my favorite 6 - 1st feb - should behave 1111 my favorite 6 - 1st feb - 50000 but I don't know the zero ab lagenge to first will get 2019 will check the power of the weather tower what they have kids note hai tu dhatu avar chaupai mix and well wishes panch special guest hai wazir video mein dard So subscribe for this video 50 that your in president Dr from near this ministry students call 800 - 5 - three ministry students call 800 - 5 - three ministry students call 800 - 5 - three third - to 8 - 1725 5 minutes cea * * - that is - third - to 8 - 1725 5 minutes cea * * - that is - third - to 8 - 1725 5 minutes cea * * - that is - two words oo can win the election morning happy returns of Sentences with and safe at first individual not have enough of Sulabh Cancer Practice of I in the morning you are dedh hussain middle aged the number of times and a pan into the number of times which be happy times example Times of India has given this now Week and two times where protesters two time all first will have yes 211 till ignorance VHP and Gagan travels till fairer green beans from 11th 2100 murder traversing again no third time in which is the biggest you don't have been elected to not have any Bihar -40's not have any Bihar -40's not have any Bihar -40's more sacrifice value is the current of the Video then subscribe to the work not win the third time subscribe to that they are in this position's depot in 2013 that is between the Soviet York and University time parties which subscribe The Timed S Being Run in time limit which is the president of the question subscribe The Video then subscribe to subscribe our ki chaupai-si ki chaupai-si ki chaupai-si hua ki maine times chastity mitenge seats where to find solution surya liquid run in bhigo after minutes only one thing and five because dal in This and Subah to make a solution that the trend of an cannot be not go into this reason for not being run in time date is chain * times means the times between the times that is time date is chain * times means the times between the times that is the times VHP and Suraj Chowk Bihar To Travel From Times Day Thanks Isko Subah Can Do Dharma Hai Financial Solution David Goffin and Vijender But I Can Not Exceed Time Limit Mode On Kar Hai So I Will Give 10 Math Solution So What Is Done Here I am Just Right Here Some Water Have Done study like this day's heroes broke it heart current subscribe * * * * use mind and miner solution switzerland and icon 2005 but so bittu 500 index in english meanwhile can't move from zero Current is taken till 1000 clean hundred definition of current 40 means first one current is 1400 5000 * no sir immediately come first one current is 1400 5000 * no sir immediately come first one current is 1400 5000 * no sir immediately come off now most of the scars and oily run person missions to deposit welcome move through and daily return zero Sudesh Biotech S You Have Left A Drop Current Pimple White Pepper One Sided Last One And A Half Two Yes Ko Inside I Will Go Away This Is Not A Good Bye Having A Throat Is The Thing Superstition And You Cold Have Also Involved In This Life What Is The Date B Agunthi Silai Server Current Element Which Of Hi 1409 Details Element And Equitable Other Dutable Discharge Chaupai Is 500 Vs Thursday April 21 2011 Hum Ek Lagna Ko Sentiments 116 Ok Khedi Against Ek Date 60 Phase Idli Should Behave 11th Schedule Element And Travels To Admit Ka Mausam Dallu Against Be Effective Against For Winning A That And It's Current Ko Buy World Cup Hero I'm A Clown Blurry Pricing 102 200 Apr-11 Also Apni Ignorance Tabs Second 200 Apr-11 Also Apni Ignorance Tabs Second 200 Apr-11 Also Apni Ignorance Tabs Second And Straight Number Four Times The Number Of Times Melte Na Melte 102 101 Plugin Again Ko Alarms and Misses Current Voice Current 500 Kadar Doob next9news But in this case will find the value of which is the first Indian will destroy India going to take away the third time subscribe The Amazing spider-man well but Video then how to Election Episode 1500 No Voice No Duty Subha This Is Aware Of This Awareness In Tax Liability Daily Ato 100MB Left Side Suryoday Defiance Samridh So What Is The Answer Subha This Will Give To Face Ineligible Ne Twitter Verification I'm Video A Time When Is That Right Now Without Thinking Only Person Can Not Make You And Understand Mode Expert Says Bigg Boss Female Chemical Logic I Don't Need To Tell You Don't Need You If You Do n't Make Any Sense Vikas You Have Enough Reminder Add You Can See The Question And Dalhousie Road Near But It Is Trying Its Best To Make Investments Will Consider Giving Time Accident Is Autonomous To Make Obscenely Funded And Sacrifice And Exertions Soaked Off And Into The Number Of Times 200 Weekend Related Stabilization Been Not To Travels Now TravellerAgain In Water Can do subscribe its divide speed multiple equation in two is the k tourism ko notice nigam 08 beam ki if we ki multiply dec to ki if k vikram 0923 living k 0share 0 comments hu is The Heroine Back Just Revenge After But Not Being With You Don't Have A K Dad This 100 Crore Ton Ultimate Zero Subscribe Moment In This That Behave Tell Him Multiply 12:00 Behave Tell Him Multiply 12:00 Behave Tell Him Multiply 12:00 Multiple Discernment 1994 Destabilizing Lecture Sure 5 Model Wash Guarantee Subscribe To I Your Show VIP 500 AND YOU CAN SEE R SYSTEMS IN 500 BC TRAVELS HAIR CLIP 5 - Back this point benefit does not mute the 5 - Back this point benefit does not mute the 5 - Back this point benefit does not mute the sleep from year to year b.a. Private sleep from year to year b.a. Private sleep from year to year b.a. Private Students Away But In This Practice Match A Single Ball Straight Can Be Used For Educational And Do Not Need For Aware What They Are Simply Decreasing 0.3 Long Node That Proceed Modern's Mix Our Understanding Bat* For Bank's Minister In This Bat* For Bank's Minister In This Bat* For Bank's Minister In This Time His To Records are also doing where is n* time to a point itself delicious vote vank 1110 is the number of length you can see not length I have to take care Assam chief and what is time thanks to so difficult to death in this case respected standard Time Which Studied Against The Shudras Vikram 0 Us Subah Can You Simply Take Mind And Have To Increase This Till It Is Din K SBI Select Committee Shri Meanwhile More Than Have To Come From Bulk Of Violence In The Backing Of Bengal Act Ki Swadeshi Shambhu Sadhu Member 13309 Airplane Mode Loot of Maths of Bus How Much The Amazing's Shoaib Is Point Se Left Example Subscribe Like Is 600 Just Running Loop 15 Min 15 Aug 05 2013 105 I Stree Store 2010 Yes Suji Liquid Vighn To That the servers of Railways Anywhere in India I have been in the students where is the length of world top gave Bigg Boss supervisors and yes suggestion but they have but this message is two to two - 82000 withdrawal Amazon message is two to two - 82000 withdrawal Amazon message is two to two - 82000 withdrawal Amazon is otherwise in this case in this Case The Water In The Number 10 222 Model 3200 OK Judgment Salman Points Seed And 100 24 Current Affair Your Colleague A Finish Sexual Subject Additional Force Latest Yes Maximum Volume Maximum 100 - 34445 100 - 34445 100 - 34445 2015 Is - 5 - Ki Bane Zero No Comments Less 2015 Is - 5 - Ki Bane Zero No Comments Less 2015 Is - 5 - Ki Bane Zero No Comments Less Here and what is i0c i will make you develop a game start right time committee commission stop this is a complete question is the biggest fan video not and they have discussed in soak of batsman 2018 fix and beat him in that is The Chief Ministers And Have Made Solution In This Case Where Were Traveling Amazing To Ignore And Time Again And Again But Believe Me Trouble Button In Big One Switch Off Institution Of Meet And Office In This Video By Subscribe Scores And Doing Only For You All Subscribe Comment And Like and Share This Edison Adheen Next Video Bye-Bye Take Care A Bye-Bye Take Care A Bye-Bye Take Care A Kar Kar Kar Do
Find the Student that Will Replace the Chalk
merge-strings-alternately
There are `n` students in a class numbered from `0` to `n - 1`. The teacher will give each student a problem starting with the student number `0`, then the student number `1`, and so on until the teacher reaches the student number `n - 1`. After that, the teacher will restart the process, starting with the student number `0` again. You are given a **0-indexed** integer array `chalk` and an integer `k`. There are initially `k` pieces of chalk. When the student number `i` is given a problem to solve, they will use `chalk[i]` pieces of chalk to solve that problem. However, if the current number of chalk pieces is **strictly less** than `chalk[i]`, then the student number `i` will be asked to **replace** the chalk. Return _the **index** of the student that will **replace** the chalk pieces_. **Example 1:** **Input:** chalk = \[5,1,5\], k = 22 **Output:** 0 **Explanation:** The students go in turns as follows: - Student number 0 uses 5 chalk, so k = 17. - Student number 1 uses 1 chalk, so k = 16. - Student number 2 uses 5 chalk, so k = 11. - Student number 0 uses 5 chalk, so k = 6. - Student number 1 uses 1 chalk, so k = 5. - Student number 2 uses 5 chalk, so k = 0. Student number 0 does not have enough chalk, so they will have to replace it. **Example 2:** **Input:** chalk = \[3,4,1,2\], k = 25 **Output:** 1 **Explanation:** The students go in turns as follows: - Student number 0 uses 3 chalk so k = 22. - Student number 1 uses 4 chalk so k = 18. - Student number 2 uses 1 chalk so k = 17. - Student number 3 uses 2 chalk so k = 15. - Student number 0 uses 3 chalk so k = 12. - Student number 1 uses 4 chalk so k = 8. - Student number 2 uses 1 chalk so k = 7. - Student number 3 uses 2 chalk so k = 5. - Student number 0 uses 3 chalk so k = 2. Student number 1 does not have enough chalk, so they will have to replace it. **Constraints:** * `chalk.length == n` * `1 <= n <= 105` * `1 <= chalk[i] <= 105` * `1 <= k <= 109`
Use two pointers, one pointer for each string. Alternately choose the character from each pointer, and move the pointer upwards.
Two Pointers,String
Easy
281
136
hey everyone welcome back to my channel before we get started don't forget to click the Subscribe button if you want more videos about coding interviews so in this video we'll be solving the problem lead code single number so let's get started the problem is that they give us a non-empty array of integers give us a non-empty array of integers give us a non-empty array of integers and the task is to find the element that appears only once in the array so for example let's say we have this input array the element that appears only once is four and note that in the details problem we must Implement a solution with linear runtime complexity and use only constant extra space but in this video I will show you both solution using a linear space complexity and also constant space complexity so the Brute Force approach to solve this problem is by using a hash set or hash table let's say we have this input array the first thing we need to do is to initialize a hush set that's going to have as a key the element of the array and this value the time of appearance of the elements inside the array so we start by looping throughout the array and add each iteration we store the element inside the hash set for example 4 and the value to be 1 which represent the number of operands then we move to the next number we have one we started inside the hash set and we give it a value of 1. the same thing for the element to move into the next element one so we already have one inside the headset so increase the number of operands to two and the same thing for the last number because we already have seen it finally we're going to Loop throughout the array another time and that each iteration we're gonna access the headset using the element of the current iteration and check if its value is one so once we found it we return the element so the time complexity for this solution is often because we are looping throughout the array once and the space complexity is also often which is a linear space complexity because we are creating a has said that related to the input array so the second way to solve this problem is by using a mathematical formula or a bit manipulation method so let's see how it's going to work so first we start by taking the sum of the unique element that we have in this array and then we take the sum of all the elements that we have in the array and then we will have the formula for finding the unique elements and array using a byte manipulation and the formula is 2 multiplied by a plus b plus C minus a plus b plus C which equal to C so if we did the calculation in this formula we'll have a result which equal to 2 multiplied by C minus C which is going to give us the result so basically the formula is 2 multiplied by unique sum of all the elements inside the array minus the sum of all the elements inside the array which equal to the result so let's say we have this input array so first we start by calculating the sum of all elements and our array which is equal to 10 then we calculate the sum of all the unique element and the array which will give us seven actually that will apply our formula by multiplying the unique sum of the elements in the array by 2 which is going to give us 14. then after that we calculate the difference between them which is going to give us the element that pair only once in the array which is in this example four so the time complexity for this solution is often because we are looping over the input array once and the space complexity is off and since we are using a set function and python that create an object related to the input array so the best solution and the solution that have a constant space complexity meaning of one is by using the exclusive or operator and the exclusive or operator is a bytewise operator or it's a binary operation that takes two binary numbers and perform the exclusive or operation on each pair of corresponding bits and is produce a new binary number as the result so let's see the rules of the exclusive R operation so the first rule if both bits are one then the result will be zero so if both bits are zero then the exclusive or bit will be zero the last rule is if one bit is zero and one bit is one then the exclusive operator result will be one so let's say we have this import array so we start by looping throughout the array and for each integer we perform an exclusive or operation so the first iteration will have 4 and binary and one and binary so we have zero and one which give us one then we have zero and zero which give us zero we have one and zero equal to one and we have zero and zero which equal to zero so the result will be five which is in binary equal to the result from the exclusive or operation so the same thing we're gonna repeat the same process by using the exclusive or operation as all the numbers so since every number and the array appears twice except for one all the pairs of numbers will cancel each other out when we perform the exclusive R operation on them so the only number that will be left is the unique number that appears only once and it's four so the time complexity for the solution is often since where it's written throughout the array once and the space complexities of one sense we are not allocating any auxiliary space and memory that's it guys so let's jump what code in the solution so for the two first Solutions I'm gonna write the code and vs code since then delete code question they only ask for constant space so the first solution will be by using the hash set which have a linear time and space complexity so we start by initializing a asset then we Loop over the array and that each time we check if it's the first time the elements appear in the array if true we give it a value 1 otherwise we increment the value of the key element by one then we'll Loop another time over the array and we use the hash set to search for the element that we have the value equal to one and we return it as a result so the second solution will be by using the mathematical formula and it's going to be just one line so we'll turn two multiplied by the sum of the set of the unique elements and our array minus the sum of all the elements in the array so the last solution will be by using the exclusive or operator and which have constant space complexity so we start by initializing variable called results and set its value to be 0 then we'll Loop throughout the array and for each element will perform the exclusive or operation with the result variable so since every number in the array appear twice except for one all the pairs of number will cancel each other so the only number that will be left is the unique number that appear only once and finally we return the value of the result which will be the unique number we are searching for that's it guys thanks for watching see you in the next video
Single Number
single-number
Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space. **Example 1:** **Input:** nums = \[2,2,1\] **Output:** 1 **Example 2:** **Input:** nums = \[4,1,2,1,2\] **Output:** 4 **Example 3:** **Input:** nums = \[1\] **Output:** 1 **Constraints:** * `1 <= nums.length <= 3 * 104` * `-3 * 104 <= nums[i] <= 3 * 104` * Each element in the array appears twice except for one element which appears only once.
null
Array,Bit Manipulation
Easy
137,260,268,287,389
61
hello everybody today i'm going to solve this problem rotate list let's read the question first given the head of a linked list rotate the list to a write by k places okay so given a linked list which is a linked list which has a node every node has a value and then a pointer to the next node and there are some integer k so that we have to rotate the elements so for example this linked list for the first rotation this 5 is broken from this 4 and comes to the front so it becomes the head of the new linked list the second rotation this 4 comes to the front and then it just becomes the head of the new link list right so every step we have to rotate it like that so given an integer k if you that if we rotate this list k times what is the resulting uh linked list or the list is going to be it's a singly linked list so we have to find that so before trying to solve this problem let's try to analyze the problem right so we have given a linked list which has which is like this so every time let's say k equals to 1 we break this from here and then migrate this linkage to here and then this becomes the answer of that question of the solution right so if k is equals to 2 we leave it intact and we break this uh right and then we again do the same thing we would point it here and then this becomes the head of the new linked place right so uh let's say let's see the constraints on that the constraints is that i mean note that value isn't really care about note that value but k can start from 0 and then k can be 2 into 10 to the power 9 right so this is the value of k it doesn't say anything about the size of this linked list can be anything so one easy observation that we can see that after five rotations it becomes the exactly same linked list that it was before when we do the zero rotations and then it just repeats so we can easily like if the size this is s is the size of the linked list right so after s rotations it just starts from zero so we can if the k is greater than size we can easily reduce k equals to k modulo divisions size right so this way we can uh skip the redundant rotations which will result in the same increase and then do the final rotation only right that's what one thing one optimization that we can do another optimization is so if the size is five so for example in this area size is five right and then we are if we are doing one rotation then so from the initial head here we have to go two three four places right and that will be the tail of the link list and the next one will be the head of the linkage if we are doing uh two rotations then we have to go one two three places from the head right and this becomes the tail of the linked list and then the next element becomes the head of the necklace so clearly like we have to go s minus k nodes and this node becomes the last element of that new linked list and then next element becomes the head of the latest right if we can find that i think our algorithm is really easy so basically our algorithm is go s minus k nodes right new and equals to let's say we are in the key node which is s minus k time k times away from the head right the new head will be t dot next and then again since this is the new head if case of 2 we have to again go up to the end and then when next is null we could point that to the head of that our previous linked list and then we can simply return this four as a solution right so yeah that's what our algorithm should do so let's code it so what we are going to do is first uh the constraint does not say anything about the value of head which can be null or it can be a one length or two lengths right so we have to take all those base conditions as well okay right what if let's say we have a function called size equals to right now let's implement this function it is not normal so count equals to zero and then we keep increasing head until it's null right and then finally we so we have a function here if what if size is equal to one then no matter how many times we rotate the linked list it's still going to be the same right if size equals to one then we can get it on head then we can decrease k by doing k more loaded than size right uh what if k and size are equal so if we have five elements and then we just rotated it five times then it will be the exactly same linked list that we started with so we can handle that situation also k equals to zero and we have two calculations now uh the next step is we have to go minus k nodes right so to make our calculation easier let's start with a fake node this is just uh some domino that we created and we assign value to our head okay and then we have a second pointer which we assign to the new net now let's say so we have to go size minus keynotes forward right and that is our node so since we are going from here it will be that the next node of this node will be the last node in our new edit english okay so since we are here and we started from new head so the next element uh basically will be our uh new head right so we will find our new heads next pointer to the teams next pointer because this is going to be our new head and then the team will be the tail right so so we have to point this to uh now and then we still have to go to the end of the original linked list and assign the next value to the head of the previous linked list right so let's start with that tab equals to next and and all we have to do is just which is our solution so this is basically how the solution can be achieved something is new head damn what is going on people whoa so let's try to submit this and hopefully there will be no issues yeah so this is 100 faster than in solution uh hope you guys understood it thank you guys for watching see you all bye you
Rotate List
rotate-list
Given the `head` of a linked list, rotate the list to the right by `k` places. **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[4,5,1,2,3\] **Example 2:** **Input:** head = \[0,1,2\], k = 4 **Output:** \[2,0,1\] **Constraints:** * The number of nodes in the list is in the range `[0, 500]`. * `-100 <= Node.val <= 100` * `0 <= k <= 2 * 109`
null
Linked List,Two Pointers
Medium
189,725
1,478
Hello Friends Today I Will Discuss The Problems To Meet With Heart Problem And Avoiding This Video In The Problem Set Of List To Dot Problems Samay Jab Play List For To Heart From Its Front Part Is Dros Question That You Can At Least Show The Problem Name Is Allocate mil boxes to solve the problem statement from zif houses of uninterrupted service can see you are giving back water line and inside quiet line is strange can see this only possible from 0lx 1777 number and in every house hsn code wali vacancy thistu 512 and 10 Give Information Email Boxes You Can Export Index Number Length Show This Foot's Mill Boxing This Number Entry Operator Not The Minimum Total Distance Between Each House And Voice Mail Box What Is Mean That This Portlet One Mail Us At This Point Where Mail WhatsApp District One Point From This Point Leaf Minor Minimum Distance From Every House Platform Add To The Nearest Mail Cost Despite Box Button This From This Point It Like Fight Birthday Smell To Candidate Will Office Distance From Shoeb For Every House After To Find The Difference Between The House And Near a small boy and total all the song and find out what you want to minimize the total distance to install get boxes sanjay dutt total difference and total mother house distance from the boxes of specimen more problems subscribe loot criminal law bill boxed edition Twitter The Amazing Try In The Service Of Them Clear Cut Hit But Industry Benefit Conference Updates Appoint Dot Ok Of Water Distance Of Laxative Like 500 Meaning Of The Most Important But Bigg Boss Way Today When Lost But Effective One To Three Click Away From This Problem problem first and where is my channel thank you but and now school boys subscribe now to receive that and loves oo want to vote for weight loss what is the function you will put one mail box for this platform distributor one mail box office Poster Banner State Mandsaur So This Mobile Effect Possible Group And Its Possibility Country Select This Which Number Houses In Two Different Drops Of Size Like Punishment Tweet Where To Make A Gruesome Acts For Every Referral Code Will Cause Notice 108 Position Should I Pod Like Ameer cotton electronic withdrawal ke hai ya hai so let's road and mulayam and assume dasha this form house like this point to that is the meaning of [sangeet] ke din what is the best dialogue in the middle and not middle birth medium of this point ke Basis Of Mauni Twist The House Of The Meaning Of The House Of The People Great To Do Subscribe Video Subscribe Is Very Simple Have A Can Of And Don't Drink Water Softener Other Independence Problems I'm Telling You Shift Grandma Date Off The Free Mode Way Fight Possible Find Out The Cost For Putting Up Between The City NJ Ay When The Coordinator Is n't Telling You All The Quarter Number Line Subscribe That 114 0 Of 148 0 Isn't That Bigg Boss Dick Into A Maximum Of Inspiration For Decades Due To Which Can Take For Every ing fabric youtu.be Can Take For Every ing fabric youtu.be Can Take For Every ing fabric youtu.be g the matrix of now half minute research for every i sanjay justified this cluster and because it works to vandalize toll free leg research university of fun today that point note if i want to make a post box play list the meaning of this Thank you all the best 1957 sorry display liquid of birth to develop of this holy light ca a bigger in table in which mountain start wave ok effective like this half hour time table of science switch 600 450 paramilitary force starting and ending date Which Means of Taking All Houses From Internet Which 148 Time Benefits Benefit The House 10 Meter Point Is The Mean Of The Mean Equal Vision Under The Beneficial Point To Do The Tree Of Knowledge Third Point Is The What Do For Every Nj Ay Justification If you subscribe my channel by pressing subscribe button The Channel is Antarctica of Annual Return for Age Central and to in Foreign Travel and Open Loop to Find the Shortcut So That Will Take You of Thankful Operation in Which You Can Build Up Smart Recent Visits To Right The Minimum Cost Effective Bad Luck What Is The Minimum Cost Place Mail Box In The Internal To Z In This Place Is Media And What Is The Cost For Taking That All Cities On IPL Means Difficult Loose Central What Is The Cost Of Living Nor Mail Box and Nodal Officer Positive Effect Or Make Matrix Oil These Nurses How I Can Make Every Possible Interview So What I Can Do That Bigg Boss Is Back War Total Abhi Which Miser Is Dutable He Also Protects Dual App To And Every State At Every State In 10 But difficult in these slums of his position not giving iffico swift liquid in next in this direction houses and to make key internal subjects for every Indian who will apply to post lots of questions so what is difficult to others like this that daily and like This 8 - In travel to start at this point 8 - In travel to start at this point 8 - In travel to start at this point and wife's minus point to laptop lemon juice one porsche boxter photo for every point where the state in which only bare main travel to stop maitri wa central at this point till current point to make another story After to start now underway at this point and number of post offices like and post public places where to put the letter later decree back and astrology for problem pure cotton channel not subscribed ki subscription court in which state is the function investigative for short term Deposit Find The Mean Is The In The Land Of Houses This Viewpoint After Thank You Find What Is The Cost Of Title And Jainism At Night And Father For School In Travel From X Is Equal To How Do The Cost Price Se Zara Cost Distributor Media House Amazing to the meaning of - every house in House Amazing to the meaning of - every house in House Amazing to the meaning of - every house in dental most difficult interval of abuse and media house is the vice president house wife is five distance of every possible on whatsapp from the post office on that object will boss show the final journey Birth Story for Kids Better Gautam Matrix in turn will make it possible to minister in this function From obscurity to know what is the language of the world in which it is one and a half inches and subscribe the total cost of what will start from that point System Dos Will See What is the Meaning of the Apps that iPod 208 This Point and What Do Their Building My Internal Certification Table and the Cost of Central African Republic Day Function Get Started 6.1 Speaker Boxes Function Get Started 6.1 Speaker Boxes Function Get Started 6.1 Speaker Boxes of Management and Start Hotspot On Come Complete Information In this function will be dancer but in the answer to work cost effective a starting point start the fennel in self respect trust and it over and for a subject effective way controller this is a measure to evidence of this fact and points movie shift time and point from Daughter and every country effect adjust first and anu measure cost possible and spread this interview amazon qualification further for key believe Nandish clean start-1 blackmail believe Nandish clean start-1 blackmail believe Nandish clean start-1 blackmail lots of points normal person's one and five plus one big boss according deposit it xa1 plus one so every To The Same Back In Time Tables From Action Now And Water Overnight Complete The Way Nice Guy And My Next Point Because Congress And Left Stars In A Point Mike's Criminal Number For This If You Install Us Begum Joe Effigy 10 And Start T20 20 Minute Notification Vital And Observed The God Only When The Total Number Of Obscuritism 0share 0tweet K Marquis Kido 90 Number Ko K Falooda Harshad Patel Planning 110 And Not Updating This Widget Posted By Gautam Buddha Post Subscribe if you liked The Video then subscribe to the Page if you liked The Video then Product Cost For Every Day Here Every In Trouble And Stored In Recent Research To Live Like Makers Cosmetics And What Are You Doing Starting From Starting Index Images To Have Elected From Jyoti Every Individual 1480 Replacement Gorakhpur David Callman Function Held Till Has Been Taken As A Temple In The Middle Of The House For Boys Char Will Start From You For Betterment Of The Opposition In The Middle Of The Central And Because They Are Told One Post Box Number Post Office Let Its Mention Any Fear At All New Electrification New Answer Total Cost For New And Exciting And Connect With Five Plus One That Salt Go To Post Office Send That I Will Not Get Solution At This Time Total Cost Will Not Get Solution Give Equal Sea Came A Lot Of Cases Ideas Difficulties Strange Can See So Checking Development went but travels here time control act for 8th to 8 9 video le jaipur that and economic and villages which you can see i am fabric computing this total cost in this quest of taking two houses are attacked with acid 10 meter different situations and half T Point Subscribe button is more subscribe and subscribe the Channel
Allocate Mailboxes
maximum-number-of-events-that-can-be-attended
Given the array `houses` where `houses[i]` is the location of the `ith` house along a street and an integer `k`, allocate `k` mailboxes in the street. Return _the **minimum** total distance between each house and its nearest mailbox_. The test cases are generated so that the answer fits in a 32-bit integer. **Example 1:** **Input:** houses = \[1,4,8,10,20\], k = 3 **Output:** 5 **Explanation:** Allocate mailboxes in position 3, 9 and 20. Minimum total distance from each houses to nearest mailboxes is |3-1| + |4-3| + |9-8| + |10-9| + |20-20| = 5 **Example 2:** **Input:** houses = \[2,3,5,12,18\], k = 2 **Output:** 9 **Explanation:** Allocate mailboxes in position 3 and 14. Minimum total distance from each houses to nearest mailboxes is |2-3| + |3-3| + |5-3| + |12-14| + |18-14| = 9. **Constraints:** * `1 <= k <= houses.length <= 100` * `1 <= houses[i] <= 104` * All the integers of `houses` are **unique**.
Sort the events by the start time and in case of tie by the end time in ascending order. Loop over the sorted events. Attend as much as you can and keep the last day occupied. When you try to attend new event keep in mind the first day you can attend a new event in.
Array,Greedy,Heap (Priority Queue)
Medium
1851,2118
328
hello everyone welcome to quartus camp we are second day of december let go challenge and the problem we are going to cover in this video is odd even linked list so the input given here is ahead of a linked list which consists of odd even nodes and we have to return the reordered list in such a way that all odd indices comes together first and followed by the all even indices notes so this is a pretty simple uh linked list problem so let's understand this with an example so here is a given linked list the idea here is to find all the odd indices starting from the first index because this is considered as odd and combine all the odd indices together and then combine all even indices together so how this is gonna work is we're gonna start with adding the node one and then followed by all odd indices nodes which is three and five so after five we don't have any odd indices left so we gonna combine all even indices together so two four and six are going to be part of one linked list so finally we have to group all odd indices followed by the even indices so here is the odd indices and here are the even indices so we have to make a connection from end of order dices to the starting of the even indices so this is going to be our output so practically you can do this by having an extra memory and i trade every linked list and add every other node to a one linked list and add the same way the even indices to the another link list and link it but here the challenge is we have to solve this and big o of young time complexity and big of one space complexity which means we should not use extra space and we have to iterate the linked list only once so how are we going to approach this so like any linked list problem we have solved we are going to use a two pointer technique because two pointers always comes to help when it is a linked list problem which is pretty easy as well so let's see how we're going to use two pointers to come up with a linear time and constant space solution so as i said we are going to have two pointers odd and even and these odd pointers is going to traverse every odd node in the linked list and same way even node even point is going to traverse through all even nodes in the linked list so we are going to have one more pointer event head to identify from where we started our uh even notes because we have to combine the end of odd to the top head of the even so now starting from the very first node the odd pointer is going to traverse through the odd nodes only so here the r node is going to be three so now our pointer is gonna make a move from node one to node three by removing the connection to node two and establishing a new connection to node three and now our odd has traversed or pointed its next node so our r pointer is gonna move ahead to the node where it has to be same way now the even pointer is going to make its move by removing the connection from two to three and adding a new connection from two to four so it is going to traverse to the next node so same way these nodes are going to remove the connections and travel one but other node to establish the odd and even connection so finally all the odd and even pointers move towards the end of the linked list because after five there is only none left so it has to combine into the head of the even linked list and since everything is done we have to make a connection from or node end and the even node start so we establish a connection from odd node or dot next to event head so yes this looks messy but this is the final solution we have to return so this is the final solution actually that has all the odd nodes in the front and all the even nodes in the back so yes this is as simple as that and this is going to work in big o of n time complexity and big o of one space complexity so yes let's go to the code now so yes as usual we are going to cover the base conditions that if the linked list itself is null then we are going to return null other than that as i said we are going to have three pointers that is odd is going to start from head e1 is going to start from head dot next and even head is also going to start from head dot next or even so we are going to iterate till the nodes reach the null pointer so every time we are going to point our or not or dot next is equal to even dot next or dot next both are same way odd is going to become or dot next which is nothing but the odd pointer we had so once we move the pointer towards the next note the odd pointer is also going to traverse which is very similar to the even dot next tab as well so once we move or dot next to even dot next then even dot next is going to be or dot next or even dot next dot deck next both are same way once we move our pointer we are going to update our or i traverse our even pointer to the next node so once all the traversals are done finally we are going to connect or dot next with even head so yes that's it finally we are going to return head so yes this is it let's run and try yes so let's submit yes the solution has been accepted we have completed today's challenge so thanks for watching the video this is the fastest solution and if you like the video hit like subscribe let me know in comments thank you
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
1,385
so hi everyone let's try to solve this problem which says find distance with value between two errors so uh problem statement is something like this given two integer errors i one and two and integer distance d return the distance value between the two areas so and what is that distance value that has been defined over here in which array one of i such that there is not any element added to of j where the difference between the absolute difference between them is going to be less than or equal to d so what it is saying i will try to tell you from here let's say we pick this number four and for four we have to travel through whole this array in a two and we have to get the difference between them the absolute difference let's see the from the first one n minus 4 that is 6 which is greater than that is point which is greater than 2 that is fine then 9 minus 4 that is also greater than 2 1 minus 4 that is also greater than 2 8 minus 4 that is also greater than 2 so there is a one number which we have found in this array whose absolute difference is not less than or equal to 2 so we got the answer four that is not four but we got one four then similarly we will travel for five and for five also we will find that there is no such integer and this side is two which is less than or equal to this distance d whose absolute difference so we got 1 and this as 2 for 8 we will find that this is there so as soon as we got it we will break that 10 minus 8 is 2 which is the less than or equal to so as soon as we'll guide it we will break from there uh that was almost all the question so that's it saying it will give you two so let's try to solve it now so we are traveling we are traversing from first area first of all foreign i less than your array one dot length i plus then we also travel from the for every number over there we will travel in the secondary which is going to be you will start from 0 is going to be less than that 2 naught length and j plus now we pick a number let's say called first from the first array which is this one so we'll i'll call it a one off i pinned it now what i'm going to do i want to travel it in the i want to check it with every number of the secondary so i will say and second is going to be a 2 of j if math dot absolute of second minus first less than or equal to your d then i found a number so i will break out from here for sure and i will break out from here and that also tells that i got a number so for to maintain that i will need a boolean i will need a flag so boolean flag initially it will be what it should be false that there is no such number found and then as soon as i got it i'll say flag is equal to group and hence uh i can get it so if my flag if it is travel from the whole secondary and for every number if the flag is false look flag false means what we haven't found any number whose difference absolute difference is less than or equal to d so we have to increase the count so initially we also need to maintain account which was zero and i will say count plus and then i will return the count so that should be the whole code i think time complexity if you look it will be for every element you are traveling you are traversing the for each element in the area one you are traversing the second array also so it will be about the size of poster into the size of secondary and that's it that's how you will solve this problem so thanks for watching this one
Find the Distance Value Between Two Arrays
number-of-ways-to-build-house-of-cards
Given two integer arrays `arr1` and `arr2`, and the integer `d`, _return the distance value between the two arrays_. The distance value is defined as the number of elements `arr1[i]` such that there is not any element `arr2[j]` where `|arr1[i]-arr2[j]| <= d`. **Example 1:** **Input:** arr1 = \[4,5,8\], arr2 = \[10,9,1,8\], d = 2 **Output:** 2 **Explanation:** For arr1\[0\]=4 we have: |4-10|=6 > d=2 |4-9|=5 > d=2 |4-1|=3 > d=2 |4-8|=4 > d=2 For arr1\[1\]=5 we have: |5-10|=5 > d=2 |5-9|=4 > d=2 |5-1|=4 > d=2 |5-8|=3 > d=2 For arr1\[2\]=8 we have: **|8-10|=2 <= d=2** **|8-9|=1 <= d=2** |8-1|=7 > d=2 **|8-8|=0 <= d=2** **Example 2:** **Input:** arr1 = \[1,4,2,3\], arr2 = \[-4,-3,6,10,20,30\], d = 3 **Output:** 2 **Example 3:** **Input:** arr1 = \[2,1,100,3\], arr2 = \[-5,-2,10,-3,7\], d = 6 **Output:** 1 **Constraints:** * `1 <= arr1.length, arr2.length <= 500` * `-1000 <= arr1[i], arr2[j] <= 1000` * `0 <= d <= 100`
If a row has k triangles, how many cards does it take to build that row? It takes 3 * k - 1 cards. If you still have i cards left, and on the previous row there were k triangles, what are the possible ways to build the current row? You can start at 1 triangle and continue adding more until you run out of cards or reach k - 1 triangles.
Math,Dynamic Programming
Medium
815
1,004
Hello Everyone Welcome back to my channel Saurabh is going to ask which 2130 is the problem in Domchanch, so I have added it in it, there will be amazing meaning and need, you have learned something and please tell us maximum how many positive ones will there be, so I am Alarm set clip art most cases Okay like see here is from here and we can click means can create So if here and if I make these then this is what I make then this is okay here so by the way how do you see the maximum So, this is what I have in it, if we look, there is one guy here, it's ours, okay, this is what is being made, this is ours, how 5s of Ireland, now we can click two, okay, friends, we can click, so this is 321, friends, we will click. So if we make a mobile then we will weave this gallows upside down, okay and see which one we have here, this is the one, I can make the habitation of this Jio in it, the remaining four can be made diarrhea and we can expand this video further, so here we have Which positive vibes will come in this sex, then the answer is that sex is okay, then let's see how we will approach this problem. So basically, we have constraints, first let's see what we have given in the question. -What is the constraint before sunscreen so -What is the constraint before sunscreen so -What is the constraint before sunscreen so that we have that we can click on at most Okay for this so k hero means if we can click on k0 we can comment more than that means that this You can click on Drosh, meaning if our support area is like this is our area like this, it's okay, like the family members here, then whatever maximum is ours, we can raise it as much as possible. Look, this is the second thing here also, so sir, why is it so, because if they make others one, then the pack will remain positive one. Okay, so the first amazing thing from our observation is that if the change hero is flip salute, then whichever city of ours is one. Whatever is made in the morning is fine, we can keep maximum cheese rolls in it, there should be two heroines, keep it in 30 cans, if something like this happens here, if it comes to 30, then it will be wrong, not inconvenient, we made them, they became white, then This zero on three threads, this will remain the same, so which Yashwant will this become, this is just so many degrees of worship, this will become smooth, then we can have the SDO of man, I in this, when we get the tantra in these directions, we are told that Art most can be the villages near us, is n't it right and we will have to take it out early in the morning itself, to take out the positive, approach these things will give light to the mind, you can take out astrology siding vidmate software in the sliding window Okay, and we will keep the sliding window ma'am of the country, there should be more than one heroine in one of our windows, Dada Zindabad, all the girls who want a girlfriend, because there is a maximum and on removal, which should be there for the seats, Dada, what can they be of use because the items If the stick came then how is the work done, it could not be more than ripe so that if we put a sliding window in it, then let's see how it is fixed in the siding, then how do we always do in sliding window, we take both the points, this is our point, there is a point at one o'clock and Both start from the beginning, okay, so what have we done, I have placed this and when we have here, okay, now what we will do is we will create a window in which and we will always maintain this video, meaning it will always remain in our window. So let's see, we have made two points and we will make one answer in which we will start the length of our maximum positive lineage. Okay, so first of all you have hair here, so we will take the object, okay whatever half the diseases like. That I have no worries, those who have moved ahead have no worries, go ahead, okay, if you agree, we have no problem, we will pay ₹ 1, okay, and as we no problem, we will pay ₹ 1, okay, and as we no problem, we will pay ₹ 1, okay, and as we move forward, Rajesh, as soon as we move me forward, then our The answer is, how will cancer be calculated? The answer will be maximum and the answer will be its own and change - I plus one minus plus one will and change - I plus one minus plus one will and change - I plus one minus plus one will give us the size of the window. Okay, wherever you have internet, whatever this point is, if it is jail - we will internet, whatever this point is, if it is jail - we will internet, whatever this point is, if it is jail - we will do it because there are indexes. We will have to do plus one so that we get the total of all the elements that are in between. Okay, so as we move forward in G, our number of all e want to will keep increasing. Okay, it is here, when we come to J2, our Answer: Ajaygarh two come to J2, our Answer: Ajaygarh two come to J2, our Answer: Ajaygarh two minor has come, it is zero plus one i.e. three, so the minor has come, it is zero plus one i.e. three, so the minor has come, it is zero plus one i.e. three, so the answer has been hit, Mr. Pradhan Sir, now we have the account that when we do, we will know its value and for how much, we can keep it, so there is no problem. This is it, so we will move ahead. Okay, now that our muscles have come, we will again make its account bigger and the account will be two, but we still wanted the eight most key two, so it is complete, there is no confusion, we are going okay. We will go to our place here, our lamp has come here, so we will fix the same cord again, now it will come here, why problem, because look, there is zero weakness, but at most we can keep two in this survey of ours. Ko Mara Saawariya Forest Our Morning Bane We have brought some from here to here but in this we can only take food on two or three threads, okay so here we will have to do our window side now our window was some I All this, so much request, now if we have to side this video, then first of all, when we came here, the size of our window will be taken as the answer. Okay, when we came here, we will do cycle stunts for that month, so when we are here Okay, now here we have our receiver country, okay, so what we have to do is, yes, we will do the window side, that is, we will declare I. Okay, here this I is our gel on our face, which is our fabric and I is our here. But we will keep increasing I till the zero account of ours is hit, return it in Chicken because we have to maintain the winter maintenance of science forever, now the use of Jio will be free, otherwise what will we do, we will keep increasing I till. If our account Kunwar does not come or unless it is from the wonderful one, then I want something here now, then the one who will come here, when the one from here, either here, this is good, okay, when this one is found, then we are one We will reduce the weight and we will move forward, so now all these marks of ours are done, okay, all these Marathi victims have become victims, now our window is necessary from here, it is better from here, okay and see this in this video. Zero is gone and now Jio phone is 2, ok, 210 which is a good thing in most countries, the thing is always use maintenance, ok, so we have done this, after that we start back to our work, ok, this will move forward. One stranger, there is no problem, ok, yes, I came here, no problem, could not make it, again there is no problem, while the wallpaper end, there is no problem, then here it is on the agencies, I am sticking it, now look carefully, if it is on the vegetables, then the shallow account will increase for free. Now this will happen, as long as it is ours, how will it grow, we will have to like it, we will have to do window tips, so whatever leadership we do, we have hit here at the police station point, now this I will move forward and the speed that has come here has the right, so now these three are ours. The work will be done because we have made that U in next, so our front which was broken again from minutes ago, okay, so our one that has come now is next five minutes ago and in this way it will go to ours here up to five so See here now this window of ours is closed device is the size of minutes, they will keep updating so the size of this video was Guardian - i plus one i.e. see was Guardian - i plus one i.e. see was Guardian - i plus one i.e. see how much time - is f5 how much time - is f5 how much time - is f5 a plus 13151 five plus one six science most 2010 this 123 456 our a If the answer is correct, then let's discuss this algorithm again in detail, what have you done? First of all, we took a point of Ali A0 I and district, which we put aside, we created a zero account variable, which is called in English. Covered with districts and will take an answer variable in which maximum lens maid so give it initial in ur that I am thinking negative okay after that when we will run our loop till our J point is our end of A to Z He goes till then, okay, if it is ours, then look at us, if our vehicle is coming, okay friend, then if ours is a forest, then we will do it to me, if you don't have any problem, then continue, we have to do puja, otherwise what do we have to do? If we have then what we will do first is increase our zero point that whatever we get in the personality of Aggarwal, we will give him the village Kanpura like you remember, here whenever we got him, we used to increase his zero point, okay then we will check that if If our zero account exceeds the market, we will have to declare income. If we have to tip our window, then we will shift the window till our zero account. I am working here as long as our account is ours. The latest is that it is okay, as long as Maharaj Law can be better than that, we will keep flipping our senses. It is okay, so there is no need to come here with this condition. You can apply the advice that if there is video conferencing rate, then what should I do? Hamara yaar off IPL T20 pada hai toh kya kar jio kaun ko - are doing that toh kya kar jio kaun ko - are doing that toh kya kar jio kaun ko - are doing that we got only one and i plus ok this is our potato job and every time we wonder what show we will keep doing in our today Maximum off on. Fun - I plus one is always there, keep in mind that Maximum off on. Fun - I plus one is always there, keep in mind that Maximum off on. Fun - I plus one is always there, keep in mind that Z plus will always do it because this is our moving one. Okay, so this is basically our algorithm. Let's see. Python's co is in the description in C plus. This is very much. See, first of all what we had decided was that we will take four brambles, okay, I will have 0.5 inches, so we have brambles, okay, I will have 0.5 inches, so we have brambles, okay, I will have 0.5 inches, so we have taken this, continue and okay till the time gel add is required, if it is 1000, then we will continue increment and Then we will do this, if the number of counties has increased, then let's shift to some tips for winter, then name the file, if you are becoming a hero, then control the account of the receiver - do one more and control the account of the receiver - do one more and control the account of the receiver - do one more and I will always keep doing it as long as the loop is good. Okay, after that we will come out later, we will take more cycle time and keep making agreements and we will get the answer in the answer pair, so we just submit this little box that basically keep in mind that what is the point in the effort that we always have to Along with maintaining the size of zero, it means that it is okay, like, how will the zeros increase, okay, like, or whatever is there, how will it increase, then we will increase the to take out, you will shift the i so that we can take out whatever, okay, so commissioner video help started. The video will help you, please like and subscribe the channel, more in the next video.
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
68
Hello everyone, welcome to my channel, we are going to do video number 18 of this. Lead code number 68 is hard marked but it is quite easy because in this you have to do only what is written in the question, do not put any extra mind, okay further it is this. It has been said that you do that and your time will be reduced. The cleaner you code, the better impression you will make. It is okay in the interview, that is why such long questions are irritating but they are quite simple because you just have to do what is being asked. In this question, the name of the question is text justification. Google asked this question. Look at this question. You have to say in the question that you must have been given a string of words. Okay, you must have given a singer that there should be maximum characters in every line. Understand the meaning of justify. What is the meaning of left hand side, what is the meaning of right hand side, if they understand then give the pulse but we have to keep in mind that there should be maximum number of characters in every line, it cannot be more than that, this is very important, this is distributed further possible. Okay, this is where I got confused. Number space is okay, business stall, Sandeep Wright, I will explain it now, it will be more clear than the example. Now look, another big poor size has been given here in the last line, which will be the last line of your result. OK IT SHOULD BE LEFT JUSTIFIED ONLY AND NO ACCESS SPECIES INSERTED BETWEEN WORDS OK I WILL EXPLAIN TO YOU WHAT IT MEANS OKAY NOW LOOK PAY ATTENTION THIS IS AN EXAMPLE YOUR MAXWELL IS 16 SO SEE THIS IS 16 THIS IS ALSO 16 I have written it here, so let's start writing, let's take this, first what is this, S, after that we are giving a space, A, N, so these are three words, if it is not an example, then we will not be able to write the example here, okay. Means if we write example here then how much is 1234567 express, we have to do invalid distribution, it is okay, here we can fill special, then we reduce the question by one, okay then look 7, look, you must know this, like mother takes it is a string. There is a statement, there are three words in it, one, two, three, see how many there will be, one, two mattresses, no meaning, space, know how many there are, total number of words, as many words are accounted for, how many words are there, one, two, three, subtract one from it, look at the number 3. - 1 Number of spaces, how many are there? One word has been added, what does it mean that there will be two mattresses, look for sure, there are two mattresses here, it is ok, yes, nothing else has been added here, that is why nothing has been added there, but if there are two hours, see. There are 2 hours here and how many space stalls are there, I have 7, not 7, actually there are 8, look here, pay attention, how many are there, 1234567 and this is eight, right, the total, I have, okay and how many words have we written, total three words have been written Okay, if three words are written in this line, then there will definitely be two mattresses. I just taught you below. Okay, there will be two mattresses, so the total space is eight. And how many mattresses are there, so how many mattresses should be distributed? If there is space in both, then do it. Both of them will get 1234 pages, here after that I wrote this, after that remember I wrote the charge for that also 3 4 After that I wrote A and N, okay what was et, how many total cases went back, so total money, how many children did I have? Remember, first calculate the number of words written, one, two, three, five, six plus eight, this is the account of my character, I did eight characters in one line and the total number of characters in one line should have been 16, so 16, I did 60. So, if there are eight children i.e. eight species of children, did 60. So, if there are eight children i.e. eight species of children, did 60. So, if there are eight children i.e. eight species of children, then I understand how many more mattresses will be there, how many words have we written for the species, how many total words have we written, one, two, three words have been written, if you do minus one, then the number of mattresses will be taken out, then write down its stalls. How many do I have, two at those two places, first I have to distribute all the species, okay, so how many stalls were there, we had two stalls, and how many spaces we had back, eight, okay, so 8 - 8/24, that's it, eight, okay, so 8 - 8/24, that's it, eight, okay, so 8 - 8/24, that's it, okay. Now if we move ahead then other things will be clear. Okay, now look here, I have written the example. Okay, after that, after giving one page, I have written off. Right now, I am writing after seeing only one space, then let's see what happens. Wrote off, after that look at the express text and also wrote it. After that look at one page. Tried to write justification but it did n't work and again there is no space. Okay, so I will write it below. It's okay but now again. Let's do the same thing, total here, how many characters should have been there, it should have been 16, right, it should have been 16, but we have written how many are 1 2 3 4 5 6 7, ok 8 9 10 11 12 13, so the total must have gone back, there must be three space children for sure. No, it is okay because we had 13 total marks and 16 marks were fit and we had done it with 13 characters. 3:00 Baj Gane 3:00 Baj Gane 3:00 Baj Gane How many words have we written? If we have written one word, two words, three words, then how many mattresses will there be? There will be two mattresses, two friends will return, one more, this and this. One, this is fine, so how many stalls are there, if there are two, then three species have to be divided among these two. Okay, there are three species, we have to divide them among these two, that means there will be at least one pest in all the stalls, but look friend, Lot Well, let's go here, the express has gone here, this is the express here, then also this one stall here too, space had to be given here too, it has gone here too, okay, now look back, how correct it is, here it is said in the question, right? The extra space that goes back and you have to justify it from the left most side means you cannot put space here, okay you have to justify it from the left most side Exercise One Child Neither is there any saving on the access nor from the left side which mattress. Keep putting there those who are given to it, otherwise it will get shifted. Here is one more exercise which was given, at least this much will be given to them as extra. This is okay, so what was there together was put here. Look, I had to give a space. So I gave it and whatever extra was there, I gave it here, it became zero all at once, no problem, the exam was written off here, there was a space here, look at the extra, now my no has been completely justified, right at the end. Here the character 'A' is there is at the end. Here the character 'A' is there is at the end. Here the character 'A' is there is no space and it is correct, it should not have been there, okay, it is clear till now if we move ahead, it will be more clear, now look, it is given in the question, it will be my last line and now. We have come to the last line, this is the reliance line, see what is said in the last line to do but D last time only look at the word between, pay attention here, the word between was one word and one word was inserted, the extra one was also inserted here only. It was right, going from left to right. Okay, if you take a mother, then one would come here and insert another here, okay, but there was only one here, okay, so now let's see what he is saying in the last line. It is simply saying whatever is your letter in the line, whatever is the word, put it in front, just keep it left justified, do not put extra space between the words, the meaning is fine, let's see the last line, what is the justification, maybe yes, J U S T I F. I C A T I O N Okay, this is clear till now look after this, if there is a dot here if there is justification, if there is one more word after justification, mother takes it, then there is one more word, then you know what I used to do. Just when we take mother, there is no dot near the justification, this is so much, so I don't know what it does, I just give 's' here and leave it. give 's' here and leave it. give 's' here and leave it. Okay, don't give any extra space in the last line like if this, otherwise what do we do if this. If there is no last line then remember that the extra space that has gone back is adjusted here and here in the last line, it means to insure that space should not come in the last but all this is not to be done in the last line. What in the last time? All you have to do is get a space, okay, put it on the next word, then you got the express, then put the next part, okay, it is clear till now, then look at this, example is enough, is n't it an example for such questions. Right from the beginning I told you many things, how many spaces are there, how many stalls are there, every mattress will have at least this much space and the extra will be given to everyone from left to right. Okay, it is clear till now, so look, it is the cleanest. What is the way to write its code, what I thought is that I will simply start from here, I will create these lines one by one, first I will create this line, then this last line, if it is okay then I will reduce it and start from here. From the first word, first of all, see whether I will be able to take this word in any line or not, then see whether it will be one line or not one line, here is the length of each word, meaning it is so guaranteed that one word is No, that is less, that yes in this will be confirmed, it will never happen that the length of one word is more than the entire line, so do n't take tension about it, okay, it will not be given, okay, so now my line is so much that I don't need it. I know 100% that I can take this disc, I can definitely so much that I don't need it. I know 100% that I can take this disc, I can definitely take the disc, I will be able to leave the country in the first line of mine, I will definitely be able to take the first word, now see, take the next word. Can't or can't, it's okay in this line, for knowledge, I have looked at the next word, why am I taking it? Okay, so look, it's an obvious thing, I will definitely take this, one word will come to that. After that, see how the word that I am taking will come, its length will be two plus one space, it will also take one plus space, so do you know when will I be able to take it easy, when the character of whatever word I have added is there? Length of i.e. ki added is there? Length of i.e. ki added is there? Length of i.e. ki kar plus one why space, only then you will come up with a new word, it is ok, it is clear till now, so it is an obvious thing, now I will keep checking this every time, pay attention to you, I started from i = 0, attention to you, I started from i = 0, attention to you, I started from i = 0, ok. And so I am late in writing the letter here, I am also late in writing its account that the first word can be taken, I will make the word of length, okay, I am only writing the letter, here there will be letter plus and space also, mother, let's take the meaning now. I have added multiple words, now this is the one with the word us, this is the word Jeth, so I have kept the letter Khon toh, but I will keep the space account as well, the plus account will last as long as it lasts. Hey, I am fine, take this, you should be equal, you should be max with, brother, only then you will be able to take this word, I am maintaining the letters account separately, how many letters have I made till now, letter account plus account, a flood. Let's see how many more words can be used. It is clear till now, this much lesson will be clear to you very well. The first word that I will take in every line is the one that I can take. I have put it in the question that its length is length give equal tu maa fit. If it happens, I am holding a separate meeting in the letter account and the space is as much as the accounts are, right now it is fine in starting from zero, so when will a new word be able to be added, when its length plus it comes with a space, only then I will be able to add it. So look, I have added it in the letter account, it must have been clear till now look when I came to know how many letters I have added to him, how many letters are only in the letter account, then I am very happy that brother, how fine is Maxwell Thiada? How much was the max with mines letter will be left? Remember how much black space was there, tax here, eight here, how was that eight calculated, how did you calculate the total number of letters, six two eight minuses, doing the same, total number here. I have taken out the remaining stalls, okay, now how many people do I have to distribute these remaining stalls, that is, how many mattresses will there be? Remember, we were taking them out, because I had taken them at the beginning, okay? How long is it okay to break after coming here? So after I had taken the country, after that when I came here it is okay, then I saw that yes, this is possible, I can take this, remember I made space plus one. Here, the space was made plus one, okay, so the value of the space became one, that is, one space was added and that space is this one, okay, after that, when it is here, I said, we can take this also. Then the value of space will be plus one, then another space will be added and that space is this one, otherwise the value of space will be 2, we will not be able to take it, when it comes here, it will break here, it is true that we will take only 15 words. You will find it on the first line, if it is ok, then I must have got the space account from there. Ok, then you can say mattress, space count will be done after speaking, I will not speak, I will write it down, mattress is it, how many hours are left, it is ok here too. Instead of space account, the word mattress is butter. Mattress is fine here also, so now let's find out that brother, look here, this is very important. This one is a little scary. Earlier, I had also told you about this. Look here, mattress space. How much space is there in every mattress? Okay, tell me it is okay and I have the total here, just one extra thing, what do I have to put in the question, it is given that if k = k = k = n, it is out of bounds, do you know what it means, I am sure that I am filling the last line. Right now I am filling the last line because when last time I was filling here, now it is the case that I must have filled the justification, after that it must have come here, so it means I am in the last line, now remember the life line. I told you, brother, how much space should be given in each mattress, if only one is given, then I will update its value, the value of space has been made one, it is okay, any extra space in the mattress is okay, till now it is clear, now look, I need something. No need to do it, simple, I am taking out my string line, okay, I will send the find me line function, it is clear till now, what have I done in the first line, I have done so much in the first line, now I will create the next line again, so here it is again from here. I will start here, the last time was zero, then I will start from here, okay for the next line, so it is obvious, what will I do here J = Sorry I, then where will I J = Sorry I, then where will I J = Sorry I, then where will I start, I will start from here and this is the whole thing. The entire vine will move inside the look. I arrest it. Okay, in the beginning, I must have been zero. Okay, and the entire vine will keep growing on one vine, with the help of K. Okay, now what should we write? The fine line is very simple. Look now. Look, we are going to draw the whole line, okay, so look, we have got everything we needed to make this line. Look, what have we got, I am here, I also know I and I am here. But it means it will run from I &lt; to S, know I and I am here. But it means it will run from I &lt; to S, know I and I am here. But it means it will run from I &lt; to S, meaning I have to put these three words, okay, I also know this, okay, this plus is going on, right now it is empty, till here it is clear and see, whatever I have to do to make this line. Extra mattress is required, space is required in the mattress, that is also known and the extra, sorry, how much space is required in each mattress is also known, here is what was taken out and how much extra will be available in each mattress, that is also known, okay, I mean, what do I know? I write here how much space will be given in the mattress, I know it is ok and one more thing, I know what has to be filled in the mattress, that is also known to me ok, so let's start, how much space should be there in the mattress, S Plus, it is ok till now it is clear. After this, pay attention to one more thing that as much line as you had to put, keep giving as much space as there is in the mattress, which is fine, what does it mean brother, to do extra space, that is, if the extra space of the mattress is &gt; 0, it means that a if the extra space of the mattress is &gt; 0, it means that a if the extra space of the mattress is &gt; 0, it means that a child has been born. So give jo na meaning add to the line jo line plus will be finished my string will be ready the line will be ready ok I will do simple return line which is mine na which was mine Maxwell Maa let's take that is 10 ok one two Three to five is fine, it's fine to do penance like this, there is no space to put the apple, so I will fill the entire space in the line for the remaining stalls, okay, so I am saying this, Ville, if my line has been made, then only this much has been made. Okay, he couldn't even be equal to Maxwell, mother, let's take the length of the line, if you make the line which is my line, I have just made all this here, right here, if its length is still equal, take it. Are you okay? Keep appending that line plus this is equal. You keep adding extra space as it is. So I hope this entire code is finished. All we had to do was paste the code from the story, ours will be reduced. If you want to code quickly, let's code it, finish it quickly, it's okay, and the Java code will be found in the comment, and I will share the time complexity in the comment, whereas it is quite easy to find the time because the volume is visible. Just keep on adding it in time which is ok, vector of string result is taken, ok and N = word dot size is taken and ok and N = word dot size is taken and ok and N = word dot size is taken and what is taken so that if it comes less later, then what else is ok now look. What did I say that I will keep on issuing letters account i.e. I will take the word will keep on issuing letters account i.e. I will take the word will keep on issuing letters account i.e. I will take the word of i dot length ji to this word Mattress is ok till now it is clear, now see this mattress is space na means how much money will be spent in each mattress. The total number of stalls remaining, the space was to be disputed equally, not divided by the total number of mattresses, it is clear till here and extra piece Gudda is ok, meaning accessories have to be given to each mattress, how many are there, how many remaining mattresses are there, modular mattress is ok and even better variable. Keep the name of so that you can understand it better, this is how I understood it, okay now look and yes, pay attention to one thing, the story, this mattress should not become zero, okay, if it has zero relief, then it will be a mess, otherwise I would have put the check here. I am saying that if this is equal to zero then I will take zero otherwise then I will divide it and show it, let me do the same thing here too. If this is equal to zero then it will be zero otherwise then we will take it out. Okay, it is clear till now. And remember, here they also used to put the check that if J = N then it means this is the that if J = N then it means this is the that if J = N then it means this is the last line and what was said in the last time that keeping left justified is only dividing and which is only one space in every hour. This hour space should be one only and if you don't want to put any extra space in the mattress then it will be zero. Ok till now it is clear. Now do simple Now just remember to write me this find line in it. What all had I got, I have got it, and what else have I got, okay, so I just have to write this function, I have to find the string line, okay, you can pass help in this and what else, all these are passed here. Do it's a string, okay, plus s plus, so much space had to be given in the mattress after every word, let's give the pulse, mine was also not corrected in one go, okay, so you should also direct, okay, after this is in online. This was mandatory, so much had to be added, after that if there are extra children then assign them left then right, let's put a line in all plus this is equal, you are fine and also change it, whatever is done to it, make it minus it is fine. Whatever was extra, they will keep doing it. Now in the last I remember I had said that if the line dot length is there, if they have taken it, we have written all the things, but pay attention to one thing, what have we mixed here? Given, remember when the last word is the last word of any line i.e. last word of any line i.e. last word of any line i.e. Jab ke is equal to tu ke minus one means this is the last word of my line, so remember, no space was to be given after this word, remember because. Before that I must have adjusted these spaces, so I do not have to put any space after the last word, okay, so I will continue in this way, okay because I have already added this last word here, after that this But the look will end after continuing, so you can either continue or break, the matter is the same, so I must have added the minus one here in the line and after the last word, no space after the last word off. Online is ok so I think it was mic test failure Thoughts same I go you know about this ok submit hopefully should run time complexity more code you will get in comment have you definitely solved this question any doubt Hota hai read in d common area aur try tu help c u aur d next video thank you
Text Justification
text-justification
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified. You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces `' '` when necessary so that each line has exactly `maxWidth` characters. Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right. For the last line of text, it should be left-justified, and no extra space is inserted between words. **Note:** * A word is defined as a character sequence consisting of non-space characters only. * Each word's length is guaranteed to be greater than `0` and not exceed `maxWidth`. * The input array `words` contains at least one word. **Example 1:** **Input:** words = \[ "This ", "is ", "an ", "example ", "of ", "text ", "justification. "\], maxWidth = 16 **Output:** \[ "This is an ", "example of text ", "justification. " \] **Example 2:** **Input:** words = \[ "What ", "must ", "be ", "acknowledgment ", "shall ", "be "\], maxWidth = 16 **Output:** \[ "What must be ", "acknowledgment ", "shall be " \] **Explanation:** Note that the last line is "shall be " instead of "shall be ", because the last line must be left-justified instead of fully-justified. Note that the second line is also left-justified because it contains only one word. **Example 3:** **Input:** words = \[ "Science ", "is ", "what ", "we ", "understand ", "well ", "enough ", "to ", "explain ", "to ", "a ", "computer. ", "Art ", "is ", "everything ", "else ", "we ", "do "\], maxWidth = 20 **Output:** \[ "Science is what we ", "understand well ", "enough to explain to ", "a computer. Art is ", "everything else we ", "do " \] **Constraints:** * `1 <= words.length <= 300` * `1 <= words[i].length <= 20` * `words[i]` consists of only English letters and symbols. * `1 <= maxWidth <= 100` * `words[i].length <= maxWidth`
null
Array,String,Simulation
Hard
1714,2260
1,051
hello everyone so now we're going to solve called something called height checker it says that the school is trying to take an annual photo of all the students are standing in a non-decreasing order non-decreasing order non-decreasing order okay you are given integer array Heights representing the current order of students each Heights is the height of this written number of indexes where expect height is not equal to expected okay so it says what's expected where I expected is height of each student in the line okay so we are given an array which is basically the heights there's supposed to be another array expected which would be the actual correct ordering of heights in ascending and whenever they don't match you increment account and you have to tell how many they don't match okay so I think this is fairly straightforward in the sense that we're given Heights I need another array which would be expected right and this will be the sorted version of this so first of all I need this earring so let's clone okay and this will get all the values of heights in expected and then I'll simply do arrays.sort expected then I'll simply do arrays.sort expected then I'll simply do arrays.sort expected uh now what I'm going to do is I'll go over all the values of this for and I starting from 0 I less than Heights dot length I plus and I'll check if my Heights of I is not equal to X Factor of I if that's the case I'll have a counter it will check the difference let's keep it zero that's friends plus and then at the end of it I'm just going to return the difference yes so let's see if this works yes it does submit oh yes awesome so basically here the idea was simply to get all the values sorted and once you have them just see if there's any difference between the two values if that is you maintain the counter which will keep track of these and you return it so in terms of time this is O of n because you'll go over the app oh actually it's off n log n because we are doing a sort here and this sort is going to be of n log n so time will be off and login in terms of space it will be o of n because I am creating the next this extra expected array which will have in elements so yeah this will be the time and space complexity thank you
Height Checker
shortest-way-to-form-string
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in **non-decreasing order** by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `ith` student in line. You are given an integer array `heights` representing the **current order** that the students are standing in. Each `heights[i]` is the height of the `ith` student in line (**0-indexed**). Return _the **number of indices** where_ `heights[i] != expected[i]`. **Example 1:** **Input:** heights = \[1,1,4,2,1,3\] **Output:** 3 **Explanation:** heights: \[1,1,4,2,1,3\] expected: \[1,1,1,2,3,4\] Indices 2, 4, and 5 do not match. **Example 2:** **Input:** heights = \[5,1,2,3,4\] **Output:** 5 **Explanation:** heights: \[5,1,2,3,4\] expected: \[1,2,3,4,5\] All indices do not match. **Example 3:** **Input:** heights = \[1,2,3,4,5\] **Output:** 0 **Explanation:** heights: \[1,2,3,4,5\] expected: \[1,2,3,4,5\] All indices match. **Constraints:** * `1 <= heights.length <= 100` * `1 <= heights[i] <= 100`
Which conditions have to been met in order to be impossible to form the target string? If there exists a character in the target string which doesn't exist in the source string then it will be impossible to form the target string. Assuming we are in the case which is possible to form the target string, how can we assure the minimum number of used subsequences of source? For each used subsequence try to match the leftmost character of the current subsequence with the leftmost character of the target string, if they match then erase both character otherwise erase just the subsequence character whenever the current subsequence gets empty, reset it to a new copy of subsequence and increment the count, do this until the target sequence gets empty. Finally return the count.
String,Dynamic Programming,Greedy
Medium
392,808