id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
1,887
and good afternoon to all of you today we have problem which name is reduction operation to make the array element equal lead code B8 87 problem so before going forward in this video please make sure that you have like And subscribe 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 code and try to do the code also then it will be beneficial for you and if you simply see this video and then do the code it will not be beneficial for you so do The Code by yourself then see this video let's read the problem statement we have given an integer array nums our goal is to make all elements in nums equal to complete one option follow these steps so these are some steps that we have to follow find the largest value of nums let's index I and its value be largest and we have to find the next largest that is just smaller than means strictly smaller than the largest value and we have to convert nums of I to next largest means largest value to next largest value is the just smaller than the largest value so let's uh see the let's directly go on the approach part for this let's see so we have a array which is 513 so firstly we have to find the largest element so I have some methods to find the largest element I can use priority CU sets also and map also so I'm using the priority CU then it will be 531 because it is in priority CU if I use a Max then it will be in increasing order then it will be 531 so we have in this 531 our largest element is five and our next largest element that is the just smaller than the largest element means strictly smaller than the largest element so next largest element will be three so we have to convert the largest element to next largest element means we have to convert 5 through 5 to 3 then it will be 3 1 now we can see there are two threes me number of count of three equals to two so we have to convert all three to one so how we can create a map so that we can count the frequency also so the frequency of three is two and the frequency of one is 1 so we can convert the three which is the largest element to the next largest element that is the one so this will be one and uh what we will do here we have done the first uh conversion so it our answer will be one now we will add our in our answer that will be means 1 + 2 that answer that will be means 1 + 2 that answer that will be means 1 + 2 that will be three then three will be our answer because uh we can see that frequency of 3 = to 2 if we convert frequency of 3 = to 2 if we convert frequency of 3 = to 2 if we convert three see here three is coming two times so we have to convert the three so it will be 1 + 1 2 and our final answer it will be 1 + 1 2 and our final answer it will be 1 + 1 2 and our final answer will be three so let's take another example here we have given this array so if we use the priority CU then it will be the order of the array will be 3 22 1 so now we can create the frequency we can use the map so Three is coming only one time two is coming only two times and one is coming two times so now this is done so our largest element is three and our next largest element is two so we will convert the largest element to next largest element means we have to convert three to two so it will be two and the frequency of this new largest new value is one so we will add this in our answer then it will be one now we can see our frequency of two is three and the frequency of one is two because we have not done any operation in this so it will be save so one is coming two times and one is two is coming three times so now our largest element is two and our next largest element is one so we have to convert largest to next largest then it will be one so we have to add the frequency in our answer so will 1 + 3 4 our final answer so will 1 + 3 4 our final answer so will 1 + 3 4 our final output will be one comma five because one is coming five times and we have not given any in next largest element so we will stop here and our answer will be four so let's discuss about time and dis space complexity for this so we can see we are using priority Q so it will be n log n and we are Al also using uh map then it will be big go of and so let's uh add these two big of n log n plus big of n so it will be big of n log n and space complexity will be big of and because we are using the map so we can reduce the space because we are using the map why we are using the map we are using two data structure in one question so we can optimize this so we can optimize big and space complexity I talking about space complexity so big and to big of Logan so how we can do this big of log and big of bun also so let's see we have the given arrays 32211 so what I will do is I will create a count variable and our I will create answer variable that I have to return so I will not do anything with our answer variable so I will do the operations with our count variable so whenever I will find the transformation I will add count I will add one in count means like initially I will add one in count so as you can see I have found the transformation so I will add this in our answer so it will be one now I will this three will convert to two now I will go forward and I will see another transformation so here's the transformation so we can see two is coming three times so I will add three in this so it will be 1 + 3 = 4 so three in this so it will be 1 + 3 = 4 so three in this so it will be 1 + 3 = 4 so let's see the code so that we can understand properly so let's discuss about time and space complex for this why it is optimized solution because here we can we are using the we will sort this actually we'll sort this in decreasing order you can sort this in increasing order also so that in that particular question that you have to Traverse from the back I will Traverse from the start so I will use the reverse order of sorting and in that method the time complexity will be go anog and that is same as a previous time complexity but the space complexity here is B of log n because we are sorting and we are storing some elements or it can be big of one also so big of log n is the time complexity for this let's uh see the code for this so in this what I will do is I create int nals to nums do size I'll sort in reverse order you can sort in uh increasing order then you have to Traverse from the back I'm starting from the start I am traversing from the start variable start pointer so I have to sort this in a reverse order means in decreasing order so sort how we can do nums do ran comma nums dot R and that will give me the reverse order of reverse decreasing order means decreasing order of 4 AR now I what I will do I will create in answer that I have to return and int count varable I am starting from in count equals to 1 why I'm starting from count equals to one let's see for in I = 1 to I less than n then I ++ for in I = 1 to I less than n then I ++ for in I = 1 to I less than n then I ++ now I'm traversing from the start and I will check if nums of I is not equals to nums of IUS 1 then I will add this count in our answer variable answer plus equals to count and other in otherwise what I will do I'll increase the count because let uh let's see in this I have increased of kind I have changed this three to two and I have increased the count lights burn then two then three and uh here I have I found the transformation so I add this count in our answer so it will be four now what I'll do I'll return our answer so in this code what I have done is I have created our answer variable that I have to return and count because I will increase the count again and again when whenever I feel I found the transformation and I why am I starting from the I = to 1 because I have to from the I = to 1 because I have to from the I = to 1 because I have to check the previous element of also if that uh current element or previous element is not sa then I will increase the I will add that count in our answer so I have initially added the count in our answer then otherwise I will increase the count Let's uh run this code yeah it is working perfect let's submit this as you can see it is working perfect as I have told you as I have already told you that the time complexity for this is we of anog because we are only sorting that and space complexity B go of n big of log n sorry because some somehow we are storing some elements in that array or it can be big of one it depends on so if you find this helpful then please like share and subscribe and if you know another approaches for this I have already told you about another approach that priority Q map you can also do that approach and uh let's see the next video
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
729
hey everybody this is larry this is day three of the august leco day challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem uh yeah just a random quick update i did trivia night here in new york there's a trivia league uh definitely recommend everyone to trivia but i did it with a bunch of my friends this is loading really slowly um and yeah and we finished second place today it was a good comeback we were down a lot from the first round but we kind of four our way back and got i guess more free alcohol which is good what is going on but yeah so i'm having a good swell day also a little bit uh burst in a good way and as soon as i can open these uh what is going on here well uh yeah running into some technical difficulties but hope everyone's doing all right on this fine uh tuesday or wednesday depending on when you're watching this let me click on this again oh there we go now it's loading that's really weird anyway yeah let's look at today's farm and as usual as i would say i do plan to do a bonus question after this a random question i haven't sell before so definitely you know hit the subscribe button and hit the bell and get notified on those problems as well anyway today's problem is my calendar one or my candle eye you're implementing a program to use as you can there new event if it doesn't cause a double booking so double booking is something about intersection and start to end okay um so you just do start and end and youtube start doing it with 10 to the nine okay so the one thing that you would recognize here is that there's a sort of um there's a sort of um how do i say this there's a sort of like uh um structure there's a sort of structure in which um you know it's very binary searchable is what i was going to say and you would do uh in the sense that because we don't have to we i guess even when we move stuff it's okay but because we only add stuff we can definitely um do a binary search and then change it and then add stuff um and it's by now binary search is not the right or well binary search is part of the answer the other part of that binary search is having a binary search structure and that structure is going to be very often a binary tree so okay so i think i spoke too quickly about the binary search but for a reason that you'll see in a second but if you do it in a binary tree or maybe a segment tree type thing um this would be perfectly well i guess you can do segment three because it goes up to ten to the nine but yeah but that's basically the idea is this binary search tree and a balanced binary search three will allow you to do a read and uh and an ad in of one time or whatever right oh sorry oh of luck end time obviously i don't know why i misspoke like as i made my trying a little bit but yeah the way that i'm gonna do it is with sorted list which is kind of a magical thing from uh from python so yeah and idea we have to be a little bit careful but it really is pretty straightforward i think we let's see we want to binary search how do we want to bind themselves we want to binary search to start um because basically what we want to store is the left and the right and then here what we want to do is just do a binary search and then look to the left look to the right to see if they intersect with either of those ones i think that would be good enough um i could be wrong but yeah um maybe you have to do an extra one if you really want to be safe like two on the left two on the right but i think one should be good because you wanna see if your current segment clips with the one on the left or the one on the right and if it's if it matches exactly then you encrypt the one on the right but if you don't match it then it's gonna be the one on the left um depending or like yeah otherwise it's going to be the one on the left and then you'll just have to check i think that should be good but yeah so if so now we have self.sl of yeah so if so now we have self.sl of yeah so if so now we have self.sl of index so okay so well first we have to check that index is less than length of self.sl index is less than length of self.sl index is less than length of self.sl less than strictly if this is the case and uh okay so this is the case then let's check this so then here i'm just going to call left right is you go to self.setup index is you go to self.setup index is you go to self.setup index and then what happens right then we check whether it overlaps so if the or um yeah okay then it overlaps yeah is it inclusive exclusive oh it's what is pinging me okay muted stuff but uh okay so this is actually so we just have to be a little bit careful but i think we can just minus one on the end sign should be okay because it does it's a co open range so yeah then if this is the case when we return force otherwise we do sub dot sl dot add of uh start and actually we forgot to do so this is one of them and then the other one is if index minus one is greater than zero uh yeah then left right is equal and then we try to we just do the same thing but for index minus one maybe we could use the helper here uh we add and then return true and i think this should be good maybe i have my oh wait we have to do n minus one to make it inclusive just slightly easier for me let's see okay that looks good let's give it a submit i it's very easy to have it off by one so we'll see apparently last time i had two wrong answers and this one i have one wrong answer so maybe i should be a little bit careful but honestly some of it is just me being lazy but uh okay so let's see what the discrepancy is or maybe i hope that it's a minor discrepancy and not just like some major thing but i like to click on diff so okay 47 33 41 uh did i return the wrong thing oh no i returned the right idea i mean okay so let's see so we have 47.50 then we have 2341 so we have 47.50 then we have 2341 so we have 47.50 then we have 2341 then we have 39.45 which is bad 33.42 then we have 39.45 which is bad 33.42 then we have 39.45 which is bad 33.42 which is also bad and then 25 32 which is good and then 26 35 which is bad and then 1925 oh i see uh that's just sloppy because i did n minus one because i want it to be inclusive but that also means that this end should be inclusive right so because this 25 clips this one it thinks it overlaps but it doesn't so um i just need to be better about this or consistent about this um that was just sloppy let's see if that fixes it oh it still is wrong huh oh and then now is the last one let's see so yeah so okay so let's say this was uh corrected to be true is the oh this is it no this is right and then 3a let's see uh and then 8 13. it's okay and then 1827. oh i knew that this was going to be the case ah but i was i thought that maybe i could be lazy on this one but i was just wrong so what happens here is that uh yeah i mean i just needed to do the whole thing um okay let me actually rewrite this a little bit uh to make it inclusive so now this is more clear and i actually thought that i needed to do this but i couldn't prove it but i was just lazy and then i thought that uh this was the logic as well um yeah and this should be good i think especially now that we are oh well this one's wrong because now we want to uh because we didn't subtract one just so happens that was right but okay let's give it a quick submit again um again this is just me being lazy maybe i could have came up with more cases but this is good so yeah i was just literally sloppy with two things one is um not paying attention about the inclusive exclusiveness which is something that happens a lot so maybe i need to be better about and this is the type of farm that i don't know why i'm rushing that much but still um need to be better and this one i knew but i thought that maybe i could get away with it because maybe i think i miscounted in my head but um yeah so what's complexity here well we're to do two binary search and one binary ish insert a log event insert so this is going to be o of log n and that's pretty much it of n space of n log n time and yeah that's why i have this one let me know what you think stay good stay healthy to good mental health i'll see you later and take care remember i'm going to do a bonus one after this so definitely check that out uh give me some love and support i want to because what i did last time okay i'm not gonna i guess i had the same i oh i did a binary search on both i think that would have been a little bit trickier but um and as you can see with the wrong answers okay anyway stay tuned bye
My Calendar I
my-calendar-i
You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a **double booking**. A **double booking** happens when two events have some non-empty intersection (i.e., some moment is common to both events.). The event can be represented as a pair of integers `start` and `end` that represents a booking on the half-open interval `[start, end)`, the range of real numbers `x` such that `start <= x < end`. Implement the `MyCalendar` class: * `MyCalendar()` Initializes the calendar object. * `boolean book(int start, int end)` Returns `true` if the event can be added to the calendar successfully without causing a **double booking**. Otherwise, return `false` and do not add the event to the calendar. **Example 1:** **Input** \[ "MyCalendar ", "book ", "book ", "book "\] \[\[\], \[10, 20\], \[15, 25\], \[20, 30\]\] **Output** \[null, true, false, true\] **Explanation** MyCalendar myCalendar = new MyCalendar(); myCalendar.book(10, 20); // return True myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event. myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20. **Constraints:** * `0 <= start < end <= 109` * At most `1000` calls will be made to `book`.
Store the events as a sorted list of intervals. If none of the events conflict, then the new event can be added.
Design,Segment Tree,Ordered Set
Medium
731,732
767
Hello gas welcome to me YouTube channel so today we are going to solve the problem seven six seven your nice string so what is the question that I have been given a string and the characters have to be rearranged in such a way that any two characters It should not be equal. The one with adjustment is fine as it is, so now it is A. B. So this cannot happen. Even if you do it, keep only one. Still keep it. Then two A will go. If this is not possible then it will be empty lion. Will return. Okay, so this is a question, so what will be its root four solution? Let's see by leaving the time constant. Okay, for now, let's leave the time constant, no matter how much it is, it doesn't matter, just find out the basic solution, like if A is B, then A is B. If it happens then it is three permutations and it can also be that it is from both the characters so a little less permutation is being made but then take out the head, okay then what other way can there be, if it is too much then the time complex is too much, so now this How to optimize ? So, for example, ? So, for example, ? So, for example, on this example, I have to rearrange it in such a way that no adjacent one should remain equal. Okay, so how can we think about this? So see how many distinct characters I have in this, and if there is only one, then I should take a character which has higher frequency, what will happen to it that it will get adjacent And the character which has low frequency, so the one with low frequency is doing the one with low frequency, there is A next to it in adjustment, now that one with low frequency is two and mother, take A, B was A, so now we have taken B. What back did I have If I If I If I finished it would have been profitable, but in 1 lakh less Bastar, it has less relief than a few, if it is with some character, then what will we do in this too, that we are whose maximum character. We will choose that one first, it is beneficial that while doing it till the last, its frequency will reduce, if it is high then we will have to finish it first, otherwise it will go back to the last, so we will do the same, we will take the one with high frequency first, okay B-2 Yes, there is one and this is also one, okay at one place, okay, now what is my shortage, I will take the one which has higher frequency first, then I will do 1000 and the second one which has higher frequency, why because I will have to finish both of them quickly otherwise. That one will go back in the last, if we don't finish it first, then Ed, we took it first, and still, and yet, and the alien is fine here and there, it went back quickly, from the beginning, you take it from A, less, let's put it from B first, then like put it. Then we put one more big and then another big and then how much did A get 2 4 3 5 It happened that if A is more then if we make adjustments to it then we will get more benefit and then B will also get the benefit. The second maximum character which will be the second last to be created will have to be eliminated first, so we will take the maximum and the second maximum again and again from this and then we will create it, so as you see, we will take the maximum character, first we will take A, how much of this child do I have? Done from five, still we will open, we will finish first because there are chances that he will go back in the last, ok, it became less, then it became three, now look, again B came, B is done, ok, so what to do, names will come out and second maximum. It will come out fine and after taking it in the loop itself, then we will connect both of them and then we will mine the frequency of both, so see if we can do better than this, we will raid the loop again and again, then find out the maximum second maximum and then do the frequency, then it would be better than this. What can we do so that it can be done in a single transaction? Okay, so for this, if I have three, two, one, okay, now what data structure do I have in which there is always maximum relief at the top, how do we enter it? If we give maximum at the top then it will be maxi max data and then we will keep on addressing, we will take maximum second maximum and then we will do 20 mines till we keep doing it as long as there are two characters inside it then it is fine so like if we take the first then it should also be like that the frequency of both should be minus. Gone one by one, okay, still then A and B became zero, now how can this also happen in the last, okay, so what will we do for each of the A's, we will take them out and add them outside the loop, okay so that You could have directed it like this but you have to put a condition that which of the two characters has a child, add it, now see, you can optimize it a little more, how now take mother, I have B and C, it's fine, this can never happen. How much is N in it? So we will not be able to keep 426 plus in it. So if any character is more than N + 1/2 then we cannot keep it. So let's is more than N + 1/2 then we cannot keep it. So let's is more than N + 1/2 then we cannot keep it. So let's see its code. The code is also very easy. There is nothing much so see what we did first sir. Optimize by finding out the frequency and maybe in the beginning it should be said that if the frequency of any character is more than n+1/2, more than n+1/2, more than n+1/2, how to do this, A and E are more than 3, it is okay and its para is first and second. The first one will have its frequency and the second one will have its character. Okay, the character should also be known whose character is that which we have popped above. So keep it first because you can do it in any way, whatever you will keep first, based on this. But it does, okay, so we keep the frequency on it, the computer will compare, the one with the maximum frequency will be kept in the open, okay, so now it is okay to iterate, what will be on the top, the one with maximum will remain first, so whatever is the maximum, now again and again I You will have to check which is the maximum and in which second, so take out the maximum and pop it first, it is okay, it will be added later by doing minus one, but if you do not pop the time, then again it will give the maximum, this character is okay. So we will pop it, if we give another character besides this then we pop it and then this del is got the second character. Now what did we do in the answer, who was added to the first one, the string that created the answer, when we were pushing here, for how long was we pushing? We were saying that now if it has become zero then there is no benefit in putting zero again with zero frequency. If the zero one has become zero again in the line then give greater one, only then we will ask again after doing minus one the frequency is one. Ok, in this way the same was done in p2 also. Now see what will happen in this method. We are going with a valid key. In the beginning it will be impossible only if the frequency of any one is more than n+1/2. It will be bought there only, more than n+1/2. It will be bought there only, more than n+1/2. It will be bought there only, how will invalid ever come here, it is okay below this is where we return these valid ones, so whatever is made here will always be your valid cut, so why are we adding it here, mother? Take a character that went back, like this one came back like A B, this one came first and then again relief from both now becomes zero but not from both because in the first time both of them would have been a sin and then the second time. Both of these become zero together, so if there is one, that means there is an extra character, it has to be added. Okay, then what is its time complexity? N vector is created.
Reorganize String
prime-number-of-set-bits-in-binary-representation
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Math,Bit Manipulation
Easy
191
63
Aa Gayi Ab School And Welcome To Brothers Pages In This Video You Will See The Question Unique Part-2 Situated At The Top Left Corner Part-2 Situated At The Top Left Corner Part-2 Situated At The Top Left Corner And Download The Bottom Right Corner Of Northern Part Of Speech And Travels And Tours And Travels Distraction Or Dash Kholo Unique Path Know Why Can't You Travel With Specific And So You Can Travel Part-1 Subscribe Possible Unique Sin Robot Top Left Corner You Need To Read And Write The Thing 's Problem subscribe and subscribe 's Problem subscribe and subscribe 's Problem subscribe and subscribe the Channel Please subscribe and subscribe the Of the last point the festival is this Going to definition and by doing but in all possible predictions for all the sense secondary I will find out the past decreases that particular point and adding amazed at how do you do solution to the great and subscribe top left corner subscribe definitely possible for you Can Only Move In C Plus One Comment The Conjuring R0 N0 Tak Olympic Record Calling Function On These Tourists And C Where You Can Result In A Very Fatal Attraction Can Improve Your Life Will Give Me The On The Great Subscribe To Exhibition Setting To Dinner Finally I can just return the past white navratri diet hai to aapne one column kunwar natwar singh dang ding dang is digit hai 210 mein united condition me ram setting back ismail one column harisingh out of the bond and above great value is an object in the interest of Just returning from this point to that is the water problem does not come to the point to point and doing part plus one class 10th hua ke ahmedabad based dak par bichh diye se subscribe give you have enrolled in kollam size of me and you are this Used for using back and intermediate result re turn of the same size add top grade in his leadership quality killers will not with its values ​​in - a that in finally absolutely dad on the great and bring water and returned and the last salute cigarette and approach undhiyu Subscribe &amp; 2019 - Simply Written On Co Subscribe &amp; 2019 - Simply Written On Co Subscribe &amp; 2019 - Simply Written On Co Unmute Calculator n And Meditative Value Of The Rupee Fall Will Impact Today's Edition After Departures From Right Hand Is Used In Addition To Return To Power &amp; Used In Addition To Return To Power &amp; Used In Addition To Return To Power &amp; Subscribe Button Click Reduce To Off Subscribe The Amazing Waterproof See You That Do it relative by using top downloads from particular point to this point I will be coming from left to stop them from the road and columns right to reach is this point tours from all parts of the year from top to bottom flashlight on corner how Many Unique Pa Possible From This Point To The Point Will Be Taking One Arrested By Others Which You Will Not Be Knowing You Will Update You Can Read And Subscribe To Who Is The First Sale And 10 Starting Salary In This Just 1000 Know Where Possible Axis To You Are You Will Only Be Updated On Kar Do That You Will Behave In Condition Score This Post Vacant Post Column And For All The Shamil How To Know The First Come First Will Get 2014 That Navneet To See The Condition When They Can Feel 140 The Self Bomb 80 And Unreasonable Only If They Special Weight And Tips Current Se It A The Subject And Said Its Previous Celebration Reachable In Case Of Previous Role And Previous Column Name Not Doing - - - - And Previous Column Name Not Doing - - - - And Previous Column Name Not Doing - - - - Give The Value Of Karan Se At Least 108 Seervi notification other edition of life in a hua hai main finally fuel just written in the bottom right corner hai hua hai pehle front is code india getting upset result list up ministers and not submitted for the time complexity over this issue of crops and Where's Going Uber Slow Trick Butter Space Complexity Extra and A
Unique Paths II
unique-paths-ii
You are given an `m x n` integer array `grid`. There is a robot initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. An obstacle and space are marked as `1` or `0` respectively in `grid`. A path that the robot takes cannot include **any** square that is an obstacle. Return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The testcases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** obstacleGrid = \[\[0,0,0\],\[0,1,0\],\[0,0,0\]\] **Output:** 2 **Explanation:** There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right **Example 2:** **Input:** obstacleGrid = \[\[0,1\],\[0,0\]\] **Output:** 1 **Constraints:** * `m == obstacleGrid.length` * `n == obstacleGrid[i].length` * `1 <= m, n <= 100` * `obstacleGrid[i][j]` is `0` or `1`.
The robot can only move either down or right. Hence any cell in the first row can only be reached from the cell left to it. However, if any cell has an obstacle, you don't let that cell contribute to any path. So, for the first row, the number of ways will simply be if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] else obstacleGrid[i,j] = 0 You can do a similar processing for finding out the number of ways of reaching the cells in the first column. For any other cell, we can find out the number of ways of reaching it, by making use of the number of ways of reaching the cell directly above it and the cell to the left of it in the grid. This is because these are the only two directions from which the robot can come to the current cell. Since we are making use of pre-computed values along the iteration, this becomes a dynamic programming problem. if obstacleGrid[i][j] is not an obstacle obstacleGrid[i,j] = obstacleGrid[i,j - 1] + obstacleGrid[i - 1][j] else obstacleGrid[i,j] = 0
Array,Dynamic Programming,Matrix
Medium
62,1022
1,689
hello friends so today in this video we're gonna discuss a problem from lead code which is a medium problem name is partition into minimum number of deci binary numbers so the code is very simple i'll first tell you what the problem statement is telling you to do it states that you are given a decimal number in desi binary form or a number in deci binary form is a number which consists of only zero and one okay so as you can see any number which consists of zeros and ones are called deci binary number now you are given a string s that consists of a positive decimal integer so you are given some integer which is like 32 or like this number or very large number in a form of a string so now you have to represent that integer into minimum number of deci binary numbers so you have to represent this number into the minimum number of decimal numbers how much minimum number you have to use that's the problem so now what you can see in this problem is every number can be represented by only zeros and ones and if you add them then you can get that number okay so now what you can easily understand is if you want to get a two here okay then every number which you have any two numbers will be having one at this position and one will be having zeros because when you add all of these numbers these two will this one will add and become two and all of these one will add and give three what you simply find here is this number three which is the maximum among all of these digits is the number of ones required so if i have three then i should have three numbers all having one okay in this as you can see i should be having eight numbers such that this position should be one in all the numbers but in the in this position you can put only two now like two numbers to be having uh like one and other should be zero what i mean by this is let's assume i have some number which is equal to okay let's change it out i have an outline yeah so let's see if i want let's see here uh 32 so if for a third number what you can easily see here is for all the numbers on the first position there should be one but for the second position what you can do here is you can put like one number has been zero and other two numbers having one so that the sum will be 32 okay so as you can see it means that three is here so it means that there should be three numbers because if i have less than three numbers then i cannot get three here because for getting three here there should be three like there should be at least three numbers so that everyone should be having one then only i can get a three at this point for two i like because this number is less than three then for this two what i can do is i can make any two numbers one and just leave out the one number which is zero maybe it is zero here again so what i can do i can make all of them zero so the simple technique what you can see here is i should be having the minimum number of numbers required is the maximum among all the digits because the maximum number i can get is like the maximum digit i can get is nine so in maximum of nine numbers i can make every number because if i want to make lectures 92 then what i can do here is i can make nine numbers all having one and only two numbers i can make one and other them should be zero so that it should be nine and they should be two i will get the point so what you can simply do in this problem is just iterate over all the integers or like all the characters in this string and then find out what is the maximum integer that convert that character into integer and find out which is the maximum integer and that's the number of uh numbers actually you are required to form the total number of uh like total number of desi binary numbers required to make this string number i hope you understand the logical quote for this problem if you have any doubts you can mention on i'll see you next time until then keep quoting and bye
Partitioning Into Minimum Number Of Deci-Binary Numbers
detect-pattern-of-length-m-repeated-k-or-more-times
A decimal number is called **deci-binary** if each of its digits is either `0` or `1` without any leading zeros. For example, `101` and `1100` are **deci-binary**, while `112` and `3001` are not. Given a string `n` that represents a positive decimal integer, return _the **minimum** number of positive **deci-binary** numbers needed so that they sum up to_ `n`_._ **Example 1:** **Input:** n = "32 " **Output:** 3 **Explanation:** 10 + 11 + 11 = 32 **Example 2:** **Input:** n = "82734 " **Output:** 8 **Example 3:** **Input:** n = "27346209830709182346 " **Output:** 9 **Constraints:** * `1 <= n.length <= 105` * `n` consists of only digits. * `n` does not contain any leading zeros and represents a positive integer.
Use a three-layer loop to check all possible patterns by iterating through all possible starting positions, all indexes less than m, and if the character at the index is repeated k times.
Array,Enumeration
Easy
1764
1,588
hi i am shim gupta and today we are solving some of all odd length summaries it is a easy level problem on lead code uh problem is very straightforward like uh they give us a vector i have to return the sum of all odd length subsequence of this array like uh what will be the odd subsequence let uh see from this explanation uh one will be the subsequence four two five three and uh and another odd length subsequence will be three length a length of three where one four two can be a subsequence four to five will uh we have one of them and two five three and uh here is the last one which is the length of 5 so it is also the odd length so we have to return the sum of all or odd length subsequences right so yeah so let us let's start okay so um for doing this question uh i will be using prefix sum and i will create a prefix vector where i stored the sum of the running sum of the vector let's create one first of all let's declare the size of the given array and for the same size i will be creating a prefix some prefix sum array where i will be storing the running sum of the vector right so let's assign letter sign the first element of this sum will be the first element of the given array okay so right let's create a variable sum and we will store our sum of all the odd length subsequences and return this sum and at the final as a final result okay so uh okay so let's traverse through the vector and create a prefix array okay so pre some prism of i will be the sum of the previous index plus the current index and let's store the sum of this array okay in the sum vector actually uh here in this step i calculated the sum of these five subsequences of length one so iterating through this i can see the sum of these five because it is a length of one so i just created a sum variable initiated with the first element and iterates iteration start with the one till the end then i will be having the sum of all these five subsequences right okay this is the one thing and the next thing is this prefix sum array um as you all know that what is prefix i hope you all know but let me give you a brief about what is the prefix sum array like uh prefix summary of the uh let's understand from this one example like example uh i have an array uh any of values 1 comma 2 comma 3 right and if i want to create a prefix sum array for the for this a vector so what will i have to do i will create a same size of a vector as a um three named as pre named it as a three okay so uh in this vector i will be storing one at a first index and one plus two at a second index one plus two plus three at a third index right so um this is uh what will be this uh where do i use this i will be using it uh for calculating the sum of the ranges like if i want to uh want to have a sum of these two numbers then i will directly return this index of this vector it will it has a sum of these two elements so i will directly return that uh this index in our order of o of one right of one okay this is a very small vector so um we don't have we don't see the proper use of this prefix sum but suppose our array of a very big number so in the in that case a prefix sum array will help us so to uh to solve a bigger problem we created a prefix sum array okay so now let's after creating this let's declare okay i'm actually uh it is a length uh odd length so uh i started it with initialize it with two and uh i incremented in every iteration i increment the value of i with two so i so in this manner i will be having the odd length so for j will be started from zero and the condition that i can put here uh g n um j plus okay second loop is in the second loop uh we will be checking that if j equals to zero right in that case i will be directly uh return i will directly sum the value of three of i three sum of i right please sum i okay pretty soon okay so um otherwise if not true then i will be summing the value of i plus j minus my bad sub 3 sum okay free sum of j minus 1 okay so let's understand why this is working like uh if i have to calculate the sum of uh some of this two these two values so how do i you use this prefix some array to calculate the sum of two or three so what will i do i will access this element and minus uh the iv minus like uh at the this index the sum will the sum that is stored here is the sum of first index second index and third index right from our a array first index plus second index plus third index it is the sum of third index right so um so if i have to calculate the sum of these two numbers so what will i do like one plus two plus three so i will subtract the uh the second index the index before the second index like this is the sec at the second index from this point to this point i will be having the sum of uh some of those two indexes so uh so what will i do there is an extra one here so that's why i want to subtract this index from this in this manner i will be having the sum of uh 2 plus 3 right like 1 plus 2 plus 3 minus the index before the second like i want to calculate the sum of the range for uh first comma second index this is the range that this is the range uh in which i want to calculate the sum right in our air this is a one index one first index in the second index so i want to calculate the sum of this two indexes inclusively right so yeah so i want to do this so for doing this what will i do i will be doing this in this manner 3 of second minus three of zero y zero uh because uh one is uh is already summed up at a second index so i want to subtract this value so that's why this uh i'm subtracting this value okay so from this value subtracting this like it will become 1 plus 2 plus 3 minus 1 so in this manner what we left with 2 plus 3 and this is what i want to calculate right like 2 plus 3 right so this is how it's working okay so great okay so now uh our sum variable having the sum of all the odd length subsequences of the vector right so now return what happening caps return um so i guess um okay i guess this will work let's check okay just cooking my bread okay let's check this on the other test cases great okay now let's submit let's see okay so the uh suda uh our solution get accepted so thank you for watching that's it for this video
Sum of All Odd Length Subarrays
sum-of-all-odd-length-subarrays
Given an array of positive integers `arr`, return _the sum of all possible **odd-length subarrays** of_ `arr`. A **subarray** is a contiguous subsequence of the array. **Example 1:** **Input:** arr = \[1,4,2,5,3\] **Output:** 58 **Explanation:** The odd-length subarrays of arr and their sums are: \[1\] = 1 \[4\] = 4 \[2\] = 2 \[5\] = 5 \[3\] = 3 \[1,4,2\] = 7 \[4,2,5\] = 11 \[2,5,3\] = 10 \[1,4,2,5,3\] = 15 If we add all these together we get 1 + 4 + 2 + 5 + 3 + 7 + 11 + 10 + 15 = 58 **Example 2:** **Input:** arr = \[1,2\] **Output:** 3 **Explanation:** There are only 2 subarrays of odd length, \[1\] and \[2\]. Their sum is 3. **Example 3:** **Input:** arr = \[10,11,12\] **Output:** 66 **Constraints:** * `1 <= arr.length <= 100` * `1 <= arr[i] <= 1000` **Follow up:** Could you solve this problem in O(n) time complexity?
null
null
Easy
null
173
welcome to tim's leco challenge this problem is called binary search tree iterator implement the bst iterator class that represents an iterator over the in order traversal of a binary search tree now what is the in order traversal of a binary search tree if you recall it's basically the leftmost then the node itself and then the rightmost that's going to give us actually the sorted order of our bst essentially we want to form a class that's going to kind of mimic the recursive call but we have two functions here we could return a has next which is a boolean of whether or not there is another node available or the next which returns the value of this current node and then moves the pointer to the right so this kind of makes it seem like the best way to do this is to append our node values into an array doing it in order traversal using like a recursive function and then write functions for has next and you know that would be pretty easy but let's try something else let's instead try to simulate the recursive stack here uh using this iterator so if we were to do this in order how would this recursive stack look essentially we would go remember in a in order traversal we go left and then this node and then the right node right well if that's the case then we would go left and if there's anything to the left again we'll go left and then we'll put onto this recursive stack all the lefts and the very last one when the where there is no left node anymore that's the smallest value right so what's the next one after that well it's the one that's on top which would be like on this recursive stack whatever is on top of that but we have to also make sure to add the right node of this node onto our stack as well because we can't just not uh assume that there's no more left there is going to be more on the right side and to that right side there might be more on the left side again so basically what we'll have to do is once we pop off the smallest node we'll check to see if there was a there's a value to the right of this node and there is we will add that and then we'll also add everything to the left to kind of mimic that recursive call so i'll show you what i mean let's just say we had our bsd iterator and we have this tree nodes i'll clear up a little bit what we'll do is we're gonna have a stack here and this is gonna kind of simulate the recursion i'll be empty at first and if this is in order we're gonna go left as long as there's a left one right so we'll have just mimic that we'll say cur current node is equal to the root while there's a curve we're going to add to our stack this uh tree node and then we're going to go to the left say left and that at the very top of the stack should be the smallest number so here it's say seven then we go here and that'll be three and then that ends our uh current recursion right now what do we do when we go next well we clearly we have to pop off whatever is on our stack right so make sure that there's a stack to begin with if not self.stacked then we just return um i self.stacked then we just return um i self.stacked then we just return um i don't know we turn none i guess otherwise we're going to pop off whatever's on ourselves whatever's on our stack but before we return this value we want to make sure to add on to our stack here okay whatever this is here there could be some values to the right of it right and because think about if there's something to the right of this it would be 4 or b5 or v6 and if that was the case that's not on our stack yet so we have to add that but it's not just that we also need to add everything to the left as well to make sure that the next one is indeed the next number that's going to be greater than this number so what i'll do is let's just have current pointer pointing at the candidate we'll say if there's occur dot right well uh well let's make curry equal to kurt all right otherwise if there's not then curve will sequel none and we're going to mimic the same thing here we'll say uh while cur just add it and then go all the way left again and the very top one should be the next number that's where this has next all this really is whether our stack is empty or not the stack shouldn't be empty if there's more nodes coming down the pipeline so what's the return self.stack whether that's equal to an self.stack whether that's equal to an self.stack whether that's equal to an empty list or not all right so let's make sure this works here looks like that is and there we go so this is just a old n time complexity and because of our stack i suppose it's also all then space complexity but uh but yeah i kind of like this problem because um it kind of simulates the recursive uh stack if you were to do this recursively and kind of just gives you a nice idea of like how it looks like uh you can certainly just put it into an array and you know return the index numbers like that but uh what's the front of that right all right thanks for watching my channel remember do not trust me i know nothing
Binary Search Tree Iterator
binary-search-tree-iterator
Implement the `BSTIterator` class that represents an iterator over the **[in-order traversal](https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR))** of a binary search tree (BST): * `BSTIterator(TreeNode root)` Initializes an object of the `BSTIterator` class. The `root` of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST. * `boolean hasNext()` Returns `true` if there exists a number in the traversal to the right of the pointer, otherwise returns `false`. * `int next()` Moves the pointer to the right, then returns the number at the pointer. Notice that by initializing the pointer to a non-existent smallest number, the first call to `next()` will return the smallest element in the BST. You may assume that `next()` calls will always be valid. That is, there will be at least a next number in the in-order traversal when `next()` is called. **Example 1:** **Input** \[ "BSTIterator ", "next ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext ", "next ", "hasNext "\] \[\[\[7, 3, 15, null, null, 9, 20\]\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\], \[\]\] **Output** \[null, 3, 7, true, 9, true, 15, true, 20, false\] **Explanation** BSTIterator bSTIterator = new BSTIterator(\[7, 3, 15, null, null, 9, 20\]); bSTIterator.next(); // return 3 bSTIterator.next(); // return 7 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 9 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 15 bSTIterator.hasNext(); // return True bSTIterator.next(); // return 20 bSTIterator.hasNext(); // return False **Constraints:** * The number of nodes in the tree is in the range `[1, 105]`. * `0 <= Node.val <= 106` * At most `105` calls will be made to `hasNext`, and `next`. **Follow up:** * Could you implement `next()` and `hasNext()` to run in average `O(1)` time and use `O(h)` memory, where `h` is the height of the tree?
null
Stack,Tree,Design,Binary Search Tree,Binary Tree,Iterator
Medium
94,251,281,284,285,1729
965
hello friends so today we are going to discuss another lead code problem the problem is uni valued binary tree so what is the problem description so we are given a binary tree and we have to check whether the tree is uni value so what does it mean univolu means what so if every node in the tree has the same value and what we have to written is we have to return the boolean value so it can be either true or false so let's take an example one so here if we see from the top and if we go down the bottom from at the left side and similarly at the right side so we can see what are the value of the root node that is the one and we are having its children's and its grandchildren all are having the same value so that's why for the example one the output is true now let's see the another example 2 so here if we can see the root value is 2 then its children value left and right is again 2 but if we see the left children and left of left children so it has the value of 5 and that's why it is returning as a false so it's a pretty straightforward problem so let's get into the code part so here we are given a function is unique value and which accepts a three node that is a root node as a parameter so what we are doing here so let's say if our tree is empty at the initial state so we just have to simply return true because empty tree has a nothing so that's why it is a true now what we are doing is we have created a pre-order function over here pre-order function over here pre-order function over here and it has two parameters one is the three node and another its current value so what it does is so it's basically a simple left traversal and a right traversal of the tree so inside this function what we are doing is we are again doing the same check if the tree node value or if the root is none then we are simply returning true and let's say what so initially if we see over here for the example if you can consider any of the example let's say if you consider the example one over here so initially this prime that is previous value that is a one so we are checking over here with so whether this root value is equal to previous so here the root is one and again the previous value is also one so this condition doesn't get satisfied so here it goes to this block so here what we are doing is we are simply doing the left order traversal and we are doing the right order traversal and we are making sure that whether we are getting true value if both the sides are true it means we are finding the similar value on the left of the tree and similar value or the same value on the right side of the tree in that case only it will return the true and finally we will get the output as a true over here okay and in case if it doesn't get matched so either of the tree will return the false at this line so let's say for example at the right side in example 2 if we get the true as a response over here but in terms of if we see the left child of child so in that case or we can say grandchild so here 2 will not get matched with the 5 and that's why it will return the false so false from the left side that is a false and true from the right side but again it is a condition and conditional operator so it will not go to execute the right part because the first condition is false so implicitly it will return the false as an output so let me quickly run this and let's see the output okay so here the solution is super fast and the runtime is 0 millisecond which is a faster than 100 java submission and let's see the test case coverage so we can see it has covered all the 72 test cases over here now let's come to the time complexity and the space complexity of this algorithm so we are not initializing anything new or any kind of data structure so time complexity is uh sorry the space complexity is big of 1 and in terms of the time complexity so we are going down the bottom of the tree so that is a time complexity is big of height of the tree so we can consider it as a big of h or big o of n whatever it is suitable so i have posted the solution on github and i have uploaded the link in the description section below so if you like this video please do like and share this video and comment this video and stay tuned for the next one thank you
Univalued Binary Tree
unique-email-addresses
A binary tree is **uni-valued** if every node in the tree has the same value. Given the `root` of a binary tree, return `true` _if the given tree is **uni-valued**, or_ `false` _otherwise._ **Example 1:** **Input:** root = \[1,1,1,1,1,null,1\] **Output:** true **Example 2:** **Input:** root = \[2,2,2,5,2\] **Output:** false **Constraints:** * The number of nodes in the tree is in the range `[1, 100]`. * `0 <= Node.val < 100`
null
Array,Hash Table,String
Easy
null
1,751
hey everyone welcome back and let's solve our more lead code problem today so today we're going to solve lead code uh 1751 which is going to be the maximum number of events that can be attended too uh so we're given an array of events where each event consists of three value or three values which is the start date the end day and the value and uh the event stats at the start date so let's take this example uh so it starts on day one ends on day two and it has a value or we get a profit of four by attending this uh similarly the other event stats on this day ends on this day and we get a profit of this so we have an even list like this and the K is the upper bound on the number of events which we can attend so we have to attend uh two events we cannot do more than that and we want to maximize the total uh the total value of the profit which we can do by attending this event so return the maximum some of the values that you can receive by attending demons now whenever we have something like maximize or minimize then just make sure that it's something which is probably going to involve dynamic programming and for this particular instance it also we also see that uh it involves intervals kind of a thing so when you get something like intervals uh think about sorting when you see something like maximizing on minimizing think of GB is probably going to be one of those so it's this problem also is involves sorting also and DP as well so similarly let's have a look at one event example just to understand uh this better so we have these events and the value of K is 2. so how many events can we attend so there's one more condition which is given that if you're attending particular events you can't really uh start an event which ends on the same suppose if you attend this event uh you can't really uh go ahead and attend this because this is going to end on day three and the next event should be definitely be more than this okay so for to you to be able to attend this event the start date has to be greater than or strictly more than the end date for this event so it has to be at least four for you to be able to attend this so if we can try all possible different combinations but uh this is the answer or this is the event which is gonna do the one which will be attending we can't really take this also because it ends on day two this starts on day two so yeah it should not be overlapping okay it should be a strictly increasing uh for you to be able to attend that so that's the answer for this problem uh now let's have a look at the constraint okay so uh we see that uh we're given a constraint in this manner okay K times events that length has to be less than this value which is usually five times ten to the power five or ten to the power 6 in this case now this gives us some idea that our state has to be uh comprising the value of K and also the events total length or the indices so these are some essential uh things which we can see from here and the approach we will be taking for this is going to be the knapsack zero one kind for DP uh we'll also need to store these intervals because uh we will be starting out from the first one and then we can just move on based on the start time we're going to start this entire events list and then we're gonna go ahead perform binary search to find the next possible uh interval of the state which we can transition to and then it will try to maximize the total uh profit which we can get by attending these events so let's hit the drawing board and see what's the approach which we'll be taking for this problem thank you all right guys so uh we have the given list and the first step over here would be to sort this given list by the starting value so what I mean is the start time you'll be sorting this uh given list of the events and once that is done we will be using this for State transition and also for performing the binary search so that we can find the next optimal state which we want to transition to now the state for this uh recursive dp01 Maps app kind of a problem will consist of two values one would be the index and the next one would be the value of K currently at this age so K is going to reduce by one so it's three it'll go to two one and then we'll stop once it reaches uh zero so these are the two values which will consist of the state and we will start off with the first element itself so we'll start off with uh zero comma the value of K which is three and we're going to move ahead from this value now uh at each index or at for each element we have two options either we take that or we don't so let's suppose we can take two possible routes from here okay so let's suppose we take this value so we're going to add the value okay are we going to take the value for this even which is a one in this case we're going to take one over here and then we're gonna move on to the next state now uh notice that for finding a next stage we're giving a condition that the start value of that state has to be uh at least bigger or it has to be strictly more than the end value for this particular event okay so in this case suppose it's one in this case now if I want to move on to some other uh event it has to be greater than one so at least two should be the start value of the next event which I want to attend or which I want to take so we're gonna do a binary search on this segment okay the one starting from here reason being it's sorted and the next reason is it will help us bring down search to log of N and yeah that's the core concept over here in this question so we'll have to do a binary search to find such value which is strictly more than the end value of the current event which I'm attending so we see that it's still only in this case Okay so we're gonna move on to that particular uh event and now the state here in this case would be one which will be the index now of your own and game will go down by one so it will be two in this case it's okay so we're at the same similarly if we didn't choose to move uh to uh take this event we can just move ahead we can just increment I and we can just keep the state same as before right now suppose we're on this state uh I can take this event so I'll just take that and I'll add two which is the value we have over here the value over here and then I can just move on to one more uh state which is two comma one and Y2 because it has this three is strictly increasing then the N value which we have over here of two right so we can move to the set similarly I can skip this so in that case I can just move on to two comma two and that's how State transition works for this particular case okay I'm at zero one two I'm at three comma 3 automatically now I need to move on to the next particular event and I can definitely do that so with a value of three I move on to 3 comma zero but I have to stop over here because K is now zero and we're going to stop our recursion at that point itself so that's one value which we got over here that's one two and three so this is one of the uh possible answers but we're trying to maximize that so that's why we use the DP approach over here now coming on to this brand suppose here also we have two options either we take or we don't so I'm just gonna skip some of the states which uh we won't really get the optimal answer on and I'm just gonna go with the most optimal uh possible uh sequence okay so from this um I'm at okay so now I'm at one so this particular one uh I want to take this value so I'm just going to take this value I'm just gonna take two and I'm gonna move on to the next step which is two comma two and from this 2 comma 2 I can move on again by taking this value to I will take three and now I will move on from this to this one okay so for sorry I'll rather move from this to the next one so now I can move on to the state for uh comma one or rather sorry it will be uh it will be three comma one which is that state and I'm again gonna take that value which is four and I cannot really go any further from here because uh that's basically the end of the list and we're just gonna return from that recursive call now notice that we are actually able to uh get the most optimal answer in this case so if you see this Branch the total was one plus two plus three that's six uh however on this particular uh case Okay uh now this will be zero now if I go down this path uh my answer would be uh zero plus two plus three plus four and that comes to uh nine right so that is the most optimal uh answer for this case and our uh recursive function is just gonna maximize this value and yeah we're gonna just return nine as the final answer for this uh problem so yeah we're gonna use a recursive function now notice that these states are repetitive okay so we have to come 2 and we have state overlapping sub problems as we can see so whenever you have overlapping sub problems it means that you're going to use dynamic programming so we're going to use memoization and we're going to Cache the values for these sub problems and that will essentially help us speed up the performance of our uh this recursive calls right so that's the kind of solution which we'll be implementing now if I just talk about the uh Diamond space complexity for this problem so uh notice that uh if you talk about the time complexity so we're doing it in a recursive fashion okay and then the first thing which we're doing right away is uh we're solving this uh entire error right so it takes o of n log of n complexity of just saw this and we're using a recursive function which is called for each event and each value of K now the number of recursive calls depends on the number of events and also the value of K and in the worst case each event is considered for each value of K resulting in total of n times K uh recursive calls and we have the bisect uh function as well but just call within the solves to find the next event and that starts after the current event ends and that will have an O of a log of n complexity for the binary search so the overall time complexity uh is the sum of all these values so that is a big go of n log n plus n times K Times log of n so that is the overall time complexity uh talking about the space complexity the even list is stored as an instance variable uh you'll see in that in the code and so it does not really contribute to the space complexity because you're getting that as one of the inputs uh the space complexity of the recursive function it's determined by the maximum recursion depth right and which is K so each recursive call consumes an additional space on the call stack therefore the space complexity would be a big O of K for the recursion depth and uh yeah we're also uh storing uh for basically caching those values but then that's going to save us some value so yeah we can say that uh the space complexity is going to be o of K for the space and for time we have already calculated that this is the time complexity so yeah that's about it the solution and let's now have a look at the code for the problem and that will help you better understand the entire implementation all right guys so now let's have a look at the code from the problem so the first thing is I'll be uh using or I'll be putting things in the init for this just to keep the recursive uh function uh easier to read so we have the events over here now coming to the max value uh I'm just gonna solve these events okay and by default it would be sorting it by the first value which is the start time and so it works for us else we would have used a key with some sort of a Lambda to be able to do that now I'm just going to put this events in the instance variable and then we're just gonna return our recursive function which is going to be solved starting would be zero comma K the first index and we have the entire K with us now let's go move to the core function which is going to be the solve and over here let's put the base cases first so if I is greater than length of uh events then we'll be returning uh zero and if K is also uh less than or equal to zero we can't really move forward so we're just going to return 0 in this case so these are the base conditions now uh we have two options okay so B uh we have two options uh either uh we can take events at I or not okay so these are the two options uh so let's see how we write the code for that so first we're gonna take uh s e and B which is going to start and then the value for the current event or the index we're one so these are the three values and then we're just gonna find the possible State or the index we can move to so we're just going to use the internal bisect uh method which python provides uh in another case you can just uh use your own uh yeah implementation of the binary search now what this basically does it will go over this eye table or this list in this case and it will find the index where I can put on this value now we're just comparing the start times remember and it has to be strictly more than the current end time so that's why we are using e plus one we don't use e because uh that would just give us an overlapping value we want to find for E plus one because we want it to be higher than the current end time so that doesn't catch and just take care of that otherwise it will give you the wrong answer so that is one thing and then we will just return the maximum okay so as the question says we want to maximize the value so we have two options we take this uh particular event so in that case we're just going to add the value and then we're going to move ahead and solve it for J and K is going to be reduced because we are have attended an event in the other case we can just move ahead because we're not using this particular uh event okay so we're just gonna move in to the next index okay we're just we're not going to go to J because since we're not attending this we can safely move ahead to the next particular index as well so it's going to be I plus 1 comma K in this case k won't get reduced and that's about it so that's the entire implementation for this um problem let's try to run this it should work okay it works and now one more catch we'll have to uh kind of uh be able to Cache this okay so you can either use a cache okay so you can use a self.cache uh which is going to be a self.cache uh which is going to be a self.cache uh which is going to be a dictionary uh where you can use ink as the states and then you can just check it in the solve and you just return if the value is already there in the cache okay another easier way in Python is just use the cache decorator that's going to Cache things for you that's it but yeah you can always go ahead and use the cache if you want and that should work and now let's try to submit this it should work and perfect it works so yeah we're done with this question and yeah that was it thank you so much for making it this much through the video in case you have any questions queries or any problems with this or any suggestions please leave that down in the comments below and I'm just gonna meet you guys very soon with some other video and also please share this video like the video and also subscribe to the channel it's going to help us a lot and we're gonna come back with a lot of content around system design object oriented programming and also more lethal problems until then goodbye and have a great day foreign
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
654
hey everybody this is Larry this is day 20th or gen 20th I'm trying to do more uh basically we've done the pro or I've done the prom that the daily uh prom is and I'm trying to get my money's worth by picking one random PR I haven't done before and today's random PR is 998 maximum binary tree 2 it's a medium prom uh and apparently has a lot of downloads so we'll see how this goes uh a maximum tree is a tree where every no has a value greater than any other node in the sub isn't that just a heap that's a he I mean I guess a heap is a it's a is it complete or I forget the term for it but a he it does fit this description though it may not be the general version of this but any case uh you're given the root of a maximum binary TR and integer value just as the previous just a previous form should I do a previous one first all right I guess I should do the previous one first I don't know all right let's just do this one first and then I'll make a second video doing this one maybe all right let's just do this one first uh so if you're watching this you may be confused about the title bit and how I get here but makes sense right so okay Maxim create a no value is Maxim okay yeah recurs build this upgrade okay so just repeatedly get the max right so how what is the idea well what is the sub build the left sub tree what oh so basically if you're given but see that's the part that I don't think oh uh oh Subway prefix okay I see I didn't really read this correctly uh all the numbers are unique all right I mean this is pretty straightforward what does this remind me of I mean I guess this is just like um like I mean it's not quite the same but it is the same idea with like sorting structures right um but yeah it's not that bad um so the way that we can think about it uh so we'll just have a construction thing and then here we want the left right um and yeah left right what is that it yeah I guess that's it right and basically what this does is recursively uh or yeah construct the current node yeah right and here basically we have and I think you can actually um I'll talk about the complexity later but I hope that it is not n well okay it is going to be n square but n square is fast enough is this not n Square no that's I don't know sorry I'm jumping around a little bit but yeah this is going to be n Square in the worst case but you can actually do it in much faster if you're really slick about it um and you can do this in linear time but in you can do this in linear time but that's a ridiculous solution but in any case okay but yeah and I'll explain why in a little bit but or how in a little bit but yeah so then here we have the max value is equal to just Max from nums sub left to right um I think right but plus one to make it inclusive cuz I like it to be inclusive here I like my function to be inclusive um I don't know it doesn't have to be it's just that's the way I like it right so then now um yeah and then now we have nums index of this number we probably could actually do this like much cleaner just add some lazy I'm just lazy uh okay fine uh no yeah okay let's just do it in a non La way l so okay so max is equal to num sub left um max index is equal left I guess Max index is fine right and then now we have for I and range from left plus one to right + one because we want plus one to right + one because we want plus one to right + one because we want to right inclusive uh if num sub I is greater than num sub Max index then maximum index is equal I something like that right so now we have the maximum index then now we can construct left Max index minus one so this is going to be the left um so this is the left note oh that actually over Shadows the variable so left node right node is equal to construct right uh um max index plus one right and um and yeah and then now we can return a new node a tree node where the value is equal to the max so num sub Max index uh left node right and of course we actually have to change the base case scenario a little bit which is that if left is greater than right then we return none I think that should be good right and then now we just have to return construct um zero and then n right or n minus one and it will give us AIT hopefully this is fast enough and it looks Gucci and we're good but yeah uh so a couple things I mean I did this pretty quickly but hopefully everything kind of follows um but we just recursively look at the sub away which is what they tell you the prefix and the subx um and we have to get the index for the maximum Index right um so what's the complexity here well it turns out that if you have like a link list thing kind of similar to this and the max value is the last item say then um then basically every node is going to only take out one node and so then this uh range thing is going to make it n Square because you the first time is going to take n operation then n minus one operation n minus 2 dot all the way to one and then of course that's going to be n Square over two some is and which is n square right so this is going to be n square but you can actually reduce this by using some sort of rmq solution RQ thing stands for R range I guess range Min Curry is the common one but obviously this in this problem you can convert it to Max and because the um the list of numbers is uh con or you know it's static um you can pre-process it to static um you can pre-process it to static um you can pre-process it to answer queries um you may even be a would do better than that to be honest but I but like with rmq directly but in any case even if you just do that you're able to do this in all of one time and therefore you're able to um you know like instead of having a loop you're able to get the maximum index in all one so that means that every construction of node is going to take all of one so that's going to make it linear time linear space that's pretty much it um I am going to um if you're looking for this video I don't of your um since this is R anyway I will have a different video right after this uh but yeah but that's all I have for this one hopefully it didn't go too fast let me know what you think uh yeah stay good stay healthy to your mental health I'll see you in the next video and I'll see you later bye-bye
Maximum Binary Tree
maximum-binary-tree
You are given an integer array `nums` with no duplicates. A **maximum binary tree** can be built recursively from `nums` using the following algorithm: 1. Create a root node whose value is the maximum value in `nums`. 2. Recursively build the left subtree on the **subarray prefix** to the **left** of the maximum value. 3. Recursively build the right subtree on the **subarray suffix** to the **right** of the maximum value. Return _the **maximum binary tree** built from_ `nums`. **Example 1:** **Input:** nums = \[3,2,1,6,0,5\] **Output:** \[6,3,5,null,2,0,null,null,1\] **Explanation:** The recursive calls are as follow: - The largest value in \[3,2,1,6,0,5\] is 6. Left prefix is \[3,2,1\] and right suffix is \[0,5\]. - The largest value in \[3,2,1\] is 3. Left prefix is \[\] and right suffix is \[2,1\]. - Empty array, so no child. - The largest value in \[2,1\] is 2. Left prefix is \[\] and right suffix is \[1\]. - Empty array, so no child. - Only one element, so child is a node with value 1. - The largest value in \[0,5\] is 5. Left prefix is \[0\] and right suffix is \[\]. - Only one element, so child is a node with value 0. - Empty array, so no child. **Example 2:** **Input:** nums = \[3,2,1\] **Output:** \[3,null,2,null,1\] **Constraints:** * `1 <= nums.length <= 1000` * `0 <= nums[i] <= 1000` * All integers in `nums` are **unique**.
null
Array,Divide and Conquer,Stack,Tree,Monotonic Stack,Binary Tree
Medium
1040
760
hey guys today we're going to talk about rico 760. you know since i didn't pay the premium and so i cannot access it but i found a tweak they you know sim crush in lincol you can if you don't know his website he use it too you know they give you access to the premium problems in legal and basically the question is find anagram mappings so what's an anagram so basic anagram is a word of face phrase formed by rearranging the letters of a different word or face so yeah this is definition and let's look at if i have examples so see like fried or fired listen or slam silent you know so all right so let's go to the link right here and let's look at the approach so we explain what's the anagram and then what's given a two array a and b right here well a and b and then where b is energy of a and what i want to get is return an index array representing what's the position from a to b so look at the example right here so if a have elements 12 28 46 3250 b is this arranged range different index so what i want to return is okay where is 12 and b it's an index one so we'll put one where is 28 in b in x four so we put index four right here and then so on and so on so that's what we're gonna get so how can we approach this problem it's pretty simple so first we create a array p that will return our result okay so a length okay and what we need okay we what we can do is we can use list because the list they have a index of method which we will need for when we get a index for a particular element so when you list this type image we call it list of b okay all right and then right now what do we add element in b to list b for elements all right and next we look to the a array so if we check so basically so at every index we want to set it to this b dot get the index of the particular element a so basically just like that all right so and then return p so yeah it should be there you know and the runtime should be open yeah accepted all right accept this so run time should be open time complexities o n but the space is o and two because we play a lisp all right thank you guys for the video if you like this video if it helps you help you um the journey of inner proof prepping like the video subscribe to the channel share to your friends share it to the freshmen in the school study computer science all right i'm gonna call until i get to google facebook netflix apple boom see you next time
Find Anagram Mappings
bold-words-in-string
You are given two integer arrays `nums1` and `nums2` where `nums2` is **an anagram** of `nums1`. Both arrays may contain duplicates. Return _an index mapping array_ `mapping` _from_ `nums1` _to_ `nums2` _where_ `mapping[i] = j` _means the_ `ith` _element in_ `nums1` _appears in_ `nums2` _at index_ `j`. If there are multiple answers, return **any of them**. An array `a` is **an anagram** of an array `b` means `b` is made by randomizing the order of the elements in `a`. **Example 1:** **Input:** nums1 = \[12,28,46,32,50\], nums2 = \[50,12,32,46,28\] **Output:** \[1,4,3,2,0\] **Explanation:** As mapping\[0\] = 1 because the 0th element of nums1 appears at nums2\[1\], and mapping\[1\] = 4 because the 1st element of nums1 appears at nums2\[4\], and so on. **Example 2:** **Input:** nums1 = \[84,46\], nums2 = \[84,46\] **Output:** \[0,1\] **Constraints:** * `1 <= nums1.length <= 100` * `nums2.length == nums1.length` * `0 <= nums1[i], nums2[i] <= 105` * `nums2` is an anagram of `nums1`.
First, determine which letters are bold and store that information in mask[i] = if i-th character is bold. Then, insert the tags at the beginning and end of groups. The start of a group is if and only if (mask[i] and (i == 0 or not mask[i-1])), and the end of a group is similar.
Array,Hash Table,String,Trie,String Matching
Medium
null
1,091
hey everyone welcome back today we are going to solve problem number 1091 shortest path in binary Matrix first we will see the expansion of the problem statement then the logic and the code now let's dive into the solution so here I have taken the second example from the lake website so here we are given a binary Matrix which consists of 0 1 and here 0 represents a path and one represents a block right one is like an obstacle right and we need to find a path from top left corner to the bottom right corner and we need to check whether we have a clear path or not so a clear path should be connected by zeros right so in this case it's all connected with zeros so which means there is a path exist and if there is no path exist we need to return negative one right so we need to start from top left cell and we can visit the adjacent cells in eight directions so the eight directions are something like this right so these are my eight directions and I'm going to solve this problem using BFS approach so initially I will make the first the top left corner cell as 1 which means I have visited that cell right and I will store the row and column of that particular cell in a queue so here 0 and 0 represents the row and column of the top left corner cell right and I will be initializing it with 1. so the one represents there was a path here since there was 0 which means that is one path so now we need to start visiting the address and cells from this particular cell so since these two cells are blocked we don't have to visit them we only visit when there is a 0 exist when there is a path so initially we are going to start from 0 and 0 right that is 0 throw and zeroth column cell and the distance of this particular cell is 1 that we initialized here so from this cell we are going to visit the adjacent cell that is 0 and 1. that is 0 through and First Column is zero since it is 0 we will make this as 1 which means we have visited this cell and I will append that particular cells rho and column and I will add the distance as well I will use the previously seen distance that is 1 and I will increase it by 1 so I am going to get 2 here so far we have covered a distance of 2 right I will append that particular cell row and column indices and the distance covered so far in the queue so I will run this Loop until I finish all my values in my queue so I have seen these values in the queue now I need to see this value so now we are going to start from 0 through and this First Column cell so our I will be 0 and J will be 1 and distance will be 2. so this is nothing but the zeroth row and First Column indices right that we appended in the queue so we will use Q to visit each and every adjacent cell right so in this case we have zero throw and First Column and the distance is 2. so we are going to visit the next adjacent cells from this cell right we need to visit all eight directions so here there are blocks since there are once we don't have to visit them we only care about these two cells right since that are the clear paths here so now I will visit this particular cell right which is nothing but 0 through and second column and the distance is 3. the reason why it is 3 is the previously seen distance is 2 the distance from this particular cell is 2 so we will add one so it becomes 3 right so we will append this one in the queue so there will be 0 2 and 3. then I will make this particular cell as 1. which means I have visited that particular set then from this cell I can visit this particular cell I can visit in eight directions so I can visit this particular cell as well so this particular cells rows 1 and column is 2 and the distance is 3 again from this cell the distance is 2 and I will increase it by 1 which will be 3 then I will append this to my queue so here we will be getting 1 2 and 3 then I will make this cell as 1. so now I have visited all the clear paths from this cell right I cannot visit any more cells from this side so I will return to the queue I will pick the next set of values so I will pick 0 2 and 3. so I will be 0 J will be 2 the distance is 3 right so which is nothing but 0 through second column so we will be here now so from this one I cannot visit any other clear path sorry there are no zeros adjacent to this cell so we don't have to visit any other cell so we will pick the next set of values from the queue which is nothing but 1 2 and distance is 3. so first row and second column which is nothing but this particular cell and from this cell I can visit this particular path that is the bottom right path so the row will be 2 and the column will be 2 so and the distance will be 4. from this cell the distance is 3 and I will increase it by 1 so it will be 4 and I will append this to the queue right so there will be 2 and 4. then I will make this cell as 1. since there are no any other paths we don't have to visit any other cells then we return to the queue and pick the rows and columns 2 and the distance 4 from the queue so whenever I pick values from the queue I will check whether I have reached the bottom right or not I will use this row and column indices to check whether I have reached this particular bottom right corner or not since I have reached now I will just return the distance 4 that is the shortest path in my binary Matrix right that's all the logic is now we will see the code so before we code if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting guys so here n represents the length of the grid so initially I will check if the top left and bottom right Corners are one or not if it is one which means they are already blocked so there is no path exist so I will just directly return negative 1 right then I will be creating a queue where I will initialize with the row 0 through and 0th column indices and with a distance of 1 and I will make the 0 through the top left corner value as 1 which means I have visited that cell right so here I am writing a for row where I will pick each and every values from the queue so the rows and indices are I and J and the distance of that from that particular cell is D then I am checking whether I reached the bottom right corner or not if I have reached the bottom right corner I will just return the distance d right then I'm creating the eight directions here then I will start visiting all eight directions from the currently picked cell from the queue and if it is 0 I will make that particular cell as 1. then I will append that particular cell to the queue and I will increase the Distance by one for that particular cell right and if there is no clear path is exist I will be returning negative 1 as my answer right that's how the code is now we will run the code as you guys see it's pretty much efficient thank you guys for watching this video please like share and subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
Shortest Path in Binary Matrix
maximum-average-subtree
Given an `n x n` binary matrix `grid`, return _the length of the shortest **clear path** in the matrix_. If there is no clear path, return `-1`. A **clear path** in a binary matrix is a path from the **top-left** cell (i.e., `(0, 0)`) to the **bottom-right** cell (i.e., `(n - 1, n - 1)`) such that: * All the visited cells of the path are `0`. * All the adjacent cells of the path are **8-directionally** connected (i.e., they are different and they share an edge or a corner). The **length of a clear path** is the number of visited cells of this path. **Example 1:** **Input:** grid = \[\[0,1\],\[1,0\]\] **Output:** 2 **Example 2:** **Input:** grid = \[\[0,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** 4 **Example 3:** **Input:** grid = \[\[1,0,0\],\[1,1,0\],\[1,1,0\]\] **Output:** -1 **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 100` * `grid[i][j] is 0 or 1`
Can you find the sum of values and the number of nodes for every sub-tree ? Can you find the sum of values and the number of nodes for a sub-tree given the sum of values and the number of nodes of it's left and right sub-trees ? Use depth first search to recursively find the solution for the children of a node then use their solutions to compute the current node's solution.
Tree,Depth-First Search,Binary Tree
Medium
2126
930
See in this video we are going to do question let code 930 binary sub ares with some live now binary are i.e live now binary are i.e live now binary are i.e one iragi of zero and one wait goal will be given to you d return d number of non empty sub is with some goal aisi kitni It will be sub ars whose sum is tu hai sabar i.e. the consecutive whose sum is tu hai sabar i.e. the consecutive whose sum is tu hai sabar i.e. the consecutive numbers are ok so as given here what is the output let's see the expression this is my what is it and see here their sum is two ok and their All are two, okay, the sum of this morning is also two and the sum of this sub error is also two, okay, next example, what is one, it is binary, okay, there is no problem, all are zero, what is round also, if it is zero then How many sub arcs will be out of this? Hey, you are in the form round zero, ok, they must have made all the combinations, how much is the output, 15 is ok, one, two, three, ok, five, ok, then what did you do? 5 6 7 8 9 By doing this, 15 will be made. Okay, any number of combinations can be made. Well, how can we approach the problem? Now see, when I was solving lead code 560 in this playlist, I had told you that when the restrictions become strict then How do we solve the questions? Okay, so we will adopt the same approach in this question also. Okay, let's start, take mother, this is my pass, one and the goal is two, okay, so what do we take out, we take one mother, prefix. Hey, let's take out our okay 1 2 and 3 obviously zero started we have our okay and like lead code 560 we had approached it in exactly similar manner we will approach it what we have to do is to take out such morning whose sum Two are fine or in other words we have to find which sub are and are happening with some, as you will see all these are different and are happening here, similarly this one is morning and are happening with some. You are similar to this one savere and ho rahi hai with some tu and this one savere and ho rahi hai with some tu ok so from this I thought and ho rahi hai with some tu achha so you can prefix it with sum Now you will see, mother, at this moment I am here, okay, I have to bring out how many beautiful ars are there which are happening on this one, okay, then the crossing prefix is ​​​​this, okay, so you will see prefix is ​​​​this, okay, so you will see prefix is ​​​​this, okay, so you will see if I use all these. All or whatever is written here, I round three minus, what am I saying, three minus round or prefix sum, I round minus, that is, one if one has already been prefixed, then we See how many times it has come and how many times it has come here, like it has come here twice, then our result answer will be implemented twice. Okay, if you pay attention, if you have not understood why we are doing this. Delete code is 560 question, look at it. Okay, I have gone into depth in the question. Okay, if I tell you the same thing again and again, I will go crazy. Okay, so this is a similar question. Let's start with lead code 560. What do you do first? Let's take a result, wait, okay, which we will make beautiful in the end and return it. Okay, now see what is written here, I told you that we will check whether we have already accessed the prefix or not. If so, tell us what should be done for that, we are the prefix, we are not going to take it, here we will take a prefix, we will wait, it is only okay, and we will store the prefix even in the map, it is okay, map in teacher is equals, you are okay, we will store in it which one. How many times has the prefix sum 'A' come? How many times has the prefix sum 'A' come? How many times has the prefix sum 'A' come? Okay, in the beginning, let's put in the map that 'Brother, zero' has come once. Okay, then the that 'Brother, zero' has come once. Okay, then the that 'Brother, zero' has come once. Okay, then the loop goes on and i = 0 i &lt; loop goes on and i = 0 i &lt; loop goes on and i = 0 i &lt; i plus. Okay, let's take this in a way. Waiting for days and it will do what is the prefsum on the current index? Okay, in the result, like I told you, what will you do with plus is equal, what will you do with map.get and the default will be understood what will you do with map.get and the default will be understood what will you do with map.get and the default will be understood - this is what the volume was saying to you, isn't it? - this is what the volume was saying to you, isn't it? - this is what the volume was saying to you, isn't it? -How many times has the goal come in the map? -How many times has the goal come in the map? -How many times has the goal come in the map? How many times has the goal come? If I don't come then I will add zero. Okay, obviously I will update you as well. Okay, as it will be seen here, Maa, here I am, then I have come again with two. Okay, if two comes again, then two will have to be updated, now two has come twice. Okay, so I will write this brother, now get and Audi fault yes com zero plus one. Okay, that's all brother, this is the question from three third. The question is out of all, it has been accepted. After submitting, let's see, everything is done. Talking about space complexity is big of N and time complexity is of N. You know that first of all we were doing questions about arrest. Add more to this playlist We have come to Hashman Pe, we saw that how can the questions be stubborn, how can they be 2.2 Sliding Window, we can they be 2.2 Sliding Window, we can they be 2.2 Sliding Window, we saw that now look at the condition that is there, the restriction that is there is very exact, okay, so that is why we had to do this. If there is a loose condition from the map, then how do we do it, like if something like this happens here, then we do it with the sliding window, it is okay, there is no problem, video, you will get the link of the next video on this card ]
Binary Subarrays With Sum
all-possible-full-binary-trees
Given a binary array `nums` and an integer `goal`, return _the number of non-empty **subarrays** with a sum_ `goal`. A **subarray** is a contiguous part of the array. **Example 1:** **Input:** nums = \[1,0,1,0,1\], goal = 2 **Output:** 4 **Explanation:** The 4 subarrays are bolded and underlined below: \[**1,0,1**,0,1\] \[**1,0,1,0**,1\] \[1,**0,1,0,1**\] \[1,0,**1,0,1**\] **Example 2:** **Input:** nums = \[0,0,0,0,0\], goal = 0 **Output:** 15 **Constraints:** * `1 <= nums.length <= 3 * 104` * `nums[i]` is either `0` or `1`. * `0 <= goal <= nums.length`
null
Dynamic Programming,Tree,Recursion,Memoization,Binary Tree
Medium
null
1,652
hey guys welcome back to my channel and i'm back again with another really interesting coding interview question video today guys we are going to solve questionable 1652 diffuse the bomb of lead code before i start with the video guys if you have not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications of more such programming and coding related videos let's get started so basically guys the problem statement says that we have a bomb to diffuse and our time is running out so we are given a circular array like this okay and uh so what we have to do is this circular array of code to its sort of a code to diffuse the bomb okay and if you want to decrypt the code we must replace every number of this code with a certain value okay all the numbers are replaced simultaneously that means one after the another and how to replace that number so basically we are given a value called as k okay so let's say these are our codes and this is our k value this is sort of our key right so if the key value or the k value is equal equals to 0 if it's equal equals to 0 so we have to replace the ith number with 0 or we can say that if k value is 0 then all the code values must be replaced to 0. if the k value is greater than 0 then we have to replace the ith number with the sum of the next k number so for example 5 has to be replaced with the sum of the next three numbers which is 7 1 and 4. so you can see that if i just crawl below it 5 is replaced by 7 plus 1 plus 4 then 7 is replaced by the sum of the next 3 numbers but because this is a circular array so after 1 and 4 the third number would be 5 so that's why the sum is 1 plus 4 plus 5 similarly 1 is replaced by 4 and the sum of 5 and 7 and 4 is finally replaced by the sum of 5 7 and 1 okay so once we do this then we get this array as a result and we can just return this error this is our decoded code so once you have decoded the code you can diffuse the bomb okay now if the k value is less than 0 then you just have to do the reverse you have to replace the ith number with the previous k number so for example in this case 5 will be replaced by the sum of 4 1 and 7 because they are the previous k numbers or i would say 4 will be replaced by 1 7 and 5 because they are the previous k numbers okay so another example you can see here that k value is 0 because k is 0 all the values of code are replaced by 0 and finally this example is a negative example which i have already explained you so every number is replaced by the previous two numbers so for example 3 is replaced by the sum of 4 plus 9 okay the constraints are pretty straightforward guys n is the length of the coding area and the n could go from 1 to 100 so basically there could be 100 values uh the value of the code could be from 1 to 100 and the k value can go from minus n minus 1 to n minus 1 okay so basically the length of the array right so now that we know about the problem statement guys let's go to the solution part so to start off with the solution guys i am going to first of all declare our result array and to do that first of all i'll create an element called as len which is basically going to hold the length of the code and it's a code dot length now i am going to declare the result array which i am going to return so enter is in bracket rest becomes equal to new inch and pass the length so now that we have declared the resultant array that we want to return okay so the first thing if k is equal equals to zero so let's start with the base case guys because if we are done with the base case that's the simplest case right so for if k is equal equals to zero so for integer i to zero so i less than length i plus you simply have to replace all the elements with the zero so as i becomes equals to 0 and then we will do the else condition else if k is greater than 0 some logic and then else is then k is less than 0 finally when all the if else conditions are done then we are just going to simply return the resultant array okay so uh the first case is done k is equal equals to zero we take all the result elements and then we simply assign them 0 and we return the resultant array okay so the second case is when k is greater than 0 so guys if k is greater than 0 then we are going to iterate from then also we are going to iterate all the elements so 0 to i less than length i plus but then for every element we are going to replace that element with the sum of the next key elements so we are going to do another follow for integer j equals to 1 to j less than equals to k j plus but instead of making res i becomes equals to 0 here we are going to replace rest i or we are going to assign reside to the sum of the next j element so less i become equal to s i plus add the jth element to it okay or i would say i plus jf element to it so i plus j so let's say if i is 0 so for example i is 0 so the first element which we added is the element at index 1 then the element at index 2 and then the elemental index k like so on and finally all of them will be added to rest i and if you continue this for loop then all the resultant values will be the sum of their next k elements right but obviously guys if you do i plus j and let's say the value goes greater than the length of the array you are going to get an array index out of bound exception so to cater that situation you have to do the mod of the i plus jth value with the length of the array if you do the more guys what are you going to do for example if my j is at position 3 so 3 plus 3 becomes equals to 6 if i do 6 mod 4 then i will reach to value 2 which is index i mean i reach to value 2 which is the second index here so eventually i will add one and then i will go behind and i will add all these values okay so basically if you mod it with length you will start iterating from behind instead of or you will start iterating from the cyclic position so that's why we are doing this so that even if our i plus jth value goes greater than length it will not give us the air index out of bound exception instead it will start iterating from the other side of the array okay or from the left hand side of the array now so we know is great k is greater than zero so that part is also sorted now comes the complex part is when k is less than zero so this part definitely guys we need that means iterating the ith value from 0 to i less than length i plus 1. so this thing we definitely need because we are going to replace all the values of the resultant array but because k is less than 0 this time we have to think about it from a different way so because k is less than 0 instead of iterating from integer j to 1 to less than equals to k we will create j becomes equals to minus 1 to j greater than equal to k and this time instead of doing j plus we are doing j minus okay because remember this is a negative volume okay so because this is a negative value we cannot iterate it from 0 to k or 1 to k value right we have to go from behind minus 1 to greater than equal to k now so we have got the negative value right and what index do we want to reach let's say i want to iterate the previous element so the previous element will becomes equals to i plus j right because let's say if my ith value let's take this example so if my ith value or my index value is 3 and my k value is minus 2 so i want minus 1 that means this one so when j is minus 1 then minus 1 plus the ith l value so for example in this case i is 3 and if you subtract 1 from it you will reach index 2 so index 2 will get added and then when j will be in you know minus i would say so when j will become from minus 1 to minus 2 that means this value then i is still 3 so i 3 minus 2 becomes equal to 1 so eventually we will reach 4 and 9 and we are just going to simply add these two and store them in res value okay so don't get confused why i am doing i plus j because j is negative see even if i am doing i plus j i'm still going on an index which is previous to us okay remember that obviously guys the j value could be something which is greater than the length value okay so i my i plus j could be a something uh something like minus 4 for example in this case the maximum index is 3 right whatever it becomes what is whatever it becomes minus 1 okay or minus 4 something so we don't want that so that's why always do a mod will length so that we uh reach at the value which is always contained inside our array now if our index value let's say my index value is greater than 0 then it's good but what if my index becomes equal for example if my index is 0 right if this is my index if i am at this position and the kth value is minus 2 so my next index if i go by this volume will be minus 1 right 0 so i 0 j is minus 1 0 plus minus 1 is minus 1 correct so if i try to go to a position which is minus 1 i'm not going to find it anywhere right so if you always get an index which is lesser than 0 then it basically means you have to go to a position which is previous to it so for example if i am at minus 1 if i add minus 1 to the length of the array is 4 add minus 1 to the length of the array so what is going to happen you are going to reach to the last position similarly when you will come to minus 2 for example if i add i 0 first j will be minus 1 second j will be minus 2 so then i will reach minus 2 here if i add minus 2 to my length i will reach the second last guy so that's what you have to do if your index is lesser than 0 then just add the index to the length of the array by this you will actually start iterating the array from the other side okay from the behind finally res i will becomes equals to rest i plus code of index okay then once this else is completed you have covered all the cases so just return rest so let's run this code guys let's see if this works for our example cases uh okay there is some error okay fine i wrote return rest multiple times so you just have to write it once so you can see that the example case is accepted and yes you can see that the solution is also accepted now talking about the time complexity guys so the time complexity for this solution is uh going to be n into k because we know that the length of the array is order of n and the number of times we are adding the k elements is always k right this is the for loop which we are running k times so that's why the time complexity is order of n into k the space complexity guys is order of n because we are creating another resultant array which is having the same length as that of our original code array okay but i hope guys that this solution was clear to you and it works for you as well and hopefully it helped you in improving your coding practice if i did guys then please do not forget to like this video and share this video with your friends if you are not yet subscribed to my channel then please do subscribe and hit the bell icon for future notifications and uh also guys uh thank you so much for watching if you have any comments write down in the comment section below i would be happy to read them and work on them uh so thank you so much i'll see you guys in the next video until then take care and bye
Defuse the Bomb
minimum-suffix-flips
You have a bomb to defuse, and your time is running out! Your informer will provide you with a **circular** array `code` of length of `n` and a key `k`. To decrypt the code, you must replace every number. All the numbers are replaced **simultaneously**. * If `k > 0`, replace the `ith` number with the sum of the **next** `k` numbers. * If `k < 0`, replace the `ith` number with the sum of the **previous** `k` numbers. * If `k == 0`, replace the `ith` number with `0`. As `code` is circular, the next element of `code[n-1]` is `code[0]`, and the previous element of `code[0]` is `code[n-1]`. Given the **circular** array `code` and an integer key `k`, return _the decrypted code to defuse the bomb_! **Example 1:** **Input:** code = \[5,7,1,4\], k = 3 **Output:** \[12,10,16,13\] **Explanation:** Each number is replaced by the sum of the next 3 numbers. The decrypted code is \[7+1+4, 1+4+5, 4+5+7, 5+7+1\]. Notice that the numbers wrap around. **Example 2:** **Input:** code = \[1,2,3,4\], k = 0 **Output:** \[0,0,0,0\] **Explanation:** When k is zero, the numbers are replaced by 0. **Example 3:** **Input:** code = \[2,4,9,3\], k = -2 **Output:** \[12,5,6,13\] **Explanation:** The decrypted code is \[3+9, 2+3, 4+2, 9+4\]. Notice that the numbers wrap around again. If k is negative, the sum is of the **previous** numbers. **Constraints:** * `n == code.length` * `1 <= n <= 100` * `1 <= code[i] <= 100` * `-(n - 1) <= k <= n - 1`
Consider a strategy where the choice of bulb with number i is increasing. In such a strategy, you no longer need to worry about bulbs that have been set to the left.
String,Greedy
Medium
null
67
Loot Hello Viewers Welcome Back To My Channel Suggestion Or Their Discussion Of The Problem With Difficult For Me To Death You Not Laga Do Video Please Like It Subscribe To My Channel Subah You Get Notified When The Most Innovative Without Any Positive Let's Get Started Problem In Add Binary Very Simple Problem Jeevan To - Singh Binttu Returns Problem Jeevan To - Singh Binttu Returns Problem Jeevan To - Singh Binttu Returns The Amazing I Let Us Take Care Sweet Dreams Take Care That Iyer Dates Posting End Second Singh 832 30 Inch Loongi 10 End Second Will Do Something Like This Switch Boys Atin Sodium Wave New Updates To Wicket 0f Result And Jerry That Is Vansh Hai Main To Yeh Saying This Time Naav Siron A Plus Dushman A Plus B S One Witch Carrier Song Again This Is OnePlus One So And You Will Be Amazed And Jerry Will Again 1500 Plus 9900 OnePlus One Is The Wicket 0characters for entered unemployed form will get your own so that is zero brigade and carry again with one of which will welcome one plus0 a plus b 0 bhi hua sorry armaan welcome and 109 rates might even so are some of two in 0tweet that Debit, that is a Dnyaneshwar, what are you doing, lying down, the hundred pleasures of hundred discharges, the knowledge that this 1010 and more than 40 plus one will be around 110 012, 12000 1.11 lage to will get unemployed, career and 1.11 lage to will get unemployed, career and 1.11 lage to will get unemployed, career and city improvement, your will go air. And [ __ ] city improvement, your will go air. And [ __ ] city improvement, your will go air. And [ __ ] tomorrow morning get 10101 cigarette 1010 ₹3 network problem sleep approach from this what are you doing basically a v we are starting from this is from the lost with you can see from outside the right side and 2018 in it Value e will be 0 in this app you will come here bhi jio phone par dheli will want oo torch light show with me to in and jin viewers ko * and jin viewers ko * and jin viewers ko * and values ​​of not only sharing liquid and values ​​of not only sharing liquid and values ​​of not only sharing liquid and drink it is this position for example sentences with Oo A Plus Wear Also Adding That The Hai But E Will Se Wear Not Adding Carryover Year To English E Will Take Carrier Rear AC Wind Carrier G Solve V Value Will Give Water You Will Want Ho To Amlon Candidates Need To Get Value Hello How Old Values On oneplus one bittu models of this tweet 2.0 in order to calculate value with 2.0 in order to calculate value with 2.0 in order to calculate value with that what will you do sammohan tilak to ki and spirit 253 how to that with spirits of but that will be divided into two will get a to 100MB understood what we Have Done Wear Every Time You Will Be Traveling Like This Is Trick Single Line More 210 Out of 150 Start From Decide Anil Arrangement Various Places And Will In Turn Will Always Be Done S Five Plus B Plus Ap Hai Initial Career Min 10 hai to initially given starting from this 202 plus dushman plus carriages you will come on tourism welcome to my election mintu 910 value will be the song mode to ab to here 360 ​​maurya vansh models to medium nominated 360 ​​maurya vansh models to medium nominated 360 ​​maurya vansh models to medium nominated member value get also ward 34 value vitori Ne Spinning Records All Neetu Harvesting Ne Distic This Attack Ka Answer Arranged String In So Gillard Value of Interesting Questions and Answers in Preparation and [ Preparation and [ Preparation and Divide 2012 Listen to 12345 Value Is Vansh Apes Ring in Your Eyes and Still Alive 210 Medium to One Plus One No Value Vikram to Motu Experts Sudhir Will Not After Which One Will It Before You are Calculating the Neither Its Disposal of 1000 Before the Co Tight It Life and Works Career Welcome to Back to Which is My Choice Career Option Will Repeat Also Step Sunflower Do It Now Over What Are We Are You Will Here IS Scheduled For 1000 2000 12 Tenth Results Will Come When Divided Into Two Parts 120 Hands Free Web Counters And No I Will Go On Air So now against this way you will change I am the same a 2051 plus b co 501 and carries you listen come to 200 fund value meaning Vivo before and died to carry mulligan one can carry will update 251 questions video value and patience is to novel torture camp In Forward Innovation Testing's 101 0 Here Open Understood To Prove What They Are Doing Very Simple Questions Beta Testing Carry We Are Doing Song Called Divya Calculating Value And Is Divya Calculating Alone One Medium Alarms Like 2002 Divide In Verification Video Buy To A Plate Here Know Your Parents Should Approach A The Code Very Simple What Doing Well Travels 30 Viewers Rank Calculating the Length of the Best Ringtone Regulating Length of the Best Thing in the Water Havells Vihar Phase Wi-Fi Setting Us Loud in Which Will Return File Continue Until All The Countries For Taking Its Value Is Valued For The Giver The Length Of The Value Of That And This Boy Doing It Because When A To Get This Last Value This Condition Happened By Accident And Wasting Are Eyes From 087 Been Easier To Like and 12th leading that I love you can say is from Delhi and over what doing Bihar taking lives due to its ring is dish 101 indic civilization 0123 so I will here but how to give addition for the right to express will get a Minus minus one index 123 index of this world torch light handed chatting with us in the next to take wire same thing in the interests of the value of calculating the volume to in vivo v9 plus to get converted to avoid panicking for the current Answer Is The Meaning Of The Name Of The And Posting Suite With Me Including 10 Maths Chapter 9 That And Time Black Click Here Its Direct Is Wire Loot Will Run Until All This End Essence Of All Na Niend Vidron Its Soil Health Problems Like Toh It Will Be A Great Help Length And Breath And Give Them A Between Total Yo Honey To Lenses Inspirational Prayer Oil ₹10 Continent Which Oil ₹10 Continent Which Oil ₹10 Continent Which 110th Bhi To Time And Space Complexes Can Stand Were Not Using Excel Data Structure Viewers Using Various withdrawal problem very simple but does so please like subscribe and subscribe my channel thank you
Add Binary
add-binary
Given two binary strings `a` and `b`, return _their sum as a binary string_. **Example 1:** **Input:** a = "11", b = "1" **Output:** "100" **Example 2:** **Input:** a = "1010", b = "1011" **Output:** "10101" **Constraints:** * `1 <= a.length, b.length <= 104` * `a` and `b` consist only of `'0'` or `'1'` characters. * Each string does not contain leading zeros except for the zero itself.
null
Math,String,Bit Manipulation,Simulation
Easy
2,43,66,1031
1,071
hey everyone welcome to techquired in this video we are going to solve problem number 1071 greatest common divisor of strings so here we are given two strings we need to find the largest string that divides both string 1 and string two and now let's see the logic on the solution for this problem so this is the first example that has been given in the Lead Core website and before solving this problem if you guys haven't subscribed to my Channel please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos and keep supporting so here we are given two strings and in the question it says that one of the string is concatenated with other string okay for example here S1 a b c right here S2 is ABC here S2 has been repeated two times in S1 this S2 Plus S2 right so that's how the inputs will be so what I'm going to do here is I'm going to keep S1 as the largest string every time okay I'm going to write a recursive call I'm going to keep S1 as the largest and S2 as the smaller string okay so this will be done by swapping okay if S2 is greater than S1 I am going to swap X1 and S2 so whenever I do the recursive call I'm going to break S1 and keep S2 as it is now I will show the example so initially I'm going to check if S2 is greater than S1 if this happens I'm going to swap okay I will swap S1 and S2 okay or I'm going to call a recursive function okay since I keep S2 as small all base I am guaranteed that the first from 0 to length of S2 it is going to be the first part of the S1 so when this condition fails I am going to return an empty string okay or if the condition is satisfied whether I found my substring of S1 the first part of S1 as S2 then I'm going to break S1 and I'm going to do the recursive call on this part after this okay now I'll show you the recursive call as well so initially I will check S1 is lesser than or yes less than S2 in other words whether S2 is greater than S1 if S2 is greater than S1 I'm going to swap I am going to keep S1 as the largest string always okay and if I don't find the first part of S1 as S2 it should be equal okay if it is not equal I am going to return the empty string and if it is equal I am going to break like this lenov S2 okay then I'm going to do the recursive call on this one this part I'm going to Omit this part so my new S1 here will be ABC okay now I will write another condition I'll write another condition when my S1 and S2 are equal then that is the largest common device the greatest common divisor of both strings and I will always keep S2 as it is the lowest string as it is so even if S2 is greater than S2 when we call the recursive call okay because the function we are writing a condition to swap right so every time is S1 will be it's guaranteed it's going to be largest string or it's going to be equal to S2 if it is equal to S2 I am just going to return my S1 or we can written S2 as well since both are going to be same I will also show you guys with the another example so this is the another example that is found in the lead code so here S1 is greater than S2 I'm just going to keep as it is now I'm going to check whether my S2 is in my the first part of my S1 yes we can we could see that both are equal so my new S1 will be a b okay so this is my new S1 now I call the recursive function since here S2 is greater than S1 I'm going to swap okay I'm going to swap S1 and S2 now S1 will be a b and S2 will be a b fine now I'm again going to check whether S2 is in my S1 I mean the first part of S1 should be S2 okay here it is so I'm going to break S1 again okay my new S1 will be a b okay so now I will do the recursive call again so in this case S1 is equal to S2 right so this is the greatest common divisor of both strings so I'm going to return a b fine now let's see the code so initially I'm going to check whether my string 2 is greater than my length of the string one okay if it is greater I am going to swap string 1 and string 2. I'm always trying to keep the string 1 as the largest string okay I will be swapping here now I'm going to write a condition if the first part of the string one should be string two okay I'm going to Break String 1 with the length of string two okay if it is not equal to my string 2 I'm going to return MP string else and I'm going to write a condition here if my string 2 and string 1 or equal then I'm going to return that string then if I found S2 the S2 in my first part of my S1 then I will break S1 okay I will be breaking S1 so I'm going to call recursively okay so I'm going to break S1 I'm going to take all of the characters in my S1 after the length of my S2 I'm going to break based on S2 okay and I will keep the lowest S2 as same if S2 is going to be greater here when I call recursively it is going to swap here okay if you're going to do this swapping here so it will work it's guaranteed that S1 always be greater than S2 okay so I think it's fine let's run the code as you guys see it's pretty much efficient the time complexity for this particular problem is order of N and the space complexities for this problem is order of n as well since we are using recursion that is going to be a recursive stack right the call stack so it's going to be order of n space thank you for watching this video please like And subscribe this will motivate me to upload more videos in future and also check out my previous videos keep supporting happy learning cheers guys
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
1,290
in this video we're going to go over elite code problem which is convert binary number in a linked list to integer so you have a binary number and you want to make it into an integer a decimal number base 10. so binary is base two that's something you need to know for this problem it's not terribly job specific thing so hopefully if you're if you get this on an interview and you don't know binary is the interviewer to explain it to you but um this is our example one zero one so um just a number like one zero one which is a binary number and this would convert to 5 and it converts to 5 because we have this is our ones place so 1 times 1 and then start 2's place so 0 times 2 that's our fourth place so 1 times 4 is 4 plus 1 times 1 is 5. so that's our first test case we have a couple of other test cases the naive and you know a simple way to do this uh but not the fastest way would be to um traverse through this linked list and maybe add these to a stack or something and then as we pop them off the stack we can um we'll know like what place they need to be so ones place two's place four's place um and then we can multiply each one by that number um maybe we could have a map or something or some kind of um key value pair to do that but there's a way that we can do this in one pass and if you think about let's say we have just this number one zero one so we're going to have a fourth place a two's place in a one's place and let's say we actually have um let's say a different test case for this there's a couple let's say we're just gonna do one zero one just to make it a little more helpful so we have our fourth place two's place ones place in this case we also have an eighth place at the start so another way to look at this is that we have our 1 is going to be 2 to the 0 and we're going to push that out our 2 is going to be 2 to the 1. our 4 is going to be 2 to the 2. let's give a space here and our eight is going to be two to the three okay so this is going to help us as we walk through this problem and this will as we kind of look at this we're gonna figure out how we can do this in one pass so we don't need to do that mapping that i mentioned earlier so here when you look at this you can really see there's like okay this three two one zero so it looks a little more linear and so as we add each number we're really going to be adding one extra thing here and what that turns out to be is we're just going to be multiplying by 2 one more time so how can we loop through these loop through this linked list and multiply by two one more time for each thing so let's look at how we can do that first we're so we get the head here which is the head node which has value at a next points to another node in the linked list so let's go ahead and store um we want current node and that's going to be initialized as head and then we also want our total here we can just initialize that to zero and then we're gonna be looping through this stuff and so we wanna say while there's current node we're gonna do something and in our constraints we do know that there is um there's always going to be a head at least so we're not going to ever have a an empty linked list and then at the end we want to return our total okay so within here we want to adjust our total amount so our total is going to equal remember i mentioned as we're traversing through we're going to multiply by 2 for each different place so each time our total is going to equal total times 2. and that means the first place is going to get multiplied by 2 one more than the second place and so on and so forth so this is going to take care of that for us and then we also because this last number we don't want to multiply by 2 this is just our ones place so our last number is going to be we also just want to add our current node dot val which is the current value that we have so we could condense this into one line but let's just leave it like that for now just so it's a little more clear so we're going to multiply our whole thing by two and then we're going to add the current val so let's get rid of this and add that here okay and then of course we're going to reassign current node equals current node.val excuse me chrono not node.val excuse me chrono not node.val excuse me chrono not next and then we're just gonna go through the while loop and um once we get to the end here the current node.next is gonna be null the current node.next is gonna be null the current node.next is gonna be null so it's gonna set it to null and then current node is going to be null which is the faulty statement so it's going to continue through execution pass the loop and return the total so this should do the trick for us we could run through test cases manually which is what you should do if you're in an actual interview you should like talk through how it would play out but for now let's just run this first test case see how this runs and it's accepted and our second test case will also be accepted we'll see okay it works and then we can go through the rest of these but this is um the fastest solution for converting a binary number in a linked list to an integer and it only takes one pass and it's big o of n time so this is how it's done hopefully this helps you out and we will see you in the next video
Convert Binary Number in a Linked List to Integer
make-array-strictly-increasing
Given `head` which is a reference node to a singly-linked list. The value of each node in the linked list is either `0` or `1`. The linked list holds the binary representation of a number. Return the _decimal value_ of the number in the linked list. The **most significant bit** is at the head of the linked list. **Example 1:** **Input:** head = \[1,0,1\] **Output:** 5 **Explanation:** (101) in base 2 = (5) in base 10 **Example 2:** **Input:** head = \[0\] **Output:** 0 **Constraints:** * The Linked List is not empty. * Number of nodes will not exceed `30`. * Each node's value is either `0` or `1`.
Use dynamic programming. The state would be the index in arr1 and the index of the previous element in arr2 after sorting it and removing duplicates.
Array,Binary Search,Dynamic Programming
Hard
null
1,968
hey everybody this is larry this is me going with q2 of the weekly contest 254 a wave of elements not equal to at rich of neighbors hit the like button hit the subscribe button join me on discord especially if you like these kind of contest forms people talk about the problems all the time usually right after the contest so if you're into that you want to nerd it out with larry come hang out anyway for this one it's kind of tricky it is what um in competitive programming this is what is known as a constructive uh problem there are a number of arrangements and you can do there are a lot of different techniques to kind of figure out a different oh sorry maybe not for this particular problem but there can be many different solutions and you all you have to do is come up with one of them um and this is a constructive problem because you're trying to figure out a strategy where this is not true where the two neighbors are not true um so i kind of thought about it and of course n is 10 to the fifth so you have to do this in a very quick way um in that you know n square is going to be too slow or and n log n is going to be fast enough so that's going to be the approach that we take uh and with these this particular problem you're trying to rearrange the um the array in any way possible so the first thing that i do on these things is that i sort not always but for this one i do because sorting what you're doing with sorting is that you hope that it gives you a structure that you can take advantage of and the thing that i noticed um actually if you watch me stop the live i actually um try to do it another way where because everything is unique so i made one the first observation that i made is that because these are this thing and or one other way that of saying that is that every number is unique because every number is unique let's say we have you know a and b in the first two numbers and we're trying to add c there's only one possible numbers where c is um you know if c is equal to a plus b over two then this is no good but it could be any other number and it'll be good so what i did and assuming that is unique was that i created a q um and what i did with the q was that i go okay if the next number with the top of the stack is equal to this number then we just take it and put it at back of the queue um and then go again um so i thought about it and i implemented this and you can watch me implement this live next but so i implement this and then i was like okay there is a case where that might not be good though right because for example if you just have one two and three now you're stuck in an infinite loop because you just keep on popping three and putting three back in and so forth what you needed to do is put the three next to the two and then that's when i hit a second inside of okay so a number cannot be the average of the two adjacent numbers if it's not in the middle of those two numbers right so i go okay so let's just look at for in this example um in this example we can move the three up for example because three is not within um because we know that three is bigger or yeah because three is not between one and two it cannot be the average no matter what so then the problem in my mind reflects to um how do i make this such that this is the case and what i did was that i sorted i sort the problem or i thought the input and then i take one from the left and then take one from the right so what i'm doing here now is that i take the smallest number and i take the biggest number um let's just say it's one to ten right and then next one i go two nine three eight four seven and dot right um and the reason why there's no average in between is that because for every three numbers the middle number is not between them so there's no average because it's not even in between um so same thing here and same thing here so that's basically the idea that i have and that's the idea that i implemented um you can sort this in uh and yeah of course the complexity here is that so is dominated by the sorting which is n log n time and then here it's going to be linear but it's still going to be dominated by n again um we do have a q and an answer so it's going to be linear space so n log n time of n space uh let me know what you think about this one um i think this one is one of those problems where like it's a constructive problem right so if someone tells you the answer you're like oh of course that makes sense but i hope that if you watch me solve it next you'll see that i'm actually trying different things trying to figure out different ways playing around the numbers to kind of see how i you know maybe get some feelings about it um and that's ultimately what i did i didn't i mean maybe at least in this case i didn't go oh this is you know whatever so i don't know let me know what you think and you could watch me solve it live during the contest next i'll do this thing hmm there's only one number which is so hmm oops hmm um no you could do better than that okay uh yeah thanks for watching hit the like button hit the subscribe button join me on discord especially if you like these contest problems we talk about problems all the time uh of the contest type but you know come swing by uh let me know what you think i'll see you later to a good weekend to good you know mental health and i'll see you later bye
Array With Elements Not Equal to Average of Neighbors
maximum-building-height
You are given a **0-indexed** array `nums` of **distinct** integers. You want to rearrange the elements in the array such that every element in the rearranged array is **not** equal to the **average** of its neighbors. More formally, the rearranged array should have the property such that for every `i` in the range `1 <= i < nums.length - 1`, `(nums[i-1] + nums[i+1]) / 2` is **not** equal to `nums[i]`. Return _**any** rearrangement of_ `nums` _that meets the requirements_. **Example 1:** **Input:** nums = \[1,2,3,4,5\] **Output:** \[1,2,4,5,3\] **Explanation:** When i=1, nums\[i\] = 2, and the average of its neighbors is (1+4) / 2 = 2.5. When i=2, nums\[i\] = 4, and the average of its neighbors is (2+5) / 2 = 3.5. When i=3, nums\[i\] = 5, and the average of its neighbors is (4+3) / 2 = 3.5. **Example 2:** **Input:** nums = \[6,2,0,9,7\] **Output:** \[9,7,6,2,0\] **Explanation:** When i=1, nums\[i\] = 7, and the average of its neighbors is (9+6) / 2 = 7.5. When i=2, nums\[i\] = 6, and the average of its neighbors is (7+2) / 2 = 4.5. When i=3, nums\[i\] = 2, and the average of its neighbors is (6+0) / 2 = 3. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 105`
Is it possible to find the max height if given the height range of a particular building? You can find the height range of a restricted building by doing 2 passes from the left and right.
Array,Math
Hard
null
508
uh this question is most frequent subtree sum so you are given a root and then particular return the most frequent subtruism so just keep adding and then for every single frequency you just put into the map or print to the counter and then you want to keep on track for the mass the highest frequency this is because if you want to return uh you want to return the highest frequency number in a list but at the end you want to return it in Array so um so here's it so I'm going to just use a post order so I'm going to Traverse my left and then Traverse my right and then add my current value and then this is pretty much the idea so uh let me just go through the entire solution and once I type it and then you'll be able to know so I need a map and you know integer right and I also need integers so the first the key is going to be represent the sum and then the value is going to be represent the frequency I also need to keep on some my current the highest Max frequency right as I'm initialize my map to here initialize my mass Max frequency to here I'm going to Tribute my entire tree using a DFS and put in the root and I'm going to say probably so sometimes we use the volume right and in this time we need to use in because we need to return the current frequency number for the current node right so DFA is three no so if the node is already equal to no so which means this is nothing so it just returns 0 else it's going to be sum is going to be equal to what the dfs.noda left Plus dfs.noda left Plus dfs.noda left Plus DFS plus another right Plus no double and so you can definitely use in the pre-order you know definitely use in the pre-order you know definitely use in the pre-order you know in order in this one I'm using post order it doesn't matter the frequency is going I mean the frequency is going to be the same right and yeah this is pretty much it right so uh once I have the song for the current note I need to put the sum into the map but I also need to add a frequency if there is a sum inside the map right so using the map Target or default some if you don't have it then you initial it to zero and then you plus one for the current you know the current sound frequency right and I need to keep a keep on track for my Max frequency equal to master Max and then it's either Mass frequency or what method get some right and then at the end I need to return the song because I need to keep traversing my entire tree based on the frequency for I mean for the current no frequency right so the sum is the current frequency all right so once I have it I need to Traverse my map right so ends key and then Mata key set okay and then I need the current frequency right so on that type get key so this is the current frequency so if the frequency if the current frequency is actually equal to the max frequency I need to add into the inner array right but the problem is we don't know the size of flow in Array so I'm going to just add I'm going to add another list which is a red list I'm going to play Let's Open a list of integer right in order this all right so if the curve frequency is equal to the max frequency I'm going to add into the one the release and what when I add it I need to add a current frequency which is the key right key is a frequency right the sound frequency and then the value is a frequency number like how many time it actually reach right so uh this is pretty much it right so uh when I return I need to return the in Array so I have the array list where I can try I can convert to the inner array based on this using a string and then map two in and you can initialize 2x to X so I don't multiply the value and I need to say two array all right so this is pretty much it right so let me run it right so I forgot uh semicolon so submit so let's talk about the timing space for the time you shoulders every single node it's going to be all the fun and this space is going to be all open as well right uh you put every single no uh sum into the unit I mean into the arraylist OR into the map right so it's all a frame for both so let's you know like I'm going to say the breadcrumb right here because when I Traverse my TFS I know my current uh the map right and I will just keep okay so I'm using a debug mode and just uh look on the left and you know so for the root is what five two negative three right definitely there is an app you know it didn't show and all right so 2 negative 3 4 is actually the answer but uh I don't know why I didn't show uh show the map uh this is pretty much a solution so I will see you next time bye
Most Frequent Subtree Sum
most-frequent-subtree-sum
Given the `root` of a binary tree, return the most frequent **subtree sum**. If there is a tie, return all the values with the highest frequency in any order. The **subtree sum** of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself). **Example 1:** **Input:** root = \[5,2,-3\] **Output:** \[2,-3,4\] **Example 2:** **Input:** root = \[5,2,-5\] **Output:** \[2\] **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105`
null
Hash Table,Tree,Depth-First Search,Binary Tree
Medium
572,2126
329
hey everyone today we'll be looking at longest increasing path in a matrix we'll try to solve it in less than 15 minutes okay it's a hard problem so hopefully we can solve it but if not then need code Baba zindabad let's do this okay given an M N M and N integer mean Matrix return the length of the longest increasing path in Matrix from each cell you can either move in four Direction left right up down you may not diagonally move or outside the boundary that is wrap around is not allow okay so yeah the longest increasing path is 1 12 69 mhm okay uh um mhm the longest increasing path is so why not 1 2 69 that is wraparound is not allowed 3 4 5 six in here 1 2 I don't get it for each cell you can either move okay you may not move diagonally or move outside the boundary that is wrap around is not allowed yeah I get it but duplicates longest increasing path right long this increasing path in Matrix so for me if I uh look at this 1 2 6 9 and I guess the number should not get repeated that is one of the challenge that is there got it so looking at the solution uh looking at the example the number shouldn't get repeated if it gets repeated then yeah so that makes things easier if you look at that way so if I start at like we I have to Traverse through um the array and let's say if I Trav through nine first or how should I decide which should be my moving point or how should we decided I think we have to Travers through the entire array entire Matrix and for every cell you need to calculate the distance and if the new cell uh if we Traverse the cell and if it is the longest one then we need to replace the array with the new one but other than that I don't think so we need to do anything other than that so okay first of all we need to see if it is in increasing order and if it is and it is not equal uh equal to less than or equal to the previous cell that we visited so we want to make sure that it doesn't happen that way and we do not revisit uh the cell that we have already visited so that uh we need to take care of so that being said okay so what we need to do is every time we Traverse any cell um I believe we need to have an array which um in which we'll store the number of nodes that we have traversed in an increasing order so yeah that's what we should be returning at the end yeah so how can we do that how can we do it um so let's do this we know for matter of fact that we need to Traverse the entire length of the Matrix right is equal to um before doing that let's take in row is equal to row Len is equal to Matrix do length let call Len is equal to Matrix of Z do length so we got those two and what we need to do is we need to Traverse the row L r++ and for let J is equal to Z J is less than column length j++ I need to Traverse these okay yeah and one more thing that we need to make sure is that let result is equal to an empty array right if so we'll call let new result which will be returned result new result which will be returned by TFS of i n g that will be sending along with the visited okay so along with the visited and here we'll check if new result do length is greater than result total length if it is then we will update result is equal to new result okay yeah that's what we'll do and yeah once we have done that we also need to make sure that we return our result in the end yeah so that's that um and finally what we need to do is that we need to start sending an empty array and one more thing we need to create um visited um array visited is equal to new array you need to pass the rule in to it and then we need to also fill it and map over it and need to return array call do fill with false and that should exactly give us a 2d Matrix um that will be initially false okay so we are here and what we are going to do here is function we need to Define rdfs function right that's where the magic will happen we ccept R and C then we accept the visited what we also need to send is along before the visited we also need to send the Matrix that is given to us right so once we have the Matrix access Matrix and also we need to uh result let's call it result okay yeah once we have this we need to check if we are not going out of pound and yeah um we are not going out of pH and we need to also check uh with the previous value uh if it is not equal to the previous value we need to also check that right mhm so let's do the basic check first if R is less than zero or if R is greater than equal to matrix. length or else for simpl Simplicity sake we just um Define it here so that yeah we can have access to uh to the r l and call L row let's write it properly row Len and C is sorry my bad C is less than zero or C is greater than equal to call then yeah if these any of these things happen we need to go back and in instead of okay or visited of R and C equals to two equals to true then also we need to return right return back we don't want to do anything here so return and just in case if so I come here 9 it's visited I come here so what I need to do is I also need to uh send back if it is equal to the previous S one right previous right so how can we do that I can have it here uh Define the previous one um or define null here and here I can just say previous and I don't need this Matrix anymore I also don't need the visited anymore because we are anyways writing it in the function itself so I have this previous value and the result value okay I need these let's call it rest instead of result okay and if PR is not equal to null and PR is not equal to n and um Matrix of current R and C current value is equal to previous then we don't do anything we return we don't want to we don't want part of this so we return right we don't want to do any of this and if uh if everything goes well we come here what we do is we have to first set visited of that RNC equals to true and what we also need to do is yeah and we also need to make sure yeah um instead of equal to prep we need to make sure that if it is less than equal to previous then there is no incre increasing order right so we return so if it is increasing then we know for sure that okay and we need to need to also put Matrix of I and J here okay so I am n j here and you need to push rest. push Matrix of R and C or what we can do is we can you can simply so my oh my goodness my laptop is running slow sorry about that let um let current is equal to we'll put this in here let get rid of this and let's call it current okay so we push the current value into uh onto the Matrix onto the result array and what we need to do is top left right bottom right we need to go there so DFS r + DFS r + DFS r + one R minus one is top C uh then previous is now our current and result is result I need to figure out how I'll be turning my array to so this would be + so this would be + so this would be + one this would be nothing this would be minus oh sorry - sorry - sorry - one and this would be + one and at the before leaving this we need to make sure that visited of R and C uh we are making it to false Okay so the end I suppose we can just return the result return the rest and that's how we'll get our new value so what's say guys will that work only way to find out is running this function okay it did not work but uh let's check what did it send Nan it send out Nan why is that why did you send out Nan do you have a good reason for that DFS IG Matrix if previous is not equal to null and then Matrix yeah this will for the first case it won't be triggered but for the rest of the cases it will be triggered so yeah let me check a what console.log if in fact we are uh getting console.log if in fact we are uh getting console.log if in fact we are uh getting anything back from the DFS function or at least like what are we getting exactly so what happened here was 9 99 9 so I came in here I saw this guy okay so yeah so let's say I came in here I went nine has already added oh yeah I added the nine again I shouldn't have done that if prev is I guess if I guess to deal with this uh we can just send a empty uh empty thing and it should take care of this instead of you know unnecessarily um doing it here so there should be just one nine now so 9 comes in 9 we s n and then this was less then it sent this one then 4 9 4 8 how can it send 489 really current it shouldn't have sent 489 it should have just send 48 uh or oh um guys I'm going on a break I'll be back soon okay hey everyone so we are back hello okay we are connected but why is this not showing anything anyways okay so I won't worry about that but yeah let's see uh if uh okay so 489 I came to 4 then I went okay that is a problem right I went to a nine and I went to eat it should be an increasing path right so every path that we take could lead to a maximum path okay that's what I understand and uh what we cannot have is for okay what we cannot have is so see um if we send it to 9ine and8 at this time four and 9 would be the one and okay what the hell man every time so let's go back to the EXA uh let me first of all get rid of everything that is over here okay so I have this guy 9 4 8 6 21 1 okay I drew this out so let's go here and so what I'm currently doing is if I go to four then I can move this direction this two directions these two directions are not of any right because it will return out so what we are interested in is uh these two values uh then what we can do is that uh what we can do is we can so let's see when we Traverse the eight what do we do with the AR so when we Traverse the array we have four in it then eight is greater then we add eight to it right okay and that's what we do then 8 coming to eight we can all uh we can go here so everything is less than that then we end up returning a result uh result back so we have four and8 um eight return returned back so this guy goes to goes here 4 and N so at this point of time I believe the result is um 48 okay we are sending the same result to uh this guy right so that's why it is behaving that way yeah so in instead of sending everything like this result is having the same reference right so instead of sending this way what we can do is what if we do this we spread this out but anyways like uh let's keep it so let's say we this guy returns something this guy return something to send the longest of these uh these three so I'll just do it for more couple of more minutes let's left oh let top is equal to DFS let uh bottom is equal to DFS let left is equal to DFS let WR is equal to TFS so yeah we know that yeah we want we know we want this so whatever is return back so this returns nothing turns an empty AR and this returns an empty aray return an empty AR empty aray so this guy so once okay so let's go back to here so this guy will return an empty array this guy eight then it goes here this returns an empty array to this guy for this guy if it sens rest I guess what we should be doing is we should uh be checking whose length is greater and send that fin so uh out of these four whose length is greater we need to send that by so how should we find out whose length is greater like top dot length is equal to if it is greater than bottom let's say equal to let's say greater than equal to bottom then top is equal to and sorry bottom let um greater array is equal to like this and let's call it DB and AR and LR Mar is equal to left do length is greater than equal to right dot length then left or right and finally what we need and finally we need to check let um max array is equal to DP array. is greater than equal to lr. length question TV array or LR array and finally we need to send Max array is that okay yeah guess so and if we run this now we shouldn't get 48 OMG okay so SD out so let's see console log what console log prints to Dollar do Bottom Dollar Bottom then left then right bottom oh sorry left for okay so I guess let's check it now so you're sending nine top bottom left right returns nothing because yeah so sending nine again nothing returns nothing so top bottom left right returns nothing so bottom returns 48 and left returns 489 so meaning of this is that rest how can we send a you um just a value like this is rest right this is rest I want to send it 48 I don't want to send it anything other than that like uh if I send this rest okay so how can we do the rest like I'm thinking for hello h b okay guys after banging my head for several hours on this like uh we don't have that much of time um so yeah I guess uh we can see how this guy Sol it welcome back and let's write some more neat code today so today let's solve the problem longest increasing path in a matrix and while this is a hard problem I would definitely say it's one of the more doable hard problems there's nothing crazy involved but it is somewhat difficult we're given an M byn Matrix that is filled with integers and the integers are going to be I believe zero or greater than zero so mostly positive integers and we want to return the length of the longest increasing path in this Matrix and we are allowed to move only in four directions left right up or down we're not allowed to move diagonally and of course we can't go outside of the boundaries so let's just start with some observations first of all this is an example and you can see that this is the path that is the longest it's of length four and it's in increasing order obviously we can start with pretty much any value right and pretty much starting at any position we can create a path of at least length one right this is a path of length one uh but you know starting from here then the next position that we go to is a two it has to be greater than one which it is and then the next one is six that's greater and then nine that's also greater but from here uh we can't really go anywhere else we allowed to move here uh but this one is not greater than nine it's just exactly nine so that's the longest path now one thing you might be wondering is can we you know reuse the same value multiple times right what if we have a loop of some kind well just think about it for a second if this is an increasing path of course we can't reuse any values because take a look at our path right you know the value that we get to is going to be greater than all the previous values anyway so how could we possibly reuse any of the values in our path we're not allowed to now they don't state that in the problem statement but that's an observation that you have to make on your own and in this case you know that's true and another observation we can make without even trying to understand you know what's the algorithm we'd use for this problem just by looking at this example we can make a very important observation and that is that if this is the longest increasing path and it's of length four that means the longest increasing path starting at this position is going to be of length four but what about the longest increasing path starting at this position over here what is it going to be in this case we can see that there is a path right now starting from it uh that's increasing that's of length did you get a path increasing path from two uh 268 okay so ret send one on the top bottom left right why was it 69 how come 69 and why not one see I did messed up something um but yeah let's do this going to be larger than three of course not because if they're were wouldn't here it's one because remember the solution to this problem and then I bet it will make sense now let's think about this what's the most basic Brute Force way that we could find the longest increasing path well we could basically start at every single position and say maybe the longest increasing path will start here maybe it'll start here right who knows they don't tell us where we have to start so we pretty much have to try every single position that's the brute force and let's say we you know record that in a grid that's the same size as the grid we have here I'm G to call it Li for longest increasing path and once we do that once we filled up every value in here we can just take the maximum of them and then return that'll be the length of the longest increasing path okay so for any particular position how do we find the longest length well the Brute Force again is just going to be a simple DFS I hope you're familiar with the DFS algorithm a pretty standard graph algorithm and you definitely will need it for hard level problems we're going to run a DFS starting from this uh position going in four directions right up down left right of course if we go out of bounds to the top or to the left or any other direction we're not going to continue There of course okay so we can't go out of bounds uh let's try going right starting from here are we allowed to go here well we have to compare the values right we have to look at this value is it greater than the previous value it's not greater than the previous value so we can't go here right we're not allowed to go there starting from here okay let's try going down that's the only position left that we have it's a six that's also not greater than nine so we can't go there either uh so we're pretty much uh not allowed to go anywhere so what's the length uh from here it's one because remember U one is basically like the default value we can always have a length of one starting at any position okay so we did that now let's go to the next position similarly we're not allowed to go in any of the four directions because none of them have a greater value so we'll also put a one here okay now let's try the four and this is where things are going to get interesting so pay attention we can't go up we can't go to the right but we can go to the left uh and finally we see a value that's greater than the original 9 is greater than four so we are allowed to go here that's awesome uh but now uh we're doing DFS does that mean recursively we're going to run DFS on this position again well we don't have to because we already ran DFS on this position and we already found the longest increasing path starting from that position the length of it is one so we don't have to repeat that work because we stored the repeated work inside of this Matrix so we know that starting from four we can go to this nine and that's a path of length to that's at least one path that we can create okay we do have one more direction to try though we can from four we can go down to the eight we haven't ran DFS on this position yet so we're going to have to do that now DFS okay let's go to the right that's out of bounds okay let's go up should we even go up well in reality we shouldn't but if our algorithm is programmed to try going up it'll still work for us because of course we came from the four so we know that the value up above is less than eight so if we try going up it's not going to work anyway so it's okay to leave that in the code because it's not going to break anything so that's good for us because it keeps our DFS pretty simple okay now let's try going down we can't go down because one is less than 8 we want it to be greater than eight let's try going to the left okay six is also less than eight we want it to be greater than eight okay so we couldn't go anywhere but we'd still uh of the two paths both of them were the same length so we can put a two here uh starting from this position the longest increasing path is length to but did we do anything else well we started at the a we ran DFS from this position so not only did we determine that the lip from here is two but we also determined that the lip from 8 is one because we couldn't go anywhere starting from eight are you starting to see how this algorithm itself even the DFS brute force is not inefficient because we're cashing the work we're storing the work in a Matrix so this isn't even a Brute Force solution as long as you implement it correctly it's actually very efficient as long as we don't repeat the work so now when we're not quite at the eight yet right because we're going in order in our uh Matrix but once we get to the eight we'll know we already ran DFS on it and we won't have to repeat that work so now that you're probably starting to get the idea I'm going to start fast forwarding through this explanation so uh now let's run uh DFS starting from the six we try going left can't we try going right we can't we try going down we also can't do that we try going up okay we can do that and we know that we already computed the lip from here it's one so we can say the lip from starting at six is going to be two now let's go to the second six we can't go left it's less than six we can't go down it's also that this will be a path of length to we you know one from here so uh that's uh one Poss we have a tie position computed it so we don't repeat up over here it's l the two value that's which will be 1 plus we can't go down greater than 1 + 2 four + can't go down greater than 1 + 2 four + can't go down greater than 1 + 2 four + one so we're going to put a return four we don't actually have to return solution and it's pretty efficient but how do we know it's efficient what's the time complexity of course the memory complexity is big o n * m those are the complexity is big o n * m those are the complexity is big o n * m those are the dimensions of the Matrix because we're using extra space here but what's the time complexity it's also Big O of n * time complexity it's also Big O of n * time complexity it's also Big O of n * m just think about the intuition behind it let's say our Matrix was in such a way that when we ran DFS at the first position we you know had a path such like this and then we went here uh and then we went there then here basically we visit the entire Matrix in one DFS that's going to take Big O of n * m to run that DFS but the Big O of n * m to run that DFS but the Big O of n * m to run that DFS but the good thing about that is going to be after we've done that we're going to have computed every lip from every single position right and then when we visit the remainder uh remaining values of the Matrix each of those is going to be computed in Big O of one time so you know having done the repeated work at the beginning wasn't such a big deal because the remainder is going to be very easy or right let's say each of them was exactly two but we'd see that we can't go in any of the four directions so for each of these in that case as well the time complexity would be Big O of one which means the why this is an efficient solution um and with that being said let's finally jump into the code graph problems U Matrix problems in a very formul like way and I've done it put it in some going to need to know those Dimensions um in this case we're going to have hashmap because it's pretty easy to do that in Python we is basically going toing path now of course you could just use a two-dimensional Matrix if just use a two-dimensional Matrix if just use a two-dimensional Matrix if you're doing this in Java or whatever if you want and maybe I honestly should do that as well but I'm really used to doing it this way because you can kind of just turn your brain off uh and next we're going to use uh DFS uh we have a function inside of a function so we don't have to pass in every variable such as these three that I defined up above but we are going to pass in the position that we're currently visiting which ising order so we are going to pass in what the previous value ends up being and then with all uh you know graph traversals the first thing you want to check is did we go out of bounds uh is the row less than zero or is the row exactly equal to the number of rows which means it's too big um or same exact thing with the column is column Less Than Zero or is column equal to the number of columns because that means it's too big and the last condition in this case is going to be is the path not increasing how do we know that well the value that we're currently visiting which is the Matrix at the row column position is less than or equal to the previous value that means it's not increasing and if it's not increasing then we are just going to return we can return zero just to say that the increasing path was just zero Okay so that's one base case and the second base case is a little bit easier that's if we already computed the lip at this position RC and if this and we know that because if this is in our DP hashmap as a key value then we can return whatever the length of it was that we computed and ended up storing in our DP cache so there we go okay now to actually compute the length we're just going to call it result and initially set it to one because we know it's at least going to be one that's the minimum it could possibly be and now we could use a loop to go through all four of the directions but I don't think it's really necessary we can just kind of copy and paste the same line like four times I prefer doing that rather than doing a loop but you can do what you prefer so one we know we're going to uh run DFS right we're going to run DFS on one of the neighboring positions one of them could be r + one uh and then the column is the be r + one uh and then the column is the be r + one uh and then the column is the same and what is going to be the previous value that we passed in of course it's going to be the current value right now so row column and we only want to update the result if this is greater than the result so what we want to do is set this equal or actually uh this alone is not going to be the length because this is going to tell us the longest increasing path starting at row + one and if that's the case what we row + one and if that's the case what we row + one and if that's the case what we actually want the length to be is from this position that we're currently at so we're going to take this and add one to it one plus that similar to how I was doing it or I was talking about it in the drawing explanation okay so once we have that then we want to take the max of the current uh maximum result maximum length and take this update the result if this is greater than the result so what we want to do is set this equal or actually uh this alone is not going to be the length because this is going to tell us the longest increasing path starting at row + one and if that's the case what we row + one and if that's the case what we row + one and if that's the case what we actually want the length to be is from this position that we're currently at so we're going to take this and add one to it one plus that similar to how I was doing it or I was talking about it in the drawing explanation okay so once we have that then we want to take the max of the current uh maximum result maximum length and the max of this and then you know update it accordingly and this is where we copy and paste uh four times because we want to go in all four of the directions so r + one R minus one uh directions so r + one R minus one uh directions so r + one R minus one uh also column plus1 and column minus one okay and when we're done with that the last thing we have to do is now that we've actually computed the lip starting at this position we want to make sure to actually throw it into our DP cache so let's do that before we end up returning so let's store that and then once we've stored it we can go ahead and return it so then the next time if we ever called DFS starting from the same position we'll end up returning it from our cach rather than redoing the DFS so that's where we're saving our time now that we've defined our DFS all that's left is to actually call it and remember we want to run DFS starting from pretty much every single position in the grid so we can do a nested for Loop to do that so go through every row go through every single column when we do that we also want to run DFS on every uh coordinate and what's the previous value that we're going to pass in for that well we know that every value in The Matrix is going to be uh Z or greater than zero so a default value we can pass in for the previous value uh is -1 in for the previous value uh is -1 in for the previous value uh is -1 because we never want this to return if we're looking at like the first value right and so if we pass in negative one this Oh I thought we have to return an AR okay got it comparison will never evaluate to True right none of these values is ever going to be less than negative one that's good so that's why we're doing it like this uh so once we've done that uh we're good to go the last thing we have to do is just return whatever the maximum was so we can just take our DP values which will return a list of all the values and just take the maximum of that now we probably don't need to do it like this like we could have just maintained another variable over here maybe have just called it lip longest increasing path and then just continuously updated it based on the maximum that was returned uh you can do it however you want the time complexity is the same even though we're iterating over the entire you know Matrix again pretty much by doing this that's the idea let's just run this to make sure that it works and as you can see on the left yes it does work and it's about as efficient as you can get for this problem so I really hope that this was helpful if it was please like And subscribe it really supports okay so yeah uh let's try to solve this problem on our own and let's see how it goes okay guys
Longest Increasing Path in a Matrix
longest-increasing-path-in-a-matrix
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`. From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed). **Example 1:** **Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[1, 2, 6, 9]`. **Example 2:** **Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\] **Output:** 4 **Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed. **Example 3:** **Input:** matrix = \[\[1\]\] **Output:** 1 **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 200` * `0 <= matrix[i][j] <= 231 - 1`
null
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
Hard
null
1,539
hey guys welcome back to another video and today we're going to be solving the leakout question kate missing positive number alright so this question is an easy question but i think it is a little bit more complicated than that so let's actually see how we can solve this question okay so before that so in this question we're given an array of positive integers sorted in a strictly increasing order so this over here is pretty important and we're also going to be given an integer k so our task over here is to find the k positive integer that is missing from the from this area so what exactly does this question mean let's just go over that real quickly and then we'll try to understand how we can exactly solve this question okay so over here this is going to be our array and we're also going to be given a k value and in this case uh let's see what they so they gave us a k value of five so this is the same as example one so what exactly is this question asking us for so in simple words the question is asking us for what is the fifth missing number which is not inside of our area so to actually understand what numbers that actually uh makes up of we'll try to have an array where there is no missing number so there's no missing number for uh we start off at the number one then we're gonna go to two three four five six seven eight nine ten and eleven so actually what would happen is that this would go all the way up to positive infinity okay so this over here is going to be all of the missing numbers now as it is it does not consist all the missing numbers because for example the number 2 does exist in our area so let's just clean up our area over here so one thing we could do for cleaning up our area is so we have the number two so we're gonna get rid of two where you have three get rid of three and four is also there so get rid of that as well and then seven and eleven so let's get rid of both of those as well seven and 11. okay so now these numbers over here 1 5 6 8 9 10 and from 10 every number to up to infinity is part of our missing numbers now in our question they're asking for the fifth missing numbers of numbers sorry so in that case that's gonna be so this is the first missing number second missing number third missing number fourth missing number and the nine over here is going to be our fifth missing number and this is what we're going to end up outputting which is the number nine so we'll try to see how we can actually solve this but hopefully you understood what the question is asking for and one more thing i do want to point out is this question over here the example two has the area one two three and four and we have a k value of 2. so if you look at this area as it is so we have the numbers one two three and four now as it is there is no missing number right so after one we have two after two there's three and after three there's four so there's really no missing number so in this case since there is no missing number before four then in that case the missing number is going to be everything after four so like i showed you earlier it's going to be so for example in this case we have 10 and everything all the way up to infinity so keeping that in mind the second missing number is going to be uh from 5 6 7 8 9 10 11 12 all the way to infinity so in this case they ask for the second one so that's gonna be five six the second one which is going to be the number six and we end up outputting that all right so hopefully you understood what the question is asking for but now let's see how exactly we could solve this question one way we could do this is going to be the same way that i kind of discussed the question as so what that means is basically we would kind of have a missing numbers array and using that we're going to find out what the missing number is so that's one way to do it but another way is we actually want to find some a solution with the best time complexity so in simple words we just want something which can we can get an answer through one pass and we also want something which does not take up extra space so how exactly could we do this so to do that one thing we can notice is that we're searching for the uh k positive integer right uh that is missing from this area so we are searching for something over here and another thing to notice is that we are our area is in a strictly increasing order so keeping that in mind both of those conditions mean that we could use a binary search to find our answer but now the question is what exactly are we searching for well we know we're finding the kth positive integer that is missing from the area but how exactly do we perform a binary search using these values over here right so using just the array how do we do a binary search so to kind of talk through or understand how we can do that i'm gonna go over here and show you how exactly we could do that so let's just get rid of this okay so to start off uh we have this area same area right so 2 3 4 7 and 11. now one thing i do want to kind of uh talk about is what is this area going to look like so how big is our area here the area has a length of one two three four and five so how is the area going to look like if we don't have any missing numbers okay so let me just write that down real quickly so if we have no missing numbers how is our area going to look like well that's going to be pretty simple the first number is going to be 1. the second number is going to be 2 and then 3 and then 4 and finally five so those are going to be our numbers if nothing is missing now technically uh this will go all the way up to infinity but just for the sake of simplicity i'm just gonna close it over here okay so this is how our area is going to look like when there are zero missing numbers okay so now that we have this let's talk about what we actually want to do using this information now our main goal is at a certain number so at a certain number we want to find out how many numbers are missing to the left of it so what does that mean a simple example is if you look at the number two to the left of the number two if everything was normal we would expect to see the number one but it's not there so in this case the number of numbers missing to the left of two is going to be one so at a certain number uh how many numbers are missing to the left of it okay and also one more thing i'm sorry my handwriting is pretty bad but anyway so let's just uh so kind of using this okay so this is what we want to calculate so at a certain number how many numbers are missing to the left of it so this is how we're actually going to end up calculating it and one more thing i'm going to do real quickly is i'm just going to write the index values of each of these numbers okay so now that we have this let's start off with the number two so at the number two how many numbers are missing to the left of it so in simple words uh if you just want to look at this and kind of think about it the answer is just going to be one because uh currently so at the number two so if you have a number two we would expect the number one to be on the left of it but it's not so in that case there would be one missing number over here now just talking so just thinking about it that like that won't be that easy especially for bigger numbers so is there any sort of way that we can find this out using math and the answer to that is yes so a simple way to do this is we have the number two and the number that is supposed to be in this position if there are no missing numbers is the number one so in this case to get the number of numbers missing to the left of two we can just do two minus one and two minus one gives us a value of one okay so let's just go on and you'll kind of understand how this works now we're gonna go over here and this over here is going to be our second number so the number over here is actually three but if there were no missing numbers the number that is supposed to be here is going to be the number two so using that we're going to do three minus two giving us a value of one so that's telling us that one number is missing to the left of three and that makes sense because to the left of three we would expect the numbers one and two already exists so the only other number is one so hopefully you can understand how this works i think it's pretty simple because over here we're supposed to have number two but we have a number which is greater than two by one so that is going to be the difference of the number of numbers missing to the left of it so now let's say we don't actually have this list over here how do we calculate the values then and that's pretty simple so the number that is supposed to be here is the same as its index plus one because so for example at four so the number which is actually there is four and this is the third number and how do we know that well it's pretty simple the index is at two so that means it's going to be two plus one which equals to three so it's going to be the third number and in other words the number that is supposed to be there if there's nothing missing is the value three so that's just going to be four minus three giving us one again so i'll just go through this real quickly and hopefully you didn't understand why this actually ends up working now over here we will do seven minus four giving us three so that means there's three numbers missing to the left of seven and just to be really clear that's going to be the number one five and six those are the missing numbers and finally at five uh how many numbers are missing to the left of five well in this case is going to be 11 and this is the fifth number so 11 minus five which is nothing else but well six so that is going to be uh six perfect okay so now we found out how many numbers are missing to the left of a certain number now what exactly can we do with this so here is how we actually end up finding the answer so what's going to basically happen is we want to look for a number which is just greater than k so okay so just to make this a bit a little bit easier i'm going to just have a variable called x now what is x going to stand for so the x over here stands for the number of missing numbers okay so i have a variable x and x is going to represent the number of missing numbers to the left of a certain number so in this case the x value for 4 would be 3 the x value for sorry the x value for 7 would be 3 the x value for 11 would be 6 and so on and so forth okay so i'll just call this the variable x so it's easier to kind of talk about it but what exactly are we going to be doing here so our main goal is now going to become to find out the minimum value which is just greater than k okay i'll just repeat that one more time our goal is to find out the minimum value which is just greater than k so that could become the number six seven or whatever it is so how exactly are we doing that and more specifically why are we doing that so to understand that it's pretty simple so what does k represent here k is telling us that we want to find the fifth missing number so let's look at a simple example so let's say we go to one so sorry to the number four so to the left of 4 there's only one number missing and that doesn't really mean anything because we want to look for the fifth missing number we don't really care about the first missing number we just need the fifth missing number but now when you go to the number 11 there are six numbers missing to the left of it so that means that six numbers are missing to the left of it and out of the six numbers the fifth number is going to exist right we have six numbers and we just want the fifth one so that is actually important to us and we're going to use that information to kind of get our answer okay so this is basically our goal okay so in this case what is this x what is this going to be so the number that we're actually going to be searching for is going to be this over here so the number 11. so the minimum value which is just greater than 6. sorry than the k value right which is 5. so we got that as 11. okay so to get our answer now that we've got this in value 11 and we know it's at the fourth index so all we are going to be doing is we're going to do 4 plus k which is equal to our up which is going to be equal to our answer so in other words it's going to be 4 plus 5 which equals to 9 and that is the correct answer so uh to explain why exactly we're doing 4 plus k to get the final answer i'm just going to go through how this is going to look like in a binary search and one more thing i just want to mention is that we're doing a binary search to find the minimum value which is just greater than k okay so for our binary search we're going to have a left pointer and a right pointer and the middle uh to find the middle value we're just going to do the right pointer plus the left pointer divided by 2. so 4 plus 0 divided by 2 gives us a value of 2. so we're currently at the number 4 and to find the x value and again x is the number of numbers to the left of 4 which are missing so to do that is just going to be 4 minus 3 so that gives us a value of one and one is less than k so in that case we're going to move our pointers okay so uh where exactly are we gonna move them our left pointer is now gonna move to the right side and we're gonna move it to the middle value plus one so to do that we're going to do middle value which was here plus one so third index okay so now that we have this uh what we're gonna do is the same thing the middle value is gonna be four minus three so sorry four plus three which is seven and seven divided by 2 would be 3.5 but and seven divided by 2 would be 3.5 but and seven divided by 2 would be 3.5 but we're going to round down so we're going to go to the third index so we're going to go over here and this is the middle value that we're looking for so over here um we're going to do the same thing how many num what is the x value at 7 so the x value at seven is going to be seven minus four which is three and again three is less than five so we're going to move our left pointer to the right of the mid so that would be three plus one so our left pointer would be over here so we're gonna do the same thing and the middle pointer is gonna be over here at the same place so over here we're going to have a value of 11. so over here the x value at 11 is going to be 11 minus 5 which is going to be equal to 6. so since 6 over here is greater than 5 or the k value then in that case we're going to move our right pointer to the left so that means we're going to go one to the left of our middle pointer so four minus one so right is now going to be at the third index and uh left is going to stay as it is so at this point the left pointer has a value which is greater than the right pointer by value i mean uh index bytes right so this has a value of four this has a value of three so at this point we're going to end up stopping our binary search and we're going to be left out with these two values now the value that we're concerned with is going to be whatever is at the left pointer so in this case it's going to be the number 11 and one more thing i just want to write is that the x value at 11 is six so there's six numbers missing to the left of 11. so now to find our answer what we would be doing is we would be doing l plus k which in this case again would just be a four so l has a value of four not eleven it has a value of four okay so four plus 5 which equals 2 9. okay now how exactly did we come up with this formula over here okay so to kind of derive the simple formula of l plus k what we're basically doing over here is um we want to first find out how many values are to the left of 11 in this case right and to do that what exactly did we do so in simple words what we did is we went to the value 11 itself so let me just write that so we went to array and i'll so the index is going to be the l index and we subtracted that by l plus one right so we first add up l plus one because that's the number that is supposed to be there and we subtracted it with that so in other words another way to write this the same thing we're distributing the negative sign around so it's going to be negative so minus l minus one okay so this is how we got the value six okay so let's just write that down and now what we want to find out is how many steps backwards do we need to take in order to get our fifth value over here and to do that what we're going to be doing is we have this over here and we're going to subtract this with our k value and we're going to add it by one so in this way of this value over here is six and the k value is five plus one so that means that we're taking two steps backwards to get to the value that we are looking for okay so this is what we have as it is and we can actually simply make a small simplification which is basically we have negative one year and plus one year which ends up getting cancelled okay so now this is what we have so we have area of l minus l plus k perfect now the question is we want to find out what that value exactly is and to get what that value actually is equal to what we're going to do is we're going to go to area l so in this case is the value 11. and the reason what we're basically doing over here so area l and we're going to subtract it with this value and the reason this actually works is because we know that whatever our value is going to be less than 11. since we know the missing number is to the left of 11. so since we know it's gonna be less than 11 we're going to take this as the bigger value and we're going to subtract this and this basically what this is standing for is the number of steps we take backwards okay so this is the number of steps we take backwards and we're subtracting this with this okay so if you want to simplify this okay so one thing i do want to make a small correction so sorry about this so while i was copying the values this is actually supposed to be minus k you can just rewind a bit and look at it so this is actually supposed to be minus k okay so now keeping that in mind uh let's take this negative sign and spread it around so this is now going to become minus area l plus k so in this case these two end up getting cancelled and all we're ended up with is l plus k which is nothing else but our final answer over here now let's see how we can code out the question which is pretty simple but hopefully you did understand this entire explanation i try to break it down into smaller parts and try to explain what is happening behind each step okay so now let's look at the code which is pretty simple okay so over here for our solution uh the first thing that we're just gonna have a quick check which is we're going to check if our k value is less than whatever is at the zero index and if that is the case we can just directly end up returning k so this is pretty simple and the basic idea is let's say our k value is so whatever sorry uh if whatever is at the zeroth index for our area has a value of 10. so that means everything to the left of it is not there it's missing right so the numbers one all the way through nine are missing so if our k value is with any of those numbers anything between one two nine in this case we can just directly return that k value so that is one thing that we could do and if that's not the case then well we're going to end up doing the bad research so for our binary search we're going to have a left pointer and a right pointer and the left pointer is going to start off at zero and the right pointer is going to start off at the length of our array minus one which is nothing else with the last index okay so now that we have this what we're going to do is we're going to go in our while loop and we're going to keep going while left is less than or equal to right so now we want to find out what the mid value is equal to so mid is going to be equal to l plus r divided by two and notice we're doing integer division so other than this um another way you could find out what the mid value is it's exactly the same thing but all it is you're doing left plus right minus left so you're finding the difference between those two subtracted by two sorry divided by two and then you're going to add that to the left value okay so we have that for getting our mid value so now we want to do what we want to do is find out what the x value is and in other words the x value was nothing else but the number of missing numbers to the left of our certain whatever we currently are so to do that the formula was pretty simple which was our we go to whatever value is in the mid place so area mid and we're going to subtract that with our mid value plus one now the brackets over here is pretty important so we have our mid value plus one and that is basically nothing else but the value that is actually supposed to be there so another way to think about it is the index plus one so uh you could write it like this or if it's easier for you to understand you can remove the brackets and this would end up becoming negative but i think this is just a little bit easier because this is the example that i kind of talked about in the explanation so if sorry um okay so if this value over here is less than the k value then in that case we want to be looking for bigger values since that we want to look for bigger values we're going to move our left pointer to the right so that's just going to be mid plus 1. now if that is not the case what we're going to do is we're going to move our right pointer to the left so that's going to be r is equal to mid minus 1. so that should be it and at the very ending we're going to end up returning our l plus k okay so if you submit this it should get accepted okay so that should be it for our solution hopefully it did make sense and do let me know if you have any questions i'll try to answer them alright so thanks a lot for watching guys
Kth Missing Positive Number
diagonal-traverse-ii
Given an array `arr` of positive integers sorted in a **strictly increasing order**, and an integer `k`. Return _the_ `kth` _**positive** integer that is **missing** from this array._ **Example 1:** **Input:** arr = \[2,3,4,7,11\], k = 5 **Output:** 9 **Explanation:** The missing positive integers are \[1,5,6,8,9,10,12,13,...\]. The 5th missing positive integer is 9. **Example 2:** **Input:** arr = \[1,2,3,4\], k = 2 **Output:** 6 **Explanation:** The missing positive integers are \[5,6,7,...\]. The 2nd missing positive integer is 6. **Constraints:** * `1 <= arr.length <= 1000` * `1 <= arr[i] <= 1000` * `1 <= k <= 1000` * `arr[i] < arr[j]` for `1 <= i < j <= arr.length` **Follow up:** Could you solve this problem in less than O(n) complexity?
Notice that numbers with equal sums of row and column indexes belong to the same diagonal. Store them in tuples (sum, row, val), sort them, and then regroup the answer.
Array,Sorting,Heap (Priority Queue)
Medium
null
16
hello everyone today we're going to be looking at three sum closest which is lead code problem number 16 this is a medium problem and it states given an integer array nums of length n in an integer Target find three integers in gnomes such that the sum is closest to Target so return the sum of the three integers we don't need to return the integers themselves just the sum and the key word here is closest it doesn't have to equal the Target it just needs to be the closest to the Target and we can assume that each input has exactly one solution so if we look at the first example here we see that nums isga 1 2 1g4 and the target is one so the output is going to be two because according to the explanation here we have -1 + 2 + 1 the explanation here we have -1 + 2 + 1 the explanation here we have -1 + 2 + 1 = 2 so that's the closest we can get to = 2 so that's the closest we can get to = 2 so that's the closest we can get to the Target in the second example we have three zeros so the closest we're going to get there is just zero so let's take a look at how we're going to do this we're basically going to go through the entire array nums we're going to start at position zero and we're going to have two pointers we're going have a low pointer and a high pointer so we'll sign the low pointer equal to the next number in the sequence next to the uh initial number and then we'll sign the high pointer equal to the last number in the array and then we'll just add those three together so we got 6 -6 -3 + 5 is three together so we got 6 -6 -3 + 5 is three together so we got 6 -6 -3 + 5 is equal to4 so4 will be our result current result and the target we're trying to get to is zero when now4 is less than the target so we're going to increment the low so now we've got -7 + 5 -2 so now low so now we've got -7 + 5 -2 so now low so now we've got -7 + 5 -2 so now we'll make the result or the difference equal -2 which is closer than -4 however equal -2 which is closer than -4 however equal -2 which is closer than -4 however that's still less than the target so we're going to increment the low again and so now we've got -6 + 2 + 5 equal 1 and so now we've got -6 + 2 + 5 equal 1 and so now we've got -6 + 2 + 5 equal 1 so now one is greater than the target so we're going to decrease the high value of the high pointer so now we have -6 was negative pointer so now we have -6 was negative pointer so now we have -6 was negative 1 and the low and the high are now adjacent to each other so we need to basically increment the initial pointer so now we're atg3 we'll sign the low and high just like we did before and then we got4 + 5 is 1 so B before and then we got4 + 5 is 1 so B before and then we got4 + 5 is 1 so B remember we're just looking for the smallest difference we don't care about the actual numbers that add up to that difference so this doesn't change because it's the same as it always was even though one is also closest to the Target and we're going to increase the low because the last result was1 so now we have -3 + 2 negative 1 was1 so now we have -3 + 2 negative 1 was1 so now we have -3 + 2 negative 1 plus so we have four so now we' have two plus so we have four so now we' have two plus so we have four so now we' have two high so we got four over here so we're going to decrement the high and now we've got plus two which is still but because they're adjacent we're just going to go on to the next one so initial pointer is going to be at negative one you're starting to get the idea here we got low and a high and we'll see that is equal to six which is so now we got to decrement the high and we've got four and low and high are next to each other so we can increment one here so basically we've come to the end because we've the initial poins at two and the low and the high are going to be three and five which are adjacent to each other so it doesn't there's no need to continue on that path so let's see how to code this so the first thing we need to do is create a variable to pass back so I'm going to create an int I'm going call it result and I'm going to make it equal to we're going to start at pointer zero so nums zero then we need to add the next number in the array which would be nums one and then we're going to add the last number which is nums length minus one those arrays are zero based and so that will be our initial result now we need to do a sort of that nums that we up here that we passed in and now we just need to start looping through like we did in the example so we'll do for in I equal z i is less than num's length now we're going to do minus two in this case because we've already taken care of length minus one so we don't want to um grab that number again so we do minus 2 and i++ all right now in here we need a few i++ all right now in here we need a few i++ all right now in here we need a few variables so now we're going to have our pointers so I'm make an in start equals I + I + I + one then we can also do the n value here so n is going to be equal to do nums length minus one and these are the two pointers that we're going to move um up and down the array the low and the high all right so while start is less than the end we're going to do some stuff what are we going to do so first we need to add we need to create a variable called sum so this is going to keep track of the addition of the three numbers so we'll have nums I which is a pointer and then we're going to just add in nums start oops and nums end all right so now if that sum is greater than the target then we need to decrement the N which moves the high pointer to the right which we saw in the example else we're going to increment the start by one start Plus+ all right Plus+ all right Plus+ all right now we need to compare the sum to the result so if we're going to do the math absolute which will get the positive values so sum minus Target okay if that is less than meaning it's closer to the Target math ABS result minus Target yeah okay then the result is just going to be equal to the sum assign some value to the result all right so now that we get out of this at the end we're just going to return result and that is pretty much the entire program so let's debug this real quick to see it an action okay I use the first example 1 2 1 and -4 and a the first example 1 2 1 and -4 and a the first example 1 2 1 and -4 and a target of one so we'll start here okay result is3 three we're going to sort the nums value of the nums array and now we're just going to Loop through here so start will be equal to one and end will be equal to three all right so while start is less than end which is true in our case the sum is equal nums of I which is going to be the -4 plus the -1 plus the -4 plus the -1 plus the -4 plus the -1 plus the 2 so if sum is greater than Target which it isn't so now we need to increment start by one now if the sum minus Target is less than the result minus Target which it isn't then we will assign uh result equal the sum all right so now we're going we moved the start pointer so now we're just going to check the numbers again and we see here what do we have start in so sum is NE 1 so we're going to increment the start and in this case the sum minus Target is greater than result minus Target which is one which is yeah result negative one okay so now result is ne1 and start is not less than n so basically the start and the end pointers right next to each other so we're going to break out of that while loop and now we're going to go uh in increment the initial pointer so now the initial pointer becomes one and start becomes two and end becomes three so this one will Loop through add those together the sum is two the sum is greater than the target which is one so we're going to decrement the end pointer in math ABS sum minus Target is less than result minus Target and so the result now becomes two all right and now we've got a we're done with that one because the start and end pointer are next to each other and that is it because we hit the yeah we would have put start up here and yeah there would have been too much overlapping or overlap so the result here is two so if we pass that back and that is our answer so let's hope I coded this right we'll run that it was accepted and then we'll submit it and better than 13 and 18 let's try it one more time sometimes I don't always trust well we're getting better 30 and uh memory usage is less than 36 so we'll run with that not the quickest solution but I think it's the most self-explanatory all right now let's self-explanatory all right now let's self-explanatory all right now let's look at the space and time complexity for time complexity assort of an array is n log of n but because we're doing an nested for Loop we've got n squ so this actually trumps the N log in so the time complexity for this solution is uh Big O n^2 and the space complexity is O of n^2 and the space complexity is O of n^2 and the space complexity is O of n so as you increase the input parameter the logic inside the solution will use more space and that is it so thank you for watching hope you learned something and we'll see you next time
3Sum Closest
3sum-closest
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`. Return _the sum of the three integers_. You may assume that each input would have exactly one solution. **Example 1:** **Input:** nums = \[-1,2,1,-4\], target = 1 **Output:** 2 **Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). **Example 2:** **Input:** nums = \[0,0,0\], target = 1 **Output:** 0 **Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0). **Constraints:** * `3 <= nums.length <= 500` * `-1000 <= nums[i] <= 1000` * `-104 <= target <= 104`
null
Array,Two Pointers,Sorting
Medium
15,259
138
hello everyone welcome to day 12 of march lead code challenge and i hope all of you are having a great time even before jumping onto the details of today's question i would like to inform all of you out there that today i am going live it's gonna be the first the second doubt clearing session along with this i'll be giving away a surprise amadron gift card to all those developers who have been coding along with me on coding decoded repo it's gonna be a great surprise for all of them so i want you to join me and encourage me be my support system this time during this live session now let's get back to the question today's question is copy list with random pointer here in this question we are given a linked list that has two nodes instead of one the next node and a random node what we need to do we need to create a deep copy of this linked list and return the head of the newly created linked list to your surprise for all those who have been associated with the channel from a long time must know that i have already solved this question in the month of february 10 2021 i'm attaching the link in the description below do check this video out and i hope you have a great time watching it up also if you're interested in the linked list problems that we have sold so far these are 28 in number and i'm attaching its link as well in the description below do give it a shot i hope to see you soon in the evening take care good bye
Copy List with Random Pointer
copy-list-with-random-pointer
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`. Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**. For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`. Return _the head of the copied linked list_. The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where: * `val`: an integer representing `Node.val` * `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node. Your code will **only** be given the `head` of the original linked list. **Example 1:** **Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\] **Example 2:** **Input:** head = \[\[1,1\],\[2,1\]\] **Output:** \[\[1,1\],\[2,1\]\] **Example 3:** **Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\] **Output:** \[\[3,null\],\[3,0\],\[3,null\]\] **Constraints:** * `0 <= n <= 1000` * `-104 <= Node.val <= 104` * `Node.random` is `null` or is pointing to some node in the linked list.
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list. For e.g. Old List: A --> B --> C --> D InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
Hash Table,Linked List
Medium
133,1624,1634
1,395
hi guys hope you're fine and doing well so today we will be discussing this problem from the lead code which is count number of teams so this is the 19th problem of the dynamic programming series so if you haven't watched the previous videos you can consider watching them since it will be really helpful for you to understand the concepts in the upcoming videos and in case you are new to this channel you can consider subscribing it and pressing the bell icon so that you don't miss any of the upcoming updates so let's start with this question so the question states that there are n soldiers which are standing in a line and each soldier is assigned a unique rating value so we have to form a team of three soldiers amongst any of them that are standing in the line and the condition is that for example we choose the ayat jaith and kf soldiers basically these are the indices of that soldiers which are standing in a line and the condition is that either this i j k rating should be in increasing order or in decreasing order so these are the two conditions by which we can form a team and then we have to return the number of teams that can be formed with the given condition so let's have a look at this test case so the test case is two five three four and one yes so if we clearly look that if we choose this two three and four so they are in increasing order so this contributes to one of the teams that can be formed so the next can be like 5 4 and 1 because they are in decreasing order 5 4 and 1 and similarly the other can be this five three and one so if we clearly see that only these three are the possibilities that can be formed and these are the total teams that can be counted and as an answer so the answer for this test case is three so let's see like what can be the naive approach to approach this problem so just let me write it again 2 5 3 4 and 1. so the first thing that may come up to your mind is that since there are i j k so since there are only three members in the team so what we can do is we can simply apply three for loops nested three nested for loops so these are the three nested for loops and in these nested for loops what we can do is this is for the i starting from 0 and going up till n and incrementing i this is j is equal to i plus 1 and what we are doing here is that j should be less than n and again j plus and here also k is equal to j plus 1 yes and k is also less than n and k plus so now here we can simply put this if condition we can also create a count variable outside it count variable is equal to 0 and we can just simply put this condition that rating of i should be less than rating of j should be less than rating of k so in case this is the condition then also count plus or the other condition can be otherwise that rating of i should be greater than rating of j should be greater than rating of k so basically it is not i j k but yes rating of let it be our array so that is how this will be done on all these so this is one of the things that can be done and we can simply return and simply return the count so if we do this approach so let's see what is the problem with this approach so let's have a look at the constraints of this problem so if we clearly see that the value of and basically the length of this array which is the rating value is of the form 10 to the power 3 in the worst case and if we clearly say here that the time complexity for this algorithm is of the form n cube so if we apply this to here it comes out to be 10 to the power 9 operations since we know that we can only do approximately 10 to the power eight operations approximately in one second so this is definitely gonna give time limit excuse me to us so this approach should not be opted for but in case the constraints would have been low like of the form 10 to the power 2 then this could have been done with this algorithm so now let's see like how can we optimize our approach so before moving to the optimal approach let's see what part of the algorithm is just creating time limit exceeded and how can we just eliminate that so firstly let's consider we are given this array let me just create it and the values of this array are like seven and five so here we are given six 8 3 1 and again 7 yes so according to that algorithm let's say i is this j is this yes which is this and this k will obviously range from this index to this index right so let's take out the total number of teams that are possible with this i and j firstly if this is the k then is it possible to form the team no so if this is the k then also it is not possible if this is the k yes it is possible because 7 is greatest 5 is lower than 7 and three is again lower than five so yes this is possible so first possibility is seven five and three so the next possibility is if we move to 1 so yes this is also possible 7 5 and 1 and if we move on to this 7 like is it possible no this is not possible let me just write it again yes so this is also not possible so with i referring to the seventh value and j referring to this five value so the total number of teams that can be formed with k varying from this range to this ranges basically only two values so if we clearly see that what it is actually indicating is that the total number of values here in this range which are basically less than five so why do we need to iterate over it again and again what i am trying to say is let's see it in another way like we have been iterating over all the indices for this particular i and j if rather i would had a value like 2 which depicts the total number of values to the right of this j which are basically less than this value of the jth index if i got that i would have just received my answer for this j but if my now j is changed to let's say yes now my j is changed to this now what will i do is according to the algorithm what i have been doing is i would have again iterated over this range and found out whether this value is less than j or not so in this case if we see that the answer for this should be if we can simply calculate the total number of values to the right of this value six which are less than six it should be basically three not three two again two three and one so this would have also contributed to only two answers so my aim should be not to just iterate over all this range again and again with that k which creates an extra for loop but my focus should be on like how to get that the total number of indices whose value is less than this jth value in just o of one time so if i can do that my algorithm will be reduced to o of n square because the last and that we were applying for k will now just give me answer in o of 1 so this is how we can reduce our algorithm so now let's have a look at a test case and understand that how can this be implemented so let me just write the test case and which is 25341 two five three four and one so what will i do is i'll create an array which will tell me the total number of values which are less than a particular index let's see how can we create that yes so if i am standing at this index the total number of values that are less than this index to the right of it are none basically so no use of it will simply be zero and if i am standing at this index the total number of values to the right of this index which are strictly less than this four value is only one so the total count is one and now if i move to three third index then total number of values to the right of this will be i will be iterating over all these values like whether 4 is less than 3 no whether 1 is less than 3 yes it is so i'll just put value 1 here and if i move to 5 now i'll again iterate over all these indices and find out whether this value is less than 5 or not since this value is less than 5 it will become 2 1 now this is also less than 5 so total is 3 and if i move to this two total number of values i'll again move to five then to three then to four and then to one so out of all these values i find out that the total number of values that are less than two is only one so let's write down one here and it should be three so to make this array let's call this array uh dp array yes let's call this a dpis so after creating this array we realize that the total number of time total time it takes is was just n square how often square like if we stand i will be this index and we will be iterating over j to find out the total number of indices which are less than this value so this is how it will take just o of n square time and similarly what we'll do is let's call this at dp1 and the next thing that we will do is two five three four one we'll create another array which we will call as dp2 and what does this mean is now we were just seeing to the right like what our values are less than to the right of it now for each index we will also see the total number of values like if we are at 4 then we will see the total number of values that are less than 4 and left side right so let's start iterating over it so if we are standing at this 2 the total number of values that are left less than 2 to the left of it is only 0 because there are no values to the left of it and if we are standing at this 5 so total number of values less than 5 is only 1 which is this 2 yes so for 3 it will come out to be 1 for 4 it will come out to be these two values so for four it is two one it is again zero so we have got two arrays basically dp1 and dp2 so dp1 says that total number of values to the right of that particular element which are less than particular index that we are standing on and the dp2 says that the total number of indices whose value is less than the particular index that we are standing on to the left side so this is what the both of them mean now what we need to do is since we are given this 2 5 3 4 1 as our original array now we simply need to apply two for loops which is from i is equal to zero to i less than n to i plus and the for loop is for i not i yes j is equal to i plus 1 and j is less than n and j plus so this is the second for loop and the if condition that will be put here is if basically r of i is less than r of j so we know that i is less than j then we should also find the total number of maximum value values that are greater than r of j to the right of the array and for the right of the error it is the dp1 array so we will for this case we will simply count plus equal to d p one of j dp one off let me just yes dp one of j so dp1 of j just suggests that total number of values that are greater than r of j to the right of it so if this is the j and let this be i this is j the total number of values to the right of this j is only one this is this one so this is what we will increment our count to we will simply create a count variable before this for loops and initialize it with zero so similarly we will create another for loop for the descending part which is this was the ascending order which is r of i is less than r of j is less than r of k this these two for loops are for this ascending order similarly we will apply another two for loops for the descending order which is r of i is greater than r of j is greater than r of k so if we clearly see that for one part which is ascending order it just takes two for loops so the time complexity here is o of n square and for this part also it will be o of n square for creating this dp1 array it is of n square and for dp2 is also of n square so in total the time complexity of this algorithm is o of n square so which can be done in one second so since the total number of not total number of the maximum value of n can be 10 to the power 3 so in the worst case this algorithm will be of 10 to the power 6 operations which can be done in one second and after applying these two for loops we will just return the count so now let's have a look at how can we code this problem so firstly let me just create this let me just change this name of the arrow to r and now what will i do is i'll simply create dp1 array of size n and dp to array of size n let me initialize this n as r dot length and now i'll create a count variable which is equal to zero and now for i is equal to zero i is less than n and i plus and now similarly for the j one j is equal to i plus one and j is less than n and j plus what will i do is so i will simply put if r of i is greater than r of j then dp1 of i plus and what will i do in another for loop is i'll start from i equal to 0 as less than n and i plus now from end j equal to 0 and j is less than i and j plus so here i will do the same if r of i is greater than r of j so again i will just write dp2 of i plus and now for this particular dp1 i'll repeat this for loop and i'll simply increment count plus equal to dp of dp1 of j and for this for loop i'll simply just repeat count of count plus equal to dp 2 of j and i will simply return count so let's see if this is running you see it is running correctly so now let's try to submit this question yes it is getting accepted so i hope you understood solution in this video and if you have any doubts you can comment down below i'll be more than happy to answer them and if you appreciate my work you can consider subscribing to my channel and giving thumbs up to this video so let's meet in the next video till then bye
Count Number of Teams
minimum-time-visiting-all-points
There are `n` soldiers standing in a line. Each soldier is assigned a **unique** `rating` value. You have to form a team of 3 soldiers amongst them under the following rules: * Choose 3 soldiers with index (`i`, `j`, `k`) with rating (`rating[i]`, `rating[j]`, `rating[k]`). * A team is valid if: (`rating[i] < rating[j] < rating[k]`) or (`rating[i] > rating[j] > rating[k]`) where (`0 <= i < j < k < n`). Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams). **Example 1:** **Input:** rating = \[2,5,3,4,1\] **Output:** 3 **Explanation:** We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1). **Example 2:** **Input:** rating = \[2,1,3\] **Output:** 0 **Explanation:** We can't form any team given the conditions. **Example 3:** **Input:** rating = \[1,2,3,4\] **Output:** 4 **Constraints:** * `n == rating.length` * `3 <= n <= 1000` * `1 <= rating[i] <= 105` * All the integers in `rating` are **unique**. In one second, you can either: - Move vertically by one unit, - Move horizontally by one unit, or - Move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in one second). You have to visit the points in the same order as they appear in the array. You are allowed to pass through points, but they do not count as visited unless you stop on them.
To walk from point A to point B there will be an optimal strategy to walk ? Advance in diagonal as possible then after that go in straight line. Repeat the process until visiting all the points.
Array,Math,Geometry
Easy
null
151
Hi guys, welcome to the channel, you are doing 90 days software engineering prep with me, this is question number six, lead code is the overall question of 75, lead code is 151 question, reverse words in a string, okay so what is the question, let me show you. You have been given a string, The Sky is Blue, you have to create it, Blue is Kaida, you have to do it in Offcourse O and you do n't have to take extra space, okay, there are some cases like Hello World, there is space at the beginning and the end, they are to be ignored. And a good two space bar example is to make a single space bar out of two space bars, then there can be a space in the middle, there can be extra space at the beginning and at the end, the rest is a simple question, okay, so what did I do? For example, let's take a case in which there are some spaces in the beginning, so I will denote the spaces with dots so that it can be seen, then dot the dot sky, one dot is blue, two dots are like this, okay, so I have given it to us as blue is sky. If you want to make 'The' then see this is blue is sky. If you want to make 'The' then see this is blue is sky. If you want to make 'The' then see this is found in the string, I have trimmed the string, there is trim function, it will blow away the space in front and back, so by trimming, you know what has become 'The dot, by trimming, you know what has become 'The dot, by trimming, you know what has become 'The dot, sky, dot' is good, here also there was a dot, sky, dot' is good, here also there was a dot, sky, dot' is good, here also there was a dot, blue. If the subsequent dot dots are also removed then the shoe and the last space gets blown away. By trimming the string dot gets blown away by trimming. Then I split it on space. The split function which is what happens if I split it is so much by trimming. This is done, then after trimming, if I split it, trimming does not change the original string. After trimming, you get a string, then I will trim dot, split and split it on space, here I note it with dot. This dot is denoting space, I will trim it, so I know what will become an array of strings, then I will get the inside the array, then there is nothing between these two dots, so I will not get anything, then look, the beginning. From to the first dot, from the very beginning to the first dot, you got the, then from this dot, to this one, there's nothing in between, you got that, the sky between this dot to the next dot. From this dot, we will get the color between the next dot and from this we will get the blue till the last one. Okay, so you will get this array, what will I do now by splitting, now put a reverse loop on this array and append it in the string builder. I will take it, appended the blue, this is the new string builder, appended the blue in it's okay, put the blue in the string builder, then put a space after that, put a space as per your wish, then for the sake of ease, added one. I put a space, put a sky, put a space, now this one does n't have to be processed, I saw while processing a string that it doesn't have to be appended in the string builder, for that I thought whether it is MT or not if its length is zero. So it does not have to be appended, then after inserting the 'the', I not have to be appended, then after inserting the 'the', I not have to be appended, then after inserting the 'the', I added a space in the last one and this became this in the string builder, now when I converted the string builder into a string, then my string is blue, the dot is sky, dot, the dot, so leave the last one. If you have to leave the last dot, you have to leave the last space, then if I leave it through the sub string function, then it becomes my string which I return, so bring it, I will do this code, the question is easy for you, so I will erase this. Look, I trimmed the front and back space, split it, got an array of words on top of the space, now I have to make a string builder, why do I have to make a string builder because appending to a string is the work of O, this string builder was made last. I will return s bud s builder dut string builder by converting it into I will return. If you have to take sub string also then you will see that I have put this reverse loop aa equal to words, I will start from the end of the array aa g e 0 aa minus Minus, I will keep getting words one by one, but I will use Word of I only if the length of Word of I is greater than zero, otherwise I will not use it. I will keep appending it in the string builder. Who has words, whose name is not a word, I will append to Words of I will keep doing this, I will keep adding one space after every word, I will keep adding one space, there will be an extra space at the end, if I have to leave it, then I will use the substring function and know myself from zero to the last. So if I put only the string builder dot length here, then I have to enter the length minus and I, then the last character will be left out, so from where we take the zero from the beginning, we will take the zero. Whatever you enter as the last index, the sub function never takes it. If it is s, then if I give the length - 1, then the last character will be left out. give the length - 1, then the last character will be left out. give the length - 1, then the last character will be left out. Okay, I think this should work and its time. We write s. If we think now, then let me think about the time complexity. I will let you see first. Submission is going on. Is it not happening, is it happening fast enough? So see this trim function o split function o array of words has come, loop has been put on the words and kept on appending o if I made a mistake here, plus equals two in the string. Now, if string plus is equal to two, then there will be a loop of o. This is an addition to the string. An addition to the string is of o. Append in string builder is of o1, so that is not a problem. In the last sub string is o, so total leg error. Is it? Did n't take extra space because string miller is output space so that is okay, this was our my brothers question number 6 of lead code 75 so this is the question I have put you mean while I have put today's journal which is ours in the link. Our first link will be in the first description. You go to the journal and tell us in the comments how is your preparation going. Keep preparing along with me. There are 90 days of preparation and we are already ready. I have solved the lead code 75. You can start solving the questions. I am doing it quickly. Dream and bud also have to be done. Alright let's meet the next question. Thank you so much. Bye bye.
Reverse Words in a String
reverse-words-in-a-string
Given an input string `s`, reverse the order of the **words**. A **word** is defined as a sequence of non-space characters. The **words** in `s` will be separated by at least one space. Return _a string of the words in reverse order concatenated by a single space._ **Note** that `s` may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces. **Example 1:** **Input:** s = "the sky is blue " **Output:** "blue is sky the " **Example 2:** **Input:** s = " hello world " **Output:** "world hello " **Explanation:** Your reversed string should not contain leading or trailing spaces. **Example 3:** **Input:** s = "a good example " **Output:** "example good a " **Explanation:** You need to reduce multiple spaces between two words to a single space in the reversed string. **Constraints:** * `1 <= s.length <= 104` * `s` contains English letters (upper-case and lower-case), digits, and spaces `' '`. * There is **at least one** word in `s`. **Follow-up:** If the string data type is mutable in your language, can you solve it **in-place** with `O(1)` extra space?
null
Two Pointers,String
Medium
186
126
hello everybody is a male and today I'm going to teach you how to solve the many rooms to problem given an array of meeting time intervals consisting of start and end times find the minimum number of conference rooms required example 1 the input is this list of intervals so every interval has a start time and an end time and every interval is a meeting so as you can see the output is 2 because you need two rooms for these meetings why because we need one room for the meeting that starts at 0 and ends Authority and then we need another room for these two meetings and because these two meetings do not overlap we can use the same room for them as you can see this one starts at time 5 and ends at time 10 and this one starts at 10:15 and ends at time 20 so starts at 10:15 and ends at time 20 so starts at 10:15 and ends at time 20 so as you can see they do not overlap so they can use the same room but this one ends at times 30 so it overlaps so it needs its own room example 2 the intervals is this list that only has one interval it only has one meaning so we only need one room so how can we solve this problem we can solve this problem by sorting every interval by the start time and then we can use a data structure like a priority queue to sort the end times of every interval and then we traverse the intervals and as we traverse the interval we push the end times to the priority queue and put push into a priority queue takes Big O log n time so we push every end time to the Prarie queue and we check if the start time we check if the end time of this interval is greater than the start time of the next interval if that's the case they overlap so we need to have a separate room but if that's not the case if this if the end time of this interval for example is less than or equal to the start time of this interval then they do not overlap so they can have or they can use the same room so that's the main idea here so the time complexity would be big-oh so the time complexity would be big-oh so the time complexity would be big-oh and log n because we have to sort by the start time and the space complexity would be big-oh of n because we are would be big-oh of n because we are would be big-oh of n because we are using a priority queue for the end times so without further ado I'm gonna show you how to write the code first I'm going to sort every interval or the list by the start time of every interval so I'm gonna say collections that sort the intervals so I will have a lambda a b8 a start - beta start so what I'm doing here is that I'm sorting the list by the start time so all the intervals will be sorted by the start time like in this example here as you can see it is already sorted so 0 then 5 and then 15 so they're in ascending order so after I saw the intervals I need to have a priority queue of integer PQ just a file of new priority queue and in this priority queue I'm gonna have all the end times of the intervals and the priority queue will keep the minimum end time at the top so as you can see that's the main property of the priority queue you can have a minimum priority queue or an or a maximum priority queue in this case I have a minimum priority queue so every time I will have the minimum at the top so I will have access to the minimum and then I can compare the minimum end time with the start time of this interval and if they do not overlap then they can be in the same room otherwise I have to have another room for this interval and I didn't tell you this but as you can see I'm using a lambda here but I can also use a comparator I can use a comparator but I prefer to use a lambda so then what I'm going to do is that I'm going to traverse from left to right so for interval in intervals and I will check every interval and if not pick you that is empty and pick you that pick is less than or equal to interval that start then pick you that pause so if I have something in the priority queue and the minimum or the top element in the priority queue which is an end time it's less than or equal to the start time of this interval that means that they do not overlap so I can use the same room for these two intervals so what I do is that I remove the minimum end time from the Prairie queue so to indicate that I can use the same room for this interval and after I remove that minimum end time I can just say P queued up offer interval that end then I only have to worry about the end time for this new interval so every time I push the end time for the interval and the priority queue will keep those end times in the way that I need them so the minimum will be at the top then I just need to return PQ that size because by the end the priority queue will contain only the end times of the meetings that the number of end times will be equal to the number of meetings that I need as you can see I always push the end times to the Prairie queue but if I find out that the minimum of the priority queue is less than or equal to the start time of this interval I remove the end time for that I removed the end time for that interval and push the end time for this new interval so I will run the code it seems to working fine I'm gonna submit a solution all right so this is working perfectly as I said before the time complexity is Big O n log n because of the sort the space complexity is Big O of n if you liked this video please press the like button don't forget to subscribe and see you next time
Word Ladder II
word-ladder-ii
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _all the **shortest transformation sequences** from_ `beginWord` _to_ `endWord`_, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words_ `[beginWord, s1, s2, ..., sk]`. **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** \[\[ "hit ", "hot ", "dot ", "dog ", "cog "\],\[ "hit ", "hot ", "lot ", "log ", "cog "\]\] **Explanation:** There are 2 shortest transformation sequences: "hit " -> "hot " -> "dot " -> "dog " -> "cog " "hit " -> "hot " -> "lot " -> "log " -> "cog " **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** \[\] **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 5` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 500` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**. * The **sum** of all shortest transformation sequences does not exceed `105`.
null
Hash Table,String,Backtracking,Breadth-First Search
Hard
127,2276
1,071
hey everybody this is Larry this is February first day of the uh the code daily challenge hit the like button hit the Subscribe button uh join me on Discord let me know what you think about today's prom and easy one and uh yeah if you're joining us uh look I'm on the lead code contest page because there's a click for 10 Lee code I don't know if that's consistent for everyone let me know if you also get the coins but yeah um the shortest month of the year so definitely take this opportunity to uh get that streak going I suppose to get that month streak but yeah let's see what am I doing 1071 greatest common divisor of strings okay so giveness t s t divides as if s is equal to some multiple of t uh given the largest string that X such that X divides both okay and they're both a thousand so well so yeah um I think this one is pretty straightforward in theory if you know the constraints um oh yeah and I am going to do an uh an extra question today just you know because this is an easy one so definitely stay tuned and check out that subscribe button or whatever but yeah but this one is straightforward if you're not overthinking it or try to be too clever um the key part is noticing that constraint is n right or n is equal to a thousand less than a thousand so then we can just prove first on the prefix of one of them and then see if it's the other one right and that's basically the idea that I'm gonna do here I'm gonna go um because basically the idea is that um the answer has to be by definition a prefix or a suffix to I mean it doesn't really matter I mean they're both the same um because that's how this division seems to work so basically what you're going to do is just take first some prefix um or suffix and then see if it also um quote unquote divides into the other one so that's pretty much it so that we can move forwards like that and basically um yeah there's a thousand possible prefixes um given you know what we discussed so then that means that and each of them will same you know take over one thousand um for comparison um linear time so it's going to be n Square which for n is equal to a thousand is a million which should be fast enough which is why I said um okay so let's get started um I mean I think you could also take the shorter one maybe it doesn't really matter I mean you know in a long scheme of things um yeah and then we just tick uh yeah maybe we can do it from one to n and then we do let's just say the current string is equal to string one to I think this is good right I'm always I always uh I always get confused about like inclusive exclusives I always have to double check um okay so this is good this is basically what we want right so then basically now we can do well I maybe we can do L for length then yeah um well maybe before that we go if and my L is equal to zero or if it's not equal to zero we continue so then we could save some energy comparing otherwise we do this and then um say copies as you go to node by L then if s times copies is you go to uh is not equal to string one then we continue as well and then we also do the same thing for the other one um sorry people keep ping me but yeah um maybe copies or you know let me go to M over l or something like that if s times copies it's not equal to string over two then we continue just for symmetry reasons otherwise this is good so um yeah so then we can just return l in theory but we actually did it well by we I mean me did it do it the wrong way so let's actually go counting from um uh from the bigger number up so we could just return the first time this happens um I returned the number and instead of the actual string so that's a mistake um I was they don't actually tell you oh I guess they don't tell you that there's no string return empty string but I guess you can say that technically maybe the empty string fits it depending how you want to Define uh it's a little bit awkward though that's why I was looking for it um though obviously I was also one but uh but yeah we can just return s and I don't know how that actually Compares without like any hours all right cool um yeah like I said this is going to be N squared this is O of N and just um just cut both of these uh or and individually so it's gonna be N squared um yeah that's all I have for this one definitely don't complicate things if you don't have to um there probably some weird Z algorithm type thing for this one but uh yeah let you know in my comments below um that's why I have for this problem I'm gonna do an extra one after this so stay tuned uh but yeah uh stay good stay healthy to good mental health I'll see y'all later and take care bye have a great month
Greatest Common Divisor of Strings
binary-prefix-divisible-by-5
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times). Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`. **Example 1:** **Input:** str1 = "ABCABC ", str2 = "ABC " **Output:** "ABC " **Example 2:** **Input:** str1 = "ABABAB ", str2 = "ABAB " **Output:** "AB " **Example 3:** **Input:** str1 = "LEET ", str2 = "CODE " **Output:** " " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of English uppercase letters.
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
Array
Easy
null
445
Hello Hi Guys Welcome To Kushwaha Set Two Numbers Part 2 In This Question Science And MP Link Playlist Details * And MP Link Playlist Details * And MP Link Playlist Details * non-resident Indians Team Mostly Acid non-resident Indians Team Mostly Acid non-resident Indians Team Mostly Acid Comes First And Inch Of The Note Container Single Digit 882 Numbers End Return Retention Request You Majumdar Two Numbers Two Not Contain Any Leading Dros Accept Number 01 Self Ok For Example Seat Haldi Number Isse 1243 Label Number 56 Or Ministry This Is Dual Sim Lutia Doob Pizza Bread 727 243 And Add Here More Than 56125 Result Of This Edition Subha No That Edition For Wedding Back To Start from behind certificate unit number three idiots se z page from back to front part hai ki adi add english hum elastic pim 342 323 427 and on Instagram 46546 509 vinod lekin em travels in english from starting to end not from end to starting sudhir verification 0280 Shyamveer Will Not Get Number-1 And Husband Number-1 Modified In This Manner Number-1 Modified In This Manner Number-1 Modified In This Manner Account Statement 2F And Three Plus 1564 In This Order In Love You To And Subsequent Events In English Fennel But What Do We Will Do Subscribe Posting Story Will Be Represented In Hindi Channel Subscribe First Day First Will Convert Into This World Will Even Numbers of List Number Two Play List Start Today Element of List in To-Do List Ek Album Ko - One End in To-Do List Ek Album Ko - One End in To-Do List Ek Album Ko - One End List To Take Into Coma That SDO Edison Electronic Description mein ka makhan wa jhalmal top link list one in this tags 125 left side effect simple function desist from list to states function in directions first list notes1 bhi kama stock int as one tips by reference because of making changes in distant third world tour wire Least One Is Not MP Album Not Equal Toe A Reminder Album Not Equal To Null What Will U Will Simply Ask Value Of Album That Album Well In Tourist Will Ask Value Of Album A Well In Tourist One And Will Do Albums Equal To Album Next Year It's not only they can take only he also reserves in parameters are not able to edit and looted and eligible to next return from the far away from all the limits of liquid will take another step to 232 373 element subscribe 900 they cannot Will Be Coming Back Notes And Will Forward One Corridor 1212 Thi Next9 800 E Will Start Will Produce Elements Edition Element India News Festival Answer Solid Just Write The Function For Telling Period Edition Of The Limits For Events 6 And Students Of Peace 2000 This Given Baking And Actions E Will Declare Variables Chord Deep Mist Zero Know Where To Calculate Dism Intex Equal To Adjacent To Top That In Twice Equal To A Student Top Also Sincere Taken In Top Ten Lines About This Tagged With Spot Back Dost Value Servant Whatsup And Stood Up The Soul Will Carry Forward Them To A Novel Endurance Orissa Modulus Point Submersible To So Drishti's swift to take element toys time and put them into the third subscribe button subscribe and 2.5 that and 2.5 that and 2.5 that that and int committee's two x plus carrier which has been verified from previous edition here will do will do will do part of magical Ek Hai Curry And Were Greatly Reduced Poochha Answer Pooch Summit And Carries Equal To Some David Beckham Notification More Videos Subscribe &amp; Notification More Videos Subscribe &amp; Notification More Videos Subscribe &amp; Share Subscribe Over Vid It Will Be Pushed Into A Snow After Chapter 10 Country A Condition All The Number Switch Off To Save Present in a answer and present in all aspects of ancestors during state will look like this 307 and this caffeine consider some incident with me to family 307 easy and office tech and answer and so content 07 2012 at last value most loud 500 verses Last Position Of Stock 9059 19 These Tabs Will Convert Into The In To -Do List Top Model Presents A New -Do List Top Model Presents A New -Do List Top Model Presents A New Window Will Lead You To Convert Into Subscribe 559 United States Will Simply Return Chief Head Teacher Will Return From These Functions Tattoo List Sunao Latest Right the function at least to list function with oo tattoo list function and ignorant and art now input start this support 250 ML list note star held between insulin tap i unil form earliest note 4 temp which will helps in treating are newly-formed will helps in treating are newly-formed will helps in treating are newly-formed link list Yesterday morning last you this note mp dad festival will intensify to take top most will intensify to take top most will intensify to take top most will not when you will make new notes are busy e agree with you value a great new notification list note 4 new play list node xx i laugh fir Divisional Till Now Chipper Additional It Means That Is Not The Dead Uniform Nod Is The Noble Vikram Head Of The Head Of Uniform Link To This Video * Of Uniform Link To This Video * Of Uniform Link To This Video * Note And All They Need A Temple To Held At Bhi Notification Is Difficult To Nail But He Did Not Equal To Null Shubh Else But Will Do It Will Simply Due From Next Physical To Notes That And Temples Equal To Temp Next Video MB Turn Off Held From This Function Of Three For Lips Over And Cold Not Run On Ye Kaisa Darwaza Editor Invalid List Note 4 Health Is Wealth To Internal Ok Surya 22222 Null Students Yes Return Head Tattoo Should Not Return Value Main Mukesh Sari Dolta Hai Play List Note Star A And Listen Cheerleading Fat Knowledge Submitted On Me Chicken Cod Decade Ego By Selective Video Teri Meri Love You can write Hindi comment section so guys please subscribe my channel and like this video thank you
Add Two Numbers II
add-two-numbers-ii
You are given two **non-empty** linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. **Example 1:** **Input:** l1 = \[7,2,4,3\], l2 = \[5,6,4\] **Output:** \[7,8,0,7\] **Example 2:** **Input:** l1 = \[2,4,3\], l2 = \[5,6,4\] **Output:** \[8,0,7\] **Example 3:** **Input:** l1 = \[0\], l2 = \[0\] **Output:** \[0\] **Constraints:** * The number of nodes in each linked list is in the range `[1, 100]`. * `0 <= Node.val <= 9` * It is guaranteed that the list represents a number that does not have leading zeros. **Follow up:** Could you solve it without reversing the input lists?
null
Linked List,Math,Stack
Medium
2,1774
270
okay let's do today's question 270 closest the binary search tree value the question is given the number deputy binary search tree and the target value we need to find the value in the binary search tree that is closest to the target the dart endowed skier given target value is a 13-point the second target value is a 13-point the second target value is a 13-point the second thing is you are guaranteed to have only one unique value in the binary search tree that is closest to the target so the example here we have a binary search tree the it's the values 2 4 2 5 1 3 if we want to find the closest value in the binary search tree that is close to that's the closest to the target 3.7 it's quite obvious that the root 3.7 it's quite obvious that the root 3.7 it's quite obvious that the root node has it is the you know the answer it has a distance that's point to knowing something 0.28 something that's knowing something 0.28 something that's knowing something 0.28 something that's the smallest compared to all the other nodes in there but this example doesn't give us a really nice idea how we actually go into traversal so the tree so maybe we should decrement this value to be like a two point seven so and then even though it says three point seven just try to imagine we're working one example that has a target value that's two point seven way let's see how we would do to manually solve this so if we're looking at the root that's obviously in our entry point to the tree we compared the difference between four and the two point seven we got one point three that's the current closest distance and four is now as far as we know the closest of no value and we should actually utilize the property of the binary search tree to help us to go and free so things number four is larger than 2.7 we should number four is larger than 2.7 we should number four is larger than 2.7 we should go to explore only the lepton children's because only the left of children's are the values that's a smaller than for all the values to the right is larger than 4 and since 4 is larger than 2.7 all the and since 4 is larger than 2.7 all the and since 4 is larger than 2.7 all the values here to the right of it's going to have larger distance to the target value compared to this node value so we should the comparative comparison of this no value and the target combined with the property of the binary search tree is telling us to go to the left so we look at the number 2 here the distance now reduced from 1.3 here the distance now reduced from 1.3 here the distance now reduced from 1.3 to 0.7 and we update and have a to 0.7 and we update and have a to 0.7 and we update and have a candidate solution from 4 to 2 and things 2 is smaller than 2 pi 7 it's telling us to go to explore the right Karina's of it and things know where we are at the leaf node there is no more we can explore after doing the comparison and updates which is this one is compared to 2.7 it has a distance of 0.3 compared to 2.7 it has a distance of 0.3 compared to 2.7 it has a distance of 0.3 which is now even smaller than the previous one we updated the candidate from 2 to 3 and since 3 is a leaf node we terminate the augurs and I just returned that returned the candidate as the final solution so that's the pretty much the solution in terms of a time and space complexity we are exploiting only one path from the root towards the leaf nodes so the time complexity is little the depths of the tree and for the space we would just use one pointer for the traversal node and just one variable to hold the candidate value so it's constant space so yeah let's cut it up or myself over and let's code so we will have a traversal node which start with the root in our entry point we have a candidate value there it just starts with the nodes value and while we are still you know still a volume node not that's something that you know when we are to leaf node the other children's are the two children's are no pointers we just move that to either side we will end up being a null pointer and we will once we do that we will break out of this value we should update the candidate whenever we move to a new node that's the we can compare the candidate with the current node value in terms of their distance to the target value that's distance the absolute difference and if the nodes value is smaller than the target that tells us we should go to the right else no model is larger than the target larger than the note we move to the left the only other option is that we just so happen to find a note that is exactly the same value as a target we should just return that Nevada and once we break out this one loop meaning that we at the very last iteration we are at a leaf node and we just do move to either side it's gonna be now so we just return the candidate so that should be the algorithm yep it's okay yeah that's a quick one bye for now
Closest Binary Search Tree Value
closest-binary-search-tree-value
Given the `root` of a binary search tree and a `target` value, return _the value in the BST that is closest to the_ `target`. If there are multiple answers, print the smallest. **Example 1:** **Input:** root = \[4,2,5,1,3\], target = 3.714286 **Output:** 4 **Example 2:** **Input:** root = \[1\], target = 4.428571 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 109` * `-109 <= target <= 109`
null
Binary Search,Tree,Depth-First Search,Binary Search Tree,Binary Tree
Easy
222,272,783
133
welcome back to Cod Meets World today we're looking at Elite code problem number 133 which is called clone graph so given a reference of a node in a connected undirected graph we need to return a deep copy a clone of that graph so each node in the graph contains a value which is an integer and then a list of all of its neighbors I think this is just telling us that it's an adjacency list and we need to give the graph back is a CO a complete copy we can't reference any node in the original graph so there's this picture here where we see an original graph and we're not allowed to return the same graph so we can't just recreate the graph and return it we have to return a graph where all the nodes have their same neighbors but these are all these blue nodes are copies of the yellow nodes and this red one doesn't work because they are actually in a different order so I've drawn a graph which kind of looks like a tree but they're one and the same and it has four nodes in it and we're going to talk about how to make a deep copy of this graph what I need to do is go through the entire graph consider each node and I need to put the exact right nodes with the exact correct Neighbors in a copy so the way that this graph would look as an adjacency list is we would have an entry in a dictionary for each of the four nodes and then we would have a list of that nodes neighbors so node one has neighbors of two and three so I would write that as two and three in the adjacency list two has only one neighbor which is the one and this is a non directional graph undirected so neighbors point to each other if that makes sense it's not a tree where it only Flows In One Direction three has two neighbors the one and the four and four just has one neighbor which is three so this problem is asking us given this adjacency list representation of the graph we need to Traverse through it and create a copy but what we'll do first is sort of just I guess a bre first search of sorts so I will have a c to put the nodes that I need to visit I'm going to have a current variable to keep track of the value that we're looking at now and then over on the right here I will draw I will write in the copy as we process everything so the way we'll start here is we'll get the root node whatever we're given to start and we will create a copy of that node by calling node with the value you and no Neighbors at the start and we'll add that as an entry in our new adjacency list which again I'll write in green no Neighbors at the start we just add that to the copy and then we need to insert the not the copy of the one the original one so the white one we need to insert that into the front of our que because that's the node that we're going to visit first to start exploring the rest of the graph so our first step is we pop off that first value in the Q we can set our current value equal to that value so we're starting at that value here that's our current so we'll do the first thing we'll do is Loop over any neighbors that this node has so the first neighbor that it has is a two so we'll check hey is there a two in the copy there is not so we need to create that node we'll create a brand new node and put it in with no neighbors and then because we are currently looking at node one and We're looping over its neighbors so it has a neighbor of two we need to also reflect that in the copy that node one has a neighbor of two so we'll take this opportunity to put a two as one of the neighbors of the one node the next thing we have to do because we hadn't seen the two before is we need to keep exploring from that node because maybe it has other children as well so to do that we will enter the white two here into the que so that we can keep exploring it on the next round now we're still on number one is our current node so we need to keep looping over all of its neighbors we already looked at two so now we have to look at three and the first thing we ask ourselves is that three in this copied adjacency list and it's not so we need to go ahead and add a three as well and just like we did for the two because this three is a CH not a child it's a neighbor of one we need to reflect that same relationship over here so again we will make three another one of the neighbors of one so those are all the neighbors and as we can see these match exactly which is good that means our algorithm is working the way that it's supposed to just like we did with the two because we explored this three and added it to the copy we also need to keep go we need to go to the three and check to see if it has any other neighbors that we haven't seen so we will also add the three to the two visit Q now we're finally finished processing this one because we iterated over all of its neighbors so we can now pop off the next value on the Q and replace our current with that value the first thing we do like last time is check is there an entry in copy already that's a two and there is that's right here so nothing to do but then we have to look does two have any neighbors and it does two has a neighbor of one so we need to reflect this in our copy so we can go in and say that two has a neighbor of one and that's its only neighbor so we've completed the full processing of this two so just like we've been doing that means we can pop off the next value which is a three make that our current and so now we're processing this three here first thing we do is look is it in the copy it already is there so nothing to add and now again we look at the neighbors so the Neighbors in the in this case are one and four so that means three has neighbors of one and four so we'll add those and because we haven't visited the four yet and the reason we know that we haven't visited the four is because it's not in the copy we need to add it to our Q so that we can visit it next so the four can go there and now that we've looped Over All of the neighbors of three we can pop our next value which is the four that makes for our current so we're down here the first thing we ask is that in our copy it is not we're missing the four so we need to go add that first so we'll add a four with no neighbors and now we Loop over the neighbors of the one that we are on so because our current is four we're looking at the four here we Loop over all of its neighbors we see that there's just one which is the three so we go ahead and add that three the only neighbors of four have already been explored we've already been there so there's nothing to add to the Q and so when we go to pop our next value it's actually empty so that means that we are done with the algorithm and to make sure that it works you may have noticed that if we compare our original and our copy each of these are equal meaning we've successfully created a deep copy of the graph first we can do a quick check by saying that if the node doesn't exist meaning it's null uh all we have to do here is return none so there's nothing left to try if we're given a empty graph but then if that's not the case we need to create our copy so we can set that equal to an empty dictionary and then we need to add to our empty dictionary which is our copy we need to add the original node I showed this in the example on the Whiteboard but the very first step is we need to add that very first node to the copy so we can do that again we can't just set it equal to node because that would be referencing the same node in both graphs we want it to be a deep copy so we actually need to create a new node but we'll pass it the same value that the original node had so this is making that first one uh in written in green except we're not adding any of the neighbors yet we'll add those when we actually iterate through the search algorithm the one other thing we'll do is create our CU so we can call that to visit we'll set it equal to a deck because that's a nice easy Q implementation in Python and then we can actually pass in our first value which will be node because that's where we want to start searching through the original graph we want to start at the top here so we can Loop while the deck is not empty so while to visit has values in it the first thing we will do is set our current and that can be to visit dot pop left which will remove the front value of the que like we did on the Whiteboard we're going to want to Loop over all of the neighbors of this value so we can say for neighbor in current. neighor we can say if neighbor is not in copy we need to add it to copy so we can say copy neighbor equals we copy we can say copy neighbor equals we have to again make a new node and set that equal to neighbor. Val just like we did up here we also need to append any of the neighbors that we haven't se scene to our Q so we can say to visit. append and we will add neighbor like this finally we also have to add the neighbors associated with this node in the copy graph not the original graph in the copy so we can say copy for current access the neighbors and then we need to append to that the neighbor that we just inserted so copy neighbor so that means we're taking the current value that we're on and we are appending to its neighbors the value that we just inserted here so that's what's happening in line 18 and I think all that's left to do is we just need to return we need to return the new graph which is copy but I think it says we need to return a copy of the given node as a reference oh the first node so I think we can return copy for is it just node because that would be the original one copy node would be the first value so I think we just return that one let's see if that works unexpected indentation these all need to come back on like that sorry everyone my fault so there we go that passes all the test cases including the empty ones so I will submit this and hopefully we're passing everything yes right on so uh that is beating 75% of the other test cases for Speed 75% of the other test cases for Speed 75% of the other test cases for Speed not doing as well for memory that's interesting because I figured we just had to create oh I guess maybe the Q is could be adding some extra space but either way this is a fun one um it seems really easy when you first set out thinking oh I just need to make a copy of this but it actually requires a breadth first search you could also do a depth first search they would be pretty much equivalent but hope you enjoyed uh leave any comments down below if you have questions concerns or better ways to do this I will see you in the next video
Clone Graph
clone-graph
Given a reference of a node in a **[connected](https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph)** undirected graph. Return a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) (clone) of the graph. Each node in the graph contains a value (`int`) and a list (`List[Node]`) of its neighbors. class Node { public int val; public List neighbors; } **Test case format:** For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with `val == 1`, the second node with `val == 2`, and so on. The graph is represented in the test case using an adjacency list. **An adjacency list** is a collection of unordered **lists** used to represent a finite graph. Each list describes the set of neighbors of a node in the graph. The given node will always be the first node with `val = 1`. You must return the **copy of the given node** as a reference to the cloned graph. **Example 1:** **Input:** adjList = \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Output:** \[\[2,4\],\[1,3\],\[2,4\],\[1,3\]\] **Explanation:** There are 4 nodes in the graph. 1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). 3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4). 4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3). **Example 2:** **Input:** adjList = \[\[\]\] **Output:** \[\[\]\] **Explanation:** Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors. **Example 3:** **Input:** adjList = \[\] **Output:** \[\] **Explanation:** This an empty graph, it does not have any nodes. **Constraints:** * The number of nodes in the graph is in the range `[0, 100]`. * `1 <= Node.val <= 100` * `Node.val` is unique for each node. * There are no repeated edges and no self-loops in the graph. * The Graph is connected and all nodes can be visited starting from the given node.
null
Hash Table,Depth-First Search,Breadth-First Search,Graph
Medium
138,1624,1634
1,349
yes today we are going to solve a little co2 problem in 1349 it's a hard problem and it's posted by Rahul right so as always we are going to explain this problem by introduce the example here so in the input we are going to have a two-dimensional array and this array two-dimensional array and this array two-dimensional array and this array tell us there are some seeds right and if the character is Punky means that the seeds cannot be used right and if it is dot it means a student can sit there right and the output put here is how many students we can put into the classroom right so we need to get the maximum number right so in this case the maximum number of students we can feel in the map is 4 right why Cannot these two seats be occupied by students because if we place a student here this student can see the students before him upper right upper left and the right so if we put a student here somewhere it's up left right left and the rights cannot be a seat sit by students anymore so that's the rule in the classroom right so how do we calculate the number of the maximum number of students so let's first take a look at the scale of this problem so there are at most M eight rows and AIDS columns is quite a small number right so as soon as we find out the scale the problem is small we need to reflect that we can use binary compression here so and it is to calculate as a maximum so we can reflect that we also need to use dynamic programming right so to use dynamic programming what is formula here so here is the formula F IJ means for the first I row if the state is J what is the maximum number of students so what is the state here today the J means if we let's say there is one row so first row right and the initial state is 0 right so 5 0 in binary format means their own right so if this city is occupied it means like this right and this is the binary format so let's translate it into decimal that is 0 1 they were there earlier right so in decimal is AIDS right and the water bar so this two seats are occupied in a means in binary is like this right so zero one right like this sorry say tea it's not eight actually is 16 so for each row we can have States because the for each seat is under occupied by students which is a 1 or not occupied by a student which is 0 so for each row we can always get a number that is less than 2 to the power of M in death decimal format right so M here is as large as 8 so it's not so big less than one solid right it's still a small number so if the ice Rose state is J so J is a decimal number which we can transform it into a binary form and that number can represent this Rose State right so let's move on what is TK here so TK here means for the ice row for example for the first row the state is K let's say his state is currently like this right so one of the city is occupied right and we can do something to this state right what we can do we can place another student into the road right for example we can place a student here so that is the transition of our state's right so initially the initial state is all their own and we can iterate all of the options we have we only have M options so at most of eight options right so we added put students at the first assets or the second assets or just certain seat or the eight seats right so we add most has eight options so we can just iterate each of them and in that way we can deduct all the other states we can have around the initial state right and we can be sure that if state J is bigger the number of state J is bigger than I stated J is always transformed from states that is less than J right so we can in this way we can deduct all of those states from the initial states right so here is a detail of the transition between two states so in the ice row we choose to place a student at D so in our example we choose a student D here right and there's a new state this is the oldest state right and the new state is k2 the or operator two one move left T digits right so D here is two so we move one two it's left right so we get odd number like this and we do our or operations so that we get number like this right so this is the new state and if the new states that original value is lesser than the new value we can replace it using the bigger one right so this guy is the initial state plus 1 right because TK is the maximum number of students we can get from this state and now we add a new student into the states so the counter of students is increased by 1 right so that is the way we get the transition between two states and to be cautious so we had to make sure we put a student at a good place right how do we issue of that so first we need to make sure that for the current States there is no students or ready occupied this place right for example if the initial state is like this we cannot put another student at this place anymore because in this place is already occupied right so we need to check it if the place itself is not occupied right and we need to also check the to the left of that place is not occupied as well because of the rule right and also to the right also to the upper left upper right so how do we check up left and the upper right here is where we need to use f IJ right so we need to in order to calculate F IJ we can be sure that we already calculate F I minus 1 and J right so we are going to have for loop for I so I minus 1 is always calculated before F I right so if these values are already occupied so we can iterate each of the values so let us say we are going to calculate F 2 right we are going to calculate all of the F 2 values in this row right that means we already calculate F 1 values in the first row right so we are going to iterate all of the f1 states so from zero to two to the power of M we are going to iterate all of them and after we get the number I mean get to the state of the first zero when we calculate as a secondary law we can be sure that the row just data of the row above them and we can check in the upper left and the upper left upper right is occupied by students right so this part can make use of the states of the upper row right so I guess that's it we can now take a look at the code here so here is the code so we initialize the F so this is n rows right and this is our two to the power of n states right we get n and n then we set the initial value to minus 1 so minus 1 is we cannot get this kind of states right for example if for the first 0 each of the seeds are bad right so you cannot get 1 you binary form for the first row right because all the seats are bad so that means F 1 or equal to minus 1 right if we'd equals to zero that means you cannot put any students in that state right you see essentially the same thing there oh and the - mines essentially does anything so the - mines essentially does anything so the - mines essentially does anything so the initial state is that if zero equals to zero right if we and take the first the row before the first zero and for the states is zero the maximal student we can put in is zero right so that makes sense and we are going to start from the first zero to the last zero and we are going to iterate all of the states for the rope before I write so J is the state of the upper row right remember that J is the state of the upper world and now we initialize the array of T and make them all 0 initially and the fullest States 0 its value is f I minus 1 J so why is that so this guy is the upper row with J as a state right and T 0 means we don't put any students in this row right so if we don't put any student in the current 0 and the upper rows it's Jay then it means we can just directly put the maximum number of students of the stated J into the T zero right because T is the aroma so we don't put any student in the current Terrell right and if I zero equals to maximum of these two numbers so we are going to use T 0 to updates if I am zero right so I guess that's also pretty obvious and the let's move on so okay here is in the current i0 the state is K so it's current rows states right and the first iteration is that we use initial States we start from the initial States and we iterate all of our options here so we can put a student at the first place at the second place all the way to the end place right so we are going to iterate all of our options to add one more student and because the current state is K right so we need to make sure that the option do not we do not choose the option that the cities are already occupied by K right if K is like this and we want to put another two Atlas the this place we are going to have force here right so this part to make sure of that this part make sure of that it's left city is also not occupied this part is make sure that the right seat is not occupied and this part is deal with J here right so do you still remember that the J means the state of the upper row so here is where we check the upper left is not occupied and here is so where we check in the upper right is not occupied and that they both use J here right so when we need to check the current 0 we use K right and we need to check in the upper row we use J so this two states are very important J and K and if all these conditions are satisfied it means we can actually put a student at that place and we can calculate the next states and that we are going to update the state's value right we always choose the bigger value and in the end we are going to choose the maximum value of for the first n rows right so and the returns the answer so I guess that's it thank you for watching
Maximum Students Taking Exam
check-if-it-is-a-straight-line
Given a `m * n` matrix `seats` that represent seats distributions in a classroom. If a seat is broken, it is denoted by `'#'` character otherwise it is denoted by a `'.'` character. Students can see the answers of those sitting next to the left, right, upper left and upper right, but he cannot see the answers of the student sitting directly in front or behind him. Return the **maximum** number of students that can take the exam together without any cheating being possible.. Students must be placed in seats in good condition. **Example 1:** **Input:** seats = \[\[ "# ", ". ", "# ", "# ", ". ", "# "\], \[ ". ", "# ", "# ", "# ", "# ", ". "\], \[ "# ", ". ", "# ", "# ", ". ", "# "\]\] **Output:** 4 **Explanation:** Teacher can place 4 students in available seats so they don't cheat on the exam. **Example 2:** **Input:** seats = \[\[ ". ", "# "\], \[ "# ", "# "\], \[ "# ", ". "\], \[ "# ", "# "\], \[ ". ", "# "\]\] **Output:** 3 **Explanation:** Place all students in available seats. **Example 3:** **Input:** seats = \[\[ "# ", ". ", "**.** ", ". ", "# "\], \[ "**.** ", "# ", "**.** ", "# ", "**.** "\], \[ "**.** ", ". ", "# ", ". ", "**.** "\], \[ "**.** ", "# ", "**.** ", "# ", "**.** "\], \[ "# ", ". ", "**.** ", ". ", "# "\]\] **Output:** 10 **Explanation:** Place students in available seats in column 1, 3 and 5. **Constraints:** * `seats` contains only characters `'.' and``'#'.` * `m == seats.length` * `n == seats[i].length` * `1 <= m <= 8` * `1 <= n <= 8`
If there're only 2 points, return true. Check if all other points lie on the line defined by the first 2 points. Use cross product to check collinearity.
Array,Math,Geometry
Easy
null
1,716
Hello everyone welcome to my channel Quote Surrey with Mike So today we are going to do video number 18 of our maths playlist, it is marked easy but it is a very good question, we made it approachable, number 1716 is calculate money in lead code bank ok so let's see. What the question is trying to say is that Hersey wants to save money for his first car. He puts money in the lead quote bank every day. Now how does he keep the money in the bank? He wants to be seen. He starts by putting. Dollar on Monday the first day is ok and every day from Tuesday till Sunday will put in dollar more than the day before right like let's assume this is Monday this is Tuesday this is Thursday this is Friday this is Saturday this is Sunday So kept a dollar on Monday, kept one more than the previous day on Tuesday, kept two on Tuesday, kept one more than the previous day, kept two on Tuesday, kept three on Wednesday, kept four here, five here, six here, seven here again when Monday starts. Look what he is doing on every subsequent Monday, he will put more than the previous Monday. Now look, pay attention. Now when the next Monday comes, tell me what he will do. See, on the previous Monday he had put one, now he will put two, okay after that. After two it will increase 3 4 5 6 sa 8 After that when Monday comes again what will he do then see the previous Monday had put two, this time he will put three ok then it will move ahead one by one r pa ₹ ₹ and so on will move ahead one by one r pa ₹ ₹ and so on will move ahead one by one r pa ₹ ₹ and so on ok so like this He will deposit so what you have to do is you have given and kept return the total amount of money he will have in the bank at the end of the eighth day total and days he has and it is collecting money so let's see this How much money will be collected in the last day? Okay, so let's see the example. It will seem even simpler. Like look at the first example, here he has only four days, so he must have started from Monday, Tuesday, Wednesday, Thursday were only four days, okay. So, one dollar was kept on Monday, two three days were kept on Tuesday, how much has the total become, the total has become 10, then the answer is 10. Okay, now look at this example, the total is 10 days, it has Monday will start Tuesday. Wednesday Thursday Friday Saturday Sunday came back ok now new Monday will start again it will be 10 days let's see one doti cha pa 6 sa 8 Tuesday Wednesday ok so how will the money be kept from this look at the total 10 days have passed since I wrote Gave 10 days, did not put one here, then kept increasing it one by one, got 6, then when next Monday came, I had kept one in the previous Monday, so in the next Monday, just do its plus and, that is, two, its plus and, done, okay then. Keep increasing one by one, 3 4, there is nothing further, he can only deposit the money for 10 days, ok, so find out the total, 1 + 2+ 3+ 4 + 5 6 7 + 2 + 3 + 4, so the 1 + 2+ 3+ 4 + 5 6 7 + 2 + 3 + 4, so the 1 + 2+ 3+ 4 + 5 6 7 + 2 + 3 + 4, so the answer is Only 37 will come, okay till now it is clear, if we see then the first approach will come, do it as it is told, ok, approach one, what is approach one, simply do the simulation you have been told to do, as it is done. Age Ask is fine, just keep doing it as explained in the question, I mean, look at what I am saying here, I have explained here that as much money as is deposited every week, keep adding it, after that when When the next week starts, increase the Monday one by two, i.e. by one, from the increase the Monday one by two, i.e. by one, from the increase the Monday one by two, i.e. by one, from the previous one, then run the whole week, it becomes seven days, then go to the third week and so on, so keep taking out each week as it is said in the question, it is okay. Now look here, pay attention, you are seeing in the first week there are seven days, in the second week it has accumulated only till nine days, okay, so we have to pay attention to this thing that we do not cross it, otherwise see, in the beginning there are at least seven days. When it is completed, remember how many days we had in total. There were 10 days, neither were there 10 days and this one has completed seven here. Now how many are left? 10 - completed seven here. Now how many are left? 10 - completed seven here. Now how many are left? 10 - 7 that is 3 so here three are left. Only three days are left i.e. last week. You see, you have to three days are left i.e. last week. You see, you have to three days are left i.e. last week. You see, you have to run it only for 3 days, you do n't have to do further days because it will be 10 days, okay, it is clear till now, so let's see how we can do it, we will do it exactly as told, first of all, keep in mind that What we will first notice is that brother n, which is the greater day, will keep collecting money till it becomes 0, it is clear till now, okay, the second step is that brother, take out the money of sen days and add it, how much will be collected in 7 days. Its ok now when sen days are gone then subtract sen days from n ok days are subtracted from n and after that go back to step one is n equal to 0 yes again money add of seven days Do but pay attention that let's assume that in this example n = 10, this example n = 10, this example n = 10, right, is 10 equal to 0, yes, right, we have added the money of 7 days, okay, that means we have added these seven days, okay, that's it. After doing n - 7 i.e. 10 - 7 that is 3 became 3, After doing n - 7 i.e. 10 - 7 that is 3 became 3, After doing n - 7 i.e. 10 - 7 that is 3 became 3, went back to the while loop, is 3 greater day 0, yes, take out 7 days, what no, only three days are left, so I write here 7. Not the minimum of days, which is left, either the days are left, look at this, here the value of minimum of n was 3, otherwise th will come from 3, that is, three days will have to be taken out, here are only three days in the last week. So what was left is okay, this thing may be tricky, you can handle it in your own way but here instead of writing down the intake, I reduced the minimum to 7A because look, only three days were left for the last one. Yes, it is three and the minimum in sa is three, so we will add up only money for three days. Okay, after that we will do the same steps again. My 7, 3-7, do the same steps again. My 7, 3-7, do the same steps again. My 7, 3-7, what has happened - 4, brother, yes, this one is a what has happened - 4, brother, yes, this one is a what has happened - 4, brother, yes, this one is a while loop here. But it will break because minus 4 which is greater zero, no, it is clear till here, so it is quite simple and yes, one thing to pay attention to in this matter is that when you are adding Monday's dice, it is neither Monday nor the starting one. There was dollar on Monday and then on next Monday it was NPS, that is, there was L, then on next Monday we will have to deposit $3 like this. If then on next Monday we will have to deposit $3 like this. If then on next Monday we will have to deposit $3 like this. If you are okay then we will handle that too. As soon as we have done it for one week, how much money will he deposit on Monday? Let's do plus one in it, Monday plus equal two, okay, how much will it start on Monday, so in Monday, one, I have added one d here, okay, so let's see a simple example, a dry run, n e two, how much was 10. Na n is equal to 10. Okay, while a while is n greater than 0, yes 10 which is greater than 0, okay, so what I will do here is I will try to find out the sane days, not even the sane days, the minimum of n is 7, right? So here n is 10 and 7 sen is there and what is the minimum if it is seven then sen days can be calculated because now the value of n is 10 so 7 days can be calculated neither so what did I do here 7 days money If you calculate then how much will be the money for 7 days? After calculating, the sum of 1 2 3 4 5 6 7 is correct. 1 + 2 + 3 + 4 + 5 + 6 + 7 is correct. Now pay + 2 + 3 + 4 + 5 + 6 + 7 is correct. Now pay + 2 + 3 + 4 + 5 + 6 + 7 is correct. Now pay attention here, Monday starts from here. If it was one then the value of Monday was one. It was in the beginning. We have calculated 7 days. After that what I said was that if we have calculated 7 days then make n = n - 7 because 7 days have already passed. make n = n - 7 because 7 days have already passed. make n = n - 7 because 7 days have already passed. No and yes, one thing to note is that the money to be added on Monday was $ler and added money to be added on Monday was $ler and added money to be added on Monday was $ler and added plus and ok that's all we had till now, this was the code datchi so let's see here 3 Gun is 0, yes, so now we are calculating the value of second week. Okay, so about the second week, what did I say that the minimum of n is 7, my th, so yes, we will calculate the value of only three days and remember the value of Monday, it was two, so two. We will start with 2 Ps 3 Ps Ch, we will calculate only three days, okay, 2 Ps 3 Ps is done and after that we will do the same again n = n 7 i.e. n 3 Ma or will do the same again n = n 7 i.e. n 3 Ma or will do the same again n = n 7 i.e. n 3 Ma or Min will become 4, this time the value of Monday. Plus will be plus but this time look at minus f which is greater than zero if it is not zero then the while loop will break so we will go out of here so see who we have added how much money we have added so much money so our answer is exactly the same here also. If it is clear, then approach one is very simple. Let's quickly code approach one and see if it is accepted. Otherwise, let's code it exactly as explained. First of all, what did I say, okay, take one variable. In which we will add all the money which we are adding in the bank. Okay, now look, pay attention, I told you that when that person will start in the starting, then in the starting on Monday, he had the right question. Okay, starting on Monday, after that for how long will we do this until my number of days is over? Okay, now look let's add the money of every week, int money is equal to start with whom will we start from Monday? How much money is there in Monday, $ is in the beginning, okay, now let's take out this money is there in Monday, $ is in the beginning, okay, now let's take out this money is there in Monday, $ is in the beginning, okay, now let's take out this week's first day, 1 day is equal to lesson two, remember what I told you, let's take out each day of every week, okay but it can be n The value of n is the value of n, if it is less than sen, then let us assume that the value of n is th, then why take seven days, neither will the minimum of n be taken from the comma, right after that, D plus P, pay attention, result plus. It is equal to see the value of money ok and money plus will keep doing it remember Monday money starting in the beginning there was one so here I added one after that next time will add again and so on so money plus Are we doing it? Okay, now this thing is clear, now that these days are over, so I have done it, we are going on withdrawing money for every day and seeing that we will increase the Monday money because now that these days are over. So now the next week which will start and it will start again from Monday, then we have made money plus, right, Monday money was increasing by one dollar every time, in the last return result has been done, ok, it is quite simple, let's see by submitting it. To pass all the cases, indeed yes we have solved this question. We have passed all the cases. Let's move quickly and understand approach 2 how it can be solved from above. Now look let's come to our approach 2 through maths. We will make it using OV approach, okay, let's assume that in OV time complex, let's take a small simple example that the value of n is 21, it is okay for 21 days and the money will be deposited in the bank, so I have written about the first week. It is kept 1 P 2 P 3 P 4 + 5 + 6 + 7 Total will be 8 That will be $8 Then + 5 + 6 + 7 Total will be 8 That will be $8 Then + 5 + 6 + 7 Total will be 8 That will be $8 Then in the second week 2 + 3+ 4 + 5 + 6+ 7+ 8 in the second week 2 + 3+ 4 + 5 + 6+ 7+ 8 in the second week 2 + 3+ 4 + 5 + 6+ 7+ 8 Why did it become two? Look, previous Monday it was one so now it was two. This is the same in the third week 3+ 4+ now it was two. This is the same in the third week 3+ 4+ now it was two. This is the same in the third week 3+ 4+ 5 and so on I also calculated the total sum that 28 35 42 i.e. what will be the total money that 28 35 42 i.e. what will be the total money that 28 35 42 i.e. what will be the total money 28 + 35 + 42 ok it is clear till now ok 28 + 35 + 42 ok it is clear till now ok 28 + 35 + 42 ok it is clear till now ok now you are noticing one thing. So this is 28, after that is 35, after that is 42. This is doing a kind of arithmetic progression form. If you pay attention, look at the common difference, what is the common difference, and this common difference was bound to come because Look, it is increasing one form here from the previous Monday. Okay, after that we used to do plus and psv, so what is the reason for doing plus and what was there in the previous Tuesday, it became plus and psv here also. Gone Plow is here Plow here is correct i.e. total seven has been Plow here is correct i.e. total seven has been Plow here is correct i.e. total seven has been added extra times. If extra rupee has been added then 28 × 7 becomes 35 × 7 becomes 42. added then 28 × 7 becomes 35 × 7 becomes 42. added then 28 × 7 becomes 35 × 7 becomes 42. So look at the common difference which is exactly seven. Is it a constant? Is it clear? Common difference is the same. So now that means arithmetic progression is being made and now tell you one thing. If you want to find the sum of an arithmetic progression, then it is already clear. What was the sum of tick fraction? What was the total number? You can also write total number of terms A, but to avoid confusion, I am writing terms total number of terms by two into first term plus last term means go by the value of n term, okay this is A1 i.e. This is the go by the value of n term, okay this is A1 i.e. This is the go by the value of n term, okay this is A1 i.e. This is the first term, this is the last term. Okay, so let's see if we can find out how many number of terms we have. Look at the total. Pay attention. Do you remember that the total was 21 days? Look, the days have passed here. The first term is this. After that, seven terms have come out here. This is the second term of AP. This is the third term of A. Okay, so see, it is coming out sen day after sen day. That is, what will be the total number of terms. Look, pay attention, total. The number of terms will be from A to Ba. Total will be the same number of weeks. First week, second week, third week. Because look here, n = 21 and I have changed Because look here, n = 21 and I have changed Because look here, n = 21 and I have changed n to 7. Okay, it is not complete yet. Wait a little more. Things will come to light, here the terms, we came to know that n is from ba, okay so here I will take out n in terms, ba is 7, so what is my n is 21, okay, so what I did, let's put it in this formula here. What is my terms n ba 7 or 21/7 21/7 is how much is 3 so I 21/7 21/7 is how much is 3 so I 21/7 21/7 is how much is 3 so I write this but look into it a1 is my first term a's 28 ok and a what is my last term my a's What is the last term? Look, it is 42. Okay, so the last term. Do you remember how we used to find the formula of A? Do you remember what we used to do to find out any eighth term? A1 P n-1 or common difference. Okay, P n-1 or common difference. Okay, P n-1 or common difference. Okay, look we know a1. 28 is ok and what is the last term sorry a1 + n - 1 * d n what is the last term sorry a1 + n - 1 * d n what is the last term sorry a1 + n - 1 * d n What is my total number of terms Here I write the total number of terms -1 * d i.e. 3 - 1 * d terms -1 * d i.e. 3 - 1 * d terms -1 * d i.e. 3 - 1 * d total The number of terms we calculated here is n ba 7 and the total number of terms -1 * d common difference. We know the terms -1 * d common difference. We know the terms -1 * d common difference. We know the common difference is 7. Okay, so how much is 28 plus 3 minus 14. Okay, how much is 42. Okay, so look at the last mm, we have also taken it out from simple A's formula, right, using an eighth term formula, and what is this, a sum of end terms formula, okay, so just solve it, 3/2 is 70. No yes, it becomes 35 in 3. Our answer has come, okay, it is quite simple, so what we had to do, we just had to find the sum of A. Okay, and here you know the first term, you can easily find the last term also. I have explained to you the terms and terms of the formula, here n is from ba, okay but you noticed here, this is a very simple example, I took 21, which is n ba 7, I did 21/7, so 3 is divisible. That is, 21/7, so 3 is divisible. That is, 21/7, so 3 is divisible. That is, if it is not divisible by sen, it is okay, let us see its example, so now I am taking the example, if the value of n was 25, then how would we calculate it, then the first week will be the same, sen days have passed, the second week is the same, seven days have passed. The third week is over, seven days have passed, how many days have passed, 7th, 21 days, okay, now the last four days are left, okay, now I have written the last four days here, it is okay on the fourth week, so okay, this is a big thing. It is simple and you will also know how many days are left in the last days, you can calculate it very easily, do it with N module, the reminder will be the same, there will be so many days left in the last days, okay, that means I am saying that remaining. The number of days that will be mine in the last week will be a middle 7, yes, as a reminder, it is okay to divide by 25, because look, if you divide 25 by 7, then 7th comes to 21, so 21 days have already passed. 2-3 7th comes to 21, so 21 days have already passed. 2-3 7th comes to 21, so 21 days have already passed. 2-3 remaining module reminder i.e. remaining module reminder i.e. remaining module reminder i.e. four days is ok then four will come 25 module 7 four comes ok so now what will we do, here we have got the model, it is of four days so if we look, we are still using the same thing. You can use the formula that you learned above, but see how many weeks it is only for three weeks, 28 35 42, so even today AP is being made, is n't it 28 35 42, this is the same progress even today, so its sum even today will be the same as last time. It was okay, just in the last we know what we will do, we will take out the final week separately, how many days will be there in it, remember how many days will be there in it, N Model will be there will be 7 days in it, we will take out the final week separately and The initial three weeks, we will figure out the progress of the first three weeks, till now it is clear, okay, now let's see how we will figure out the final week, so see, if we talk about the final week, then it is right. So in the final week, you see how much money he will give in the beginning, try to understand, that is, whatever happens on Monday, how much money will he give in the final week, okay, remember, you know that n times 7 i.e. n times 7 i.e. n times 7 i.e. 25/7. That means three weeks will have passed, 25/7. That means three weeks will have passed, 25/7. That means three weeks will have passed, one two three, only after that the remaining week will come, okay, three weeks will have passed, remember, three weeks will have passed, so in the first week, one will be given on Monday, in the second week, one will be given in the third week. Okay, so remember Monday in the starting, I gave one rep in the starting, how many weeks have passed, three weeks have passed, so what is the actual number of weeks, look at the number of weeks that have passed, add one to it. Ho number of weeks, how many times have passed, three plus one, why did we give one in starting Monday, we have made it plus one, 3 + 4, okay, so this is how we came to know made it plus one, 3 + 4, okay, so this is how we came to know made it plus one, 3 + 4, okay, so this is how we came to know what will be the first term of the fourth week, okay final. What will be the first term of the week? It will be of 1 ps, which means the number of weeks. I write here the number of weeks passed. It is okay because Monday's money was increasing in every week. No, Monday's money was increasing in every week. So, as far as the number of weeks is concerned, it is okay to add plus and to it. Okay, so 1 + 3 is 4. I am clear till now, so 1 + 3 is 4. I am clear till now, so 1 + 3 is 4. I am clear till now I just don't have to do anything. How many number of days is A module 7 i.e. 25 module of days is A module 7 i.e. 25 module of days is A module 7 i.e. 25 module 7. 3 21 modules left four i.e. 7. 3 21 modules left four i.e. 7. 3 21 modules left four i.e. how much was the final term remember 1 plus number of weeks was three 1 p is four and how many days are left only four days so I will start from four I started from the beginning and it has to last only four days So it will run for four days 4 5 6 Psa Then we will run the same for loop, it is ok for four days, what am I saying, we will run the for loop, how many days does it have to run, it has to run for just four days, one day less than equal to two. Remember this from N module, remember this in the last week because from A model, days only, that will run money, add money from A mud, days will be plus, okay and here what should we do or do, what was the starting term, starting money, how much money to start with. Will do plus k se na r ok then I will write down how much is the start money na plus number of weeks how much has been passed remember n ba se was na n ba se this much money had passed ok and that's it here we have Keep adding Result plus equal to whatever start money is added to your result and will keep increasing one by one Start money plus We will keep adding Start money plus, first Rs will be added then ₹ will be added then ₹ will be added then first Rs will be added then ₹ will be added then ₹ will be added then first Rs will be added then ₹ will be added then ₹ will be added then ₹ will be added right for four days ₹ will be added right for four days ₹ will be added right for four days That's why I have told you everything in detail, so let's put the same thing in the code and finish it, so let's start its code. First of all, what did I say that how many terms will there be? n will be 7. Okay, now as many weeks as we can find out in this given n, we will find its sum from A. Okay and remember the first term of this A will always be 28 right because I told you that We have to find the sum of every week, so remember, the first one was 28, the sum of the first week was 35, after that it was 42, after that and so on, this is what we were getting, so the first term was 28, okay, but we have to find the last term. Right because we have to calculate the number of terms and number of weeks according to that. So remember what was the last term? How was a? Term plus n mive i.e. n is my Term plus n mive i.e. n is my Term plus n mive i.e. n is my number of terms so terms mive into common difference remember common difference will always be sane right so what is my a formula for the ith term is clear till now after this it is very simple a is the sum of a It is okay to find the formula. Items i.e. okay to find the formula. Items i.e. okay to find the formula. Items i.e. items by two is okay. Either I would have done it like this. Items into first term plus last term byt is okay. Sum of eighth terms in NA. We have just applied the formula of A on Y. Okay, now comes the turn of Ba. If it is the final week of remaining days then how many remaining days will there be, you know that here I also write e equal to n module 7 will be right then int start money how much will it start from remember n plus number of weeks how many weeks have passed as many The number of terms is right, so the weeks are here, that is, n ba se na, so here I write the terms and for int day is equal to one day lesson is equal to one module, so many days will be the last one. After that on the week, do day plus and just keep adding, result plus equal to two, okay, if it is even or not, then here I write the result as if a is even or not, and here result plus e equal to two, whatever my start. Money is there, this is done and we will start doing money plus also. In the end, what we have to do is to return the result. Let's run and see. Let's see if we are able to pass all the test cases. What mistake have we made here? There will be terms instead of items, won't it be total? It is the number of terms. Item was not even a variable. Let's see the example. Test cases will pass. After that we will run and submit. Now look, pay attention to this time completion. Look at this line, it is not in ov. Line number nine, look at this. So o1 is simple, we have used the formula o f Okay, now you say brother, here you are using for loop, so pay attention, it is from n module, it is a constant, it can be zero anytime, it can be from a module. It can be one, it can be two, it can be 3, 4, 5, it can be six, sometimes it will be more than this, otherwise it is a constant, no, this loop will never run more than six times, so that is why it Is it constant? Is it fixed? This fixed number of times will run. It is always good. It will never run more than six times. This is also an oven, so it is an overall oven. Any doubt, please post in the comment section. Try to help in the next video. Thank you
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
5
hey so welcome back and there's another daily kill problem so today it's called longest palindromics substring and it's medium level dynamic programming problem and so essentially what you want to do is just find the longest uh pandoromic substring and what that is while a substring is when you just take a kind of fixed size of a particular string you can't kind of hop over them they all have to be consecutive so say bab that's a substring but you can't say take B and then grab D to make a substring they have to be kind of all consecutive or all in a row okay and so the other part of this definition is what is a palindrome and that's just where if you read it like uh from left to right or right to left you spell it the same way and so something like a B A that's a palindrome because whether you read it from left to right or right to left it's still going to kind of spell out the same word uh same thing where this is an even number of letters you could also have something like a b a and that's also considered a palindrome okay so typically this is a very popular Alico problem typically you would use something called like the two pointer method where you have a pointer pointing on one side and a pointer pointing on the other side and you kind of just move them in with each iteration and once they kind of touch each other or overlap you've proven that it's pound room as long as they've always are matching as you bring them in closer you can also do it the other way where you start from the middle and then move out and that's actually what we're going to do and so basically what you do is you're going to have one function call it okay is this a pound room and we're going to specify like our left and right pointer here and so we're going to be kind of iterating through for every kind of point in this string we're going to see if we can make a pound room there and so for the length of the string let's see if we can make a pound drone and we're going to return some substring here and so we're going to have to kind of take a slicing of the two sides and so we're going to need to define a left pointer and a right pointer such that this is like the maximum poundromic substring okay and so other thing in Python you have to add a plus one just because um it's non-inclusive on the right side it's non-inclusive on the right side it's non-inclusive on the right side okay and so we'll go ahead and Define these so initially our Max on the left we could see the Max on the right and we're just going to start them at index 0. so we're just basically iterating from left to right here and we're going to consider and trying to expand each of these points in this array or in this string to see if we can expand it and see what's maximum pounder we can create from going from the inside out okay and so to do that uh you have to consider those two cases where is it an odd length or an even length and so basically what that's going to look like is we just want to call this is palindrome function and you just need to specify okay we can either in this case start at the middle and that's going to be whenever it's a even or an odd number so this would be odd where we're going to start from the middle and expand out and that's kind of like a B A and so we're doing this and we point them both at B obviously that's going to be the same and we just decrement one pointer and then increment the other pointer okay but for the even length which is the second case we're going to say okay what if it's like a b a we're basically going to have one pointer that will be on the left kind of middle and then the second pointer which beyond the kind of right side of the midpoint okay and so what that's going to look like is pretty much same thing here except we'll do I plus one that's how you kind of get the right side of the mid okay and so that's that but what we're going to do is we have to fulfill this function here and so first thing that we're going to want to specify is just these Max left and right pointers and so from here we're just going to want to iterate and kind of expand from the inside out while it's still valid so while the left pointer is greater than or equal to zero because we want to stay within range and a right pointer is less than the length of our string but then also that while the left pointer is equal to our right pointer and so the first two cases just make sure that we're kind of within the bound so that when we index into the string it doesn't throw an error and the second cause is just to make sure that well what we're checking after all is that it's a palindrome as we move these pointers out they're the same okay so with that so then naturally with each iteration we're going to want to move these pointers such that our left pointer is decremented and our right pointer is incremented but we finally want to update our case whenever we found a new Max like substring length we want to update our Max left and Max right pointers so that we kind of can continue to maintain that maximum pound dromic substring and so to do that what you do is you just say Okay um our Max left or we want to do that whenever if the right pointer mine's the left pointer oh and what we're doing here is while left is greater than that and right is that so we specify that here sorry I got confused this should all be good um we want to update okay if right minus left plus one which is basically the size of the current running uh palindromic substring that we're taking a look at if this is greater than the current our largest Pounder with some string which is basically just Max on the right minus Max on the left plus one and so from here we just say okay then our maximum on the left and our maximum on the right we're going to want to update these pointers so that it's now equal to the current pointers and that's about that uh looks like there's something wrong here and valid syntax that looks right not sure what's going on here or i o in sorry there we go and success so that's uh today's Lico problem so for time and space complexity the time will be N squared because in the worst case you kind of expand um to the fullest with each iteration and then for space complexity well this is non-recursive is non-recursive is non-recursive um it's simply just being called and you expand and there's no extra data structures that's used to store a new memory other than just constant space variables so it would be o of one space but yeah I hope it helped and good luck with the rest your algorithms thanks for watching
Longest Palindromic Substring
longest-palindromic-substring
Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`. **Example 1:** **Input:** s = "babad " **Output:** "bab " **Explanation:** "aba " is also a valid answer. **Example 2:** **Input:** s = "cbbd " **Output:** "bb " **Constraints:** * `1 <= s.length <= 1000` * `s` consist of only digits and English letters.
How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint: If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation.
String,Dynamic Programming
Medium
214,266,336,516,647
56
welcome to dab the light development done right and today I'm going to be solving a lead code problem number 56 merchant rules let's get started and don't forget to Like and subscribe merge intervals given a collection of intervals merge all overlapping intervals now this is a common type of problem sometimes they call it intervals sometimes they call this meetings but basically you usually given an input of a race and you need to merge those numbers which overlap so for example if you have an interval 1 + 3 + 2 + 6 - you have an interval 1 + 3 + 2 + 6 - you have an interval 1 + 3 + 2 + 6 - falls between 1 &amp; 3 so they want you to falls between 1 &amp; 3 so they want you to falls between 1 &amp; 3 so they want you to merge it into 1 &amp; 6 merge it into 1 &amp; 6 merge it into 1 &amp; 6 how can we do that was a three-step how can we do that was a three-step how can we do that was a three-step process that you can utilize for other merge interval problems as well step one is always turning intervals into points step two will be sorting those points and step three processing those points all right so to process and turn this intervals in the points you can do this can extract the first the start time the end time of the interval and what we can do here is either create a class and what this class will do is keep track off the point such as X or Y and if it's a start or end point so if it started it would be true if its end point it would be false and you need to push all this points also into an array so we can push Nieporent X would be the time and start will be true and for y it would be the same thing except obviously it will be Y and this would be false but there's also another way to represent this without the class which will save you time on the writing code and probably easier to look at so let's get rid of this class points or ship the shove-it class point anyway instead we can directly push into an array and you can push an object so time is X and if start it true same thing for the Y except is start false let's print this out so you can take a look of how this points look like alright so don't worry about the wrong answer because we're not finished I'm just showing you the output really quick so this is how this points will look like time it started true three is start false you see they're separated in its own objects so here we need to sort by time we need the stew to show up before the three and we need to sort by its start because sometimes one meeting can end at the same time as another meeting is beginning but you need to have the meeting that's beginning in front of our array if they both stop start at the same time so how do we sort this point sort you should already know how sorting works in JavaScript if not I have a video on my channel that you can check out so first we're gonna check if the times are equal if it is we need to check you need to check if they're both if they both start or end at the same time because if they do then that's irrelevant to us it's same thing one can show before the other else if they're not equal we'll return it in a way where a is start if that equals to true it should show up before the one that ends and if the times are not equal then just sorted by time so as you can see basically at the time of this two intervals is equal we want to sort the one that starts before the one that ends otherwise we return in ascending order my time so we're sorting by time and by the start as well let me remove this console dot log so the next thing we need to do is process this points the way to do that is we're going to keep the counter and basically when the meeting starts we increase the counter by 1 when the meeting ends or the interval ends we decrement we decrease the counter by 1 that way we know meaning started it becomes 1 meaning in it becomes 0 what if two meetings start so the counter will become 1 and then 2 so the counter lets us know if there's an overlap of the interval or meeting whatever you want to call it or not also let's create a new points array where they'll keep all the new intervals of your process okay and they already know if the meeting is starting or not because we use a start flag so what you can do is if point is start you know the meeting has started so as I mentioned if the counter is 0 we know it's a new interval is beginning so we need to keep track of that let's say a new start so the meeting is starting the counter is 0 it's a new interval that begins and we need that point that's why we have new start and they'll assign time to it and of course we need to increase that counter else means the meeting is over so we need to decrease the counter and that the counter is equal to zero meaning there's no meetings overlapping right because if there was meetings overlapping Connor would not be zero we know this is the final point there's no intervals overlapping and we need to push that to new points using our new start and time so this is our Y time this is our x time because we tracking X's here start and every meeting or interval that ends will be here point that time and of course we need to return all these new points let's run this of course I made a mistake didn't add the arrow and as you can see we passed the tests and everything is working great I hope you enjoyed this tutorial subscribe if you didn't yet because there's more tutorials coming and also you can leave in a comment what you liked about the video and what other questions you want to see I'll see you soon you
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
14
hi today we're going to be going over the java solution for lead code 14. longest common prefix write a function to write the longest common prefix string amongst an array of strings if there is no common prefix return an empty string as i guess given here so prefix means basically the starting letters of a word so you know longest common so we're going to try to look for basically which starting sequence of letters to all of the elements in a string array have in common so if you're looking for the shortest of course it's just an empty string if you're looking for the second shortest in this case it would be f so all of them have f in common from the beginning and then if we move on to l all of them have f l in comment but if we look on to the third letter f l o but this is f l i so they don't all have three um three of the beginning letters in common so that's why we'll just return the two which is the guaranteed one they have in common which is just fl um with this one we can see that you know even the starting letter none of them have in common so we just return an empty string and so i think there are two key takeaways from here number one is that we just need one of these to be different than the other in order to figure out the longest common one we could basically look at this one we can see the fl and then even though both of these have o and o this one has an i which breaks the whole continuity which means we could just break it from there and just return however many we have completed thus far however many letters we have found thus far that they have in common and then the second thing is that the maximum length of en of the output string can ever equal is basically the shortest or smallest element in the array so let's do that let's go find it so we'll do an int minimum which is going to equal integer.max value integer.max value integer.max value and we'll have an index since that's the thing we care about we're going to look for the index of the string so that we could basically analyze it i guess and then we're just going to go through the whole array and now if str's of i dot length is less than our min then number one our min is going to turn into that length and our index is going to equal that index so after we come out of this loop we'll have the index of the sm shortest or tied for the shortest element string element so for communication sakes or to make um so for the case of making this a bit more clear i'm just going to store that in a temporary string i'll name str and that is going to equal uh strs of index okay great so now what we're going to do is that we're going to number one do a double for loop and what the how the loop is going to be structured is that our outer loop is just going to look through all the letters of our smallest string so str so in this example one it would be flow and example two it would be dog and we're just gonna look through all the letters and then our second loop is gonna loop through all those elements to see do they have that character in common so let's do that so four in ti is equal to zero i is less than scr dot length i plus i don't know why it doesn't okay there we go um and then four and j is equal to zero and now j is less than um the length of the array and we'll do j plus and for clarity's sake i'm gonna store the character we are using as a temp a character temp and that's going to equal str at i so when we look through all the elements it's like if they do equal are temporary then that's great if they don't that's the case we care about so if uh str's of j dot char at i is not equal to or temporary then we know we have basically found the longest common prefix and that's just going to be how many letters we have completed thus far so we can just return the substring of from zero to i of our str or really any other um element and if we go through this we go out of this for loop then we know that you know we have completed all of the letters which means that we can just return um str itself since that means that str itself is common with all the elements so let's see if it works okay great and now let's submit it okay great so that was lead code 14 longest common prefix
Longest Common Prefix
longest-common-prefix
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string `" "`. **Example 1:** **Input:** strs = \[ "flower ", "flow ", "flight "\] **Output:** "fl " **Example 2:** **Input:** strs = \[ "dog ", "racecar ", "car "\] **Output:** " " **Explanation:** There is no common prefix among the input strings. **Constraints:** * `1 <= strs.length <= 200` * `0 <= strs[i].length <= 200` * `strs[i]` consists of only lowercase English letters.
null
String
Easy
null
310
hey guys what's up today's question we're going to say the three one low the minimum high trees is that giving us the 2d array which is uh in edges and it will be represented by the connection between two nodes and it wanted us to find the minimum high tree the root of a minimum high tree uh and uh for this for example because you know the minimum height defined here will be the longest path from the root that you find and to the leaves to the you know the leaves node and in this path will be like the one will be zero because like whenever we uh from zero to any other nodes you will be like have the minimus last there will be one and if you see defined here will be in a loop and you will just receive a lens with two because you come from here to here because you want the longest path to be defined as the uh the height right so that we need to find the minimum you know root and to be honest the first the most intuitive idea for me is to use in pfs why is that because using the bfs we ever because we see the keyword minimum whenever i saw the keyword like minimum or surveys uh in the graph question we're just gonna use the bfs in order to get the uh the minimum or shortest you know result and for this we will actually the most infinite right there will be like first two traversal uh for every node uh node we will actually will be like to be fast uh like thickness for example we will first take this and then we're just gonna go to rest of that and find out that if we take this for the height it will be like if we take zero the height will be like one if we take one and the height will be two so that we actually to you know compare between each other the minimum length uh whenever we take you know each note be the root and then we're just going to return we first will compare and return the uh to see which one which not have the minimum last or the you know pass however this method is quite time consuming hard because that first we need to go towards the node and they are going to be faster and to be effective you will just you know we'll have the complexity of one and this will be time uh square right so that we need to reduce the time complexity and this will time limit the uh online attachment for the code and uh yeah so how are we gonna you know improving that because first our most engineering idea will be like goes first from the uh root to the leaves and it is possible to get the result from the leaves to the root what do i mean by that it's like whenever we are going to rest in the trees and uh take this for example if they we here we will just get we can actually to first to define the adjacent table right and to record it every connection situation between you know each node and for zero the back in the zero will be have like uh one two and three right and the one will have the band which contains like zero and the two will contain the bag which will contains like zero left and the same thing for three and what i mean by that it's like because we first we were just looking uh to enqueue because we obviously use you know vfs to solve this problem and to use in a queue and the queue will be first added the elements of nodes which have only one you know one element to edit that and we can delete it and to you know delete it in the corresponding banks which means that i was gonna delete that and this is gonna be the move right and you can also see from here whenever elsa removes all the kind of elements the zero will be the final result that we want you may just say it might be there isn't however i will show you that i'm just gonna show you that it happens uh actually it's cracked for every you know uh arrow grab and let's take this for example if they here we will have a like zero one two three four five right and uh we here will actually enqueue the searching another color into this one this boy and this point right because they only have one connection with each other notes uh four have one two three four uh four connection and the three have two right so we're just gonna first include this kind of voice i'm going and then that and also because each node will have the adjacent table which means that each node has a crosswinding back and we're just going to delete the corresponding the counterpart from the back so here we're just going to do that and you can see after we perform an optional delay and only you know the node that we left is four and a three so should we just you know go further no because actually here whenever you use four or three to be your root the minimum higher length will be the same because like wherever i just resume this situation three will be two right from here to here because it will be the longest path we defined as you know the higher tree and if you go uh take four as your loop and then go from here and you'll also be true so that basically what i mean is that uh the result set because in java the result will be like the least however again and uh to be honest the real will only contains one or two elements right and uh yeah and what about certain graph what does that happen well you can see from the third graph that first we do you know the same operation we first in queue the element which has only one connection with you know other nodes which is you know this one uh this one and this one right and uh we kind of like you know talking leaves and to include it and this is our three this is a four this is five this is one this is two right and then we're just going to delete that from our graph from our whatever you want the json table after we did that we actually noticed the updated situation where it will have only one connection you know compared to before where it had a two connection right here and here so basically here i will uh kind of fixing that and uh you only you know after we perform this operation and only here we're just gonna left uh this support we'll have one connection this will come right next and support highway connection and this will have a three connection right through connection so what are we gonna do next we're just gonna encode uh the seven eight nine and then after that the only element that we left are four right so it's actually the result that we want so basically by you know uh philippians from you know we're first uh using algorithm from top to uh from the root to the left and you will be time consuming however after we change our thinking process from you know the leaves and the kind of like surrounding where we start from the leaves and then we just finally reach the root and yeah that's kind of what we want and now let's see how the code to implement that and we first need to write some you know instructions in order to follow it smoothly so we first will construct the uh the json table red and then we are just gonna to using the bfs using the queue to add the leaf nodes and to remove that uh only until the end will be uh and will be like r2r1 right so yeah and then we're just gonna return that and turn that so yeah no that's we're just gonna write our record we first of all just write a uh adjacent table right here i was just gonna use that as a hashtag in order to find it quickly right and the decision table you have as released right and uh here we will actually to construct it and uh for i equals zero and less than our i plus class and the edg they'll added our new headset right integer uh and also we need to construct the adjacent table right we only just initialize that and flow in edges to our edges and we will adg that get e h zero uh edit our h1 there and it happens you know opposite and to edit that and we need a zero right and uh here we will uh see because we constructed it as successfully and then we're just gonna using the bfs so we first will need to new a q right otherwise zero is just gonna know where to perform that and uh there will be like integer uh q u a real q right and uh yeah to be honest we need to go first to resolve that and to find out whether or not it has only one connection because that's the least that we want right so we're just going to say if c i actually get all that size equals zero which means that this is a leaves that we want and we're just gonna enqueue that uh right and uh yeah specifically the uh point and let's say well it's greater than two because uh the result set will be like two or one elements uh in our results over here we're just gonna this can actually new here at the end of the code and result and to initialize that per list and say well qr is empty and we're just going to include that because the only elements that are left are cues that we want right so we're just going to edit our say code up call professor per call last version of file right and we're just gonna return result and this is a key part where we should you know keep notice on so we here we all this is kind of classic model of bfs and so you guys can you know remember that and union standard was just you know creating that and uh here we actually we need to uh pull the current number which means that we need to see and uh which bag that i want to you know remove q dot c uh pole pull first and then what are we going to do we need to for because in the uh in the set the current number contains we need to eliminate the connection between the current number and maybe other number who have the connection between each other right so integer num to our adjacent docket current number which is a hash set and we're just going to using fourier to transfer that and the error time we're just going to remove our current number right and uh yeah that's basically the point and after that we uh and minus our size right this is uh we're in our code and uh yeah i believe that's it and let's see how this is going uh it says array d q u e q d q u e u right the uq tq and uh the q oh we don't have the last two characters right and uh here we also need to you know do a adjective judgment if they equal that one and we will directly use this result set and uh to you know result i added our one right and we're just gonna return that right and nope the turret is all right and we can see it was uh what's going on and uh we here we will get this point oh here we will get this boy and uh see here right and this one can say oh there's the uh while n is greater than two we will actually let's see what's going on we first added a headset for every you know table and we got that zero one zero right and uh we here knew the dq and every time we actually to pull oh i just forgot one thing which is you know we need to add the z uh we need to find out whether or not this adjacent number will have you say adj dot gas now the our size is equal to our one we are actually to you know added the cube otherwise you're just gonna be nothing right so that's my you know error for this and you can see from here and all right the last right at the last to capitalize and see how things going up and let's test this one to you know and yeah that's basically the whole idea for this question we're gonna handle that and let's go back and trust it again first we're just gonna construct the adjacent table and then to uh get the leaf nodes because we want the connection to be only one and whenever you know the loop condition will be like if say there will exist uh two more elements we're just gonna continue deleting that because you say there are three elements you definitely can you know you limit that again however if only it has two or one element you're just gonna okay and we're just gonna edit that so yeah that's basically the idea for this three one oh the time consum the time complexity will be uh this is one and uh this will also be on so yeah that's basically the point
Minimum Height Trees
minimum-height-trees
A tree is an undirected graph in which any two vertices are connected by _exactly_ one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called **minimum height trees** (MHTs). Return _a list of all **MHTs'** root labels_. You can return the answer in **any order**. The **height** of a rooted tree is the number of edges on the longest downward path between the root and a leaf. **Example 1:** **Input:** n = 4, edges = \[\[1,0\],\[1,2\],\[1,3\]\] **Output:** \[1\] **Explanation:** As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. **Example 2:** **Input:** n = 6, edges = \[\[3,0\],\[3,1\],\[3,2\],\[3,4\],\[5,4\]\] **Output:** \[3,4\] **Constraints:** * `1 <= n <= 2 * 104` * `edges.length == n - 1` * `0 <= ai, bi < n` * `ai != bi` * All the pairs `(ai, bi)` are distinct. * The given input is **guaranteed** to be a tree and there will be **no repeated** edges.
How many MHTs can a graph have at most?
Depth-First Search,Breadth-First Search,Graph,Topological Sort
Medium
207,210
1,822
hey everyone today we are going to solve the little question sign of the product of an array so there is a function sine func X and that returns one if x is positive a minus 1 if x is negative zero if x is equal to zero so you are given integer array nouns let product be the product of all values in the array nouns return the sign Funk with product so let's see the example U are given minus 1 minus 2 minus 3 minus 4 3 2 1 and the output D is one because uh um If I multiply all values so that should be um 144 so that means this is a positive number so that's why we should return one before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get the code from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let me explain with this example so I copy this inventory from example one so the product of all values in the array should be 144 so we should return one in this case so to solve this question so important thing is that we don't have to return the specific product number um so if the product number is positive we should return one if the number is negative we should return minus one if zero we should be done zero so to solve this question um I use a one variable so let's call like a sign initialized with one and basically we get it through all values one by one and then if we find a negative number um we multiply minus one to sign variable because a negative number affects like a Plus or a minus right if we multiply like a positive number it doesn't affect like a plus or minus so that's why when we find the negative number we multiply minus one and the Divas we get like a number like a um like a from positive to negative or negative to positive so let's begin um first of all we find the negative one so in that case we multiply negative one to sine variable so now sine variable is -1 and then move next we find the minus two so this is a negative number so we should multiply minus one two assign variables so now a sign variable is one in the move next again we find the minus three so negative number so we should multiply minus one so now minus one and I move next we find that minus four so we should multiply minus one so now sine is one and move next so 3 is a positive number so we don't do anything for sine variable and uh move next we find two so this is a positive number we don't do anything we'll be next we find one so positive number we don't do anything and then finish iteration and then all we have to do is just return sign variable and then one more thing um if we have zero in input array we should immediately return zero right so that's a mathematics yeah so that is a basic idea to solve a description without being said let's get into the code okay so let's write the code is very easy so sine initialize sine always minus one and start looping for n in nums and if we find zero so uh n equals zero in the case we immediately written zero and the if n is less than zero in the case um multiply minus one to sign variable so in Python asterisk equal minus one and then after that just return sign yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be called out of n where n is the length of input array so this is a because this is called iterate over entire array once so that's why I ordered so space complexity is o1 because the amount of extra memory used by algorithm does not depends on the size of input array so it only use a constant amount of memory to store sign variable so that's why order of one yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I will see you in the next question
Sign of the Product of an Array
longest-palindromic-subsequence-ii
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,3,2,1\] **Output:** 1 **Explanation:** The product of all values in the array is 144, and signFunc(144) = 1 **Example 2:** **Input:** nums = \[1,5,0,2,-3\] **Output:** 0 **Explanation:** The product of all values in the array is 0, and signFunc(0) = 0 **Example 3:** **Input:** nums = \[-1,1,-1,1,-1\] **Output:** -1 **Explanation:** The product of all values in the array is -1, and signFunc(-1) = -1 **Constraints:** * `1 <= nums.length <= 1000` * `-100 <= nums[i] <= 100`
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
String,Dynamic Programming
Medium
516
1,802
hey everybody this is larry just me going with q3 of the weekly contest 233 uh maximum value at a given index in a bounded array um so this is a binary search problem i had a lot of struggles of this mostly because of a typo that i didn't catch uh and also i had some debugging code that i actually left in the submission whoopsy daisies um as you can see but yeah hit the like button hit the subscribe button join me on discord let me know what you think about this farm it's tricky it's hard it's fun um but yeah um so basically the idea is that and i actually misread this problem a bit all during the contest i don't know if you have the same but uh but i thought that um this thing i thought that it had to be um exactly one so what i mean is that i thought that it would um that uh i thought like it could be a step ladder which makes it really harder um but because it doesn't it basically is a strategy right i end up doing this binary search and what happens with this binary search is that there's a greedy algorithm for let's say you have an answer and you're trying to figure out if there's a greedy way of doing it and the answer is that okay jeff um you know let's say you have some index um you know you let's say you have some index like here and you know you have you know numbers to the left numbers to the right and you try x is equal to 20 right well what happens is that uh if x is 20 then by definition the left let's just focus on the right side for now um it's the same to the left but you have to look at 20. okay 20 is too big but um okay fine let's just join anyway 19 in 18 17 dot all the way down to one and then it's just one right so that's basically the minimum that you can do um and the idea here is that um if and you know and you do the left side as well the idea is that okay let's say you have a max sum that is really big um then can you salvage using this right um and the answer is that you can always add numbers to the right or left to meet max sum you can do it you know you then a lot of different ways you could even make you know um you could do 20 21 22. you know whatever right all the way to max sum i don't know some numbers so that it adds up um and you can always do this so that um because it could be you know you can imagine this to be a bigger number and then on another thing and then it adds together right so that's the general idea um and conversely though if this number you know if this number is really small or at least really small compared to our sum uh then it you cannot um you cannot reach max sum that's the only impossible case because there's no wiggle room right you cannot decrea like every number here is set so that this sum is the smallest it can be given x is equal to 20. so that's basically the idea and from that um you can notice that it is monotonically increasing uh so it becomes binary search and this the way that i do it is um uh yeah and there's a couple of mathematical formulas here uh but that's basically it this is binary search if this is good we go to the left uh or so we go to the right we set left as you go to mid otherwise we you know narrow the bounce um i'm gonna do uh i've been getting this request a lot lately so i'm gonna do a separate binary search tutorial um so i'm not gonna focus on this part right now um let me know in the comments whether you want to see it if you want to see it you know it motivates me a little bit more so hit that like button and leave a comment um but yeah but basically these are just all mathematical formulas from that point try to up solve it and derive it if you have time pause the video if you like um but yeah but this is just the number that of ones that we have on the left and numbers of ones in the right and that's basically what i have extra because they're just ones and we're forced to take those ones um and then this is just the left count and this is um you know this formula is just you know you can imagine one plus two plus three plus four plus five dot that's the formula um and so that's the format for one part of it and from start to end you know if you kind of look at um you know dot plus seven plus eight um you can think about this as uh you know to do that plus say oh just plus four right and then to get from five to eight this is how you do it you know from five to eight you take the suffix which is from five to eight um or from one to eight and then you subtract it from one to four right so that's basically the idea behind here you could work out the formula you know at home or later and this is the left side and this is the right side and that's pretty much it um and you know uh from here this will have all of log you know like h algorithm where h is the bound or u say u is to you know where u is 10 to the 10 apparently um and for here you can see that this is o of one operation more or less um you know yeah i mean yeah this is just all arithmetic and math and this is all one so this is going to take all of log u times in total um so yeah so this is actually independent of the in kind of in the number of bits i guess but yeah uh that's all i have for this problem let me know what you think and in terms of space this is all of one because we only have wearables i guess i have to mention that explicitly but yeah you could watch me stop it live during the contest next i had a numerous a lot of silly mistakes so you know uh call them out see what you think uh and yeah let me know uh this was such an annoying hard problem for me i would also say that if you struggled uh don't feel so bad because i know that my explanation and other people's explanation and that's why you watch their videos they make it seem easy um but that's why i want to show how i did it in the contest and i did relatively okay i finished 69th um and i took 20 minutes on this prom and i give more 20 like 22 23 minutes because i took a couple minutes i skipped q3 and then i came back to it um so yes so jim though the explanation is easy this i think this is a hard problem so don't feel so bad and definitely you know work at it and break it down to pieces and yeah look see if you can learn from my you know whatever messed up ah silly okay that was dumb okay length m um where is okay so the thing is less than i and adjacent value is one okay i mean so this is always going to be true anyway as long as it's positive number the sum of the numbers of indexes maximized okay hmm indexes too i mean this is just math but it's really annoying math environment and maybe binary search maybe i'll come back to it let's see if there's a minor type oh i just didn't think it through all the way all right now we have to think about q three my ranking is pretty slow but i am one of the few people who's getting q4 so okay let's think about this is a weird math problem i'm annoyed about uh maybe not annoyed about per se just i'm bad at it okay um hmm can we do binary search on this i feel like it's brian i research but this part is tricky what does it mean right that means the love let's say we want to try and answer that means that the love hmm yeah i spent way too long in q4 i don't know how to do this one so you have a step function i need paper six numbers so you have to start with oh i misread this i thought this was constrained by i no numbers of i can be anything oh then this is much different than what i was thinking okay i've totally misread this uh because it doesn't have to start with one or i think for some reason i thought you have to start with one so then now we can do a binary search much easier that way um okay maybe so we have a stir how do i oh god it's uh i mean i still need a paper because i'm bad at this math so this should have been a tip away because they're indexed once so let's see what this three look like what does three look like right okay we number i has to be a positive number so it's at least one but it could actually so we just have okay so it is binary search i think um so you just have decrementing all the way to once in the left and the right and then and all the way to once left um good enough i also for some reason thought that this has to be one and not zero or one so i was thinking about step that i should stop explaining this self default but uh okay the end is inside then um okay so it has to be positive i messed that up before say if this we want the maximum so if this is good then b1 left is equal to else y is equal to mid minus one okay and then okay so left is equal to index and y is equal to n minus index minus one what is good right so target um on the left side it's going to be the num the map is hot so it's um something like uh plus one or minus one that was fun get how which one it is five times i know it's minus one um now let's just add a function uh oh this is such an annoying problem a lot of people got it so uh okay so this is if left if we have zero numbers then this is just zero on the left okay that makes sense what happens if this is okay well uh let's just say so we have to go from right minus so right is the number of items okay no is that yeah okay um okay i don't know this is okay so if we have some plus right some press extra and i might be off by one if this is greater than max sum this is the minimal thing and we return first otherwise we return true maybe because if it's so we can always go up maybe i'm off by one though i don't know this is so awkward i don't think i mean this is already this is still not right but um 20 left let's see right see extra okay let's at least take a quick look uh just these numbers are ridiculously big so let's do a for loop to sing to c to see okay so if the max number is one the left c is negative one which is probably not what we want what are the inputs four so for index two and max six of six uh if the first number is one then maybe this is then we want we have two numbers on the left and we want this to that means that we want this to be zero so this means this should not be negative one for sure um that's just awkward but if this is one this should ideally return for when i return negative one so that's awkward um okay so if i can't focus this is tough um okay so let's say we're index two the two numbers to the left we start at one so this actually should return zero numbers um so how do i so this is t so how do i force that to be zero so t c so t because extra would be what is this two minus one two numbers on the left minus one so this is actually just this um and then now we wanna go to what is the starting point now starting point is t minus uh the number of steps to get to one so it's t minus left plus one maybe so if left why am i so bad at counting okay um so if t is one then we want to go zero steps to the left so actually we want the min of this and t minus why am i so proud of this okay so okay let's say red one why am i so bad at this red one so then we won to use zero numbers so z okay so it's t minus this thing maybe uh okay i mean this is better but the extra stuff is wrong clearly i don't know how that happened good got the wrong answer because that's just weird um okay so one two what is the two this was symmetry maybe but that still should be wrong yeah uh okay so now we're counting nothing because okay so now i think that's why i had this i already had the t minus left okay so the starting point is t minus left or one right yes why is this wrong right now because okay this part is right the extras now well maybe well definitely but why is extra wrong uh so in that case we have t minus left so yep left numbers in the right um okay so if left is zero then this is awkward it's actually really awkward why am i so bad at this if left maybe this was right overall uh nope so if left is zero then we want this to be at least one maybe yeah there's no numbers to the left then this is this should let out to zero so left is equal to zero so that's t and this should be zero why is this oh no because left is not equal to zero um so we should go so if left is one we go from four to okay now this should be y why am i getting negative one here negative one is here only if this is t what i'm really bad at this another left is one then this would be four three two one okay yeah no that makes sense why is this negative one then do i print something else anywhere because i get confused no let's just because i am just very confused oh what ah that's why because i'm dumb yes okay i had to dumb it down for myself and print out everything literally okay so this is better and also this has the same issue that's why i mean it may still be wrong but it should be slightly better three and four still okay um so this is now slightly better um okay so one we get the total sum of three is that given right um it's an array of four elements so the answer should be four so this should be this plus t actually oops no plus t is here um okay two three okay i can't believe i don't know this is but it's gonna take me a long time to debug anyway so i'm gonna yellow submit okay good oh my sounds silly like yeah thanks for watching uh let me know what you think about this farm it was good bad i don't know uh this was a interesting contest uh let me know what you think uh hit the like button hit the subscribe button join me on discord ask me questions here there wherever you like and yeah have a great week have a great time uh stay good stay healthy stay well and to good mental health i'll see you next time bye
Maximum Value at a Given Index in a Bounded Array
number-of-students-unable-to-eat-lunch
You are given three positive integers: `n`, `index`, and `maxSum`. You want to construct an array `nums` (**0-indexed**) that satisfies the following conditions: * `nums.length == n` * `nums[i]` is a **positive** integer where `0 <= i < n`. * `abs(nums[i] - nums[i+1]) <= 1` where `0 <= i < n-1`. * The sum of all the elements of `nums` does not exceed `maxSum`. * `nums[index]` is **maximized**. Return `nums[index]` _of the constructed array_. Note that `abs(x)` equals `x` if `x >= 0`, and `-x` otherwise. **Example 1:** **Input:** n = 4, index = 2, maxSum = 6 **Output:** 2 **Explanation:** nums = \[1,2,**2**,1\] is one array that satisfies all the conditions. There are no arrays that satisfy all the conditions and have nums\[2\] == 3, so 2 is the maximum nums\[2\]. **Example 2:** **Input:** n = 6, index = 1, maxSum = 10 **Output:** 3 **Constraints:** * `1 <= n <= maxSum <= 109` * `0 <= index < n`
Simulate the given in the statement Calculate those who will eat instead of those who will not.
Array,Stack,Queue,Simulation
Easy
2195
70
hi guys welcome to algorithms made easy today we will go through the day 31 problem from july lead coding challenge climbing stairs please like the video and if you are new don't forget to subscribe to our channel so that you never miss any update suppose you are climbing a staircase and it takes n steps to reach to the top each time you can either climb one or two steps so in how many distinct ways can you climb to the top for example one we can see we have two ways to climb two stairs we either climb one stair at a time or we climb two stairs at once for example two we can have three ways to climb three stairs we can either climb one stair at a time or climb two stairs followed by one for the climb one stair followed by two if we look closely to the pattern we observe one can reach ith step in one of the two ways taking a single step from i minus one step or taking a step of two from i minus two step so we can say one can reach ith step by adding the steps from i minus one and i minus two if you have noticed this is nothing but the fibonacci series using the previously calculated value is the concept of dynamic programming let's see it with an example let's take ns5 initially we know we can climb one stair in one way only while to climb two steps we can use either of these two ways shown now we can make use of the previous two values to calculate the next value so number of ways to climb three steps will be the addition of previous two that will give us three similarly for the fourth step the addition is five and for fifth the addition is eight as now we have the value at n equal to five we just return it let's summarize this process into an algorithm if n is less than 3 that is for value 0 1 and 2 we will simply return n or else we will initialize a dp array of length n plus 1. store the first three values that is dp of 0 1 and 2 and then iterate through the rest of dp array and fill it using a formula at the end we return the dp of n the time and space complexity for this approach is of n here's the actual code snippet for the method you can also find a link to this code in the description below we can reduce the time and space complexity of the solution by applying the formula to find the nth fibonacci number the formula is given as follows you can find the link to the wikipedia page for a detailed explanation and proof of formula in the description below with this formula the time complexity becomes of log n and space complexity becomes one here's the actual code snippet for this method you can also check out the link to all the codes in the description below thanks for watching the video please like share and subscribe to the channel also let me know in the comments what you think about the video
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
523
all right I'll be solving continuous sub array sum and I think it's not medium it's going to be hard the level because yeah the logic here it's highly mathematical so let's take step by step and take for example this so basically the question is if you can find a sum of sub array that is a multiple of K so 6 is a multiple of K rate for example all this 42 is a multiple of K if you can find such a sub array then we return true so let's say starting from the first element to index I let's say 0 to 3. we call it sum I if we Mo if we modulus K so sum the sum mod K it would be some K times some integer like K times 1 plus whatever value that's remaining let's call it mod K1 and same from the first element to index J every mod it by K it would be K times some kind of integer value y plus some remaining value mod k divided by three uh mod K2 sorry and if this value and this value is the same okay if the modulus value is the same then subtracting Formula One and formula 2 we get some I minus some i j on the left side and this gets canceled because it's the same value right and K we just get x minus y in bracket times K which is a constant times k so effectively the difference is the sum of elements between index I and J and the value is a multiple of K which is what we're looking for okay that's the pure mathematical explanation so basically what do you want to do is get a running sum of this array and the remainders that we get so we're gonna um once we calculate this running sum we're going to divide um we're going to modulus it by K so I think this is what's modulus six yeah so modulus six five model six one five zero Etc so we get remainder 5 at index 0 and 3 right so this means that these running values right if we minus it so whatever values we have inside that sub array is a multiple of K because here we have said that some I minus some J okay if the modulus is the same that would result and um in these in a sum difference that is a multiple of K okay so if uh index 3 0 1 2 3 35 minus 23 that's 12 right so um the summary in between it has a value that uh that is a constant of K so that's what we're looking for and we have to um consider a edge case um should we just uh run it first okay so not considering the edge case first so in future okay and for and it's I equals zero I less than non-stop length I less than non-stop length I less than non-stop length Plus okay oh we have to initialize a running sum equals zero so remember we're gonna add up our values okay and we're gonna model set by K okay and if oh and we're gonna get whatever value um map.get map.get map.get running some so basically if we miss certain condition and else what we are storing in our map is the running sum which was the modulus of K and the index okay um the running Sun and we're storing the modulus of the running sum and the index in the map okay and if so if we have not seen such a index that has the same modulus value then we just put that modulus value and that index but if we have seen that modulus value somewhere before so if okay map dot get key oh no so if we have not seen such an index um then we know that oh then we just put it but if there's such an index that exists so if perv is not equal to null oh sorry then and if so sub array has to be a length of two or more right so I minus per has to be greater than one then we return true um and else if we have done everything and then we know it's false okay that works so just I'll come I'll cover the edge case first so the edge case is when the running sum is exactly equal to the multiple of K then after we calculate the modulus of K running some becomes zero right because it's exactly equal to n times k so actually if we try to get a map dot get zero actually we don't have such a value we don't have such yeah a key or a value set so that's why we have to add um 0 and -1 to handle this case and it's um 0 and -1 to handle this case and it's um 0 and -1 to handle this case and it's value -1 because salary has to be at value -1 because salary has to be at value -1 because salary has to be at least two so I like for example I is like uh one and one minus one that's two right one plus one so that's that means that it's true so yeah it's I don't think it's medium it's highly mathematical and we use a double bracelet initialization you can just uh look at this stack Overflow I'm not gonna um do it but put 0 and -1 -1 -1 okay and we do it okay yeah so this question is really not medium at all I think the mathematical Logic Let me just summarize it okay so we're gonna add the running sum with the values in our array and calculate the modulus of the running sum modulus it by K and if we found the same modulus somewhere in two indexes and if those indexes difference is greater than one then it can form a sub array and this mathematical logic is when there's a difference between this and when modulus is the same like five oh where is it yeah five equals five then there must be a difference the difference would be the sum of elements and between I and J and that difference is also the value that also proves that value is a multiple of K so this is a constant of K so basically if the models is the same then we know that the difference in some would uh mean that it's a modulus of K so yeah the logic is first oh yeah I didn't get it at first I took quite a while to understand it but that's all and I'll see you guys next time bye
Continuous Subarray Sum
continuous-subarray-sum
Given an integer array nums and an integer k, return `true` _if_ `nums` _has a **good subarray** or_ `false` _otherwise_. A **good subarray** is a subarray where: * its length is **at least two**, and * the sum of the elements of the subarray is a multiple of `k`. **Note** that: * A **subarray** is a contiguous part of the array. * An integer `x` is a multiple of `k` if there exists an integer `n` such that `x = n * k`. `0` is **always** a multiple of `k`. **Example 1:** **Input:** nums = \[23,2,4,6,7\], k = 6 **Output:** true **Explanation:** \[2, 4\] is a continuous subarray of size 2 whose elements sum up to 6. **Example 2:** **Input:** nums = \[23,2,6,4,7\], k = 6 **Output:** true **Explanation:** \[23, 2, 6, 4, 7\] is an continuous subarray of size 5 whose elements sum up to 42. 42 is a multiple of 6 because 42 = 7 \* 6 and 7 is an integer. **Example 3:** **Input:** nums = \[23,2,6,4,7\], k = 13 **Output:** false **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `0 <= sum(nums[i]) <= 231 - 1` * `1 <= k <= 231 - 1`
null
Array,Hash Table,Math,Prefix Sum
Medium
560,2119,2240
347
okay guys let's solve top K frequent elements number 347 on leak code so given an integer array of nums and another integer K we need to return the K most frequent elements and you may return the answer in any order so that's pretty simple it's just the top K most occurring elements so for example with the numbers of 1 2 and three well we know that one occurs the most at three times two occurs the second most at two times we just want the top two and so we can return one two or two one is the same answer and of course if you had just one number and you wanted the top one well then that's going to be the same number it's actually guaranteed that the answer is going to be unique so if you had three 1es two twos and we'll say two 3es with k equals 2 well that's a scenario you wouldn't have because you would run into three ones you would want to have the one there but then between the two twos and two threes you don't know which one you want to pick well that's not a scenario you would have so the first example that would come to my mind is getting a dictionary of the frequency so we'd have well one there's going to be two of those for all of the twos there's going to be three of those and for all the threes there is going to be four of those so now that we have this frequency dictionary we can basically just sort it by its values because we want the highest frequencies so for example if we sorted that in descending order by the values we would have Well we'd have three we have four of those we'd have two we have three of those and at the end we'd have one and two of those so now that we've sorted This Bites values we just need to pick up the top two things at the beginning that's going to bring us three and two and that would be a final answer so the runtime of this would be while getting this step getting the counter that's just going to be o of n we're just adding to a hashmap while going through the array and then the other step of sorting it well we know sorting anything is going to be Big O of n log n and n in this case is basically the same n as the array because if you had all unique elements if this was 1 2 3 for 5 6 7 8 well you'd be sorting that many things and so this would be an O of n log n answer it turns out we can use a heap to get an answer of n log K where again K is the number of things you need to pick up because if you use a heap we can store up to K things in the Heap and so it's going to be a log of K interaction to move around the objects in that heap if you take an element out of it that is going to be log of K and if you put an element back into it that will also be log of K so to show you that answer we would actually use a Min Heap okay so it stores the minimum element so to get the Heap we would actually need that same dictionary from before of the frequencies so we'd again have one two we'd have two of three and we would have three there's four of those after we have that these are now basically topples of the frequency and the number that exists so we don't want to sort this thing we'll just go through its keys and values so here we would get a tupple two and one we would put the value first because we want the Heap to be organized by the minimum frequency okay so if we put 21 onto this Heap thing okay this is just going to be my Heap over here it's going to organize it by the minimum frequency the first item in this Tuple and then if the frequencies were the same it would then organize it by this but that doesn't really matter now the point of our Heap is to hold the K most frequent elements on here and it's always going to have the minimum frequency at the top since the size of the Heap here the Heap is just one element well if we look at 2 three we'd have the topple of 32 we're just going to immediately put that on the Heap cuz we want it to have the K most frequent and this is going to be a log of K interaction with the Heap we'd have 32 here and 21 is going to be above it because this has a smaller frequency than three okay now things get interesting with this tupple cuz we'd have we have four threes that's the highest frequency we want this in the Heap and we'd say Boop put it in the Heap that is a log K interaction and we have four and three that's going to be at the very bottom and then we need to pop this off so this is basically a heap push pop operation we push it on and then we pop off the topmost so that gets popped off we don't really care about that and we are through the array and notice that we have the things that we want here because remember the frequency is the first thing the keys are over here we wanted the answer to be two and three and so that is our answer so that's one way to do it which is using a Min Heap there's actually another solution where you could use a Max Heap and that is going to be an operation of n because we're going to go through n times putting stuff potentially on the Heap and N times we are going to do at most a log K interaction because we're going to have K things on the Heap now you might be wondering why this is even any better because n log n and n log K are very similar it's still n log something except if you can assume that K is significantly smaller than n which is actually kind of safe because if you had a million elements in here you're probably not going to have K as like a million if K is even just like 10% of million if K is even just like 10% of million if K is even just like 10% of what n is you're probably going to ask the question of like what's the topmost element what are the two most top what are the three most top you can kind of make that Assumption of course in the very worst nlog n and nlog K are the same but still you would kind of prefer n log K although it turns out there's actually a big O of n solution so first I want to show you the Heap solution in code and then we'll come back and do the o n answer so for the Heap solution we're going to need two Li we definitely need to import Heap Q in Python that's going to let us use a Min Heap and we are also going to do from collections we'll import counter which just makes getting a count of the elements as a dictionary a little bit faster so we'll immediately get a counter which is equal to a counter with a Capital C of the nums so that just gets a count of all the elements and then we will get a heap is initialized as an empty list okay so then what we can do is save for each key and vow in the counter. items we know that the key is going to be the number and the value is going to be its frequency and we can just say if the length of the Heap is actually less than K many things well then we can do a heap q. Heap push so we don't need to worry about popping things because we want K elements on the Heap we can just do a heap push with you give it the Heap as the first argument and then we put the Val and the key okay cuz we want it organized by the minimum frequency which is the value and we also want the key which is the number stored in it as well and then otherwise at this stage the Heap must be exactly K things because we're only going to let K things in there due to this statement here we do Heap q. Heap push pop I know it looks kind of funny but we push something on and we immediately pop it off we give it the Heap and it's the same thing it's going to be the vow in the key even if that vow or its frequency is very small it's still going to try and put that on the Heap and it's just going to immediately pop it off and if this TPP did belong we had a very high frequency we put that at the bottom of this and then it's going to pop off whatever that minimum was at this stage all of the stuff we need is stored in the Heap and that's actually just a python list you interact with it with the heapq library but it's still just a python list and so we can return the list of H at one for H in the Heap we're just going through and getting all of the value and key tles and the thing we want is the key that's the number itself and this is going to be K things because we're going through the entire Heap and the Heap is always going to have at least after it's done this part it's going to have K many things so if you were to submit that actually is going to work and we would write down that the time complexity well it's n because we're going through we're getting a counter but that's actually going to be dominated by we're going to go through the counter so that's and many things potentially what are we going to do at each step we're going to do at most a log K interaction there's K many things in the Heap it's a log to push it's a log to pop making it also a log to push popop and so we'll do o of n * log K is popop and so we'll do o of n * log K is popop and so we'll do o of n * log K is going to be the time complexity for that answer and the amount of things we'll store while we're storing potentially o of n we're definitely storing o of K except n is going to be bigger than K and so we'd say that the space complexity is dominated by just o of n okay but that was the N log K answer and as we said we can get an O of n answer basically the idea is that of all the elements here well if this is length if this has a length of nine there's no way that any element in here could appear more than nine times once twice up to nine many times you could have just the same element every single time but there's no way that's going to be bigger than the length itself so since we have a minimum number of times which is going to be well zero times or one time either is fine you could have at most nine many times well then we can make an array where the index is actually the frequency or the number of times that something is going to occur and we don't really need these spots but they would exist so we get our frequencies and we see well one appears two times and so we would put one at the frequency of two okay remember this is the frequency so we're going to put the list of one here because multiple elements could have the same frequency and then we also have two and three here so we'd say okay well at the three frequency we're going to have the number of two and at the four frequency that is going to have the number of three and notice something very interesting if you go backwards through the array from the end well you're going to have this organized by the top elements because this is the frequency you'll have the three first and then you'll have the two and you'd have whatever you'd have over this way but we only want the top K from going this way through the array and just to be clear why we actually need these as lists we'd have four threes suppose we also had four fours well then in the four spot we would also need this to have three and four in the four frequency three we have four threes and we also have four we have four fours so they both belong there so we'd go backwards through the array and we'd have like some new array where we're picking stuff up we'll get three we'll get four in there and you do this up until K which is actually two and so this would be our answer so the code to do this is actually pretty cool we'll just get n is the length of the numbers and then we'll again we'll import our counter so we'll do from collections we'll import Port counter and then we will get a counter is equal to a counter of all the numbers that's again just the keys are the number and the value is the frequency and we're going to get these things I'm going to call that array basically buckets cuz it's kind of like a bucket sort if you know what that is if not really don't worry about it so we're going to set them all just to be zeros at first so we're going to get n plus one of these things what this is basically saying if we had the array of we'll say 1 2 and three well then the thing that we would produce here 0 and Zer okay it's n + 1 3 + 1 is 4 so and Zer okay it's n + 1 3 + 1 is 4 so and Zer okay it's n + 1 3 + 1 is 4 so they're all going to be initialized to zero just saying that we don't have any stuff there and this frequency is for things that occur zero times we'll actually never use that it just helps the math this is for stuff that occurs once this is for stuff that occurs twice and this is if you had something that occurred all three times so then similar to before we'll get for each number and the frequency that we have in the counter. items and we'll say hey if the buckets at the frequency okay remember the frequency is the index so if the bucket's at the frequency if that is still equal to is zero we don't have anything there yet but we want to place the number there because it has this frequency so we'll set buckets add the frequency we'll make that equal to the number but the list of that number otherwise if it wasn't a zero that means we've already done this because we already have a list of you know one number there or two numbers there and so on and so we would need to do buckets add frequency same thing except it's a list so we will append with the number We'll add one more number that has that frequency okay now after we've built up this buckets array we just need to go backwards through it and pick up what we want so we'll get a return list of stuff that we want and we'll say go backwards through the array you do that by saying for I in the range of so start at n inclusive because again we have n+ one inclusive because again we have n+ one inclusive because again we have n+ one things you can think about the last index is actually n so n inclusive we go down to -1 basically this is exclusive down to -1 basically this is exclusive down to -1 basically this is exclusive so it actually goes down to zero and we'll do it as a step of going down one now we can say if the buckets at I if that is not equal to zero okay that means it is a list and it's stuff that we want to pick up so we will return. extend not sure if you've seen extend before but basically if you had say a list of just one two and you called do extend on that so if you extended that of say four five and so that would make it the list of 1 two 4 five okay so that's extending the list okay so we want to return. extend with buckets at I and yes you want to pick up all of the stuff that's in there now because we have the case over here that it's guaranteed that the answer is unique you can pick up all of what's in buckets at I cuz you're never going to hit K elements in the middle of this bucket okay it's going to be either before or after one of these buckets because the answer is going to be unique so if the length of return is equal to K if we've picked up K many things then we can just immediately well we'll just do a break so that it's pretty clean we will return R out here and if we were to submit that then that would work just fine okay so as we said this has a Time complexity of Big O of n why is that well we pick up the counter in linear time we can go through all the stuff in linear time and all of this is a constant operation and then we just go backwards through the array and we pick up at most K things so the time is going to be a big O of N and the space complexity well we are going to store maybe N Things over here we'll have end things in the bucket and that's really all we're going to store here we also have return but that's just going to be at most pay things and so the space is going to be dominated by o n so that's our answer and that's the fastest possible algorithm I hope this was helpful guys and have a great day
Top K Frequent Elements
top-k-frequent-elements
Given an integer array `nums` and an integer `k`, return _the_ `k` _most frequent elements_. You may return the answer in **any order**. **Example 1:** **Input:** nums = \[1,1,1,2,2,3\], k = 2 **Output:** \[1,2\] **Example 2:** **Input:** nums = \[1\], k = 1 **Output:** \[1\] **Constraints:** * `1 <= nums.length <= 105` * `-104 <= nums[i] <= 104` * `k` is in the range `[1, the number of unique elements in the array]`. * It is **guaranteed** that the answer is **unique**. **Follow up:** Your algorithm's time complexity must be better than `O(n log n)`, where n is the array's size.
null
Array,Hash Table,Divide and Conquer,Sorting,Heap (Priority Queue),Bucket Sort,Counting,Quickselect
Medium
192,215,451,659,692,1014,1919
968
hey guys welcome to algorithms made easy i am khushboo and in this video we are going to see the question binary tree cameras given a binary tree we install cameras on node of that tree each camera at a node can monitor its parent itself and its immediate children calculate the minimum number of cameras needed to monitor all the nodes of the tree so here we are given a few examples in the example one if we place the camera in the middle node it would be able to monitor both its children and parent and so with a single camera we can monitor the whole tree in the second example we would need two cameras to monitor all the nodes the note attached with this question says that the number of nodes would be in the range of 2000 and every node has a value of 0. so we are not considering the values of the nodes over here we only need to know where we want to place the camera so that all the nodes can be covered so let's see how we can solve this question so let's take this tree considering that all the nodes have value as 0. now let's start from the top and see how many cameras would be required if we start from top we know that the parent is going to be covered so we don't put the camera in the parent but we'll put it in the lower notes so over here we put both the cameras and so these nodes are covered after that these are uncovered so we'll put the camera over here and so in this case we are going to need five cameras but is this optimized we can see that we have added cameras in all the lower levels and in a tree we know that as we go deeper into the tree the nodes start increasing we have one node in the root then two and then it would be four nodes and so on in a case of complete binary tree so we need to avoid adding cameras to our leaf nodes and so what we are going to do is we are going to start from the bottom so let's see what happens if you start from bottom in this particular case so let's put the cameras in the second last level and over here we can see that the leaf nodes would be covered with that and the parent of that particular node would also be covered with this camera and with this two cameras we see that we are covering a large range of nodes now we are left with only two nodes and so we can cover these nodes by adding one more camera we can either add a camera at the root or at this leaf level over here so now you see that instead of five we are only using three cameras when we started from the lowest level and that's the intuition behind this particular problem that we need to start from the lowest level to reduce the number of cameras that we would require by not adding the camera at the leaf level which have the tendency of having the highest number of nodes now that we know that we are going to start from the bottom let's see how we are going to start so let's take this particular tree and start from the bottom so we are adding this camera for this particular node which is covering the child and the parent so we need to store somewhere that what are the nodes that are being covered by the camera that i have added because i do not want those nodes to be covered again that is i can ignore those nodes in my further traversal and so with this information i can minimize the number of cameras that i would need now that i have these nodes covered i'll add a camera over here to cover this particular node which was uncovered by the camera which is already covering its parent node so there is no chance this node could ever be covered if i am not adding a camera over here so this node would also cover this parent node 2 but that is already covered so we need a data structure which would store the unique values to mark our covered nodes now going further above we know that we have these two nodes left so i am adding a camera over here to cover its child and since it does not have a parent that means this was the last node that we needed to cover and now that we have covered all the nodes i can count how many cameras i have added in this process which is three so let's try to code this particular approach out wherein we'll go from bottom to top and keep on adding the cameras wherever needed and store all the covered nodes in a data structure that stores a unique value so over here first thing that we need is the count of cameras and the second thing that we need is a data structure to store all the covered nodes and that data structure should store unique value so we will take a set of tree node now let's initialize these data structures initial count would be 0 and this would be new hash set now what i need to do is call the dfs function so i'll call dfs on my root node and its parent being null now why do i need the parent over here i need the parent because i need to cover the parent of that particular node while adding a camera to it so in that case i need to know who was the parent for this particular node and so i'll mark parent of the root as null because it does not have any parent finally just return the cameras over here we can add an initial condition that if my root itself is null i can return 0 because i do not need cameras in that case because i do not have any node in my tree now let us write the dfs function it would be a void function and it is going to take the node and its parent over here i'll check if my node is null if it is null i do not need to do anything but if it is not null then and only then i will be processing the node if the node is not null i am going to go deeper in that tree because i want to start from the very end of the tree so i'll call dfs on left with node as the parent and on its right with node as the parent once i have done this i am on the bottommost node now i need to check whether i need to add a camera over here so that would only be possible if the parent is null and this particular node is not covered so that condition would be if parent is null and my node is uncovered or if any of its left or right are not covered so this is the condition wherein i'll be adding the camera so let's write this so this is the case when we'll encounter the root of the tree which is not covered and the other case is that either of its left or right child are not covered so we need to add the camera over here to cover its left and right now what happens over here with our code is that when we go to the deepest node its child nodes would not be covered because it would not contain the child nodes for the leaf that is the null nodes in the hash set and so we need to add that in my set so i'll do cover dot add null so that i can add the children of my leaf nodes into the covered category so now this code would not go and add the cameras on the leaf node but would start from one level above the leaf nodes now in this case i need to add a camera so i'll increase the count of it and i'll add all of its parent and children into the covered hash set so i'll add the node i'll add its parent i'll add its left and right child and that's it and this would be and it's giving a perfect result let's submit this and it got submitted the time complexity over here would be o of n because we are going to go to each and every node and the space complexity would also be o of n because we are taking a set to store all the covered nodes and the maximum nodes that the cameras would cover is the entire tree now let's see if we can do this without using the set so in a tree at a time you can have one of the three states that is either it is not covered by the camera either it has a camera or either it is covered with a camera but does not have a camera itself for that particular node so these three states can be returned and can be used to find whether i need to put a camera or not for that particular node so let's see how we can do this and we'll try to understand the code itself by doing it the only thing that we need to remember over here is the three states so i'll be marking the states as 0 1 and 2 wherein i have the camera one wherein the node is covered with the camera and 0 wherein the node is not covered so i'll still need a variable which would store the number of cameras that i'm installing and i'll need a dfs function and over here i am going to return the state of that particular node and i'll take the tree node now if the node is equal to null which is going to happen for the child node of the leaf node i am going to return that it is covered by my camera so let's quickly write down what are the states meaning so 2 means has camera one would depict that it is covered with the camera and 0 means no camera is covering this node so over here in this null case i am going to say that this node is covered by the camera because i don't want to start with the leaf node now since i want to go to the bottom i'll take dfs of node dot left and dfs of node dot right and since it is returning a value i'll take it in left and right now i need to check whether i want to add a camera or not the camera will only be added if my left has returned 0 or my right has returned 0. that is these are not getting covered by the camera so i'll add a camera over here so that my child are covered with this camera and so i'll do a cam plus to add the count in it and i'll return 2 because i have added the camera over here and this node now has a camera otherwise if any of my children node has a camera it means that my current node is covered with the camera and so i'll be returning one in that particular case and so i'll write if left has a camera or right has a camera then i can return one because this particular node is covered with the camera or otherwise i can return 0 because this wasn't covered with the camera over here i'll be calling dfs on my root node and since it is returning something let's take it in a variable calling it as answer for now what can i get into answer i can get either a 0 1 or 2. that is whether my root was covered with the cameras that i have attached in the tree what if the root was covered in that case i can simply return the number of cameras that i have added for the tree and what if the root wasn't covered in that case i need to add a camera over here so i'll return camera plus 1 so we'll be returning if answer is equal to 0 in that case can plus 1 or else cam itself so i can simply write dfs of root instead of this answer and this will be going so that's it let's try to run this code and it's giving a perfect result let's submit this and it got submitted the time complexity over here still remains of n because we are going to cover all the nodes and the space complexity for this particular problem would be equal to the height of the tree to store the recursion stack for the call of dfs function so that's it for this video guys i hope you like the video and i'll see you in another one so till then keep learning keep coding
Binary Tree Cameras
beautiful-array
You are given the `root` of a binary tree. We install cameras on the tree nodes where each camera at a node can monitor its parent, itself, and its immediate children. Return _the minimum number of cameras needed to monitor all nodes of the tree_. **Example 1:** **Input:** root = \[0,0,null,0,0\] **Output:** 1 **Explanation:** One camera is enough to monitor all nodes if placed as shown. **Example 2:** **Input:** root = \[0,0,null,0,null,0,null,null,0\] **Output:** 2 **Explanation:** At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement. **Constraints:** * The number of nodes in the tree is in the range `[1, 1000]`. * `Node.val == 0`
null
Array,Math,Divide and Conquer
Medium
null
1,168
hello everyone this is yosando today let's talk about lit code 1168 optimized water distribution village if you like my videos please support me by subscribing my channel you can find the code of this program and the complete code list new video description link below look at the problem first we are given a house in a village then basically we want to supply water to other houses let's directly jump into the uh first examples to explain better so here we have three house uh we have uh the cost to uh build the wells for each house so the first one means we build the wales for house one it costs one we build another well for class two because two and also if we don't build wells we can also build the pipes between two house so first elements one two one means if we build the pipes connect house one house two it costs one then if we build the pipes between two and three it was class one so in the end we need to return the minimum total cost to supply the waters to our house so for this example the minimum cost is three um so the best strategy is to build a well in the first house with one cost and connect one two and two three by using pipes so to solve these problems we can convert the whole problem into a minimum spanning trees problems what's a minimum spanning tree this is a graph concept so this tree is a subset of the edge of connected and on directorygraph that connect all the vertex and also without any cycles then after doing that we need to achieve the minimum possible total edge rate so basically this is the uh minimum explanatory concept then how to solve a minimum spiritual problems um so usually we can use a priority queue plus a union fight so this problem is not a typically minimum spanning tree because we have two options like pipes and the wells so here we need to convert problems into a minimum expansion problems by using a virtual node so i'm going to show how to convert the problems for using the example shows in the description so here we given three house as well then we create a new uh virtual node zero such that we make pipes as edge then we want to convert the wells and to another edges by using virtual node so the way we convert rails to the pipes is we think uh generate the pipes to the target node by using the causing valves for examples if we're given the wells cost is one two which means we want to connect node one to virtual node as cost 1 something like this and if also for the second one is we connect vertical node 0 to node 2 as cost 2. the same thing for this is means we are connected edge for virtual node 0 to node 3. such that after we convert well into the pipes we put both pipes and the wells edge into a priority queue and sort by the cost so that we have the priority queue like as follows one two one is the pipes here we swept the last elements caused into the first one to be compatible with our code later so one two one is still one to one after swap then here means we connect virtual node zero to one and the cost is one which is responding to the first element for wells same thing for the next we connect the virtual node 0 to 2 as cost 2. same thing for this and the 232 is the pipes as this one when we swap the first elements last time instead of the on the same tuple all right so then now we have all the uh edges being put to the priority queue and sort by the cost fundament minimum to the maximum then we need to iterate the edge from the top of priority queue to the end until we union all the notes to one same parents okay then i'm going through the whole solution step by step so i initial step we don't use any edge yet so we sign the parents for each node is its own parents right so zero parents zero one parents one two parents two three four three here we don't use any edge so the cost is still zero so next we get the top of the practical edge which is the 2 1 so now we're doing union find so of course not 1 and 2 will have same parents we can sign each one so here i assign the two as the common parents for node one and two then we use the edge two and one and it's cost one so next we use the second one in the priority queue we connect zero and one um since one's parents is already two so we assign zero parent also to two um then two co2 three twos two three then we increase the cost to two uh by using this edge cost so the next one is zero two h uh since zero and the two are all beyond two same trends parents right now actually we won't do anything in the unified step here we still came the same cost so next for the edge of zero two three so since zero doesn't already be assigned to two we can assign the three appearances two so at this step all the nodes have the same parents as two so eventually we will end up here and we get our one solution uh which cost total cost will be four we want you want to going to integrate the rest of the edge here um so as you may noticed for all those edges have same cost can be uh inserted into the arbitrary orders in the priority queue so it can happen we visit three two before the zero two three right because they have same cost uh in here we can we will do same thing basically because two parents is already two so we assign the three depends to two so here we will obtain the second solution they share the same cost so it doesn't matter which one is going first now let's see how these two solutions will we're given of the graph of our problems so first solutions uh we connect two and one two and twenty one and zero and the one zero one which means we build a wells for horse one um then we don't do anything to we don't connect zero and two we connect zero to three zero two three okay so right now if this is solutions we are uh building a minimum entry here we connect all the vertex by the ads and also we don't have any cycles in this graph and we achieve the minimum cost for solution two we connect zero one we connect to one and then eventually we connect two and three uh we also connect all the vertex uh and this node cycle here so this is a also um acceptable solution all right let's go into the code um so here um i'm assuming the length of wells uh is w and the length of pipes is p uh here we have a prior q squared here uh taking a tuple uh first is cost and upcoming is this the north uh kinetic by the edges uh we got greater operator here's um to make sure our top is the minimum one so first for loops we make wells to adds by using a virtual node 0 and we are inserting the priority queue uh so this step will take big of w log w is like we sorted array right on the second we add in the pipes also into priority queue here i think i made a typo here so here should be uh something w plus p log w plus p because right now the particle lens will be the w plus p eventually a serve for loop we put the parents list we create a paris list here um yeah the parents are is defined by the private function here um so it's using its own index as parents so next we are going to the unifying templates um we get the edge from the top of priority queue and we find the two parents um and also doing the path compression here in the help function here um then if the two parent cells that are different we are using this edge we do n minus which means um the total parent numbers are getting equipment by one and we add in the cost to the total cost so we will finish these loops until we have one common parent here so eventually we'll return the minimum total cost um so for the total computations we get a computation as uh omega multiply fn and means the uh the total null number sorry so this should be n as well uh it's kind of confusing uh yeah so um and the most we are doing the an iteration right and uh multiply the um the past searching computation so each uh find parents cost a function of n so this should be much greater than the w log w or w plus p log with p in previous operations then the space we are using our priority queue to store all the edge so with the w plus p so actually here we also need to pass on the space to start the parents uh speaker of n right um yeah you can find the runtime the memory usage affiliate code here in the left for this uh solution all right so yeah i think you can find the complete code in the videos below
Optimize Water Distribution in a Village
duplicate-zeros
There are `n` houses in a village. We want to supply water for all the houses by building wells and laying pipes. For each house `i`, we can either build a well inside it directly with cost `wells[i - 1]` (note the `-1` due to **0-indexing**), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array `pipes` where each `pipes[j] = [house1j, house2j, costj]` represents the cost to connect `house1j` and `house2j` together using a pipe. Connections are bidirectional, and there could be multiple valid connections between the same two houses with different costs. Return _the minimum total cost to supply water to all houses_. **Example 1:** **Input:** n = 3, wells = \[1,2,2\], pipes = \[\[1,2,1\],\[2,3,1\]\] **Output:** 3 **Explanation:** The image shows the costs of connecting houses using pipes. The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3. **Example 2:** **Input:** n = 2, wells = \[1,1\], pipes = \[\[1,2,1\],\[1,2,2\]\] **Output:** 2 **Explanation:** We can supply water with cost two using one of the three options: Option 1: - Build a well inside house 1 with cost 1. - Build a well inside house 2 with cost 1. The total cost will be 2. Option 2: - Build a well inside house 1 with cost 1. - Connect house 2 with house 1 with cost 1. The total cost will be 2. Option 3: - Build a well inside house 2 with cost 1. - Connect house 1 with house 2 with cost 1. The total cost will be 2. Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**. **Constraints:** * `2 <= n <= 104` * `wells.length == n` * `0 <= wells[i] <= 105` * `1 <= pipes.length <= 104` * `pipes[j].length == 3` * `1 <= house1j, house2j <= n` * `0 <= costj <= 105` * `house1j != house2j`
This is a great introductory problem for understanding and working with the concept of in-place operations. The problem statement clearly states that we are to modify the array in-place. That does not mean we cannot use another array. We just don't have to return anything. A better way to solve this would be without using additional space. The only reason the problem statement allows you to make modifications in place is that it hints at avoiding any additional memory. The main problem with not using additional memory is that we might override elements due to the zero duplication requirement of the problem statement. How do we get around that? If we had enough space available, we would be able to accommodate all the elements properly. The new length would be the original length of the array plus the number of zeros. Can we use this information somehow to solve the problem?
Array,Two Pointers
Easy
null