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
117
although let's talk about populating next right pointers in each node too so you're given a class note and this is uh written in c language right but it doesn't matter so the idea is you have to point your each level at the end you have to point at the no and then if you are in the same level you have to point on your following uh note so this idea is pretty much like preferred search so i'm going to use the easy way to do it first and if i have time i will just record another video for the other way and the easy way is actually using the queue to store the node and then for each level you just point your nets because you have left and right and next right just point your next to the next level i mean next note in this level so i'm going to say if root equal to no and i'm going to return no this is the base case and uh i need a q right i need q i need uh me using a lingus and i'm going to offer and add to the queue i'm going to check um i'm going to try first for you guys so if i want to traverse using breakfast search and by using q you need to know it's definitely q that is not empty then while i would return i would just return root because i would just keep changing a pointer for each note i'm not going to modify anything so for the current level is the level one which is no one right so i'm going to say inside it could be cute the skype and then i will have to after drivers the this let's the size the current size of the queue and i will just go on the next level so the reason why i using the insights is because when you offer or when you pull right you do affect your size and if you have children then you are not supposed to say okay for in i equal to zero i less than q the size because this is actually dynamic change and this is not good and i need a 10 pointer okay i'm going to say how why i need a 10 pointer for this so imagine like imagine there's an domino in front of each level and then you just point at your uh point at your next which is the current one so the current one is this no current equal to q double and say 10. is equal to current and then current x oh sorry 10 equal to 10. so i'm actually like um changing the next pointer right i'm going to modify the note dot next not the actual value right so okay so if i do think about if current 2 have to choose on the left it's not no and i'll just add into q right so okay q dot over q dot over q dot over then that's the right so if current or right is not known then i just i into the queue and at the end i just return the root so you don't have to think about like how do you actually um read a punch uh punch symbol so this is actually when you really snow and then you just print it print printer punch symbol so this is the solution and they just run it and see if i have any typo yeah i do okay let me rerun it and it's okay i pass the test so this is the easy way and i'm going to talk about how to explain the timing space complexity over here so that's time is actually all the time you have to traverse every single note definitely right so times complexity is all the fun space is all of them because you store everything every single note into the cube and it doesn't matter like um uh you pop or you over because when you're adding the q less how many times you have to add into the queue right so that would be all of it and this will be the solution and this is the preferred search solution and it is the simplest way but the time and space complexity is all the fun and if i have time i will just record another one and the space will be all of one but not for this video so if it feels helpful leave a like subscribe if you want it and then leave a comment if you have any questions and i will see you next time bye
Populating Next Right Pointers in Each Node II
populating-next-right-pointers-in-each-node-ii
Given a binary tree struct Node { int val; Node \*left; Node \*right; Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. Initially, all next pointers are set to `NULL`. **Example 1:** **Input:** root = \[1,2,3,4,5,null,7\] **Output:** \[1,#,2,3,#,4,5,7,#\] **Explanation:** Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level. **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 6000]`. * `-100 <= Node.val <= 100` **Follow-up:** * You may only use constant extra space. * The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
null
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116
451
foreign problem Short character by frequencies let us see what it says so given a string s okay sort it in it a decreasing order based on the frequency of the characters is the number of time it appears in the string return the sorted string if there is if there are multiple answer written any one of them okay example is three okay three we are giving so what is the frequency of 3 in this there is only one time it is appearing right R is also appearing one time e is appearing two times so we need to sort in decreasing order of the frequencies so that's why ee is coming first R is coming later and T is also coming later so you can see there are frequencies with the characters with equal frequencies can be in any order for example is a valid solution eetr is also a valid answer okay so it's not a problem another example is c a okay we have these things here now if we sort them okay if we sort them then we'll be having a frequencies like a c both C are okay three times so both are well done so there is no problem like this okay and that note that C is in Order character the same characters must be the factors together we need to put them together so that is the approach now for a b also we are going to put in b a okay that is also valid answer a b is also a b is incorrect okay because uh because this node a and are treated as two different characters not single characters okay so that's it and constraints are length is 5 10 to the power 10 500 to the power 10 to the power 5 is the limit and as consists of uppercase and lower cases later and digits also okay so that is it so let us try to see the approach and then we have to understand the problem the approach the project is very simple we are given the string right okay so what we are going to be doing uh we'll be making a hash map okay we'll be having a hash map in hash map for every characters for t characters for our character for the character we'll be checking the frequencies and adding them accordingly for example let us start with a 3 T So T is the right then what is the frequencies so we'll be using hashmap but we will find the frequencies for this tree uh we'll just Loop this and each and every character will check and put it to the our hash map so T is there so frequency is one in this case then for E we'll put nothing is there so we will put one now again e will be coming it will check in the value one is there so it will have one more to this so it will come two so once it is done so that is the first process that is the first thing second thing is to sort them okay to sort them depending upon the this one so we'll create a list okay from this map we'll take the all the key uh this sets Okay all the keys and then 40 re we'll sort them based on the number of frequencies so it will be sorted accordingly by using the sort function okay so sort them third step uh sort how we'll be doing will be using the comparators okay and we'll be seeing how we'll be doing okay list Dot sort we'll be using okay and this will be putting these values and after this sort we'll be getting some values like uh depending upon the frequencies we'll be getting e r t something like this will get okay ERT will be getting with the frequencies of 2 1 and 1 like this we'll get now what we are putting at the last we'll be taking each and every values e r t will be looking into this map okay and we'll be using string Builder Okay string Builder okay string Builder will be taking and frequencies will check okay suppose s is there so frequency is how many times the two is two times either frequencies so two times will be putting e so two times will push e then we'll be putting one time R will be pushing one time t so like this we'll put and we'll just return it from a return it from our function so that is it this is the approach that we are going to be using let us try to write the code for this and you can also try by yourself okay so let's start coding let us start writing the code so here first thing we are going to be doing is we are going to be making a string Builder okay we can call that as s okay we'll be writing as new string Builder okay that is done now what we are going to be doing so here it should not be S it should be answer okay then another thing is Hash map we are going to be creating so let us create hash map of character comma integer okay that we write hash map equals to new hash map okay so that is done uh there should be hash button hash map characters integer hashmap new information okay so that is done now what we're going to be doing uh we are going to be traversing and filling all the frequencies so how will be traversing that so simply for as character C h in our s dot to character array okay what you will be doing we'll be putting uh pushing each and every character in this map in our hash map so hm dot put our ch comma so we'll be first checking if our hm which is hashmap Dot get or default will do that if some values there then take that value otherwise something is not that then just take the default value which is we are going to be setting as 0 in this case so this is Hash map get our default okay plus one Plus one okay now we all got the frequencies now our task is to Simply take the keys and make the list okay so here we are we can do something this also map similarly we can do for the list will create for characters list of characters we'll put okay and in this we'll create new array list will take hm Dot key sets key set basically not key sets so we'll put key set here and what we will be doing will be using we know we need to give the name also here we didn't give any name so list dot sort will do we'll be having two thing first is ob1 comma B2 and then we will be returning ob1 minus OB 2. okay so this is the sort function here ob1 we need to get it from our hash map also so at sem dot get ob1 okay here also we'll get HM Dot get OB to okay so that is done our list is sorted now so what we're going to be doing now we are going to be just iterating in our uh list and making the use of string Builder and making the Builder Okay so first we'll be iterating in our list so entire equals to 0 okay I less than equals to I less than list Dot size or list to dot length we can use this for each also so character CH in our list okay what we'll be doing for every character so for in we start our with this I equals to 0 I less than ch that is hm dot get CH that will be our integer so this is not GM it is hm dot character okay I plus and then we'll be appending in our answer so answer dot append that character ch okay so that is done and now at the very end we will simply return our uh this one answer but that is so we'll be using two string function to written it okay so that is it now let us try to run the code and see the output so it is showing some error yeah instead of double this it should be single Dash okay now let us try to run the code so it is showing wrong answer let me check is submitted the problem was that we are we were sorting in ascending order so it should be in descending order so ob2 comes first then ob1 comes first letter so that is it for this problem so let us again revise it so that you can understand uh so string Builder we are going to be making okay for you making the use of then we're using map okay hash map basically for each characters will be storing into the rubber hash map and we'll be making a list or from this keys of the hash map and then we'll be sorting that depending upon the values decreasing order will be putting first and the smaller one later for each and every character in our list will be appending into the answer and just returning it from a function so that is it for this problem I hope you got the basic idea of the problem so that's it for this thank you for watching we'll be in the next research our problems
Sort Characters By Frequency
sort-characters-by-frequency
Given a string `s`, sort it in **decreasing order** based on the **frequency** of the characters. The **frequency** of a character is the number of times it appears in the string. Return _the sorted string_. If there are multiple answers, return _any of them_. **Example 1:** **Input:** s = "tree " **Output:** "eert " **Explanation:** 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Therefore "eetr " is also a valid answer. **Example 2:** **Input:** s = "cccaaa " **Output:** "aaaccc " **Explanation:** Both 'c' and 'a' appear three times, so both "cccaaa " and "aaaccc " are valid answers. Note that "cacaca " is incorrect, as the same characters must be together. **Example 3:** **Input:** s = "Aabb " **Output:** "bbAa " **Explanation:** "bbaA " is also a valid answer, but "Aabb " is incorrect. Note that 'A' and 'a' are treated as two different characters. **Constraints:** * `1 <= s.length <= 5 * 105` * `s` consists of uppercase and lowercase English letters and digits.
null
Hash Table,String,Sorting,Heap (Priority Queue),Bucket Sort,Counting
Medium
347,387,1741
1,601
so hey everyone I am Tanish and you guys are watching cortanish and in this video what we are going to see is the day Elite code daily challenge which is that the 1601 and which is maximum number of achievable transfer requests fine let us quickly jump to the question what they said uh we have in building number from zero to one minus one uh they have given a l building like if they have given two buildings there will be a home number to zero and the home the number to one why is that in the sense uh like it is a zero indexed houses okay that's what they have stated and you are given an array request for recused of I from y to I represent on our employees request to transfer from building from I to block guys what this state is they have given a two dimensional request which is uh like uh if they given 0 comma one what that mean is someone from house zero is building to move to house one is transferring to the house one like someone from the house zero is transferring to the house one okay that what they said and they have given many requests as far as that okay important Point very important Point all building are full initially all building are fully in Chile so a list of rickets is achievable only for each building the net change in employee transfer zero that's what definite man this means the number of employee leaving is equal to the number of employees moving in you see is leaving is equal to the number of employees moving fine guys will observe okay what the question asked is written the maximum number of request okay so from this question uh what you can guys can see they have given three houses building zero building one building that makes sense as per the question and they have given some request okay say if they have given some request and from observed from First Look is what's happening some person from how zero hand is leaving and he is reaching the same house guys that could be a possible a guy is willing to transfer his house but he changes his mind mindset and he comes to back to those is there any changes he said any changes to the size of the building he said any change to the size of the building no so that will be zero that makes sense come let's observe from the second request what that state is from building one someone from building one is going to building two so what happens here so basically the size of the building will get minus one get reduced and someone aren't willing to increase is because he is leaving building one and coming to building two so this will be minus one and this will be plus one okay fine now let us observe from the third request okay what the state is someone from building to building two leaves to reach building one now what happened what happens plus one minus one this will become zero now this is the state of building two and someone get increase to building one what happens now minus one plus one zero so at particular this all request we got zero comma zero everything is balanced what that means command is absolute as you guys clearly see at this particular second request there was some changes on minus one and plus one which was not values like this come on Simple Man like if you have a house zero and house one and this house has a capacity of one this case you have a capacity one and what the question said initially the house is full okay then some people are there one people is here one two will be here that's for sure and one guy is decided to move here to here now what happens this size of the house is one but how much people is there it is minus one no people is there basically so I like there is a zero people that's for sure and but and here it is 2 why it is two because someone left zero house and reached one house and the limit of house is long increased how that could be increased the limit of the house is only one what we what You observe that is imbalance but what if these guys come here and he convinced one guy from here to go there what will happen he will go to here now these two will become the one and this minus one will become the one by this year one guy is leaving so two minus one is going minus one plus one is coming minus one plus one what is that one now this is balance so basically whenever a guy goes out from a house and if a guy came from any other house this will be balanced okay so why the houses are always full so whenever you uh whenever you go out from a house that should be a also a guy come from that any other house to return the house so that will be balanced I think this makes sense so basically what you guys will think okay fine so basically from building one to two someone is going there okay and from Billy to someone is coming here that's the interchanging so what will happen it is a balance so what is this what you guys will be thinking okay that's a request of one comma two that makes sense and you will go and search for is there any request from two comma one that they interchange but guys his that will work his dad will work come on let's observe assume someone from building zero they used to building one what happens okay this is minus one and this is plus one okay because someone is leaving and someone is coming to the building right and building on the building too someone is leaving and someone is coming what will happen less one and minus one this will be zero now and at building two someone is reaching that will be plus one but from building two someone is moving to building zero so what that means plus one minus 1 which is again become zeros and here it was minus 1 and now some guy is coming minus 1 plus 1 it is 0. and now at this particular case it is also valid and have and we have three maximum request three maximum which is done that's for sure but he said any interchanging between building 0 to building one no someone left here and someone left here so what that means is someone left here and he got someone in from building two not building one they didn't interchange but there is also a such a case of this so is there a greedy it will work definitely not ultimately not what we can else do guys what we can else do come on see this particular stuff man these see this particular stuff what they State n will be always less than equal to 20 okay so basically what they said do a normal Brute Force do a normal brute force a recession try to do the all the possibilities try to do all the possibilities and do that and again uh we are solving this question this particular question using backtracking okay so backtracking is a prerequisite like uh you should know at least the basic of recursion I don't expect you uh you guys should know backtracking because I will be having a clear explanation how I did for the question also so basically I will have a clear explanation so need not to worry so now let's deep into the explanation how we can solve this problem okay so guys I have basically taken this particular example which states we have three houses which is house zero one two as it is zero index and we have some like some request given that from this house to this house okay now let's uh also from this question so it's basically What You observe from this question uh like is that a basically like uh if these three are valid then we are going to get three maximum request right that's for sure what uh like observe if this is this after this everything is valid you know one thing we are going to get three requests but assume this stuff is not valid but these two survive these two survived think about that what is happening here but guys not actually true but just think okay not actually true this three hour value this four three is valid not this is not valid not like that but just think about that it is not valid so what we are doing here we are not picking that but we are picking this both right so and we are in the case of generating all the possibilities so what that means initially if you can pick this or we don't pick this we can pick this or we don't pick this you can pick this or we don't pick this okay and by all the possibilities generated and if that is valid we'll take the maximum of that is as simple as that okay so basically now let me quickly start now it will be quickly too sorry so guys this will be somewhat black but whenever I draw a recursion tree you will get it here I am definitely sure about that so guys uh basically I will have two arrays of uh one is going to determine whether I have picked that or not so if I pick this I will like okay I will Mark that okay that array will be working like that and another array will have this we are looking the status of the house is that balance or not okay fine so initially I will start from the index 0 the requestion tree will boils down from start from F of zero that's for sure and from here what are the cases I have I will pick these Horrors I will never pick this I'll pick this or else I will never pick this so observe what's happening from here from how zero a person is moving to the same house okay initially I will pick that it's my one case right you have two possibilities you can Peak or not Peak that's that makes sense so whenever you pick you should definitely um definitely move the index you should not stand there why if you stand there you will be repeatedly pitching that could not be once you pick or once you not pick please move the index that's why zero plus one and now uh we have moved now what will happen to the visited array that means we have picked the index 0 so please mark it as one and remaining may have been pigment we haven't picked and what will happen to the status of the house come on guys someone is left someone is in left from the house zero that makes sense someone left so okay so basically uh that is another case which is not big so I will not pick this so let us assume see let's observe what happened so yes actually here is a backtracking happen for this particular iteration but I will not explain here it is because uh this guy is reaching from same house to same outside so that will be not clear as well I will explain that very deeply in the further location okay now this will be F of one for sure but we are not picking so what will happen to the visited array we haven't picked anything zero and what is the status of the house we haven't picked anything so the status how this house will be remain same guys that's question man that's for definite okay now I am at this index I have two possibilities I can pick or not Peak right I can pick or not pick initially I will pick and I will move the index why I am moving the index and what will my status of the house will be someone from house one most house one that means if my house one Gods minus one because someone moved out and someone this someone got increased to the house too which is plus one minus one plus one and this will be remain zero and does not have any changes now guys what do You observe we have another possibility which is not big F of 2 but can be can we further move this to that because this is the changes of peak man this is the changes of peak but whenever you go back you should backtrack you should reduce the possibilities that happened here and you should go there what will that so you have done a minus one here then do a plus one at same and you have done one do a minus one that it will go to the back state so basically backtrack and whenever you go make that array minus one plus one which will be 0 and um one minus one zero whenever you make sure you go into see another possibility which is not big make sure you backtrack the possibilities what you have done here so that is the opposite of that please so that it will not get collapsed in another possibilities so that's where backtracking comes here so as CCS that so guys observe he said the only case is that the only case hi hey man I don't think so is that the only case we should also backtrack the visited array now What's Happening Here fine we have visited zero that's fine but do we have visiting the one no so please make it a zero and come back now what will happen to my visitor array 0 1 2 and my visited array now boils down to one zero now we have changed this to zero because why we haven't picked this one house but we have picked zero in this particular iteration I think that makes sense and that actually how backtracking Works how backtracking works now the heavier standing yes index to index two okay we'll further Modi F of three that makes sense y f of three is there any Necessities to stand there no we'll move we will move now someone from house to is going to house one okay what is that what is the previous of the visited array which visited array we are picking everyone so make one that make sure now what is the status previous status of this 0 minus one that was the previous status of this now what happening let's observe two how from someone from house two is reaching house one so someone from house two is moving so one minus one will be the status of this then that will be zero and someone uh from house two is moving to the house one someone is getting increase which is minus 1 plus 1 and this also boils down to zero points down to zero and okay this is the one case and we also have Peak or not peak come on observe guys so basically what will happen so F of three and this time the visited array visited r a zero one two what we have visited the other two but backtrack I make it as zero I'll make it a zero because we are not picking that here that's for sure and now the status of how house is the series of houses this for this case no we should backtrack and babe and take it to the back step back state right so what will be the back state that is what we have done mind uh that thing will be reversed right which is minus one at this case and plus one at this case and now this will become 0 minus one and plus one is What You observe here what do You observe here dude I am pointing someone which is out of my bone foreign here reaching the base condition okay definite that makes sense okay why we cannot go down we are pointing for someone is not possible that is an Unbound error we cannot go there so that is our base condition and some more we have managed to get the answer in this array how I say that come on guys let's observe okay let's observe so from this thing what You observe What You observe this ra which we have taken the status that is everything is 0 everything 0 what that is means come on guys what that is means dude this is valid every house has the same size it remains same size fine okay now what is the big question how can you take how can you say that this three have been picked for this thing yeah for that also so go I'll go and check that dude have been possibly done so at this there are one comma one what this means I have picked the zero three keys I have picked the one trickiest I have picked the two three keys so basically whenever the account is one so that means it is the number of Records I have picked so in this case there is three picked so what I will do I will have a answer and I will take the max of that which is three in this particular case okay definitely but we have reached also for this we have reached the base condition now observe what is our status 0 comma minus one comma plus one here I am not balanced even I am not balanced man in this case I was balanced okay I can go further and I can check what are the cases I've picked but dude I'm not even balanced man I'm not even balanced then how it is possible to go further and you can say that it's a value no so whenever everything is zero go and check the size go and check how much records are picked and take it as Max whenever it is not valid please return that itself okay so the base condition boils down to if index equal to size we know that for sure and for Auto i t is 2 we are going to see the status of the array right if this ID is not equal to 0 that means that is unbalanced I will just return that or else I'll go and check that check the auto i t visited if you have the count 1 if that is equal to if the count is equal to 1 then I will make the count plus that is the number of the request I have obtained and I will have a in dance equal to into Min or some of like that maybe so now what I will do and is equal to Max of as comma and comma count and that's out that's how verification boils down man I hope you guys would have happened clear explanation and this I am not going to do this particular regression tree so that is the assignment for you please draw a request entry guys so whenever I draw a recessionary I got the cons very clear to the depth but I want that also to done for you also guys so make sure you have drawn the remaining location tree and observe so guys I think you have a clear explanation about this question now it is time to code for that so basically uh first we should have the size of that so we'll have the request.3 the one array will be like having the status of the house which will be Vector of end and that will be status and it is up to the house so that will be n and initially the status of the house would be zero that's for definite and I will have a vector of integrated y visited by visited so guys we should always determine whether we have picked this or not picked that okay that is big basically the request dot size so size comma initially everything will be not fixed guys so that will be zero that definitely so we'll have a in the answer declared in globally if and we'll have a Min so because we are going to take Max will always have the mean okay so after doing the recreation I will have the hands are modified here so basically we have written that here okay written answer okay it's as simple as that and now we've called the function over here so we'll have name the function as maximum transfer request which is MTF and we'll pass zero y 0 initially come on guys we'll start from the index 0 this is request and remaining will be like uh status visitor and five right I think that makes sense okay fine now quickly will determine this void function which is uh make transfer maximum transfer request and we'll have uh we'll have hidden will have in index that's for sure and we'll have a vector of Vector of vector of in address of request and Vector of hint address of status and we'll have Vector of visited so and we'll have the size right Pi size to uh terminate right to determine the best condition so before base condition uh we will have the all the possibilities such as initially we will pick right so whenever we pick what we will do the status of request of this particular Index right this particular index someone is command someone is getting out from that so rake of index of 0 this is someone getting out so the status will get minus and at here it will get place right because someone sorry guys this will be one and uh okay yeah I think that will make sense what that means is someone from in this guy is from this house someone is going to reach there so that should be increased that's what I have done here we are picking that so whenever we pick that please make sure you visited that index telling that hey dude I am picking you that makes sense now once this is done please go and do all the possibilities that you can do which is empty of index plus one why index plus one the is there any necessary to stand here why you are repeating picking that no that cannot be happened so index plus one request and uh status and visited and size I think that makes sense and now what is the case we should pack track we should backtrack what that means please copy this and please paste this through the opposite of that do the opposite of that which is plus 4 in this case so minus for this case equal to zero for this case and come on do the possibilities for this not pick also it's as simple as that why we are making opposite of this come on guys this is a changes for another equation tree and you should come back then when you come back you should eliminate the changes happen here so for eliminating this simple math so whatever you do minus you do so place there so that will get eliminated and it will go to the next location as simple as that this is a simple uh simple possibilities that we can do so as easy as that guys so now we'll come to the basic condition which is if index r equal to size I know man you are somehow reaching the outbound some of reaching the outbound that's for sure and what should I do here for Auto for auto it is to status if this give this ID is not equal to zero what I know the house is somehow imbalanced and this path cannot be taken this is not a valid path so I will simply return if that is not the case I what I will do I will have a count of one which is determine I have picked this much request so for auto i t is to be seated and I will go and I will check if it or you want please go and make the count plus and answer this is valid man please take it answer come on count and is it correct no we should return y return it go on out of the bound this is the base condition we should return or else it will throw an error man it will throw an error if there is you know if there is no uh typo this should definitely run let us see okay we have done a mistake over here which is recused not request okay some type of ways okay that makes sense and now just that should definitely work man okay fine now let us see by submitting that wow that is work guys I hope in this video you guys have got a clear and Crystal explanation so guys it is a lot of effort to reach at this particular uh instance of this video so make sure you drop a like And subscribe to our Channel press the Bell icon make sure you follow in my LinkedIn so that you get many uh approach what I'm going to do in future videos so guys uh still I will meet you guys in the next video I am tanishq and now this video is finished bye have a nice day
Maximum Number of Achievable Transfer Requests
maximum-number-of-achievable-transfer-requests
We have `n` buildings numbered from `0` to `n - 1`. Each building has a number of employees. It's transfer season, and some employees want to change the building they reside in. You are given an array `requests` where `requests[i] = [fromi, toi]` represents an employee's request to transfer from building `fromi` to building `toi`. **All buildings are full**, so a list of requests is achievable only if for each building, the **net change in employee transfers is zero**. This means the number of employees **leaving** is **equal** to the number of employees **moving in**. For example if `n = 3` and two employees are leaving building `0`, one is leaving building `1`, and one is leaving building `2`, there should be two employees moving to building `0`, one employee moving to building `1`, and one employee moving to building `2`. Return _the maximum number of achievable requests_. **Example 1:** **Input:** n = 5, requests = \[\[0,1\],\[1,0\],\[0,1\],\[1,2\],\[2,0\],\[3,4\]\] **Output:** 5 **Explantion:** Let's see the requests: From building 0 we have employees x and y and both want to move to building 1. From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively. From building 2 we have employee z and they want to move to building 0. From building 3 we have employee c and they want to move to building 4. From building 4 we don't have any requests. We can achieve the requests of users x and b by swapping their places. We can achieve the requests of users y, a and z by swapping the places in the 3 buildings. **Example 2:** **Input:** n = 3, requests = \[\[0,0\],\[1,2\],\[2,1\]\] **Output:** 3 **Explantion:** Let's see the requests: From building 0 we have employee x and they want to stay in the same building 0. From building 1 we have employee y and they want to move to building 2. From building 2 we have employee z and they want to move to building 1. We can achieve all the requests. **Example 3:** **Input:** n = 4, requests = \[\[0,3\],\[3,1\],\[1,2\],\[2,0\]\] **Output:** 4 **Constraints:** * `1 <= n <= 20` * `1 <= requests.length <= 16` * `requests[i].length == 2` * `0 <= fromi, toi < n`
null
null
Hard
null
435
hello everyone so in this video let us talk about one more medium level problem from lead code the problem name is non-overlapping intervals so problem non-overlapping intervals so problem non-overlapping intervals so problem statement goes like this that you are given an array of intervals where intervals of I represent stratify and endify for every ith interval you have to return the minimum number of intervals that you need to remove to make the rest intervals non-overlapping make the rest intervals non-overlapping make the rest intervals non-overlapping okay let's take some small example to understand more clearly so as you can see that you are given some intervals in an interval array and let's try to Mark these intervals on a let's say number line to visualize it more clearly let's say that we have a number line like this let's say this is one this is 2 is 3 so now let's say that we have a interval from one to two like this now we have an interval from two to three that is this control from three to four like this identical from one till three that is let's say now what you can see is that we have to somehow remove the minimum number of intervals from the area that we have that is this in like the different intervals that we have to remove the minimum number of intervals such that the rest of the intervals are non-overlapped if I just remove this non-overlapped if I just remove this non-overlapped if I just remove this interval as you can see like just the last interval then as you can see if I just move this from this array all the recipient intervals will be non overlapping okay and that is what we actually require in the end now how can we do that what you can see here is that it's better that whenever we have some intervals we have to initially like sort out these intervals so that we can do some operations on it now sorting intervals is majorly done on two ends like whether I will sort all the intervals from the depending about the initial points like whatever is the initial like you can say the left part of the intervals but I will sort them by the right part of Windows okay now what you can see here is let's take an example that if we sort it from a left part like left Point means that if I have all the intervals and uh if I sort them by the left half the left part of interval what you can see is if I just move this part and if I want I have an interval like this so one interval will be like say in cap setting all the intervals like this if I sort these intervals by this order then this interval that is starting from the very first will be the very first in the after sorting of these intervals so it will come like this 1 4. it will be 2 3 and 3 4. so these intervals will be like this after sorting now what you can see is that I will try to see how many intervals I can take so if I take the first interval because I have sorted this in this manner all the other intervals will be overlapping with it and I will not include it and that is a bad way because I'm I have taken the one that is larger and that is starting from the very start and ignoring the one that are the other end why because if I have taken this interval in let's say I am taking an interval in the answer if I have taken this interval in the answer then I cannot take these two intervals because this intervals will be overlapping with this interval so I cannot take this interval because I've taken this interval in the answer the flip side what I can do is that instead of sorting them by the initial left part why not sort these intervals by the right side so if I just completely move this out if you had like sort them by the right hand side as you can see it will be like this 2 3 4 and 1 2. in this scenario as you can see I will take the first I will take the second and then because I have taken the first and second the third one will be overlapping with these so I will not take them and the answer will be two that is perfectly fine so the overall idea boils down to here is that I will first sort out this interval by the right half uh like the right hand side in the increasing order and then after that what we'll do is that I will keep on moving iterating over this in terms of Left Right and finding out that whether this interval is like you can see is acceptable with all the intervals I have till now which are not overlapping with each other and cannot take this interval in that particular answer set of now so 2 and 3 is fine okay so now I will take the next element whether two like whether 3 and 4 is overlapping with this because I have the intervals up till now till three so which means that I have taken an interval that is up till now to 2 and 3 and because I have sorted them all the intervals after 3 will not be overlapping with this if I have any interval that is before this interval like this interval then that will obviously be overlapping with it so I will have to only take intervals that is after 3 so that is after or equal to 3 that is also fine so now I have taken all the intervals Field Four so after now only take interval set is after 4 okay so this interval is like overlapping with this interval that is going all over the other intervals as well so I will not include that in the final answer and I have to remove that so the answer will be incremented how many like internals have to move so let us move on to the code but now what you have done is that you've first sort out these intervals by the right hand side so I have to do in terms of custom comparative function that is just to sort them by the like the right most extremities of the potential after that I have this total and this last now this last what this last means that I have to first compare every interval like whether it is uh overlapping with the previous intervals that we have in the array so for that it's very better to just Mark that uh that if I have taken this interval let's say the other intervals should not so I have taken one two which means that I have taken all the way I have taken all the let's say area from 0 let's say like if I start from 0 till 2 so all renderers should be right of two it should be right of two so all the area before and 2 should be fine but if I have to start with the very first uh let's say interval so I have to match it with all the area on the right hand side of something now what is that something what you can see is that the maximum value is negative here as well that is minus 5 into 10 to power 4. so let's take it though like more on the left hand side of this value that is minus six thousand six entity by four that is this okay so what we have done is now iterating with all the intervals number one and just checking out that whether the current interval left half is as you can see on the right hand side of the last interval I have seen if it is on the right hand side which means that it is greater than that then that is fine then I will just make my last equal to the second value of the interval so as you can see that if this interval is on the right hand side of this interval then what I have to check that whether the first value is greater than the last value so the first value that is this value which is greater than the last value and the last value will be updated with this value that is the last second value okay that's it and if this condition is not matching then what we'll have to do is start we have to say that this particular index is invalid so if we just find out that certain index is invalid that is going on the left hand side of the area that we have already covered so I will not include that in the final answer and we just increment a total that is a bad interval we just don't have to include that because it is overlapping okay and that's in the nvs printer the total number of intervals that are overlapping and we don't have to include that in the final answer and that's the complete part for this particular problem this is sorting so of n log n this is O like this is for Loop so o of n so it is it in total it is O of n log n for solving or disputal problem if you still have an adult circum machine in the inbox for this particular problem I will see you in the next one to recording and bye
Non-overlapping Intervals
non-overlapping-intervals
Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. **Example 1:** **Input:** intervals = \[\[1,2\],\[2,3\],\[3,4\],\[1,3\]\] **Output:** 1 **Explanation:** \[1,3\] can be removed and the rest of the intervals are non-overlapping. **Example 2:** **Input:** intervals = \[\[1,2\],\[1,2\],\[1,2\]\] **Output:** 2 **Explanation:** You need to remove two \[1,2\] to make the rest of the intervals non-overlapping. **Example 3:** **Input:** intervals = \[\[1,2\],\[2,3\]\] **Output:** 0 **Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. **Constraints:** * `1 <= intervals.length <= 105` * `intervals[i].length == 2` * `-5 * 104 <= starti < endi <= 5 * 104`
null
Array,Dynamic Programming,Greedy,Sorting
Medium
452
35
hello everyone I welcome you all in our another D session where we'll be solving another DSA problem based on AR as previous we will also go from s Med easy medium than hard our today's problem is search index position let's check out here it is given a problem statement we will read given a sorted order of distinct integer and a Target value return the index if the target is found means we are given an array like this nums equal to this array and we are given a Target value we have to check that Target value in our array and we have to return the index at which the target value is present if not return the index where it would be if it were inserted in order means the array is given in a stand in a standard ascending order let's check out an example to know it carefully in our first example it is given that a nums is an array 1356 and we are given a Target value five we have to check the position of five in this array if we found the position of five in that array if you found our Target in nums are then we will simply return our output uh here at zuro Vector 1 it is not matching at first Vector three it is not matching at second Vector we got our value then we will simply print our output two let's check and another example uh to get it more clearly it is given that our Target value is two but the target value two is not present in our array nums then we will check uh at which position the target value is present for example uh two is not present in the array given that the element are maintained in the ascending order two will be in between three and four and the index of three will be shifted one side to uh shifted to right by one and now the two will be inserted uh the array will be modified and the two will be inserted in between 1 and three uh giving the vectors at zero Vector it will be one at second Vector uh at first Vector it will be we will get our value two at second Vector we will get our value three at Fourth Vector we will get uh third Vector we will get our value five and at Fourth Vector we will get our value six uh write an you must write an algorithm with all log N Run complexity uh we will get to know what is time complexity uh time complexity is basically it measures the amount of time an algorithm take to complete based on the input size for example for accessing an element by index we use zero of one which is a uh it is a constant time as it is directly Computing to the memory address for searching of an element we use Juro of Y time complexity which is a linear time and where Y is the size of array uh now we will write our code for the following given question so here we'll start our code first we will initialize two variables left at the beginning of vector and right at the end of vector let's write it int left equal to0 comma right equal to num nums size minus one now we will start a while room for our initialized V initialized variable while left is smaller than right we will write conditions inside it uh here uh we need to understand something that we have initialized left Vector right Vector means for example we have written the statement for example one but what if uh the element or the target value is not present in our array then we have to initialize an another variable called mid for meid equal to left plus right minus left / 2/ 2 sorry now we will write if statement for our while loop nums of m equal to our Target value then return M mid here I have written that compare the our mid value with our Target value if it is equal if they are equal then return simply return mid value we will write an else statement else if nums of mid is smaller than our Target value then return left index return uh left index sorry we have to return left index left equal to Mid plus 1 else simply return right index else simply return right Index right equal to Mid minus one we have written the statement uh we have written our code but uh we have to check one condition what if the target value is given means uh given as zero then it will be simp simply out of our array this array given array so we have to Simply return zero therefore you have to write a return left now we will run our code and check it is working or not okay so here we got the error on our line number four int left equal to Z comma right = four int left equal to Z comma right = four int left equal to Z comma right = to nums do size minus one so here we have to apply full stop okay we will run it again yes the code is ex accepted for all the three conditions now we will simply submit our code
Search Insert Position
search-insert-position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with `O(log n)` runtime complexity. **Example 1:** **Input:** nums = \[1,3,5,6\], target = 5 **Output:** 2 **Example 2:** **Input:** nums = \[1,3,5,6\], target = 2 **Output:** 1 **Example 3:** **Input:** nums = \[1,3,5,6\], target = 7 **Output:** 4 **Constraints:** * `1 <= nums.length <= 104` * `-104 <= nums[i] <= 104` * `nums` contains **distinct** values sorted in **ascending** order. * `-104 <= target <= 104`
null
Array,Binary Search
Easy
278
227
Loot Hello Guys Welcome Remedies To David C The Question Basic Related To In This Question Maze Subscribe 1020 Plus Minus Multiplication Division Withdraw Cases Against Subscribe Loot subscribe and subscribe the Channel and subscribe August Acts And Multiply The Current Number And Returned 2 Results For Diet Rich in to take again subscribe The Channel and subscribe button take Ajay loot a minute to hold the current number solanesis available karan and hold to the president will reflect on hearing this note r string into account it a loot bank temple character add it See Back To Cash Is In The Amazing Avoid Will Have To Go That Is That A Digit Hua Tha Thank Another Condition Ko Ek Film Recommendations Will Look Like This Inside Yeh Condition Dash Loot Lo Hua Hai A Certain Like This Name Idhar Avoid Appointed Point Hai Celery candidate has not software 98100 operation character who holds the operators pendant fuel incomplete for subscribe then skin the current subscribe to this lineage value current pointer has been pushed into 10 to 15 minutes update operations with current key value under current affairs in the studio is this Day Plus Second Ingredient - Also is this Day Plus Second Ingredient - Also is this Day Plus Second Ingredient - Also Only The Negative Value Of The Current Tab Insignificant Distinct Population Held To Me To The Point Of That And You Will Be Able To Understand What Do You Mean That Post The Result Of Tenth Hotspot Of That And Thus End Point in to the talk in the middle mid result will be that and take off that this note mp ko get and values ​​into the se less fuel and visitors on loot ek pan protest angle hai here height result letters for example will be loot in the morning The meeting is right result related alarm set whatsapp mid town more not only to remove vidmate app that know inside this logic of mid same in order to hold top loot withdrawal last date in hindusim will happen with visual see the meaning of is and This - Suresh Current Been Pushed Into is and This - Suresh Current Been Pushed Into is and This - Suresh Current Been Pushed Into Sanjay Dutt Last Absolutely Current Quiz That And Also In Cancer Fraction Now Subscribe Video Subscribe Addition And Subtraction And After Coming To All Oo subscribe to the Page Select Friends That Once Again That Cigarette Result Lenses Alarm Set Addressed Vitamin Complexity In This Case Which Comes For Fun World Space Complexities Ninth Class Sexually A That
Basic Calculator II
basic-calculator-ii
Given a string `s` which represents an expression, _evaluate this expression and return its value_. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. **Note:** You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as `eval()`. **Example 1:** **Input:** s = "3+2\*2" **Output:** 7 **Example 2:** **Input:** s = " 3/2 " **Output:** 1 **Example 3:** **Input:** s = " 3+5 / 2 " **Output:** 5 **Constraints:** * `1 <= s.length <= 3 * 105` * `s` consists of integers and operators `('+', '-', '*', '/')` separated by some number of spaces. * `s` represents **a valid expression**. * All the integers in the expression are non-negative integers in the range `[0, 231 - 1]`. * The answer is **guaranteed** to fit in a **32-bit integer**.
null
Math,String,Stack
Medium
224,282,785
32
hello everyone welcome to coderscam and today we are the third day of april lead code challenge and the problem we are going to cover is longest valid paranthesis so the input given here is a string which is consisting of parenthesis and we have to return the length of longest valid parenthesis in the given string a parenthesis is said to be valid if it is well formed that is for every open bracket there should be a corresponding close bracket so let's see how are we going to approach this consider this given input the parenthesis is said to be valid if it has a corresponding open and closed parenthesis so here if you see the extra brackets are the index 2 7 and 10. the rest of the strings are said to be valid that is this the second string is this and this is said to be valid other than that these three brackets are in extra brackets so here clearly wherever there is an extra bracket there it breaks the longest valid parenthesis so for example if you want to consider the substring starting from the index 0 to 6 the bracket at index 2 stopping this from being valid so now if we are going to calculate valid strings then it should be between two invalid parenthesis that is from index 0 to 1 there is one valid parenthesis and there is a break at where there is an extra bracket and starting from the next index till it has the another extra bracket it is a valid parenthesis same way starting from the next index to invalid parenthesis to before where there is an extra bracket there is one more valid string so we are going to record the indexes of the extra brackets wherever it is and by using those indexes we are going to calculate the valid substrings between them and whichever is the maximum length we are going to return the length of that substring in this case it is 4 this is the valid parenthesis which is longest out of all the valid parenthesis formed so to record or identify the invalid brackets here in the given string we are going to get the help of stack so in this stack we are going to push the indexes of only extra brackets so if there is a corresponding open bracket or closed bracket for the already existing bracket then we are going to pop it so let's start from the index 0 which is the open bracket so we are going to put the index 0 to our stack so moving on to our next character that is a close bracket so there is a corresponding close bracket for the open bracket at index 0 so in this case we are going to pop that from our stack so moving on to our third character which is an extra bracket so let's push that index to our stack so here two enters so now moving on to our fourth character which is at index three which is the open bracket so we are going to push the index to our stack which is going to be three and the next character is a close bracket so the corresponding open bracket is at index three so in this case we are going to pop that from our stack so the next character is open bracket at index five so we are going to push index 5 to our stack and at index 6 there is a corresponding close bracket so we are going to pop that from our stack so moving on to the next character which is an open bracket if you push that open bracket the index 7 is going to be there at the in stack so now let us continue our stack this side so now we are going to check the index 8 the character is open bracket so we are going to push the index of open bracket that is eight so now the next character is nine which is having a corresponding open bracket at index eight so we are going to pop that from our stack and finally we are going to check index 10 which is the extra bracket that we know so we are going to push the index of extra open bracket which is 10 so 10 enters into our stack so now after iterating through all the characters in the given string we have three indexes left into our stack that is 2 7 and 10. so by using 2 7 and 10 we clearly know they are the extra brackets so we are going to calculate the length of the sub strings which are existing between these indexes and finally written the maximum length of the substring we found so now starting from index 2 we clearly know as the index 2 is the first one in the given array so which is going to be clearly the first extra bracket so it is starting from the zeroth index to two so we are going to calculate the first sub string whose length is going to be two so next our value is seven so the next string we are going to calculate must be from the next index to 2 and before index to 7 that is from 3 to 6 which is 4 and the last is going to be 10 so we are going to calculate the length of a substring between 7 and 10. so after 7 before 10 is going to be 8 and 9 and the length is going to be 2 so out of all this 3 4 is going to be the longest valid substring so our output is going to be 4. so in some cases if after 10 there can be valid parenthesis for example if our example is having one more open and close bracket which is at index 11 and 12 in this case 10 is not going to be the last index we still have further valid parenthesis after the last bracket that is in our stack in this case after calculating all the index we are going to calculate one more substring from 10 to the length of the given string so that is between the total length of the string to the last value we have in our top of our stack that is one more valid string which is having length two so out of all substrings valid substrings we have found we are going to return the maximum length hope you are getting this solution before getting into code this actually works in big go of yen time complexity and space complexity as we are iterating our string only once and we are using stack for memory so let's go to code now so first we are going to check the basic conditions that if our string is null and i'm gonna declare my stack so i'm gonna iterate through my given string and put my indexes in stack so here we are checking whether there is a corresponding close bracket for the open bracket we pushed then we are going to pop that from a stack if not we are going to push the index of the extra bracket so now let me declare a variable index to hold the index of extra brackets which is going to start at minus 1 because we are before starting at index 0 we are going to point this at index minus 1. next which is gonna be a result we are going to return so i'm gonna iterate my values present in my stack so i'm gonna update my max length every time i find a valid parenthesis length so this first will calculate from the first invalid bracket index minus the first minus 1 index minus and every time we find a new length we are going to assign the index value to the next invalid bracket index and finally it will calculate the maximum length till the last brackets index so what if there is a valid parenthesis after our last bracket so we are going to calculate till our total length of the given string so yes finally max will be having the result so return max so yes the code is done so let's run so yes let's submit yes her solution is accepted so thanks for watching the video if you like the video hit like and subscribe thank you
Longest Valid Parentheses
longest-valid-parentheses
Given a string containing just the characters `'('` and `')'`, return _the length of the longest valid (well-formed) parentheses_ _substring_. **Example 1:** **Input:** s = "(() " **Output:** 2 **Explanation:** The longest valid parentheses substring is "() ". **Example 2:** **Input:** s = ")()()) " **Output:** 4 **Explanation:** The longest valid parentheses substring is "()() ". **Example 3:** **Input:** s = " " **Output:** 0 **Constraints:** * `0 <= s.length <= 3 * 104` * `s[i]` is `'('`, or `')'`.
null
String,Dynamic Programming,Stack
Hard
20
634
hey everybody this is Larry this is me trying to do an extra problem get my money worth on premium so uh yeah how do I do this I always forget every time yeah let's do a random RNG problem that I haven't done before so we'll be fair uh it's 6:34 find the derangement of n uh it's 6:34 find the derangement of n uh it's 6:34 find the derangement of n way hit the like button hit the Subscribe button join me on Discord let me know what you think about this one um so derangement is actually kind of hard in general uh the first thing that we notice is mod so let's do the mod um I actually don't I me I know that there's a DP and given that we have mod and Counting um we are going to have to um you know figure it out anyway I actually don't remember how to do it but I just remember that the arrangement is kind of hard um so that's well a thing that we have to consider um but um yeah it's basically no element appears in this right so H but I would also say that this is kind of a lature problem because this is actually very well studied and very well understood though I don't know why this is a medium though I mean I guess maybe for that reason it is but it's really not easy unless you've done it before so okay so let's think about it right so okay um I think the thing I would try to think about is um try to think about States right so what would be the states is going to be I mean ideally we want the numbers left but um but then we have to kind of try to uh code how to do it right um I think that also the other way of thinking about it possibly is um count the number of ways that at least one element in is in its place um I'm not sure that's easier right I mean in a weird way I guess you can sum that sequence easier because I don't know if that's true to be honest but basically you have um number of things where only one exact way no but then that's a little bit tricky right because you have only one exact thing that is in the original array that means that you basically have to um you know like you have one thing and then it becomes like a DP type thing right um and then you just kind of like I don't know I mean it's fine I think it just that it becomes n Square actually don't know I don't remember how to do it I just remember it was hard the last time I did it which might have been like decades ago um which you know but okay I mean but the idea is here um for a d dynamic programming solution um I don't think there's a I think the tricky part about this one is that it has like it grows in such a weird way that there's no yeey um formula but maybe I'm wrong so let's think about this one this may take a while and again this is a very well studied form so if you actually want like an explanation and proofs and stuff like that I would Advocate just Googling it to be frank uh derangement is a very popular thing it comes up in random places in um real life which is why it is well studied but that said um if you would want to watch uh an idiot me to try to see how to come up with this from scratch then you know you're at the right place um hm okay so I mean if n is equal to one we have zero right and I'm just going convert this to Big um then we have zero and then let's say now we have two how can do we get to look at one at a time right basically okay so the first one has one choice and the second one has one choice okay but that's like trivio so I don't know how to um yeah okay so but with three it gets a little bit funky right because three there are like okay so the one has to go into two or three so the two choices for the first one um and then but then there are some consequences um because if you go to the two then the two has to well it has to go to the three I mean it could try to go to the one but then the three would match so I don't know how the weapon present that in terms of States I mean at least not in a reasonable kind of way um the way that you know like bid mask is not very useful because the ends are pretty big right um can I uh the way that I'm or the thing that I'm trying to think is how can I get sub problems out of this right so okay so you have n numbers the first number so I guess the two things maybe which is whether I see maybe right okay I don't know if this is true but we'll see right okay so basically if you have N Things okay so you have to kick off with the first item right so the first item you know uh has to choose something that's not itself that's going to be end times and then now the second item it iters so it cannot choose itself for obvious reason but it can choose to end a previous cycle or begin a new cycle right if it what happens if it begins a new cycle if it closes a previous cycle then that's just um you know then now you get the recursion of the next number but if you don't close a cycle then you have a new thing if you don't close a circle cycle what happens well okay instead of thinking too abstractly let's just play numbers right so 1 2 3 4 5 so then now let's say one we put on the second slide and then now two we can choose to close it and then that of course is just a um you know now you have n minus three or whatever it is n minus two rather so you have three left um but then the other thing you can do is just choose something else and what happens when you choose something else that means that now I guess you don't create a new cycle you just kind of continue the cycle so that means that you always have two things you have one cycle and then you have the other um thing right and then now three what happens I guess that's the tricky part right but then here for all um like you could kind of relabel them right because here that's just say we select four but that is actually equivalent to um the next number being four right so you can actually in theory Swap this in three and this is four and it'll be the same state you have to count the number of things but then that means that this is an unclosed thing and then yeah so you have two choices between everything you have close and unclose okay think that maybe make sense that's uh I mean I'm just going to write it out a little bit um we'll see if this actually is good to be honest I don't know that it is um right so then now and I might need an extra bullon or something I don't know um but yeah well I mean or just like another thing right so here count uh no Cycles right so here and then now the no cycles and you have to begin one because you can't choose yourself so there's if there n numbers left there end minus one way of choosing a new cycle so the answer is going to be this times um count Cycles count with Cycles maybe or with cycle I suppose no cycle no Cycles but now with n minus one number so then we can kind of return this right that's the only choice you have no and then count with psychos psycho um you have two choices right you have you could um let's see where is the base case if you have a psycho and with n is one left then that's it right you have no choice but that's good you have one because there's only one place to put it uh and then otherwise you could end the cycle which is um so there's only one way to end a cycle which is the number that's missing so it's going to be 1 time count no cyes uh n minus one because now there's okay yeah U so that's that and cycle and then the other thing is um beginning or not beginning but at continue to the cycle so yeah continue cycle is equal to um really any other number right so that's just going to be n minus one um and this is the cycle thing is a little bit weird but it um weird phrasing I'm think so the reason why I say cycle is because I'm thinking in terms of permutation cycle another way to think about this is actually that um your seat is taken if you will right um because if your seat is taken then you have to take a random someone else's seat and here you can take your own seat I think that's basically the idea okay so then container CYO is just this right uh count with psycho and then n minus one yeah and then now we can return End Cycle Plus continue cycle uh yeah I mean we have to do some mods math but I just want to see like how um I just want to see if this at least gives me roughly the right answer and we have to of course do memorization and stuff like that but it looks good for these well I mean these are very silly base cases so we have to I don't know um I don't want to go too big because this does grow exponentially so this should give us a good test and this looks okay so I think we're in a good place and of course we have the mod so let's actually clean this up now that we kind of verify that's kind of super hard I don't know that I'm explaining that I spring this solution very well I would say that though it is kind of hard for a medium I don't know that this is a medium uh maybe it is maybe I just have kind of a weird hang up on this one uh that could definitely be a thing uh and we don't need this anymore because that's the base case here so you have this we want to you want to mod it oops here you Al want to mod it so okay um and then of course the other thing is that um yeah the a couple things you can do I mean we kind of did this chat with um I did a problem like yesterday but I don't remember if this was just like RNG because it just seems way cdental because this is RNG right but uh but yeah but you can actually you know you look at this and you can actually know that this looks back so we can actually replace this with that but I'm not going to do that today I'm just got a little bit lazy so let's just add memorization to this so H um you know maybe psychos has cash is you go right and then we can write something like yeah if otherwise I don't know why I'm writing it like this but right and of course we should do it with this as well so yeah oh huh I got confused to naming okay fine so my computer's a little bit lagging I we have too many windows open to be honest hopefully the video at home is pretty okay um going to do a little bit of lazy copy and paste right and yeah I do get questions why I do it this way but I just think it's easier to read when you look at this right and I hope that you agree what the psychos guy sh what am I doing I need to fix my mic I think I the way that I my setup is just that it's moving over too much but uh okay sorry friends I'm trying to calibrate it but uh yeah all right anyway let's give a spin hopefully I don't have any typos and now we can try the really big numbers I think that's close enough oh yeah uh H that's a little bit sad yeah the reason is because I guess we have two of these and 10 to the six is a little bit big um I think there is a I mean we can up rewrite these as um Bottoms Up for sure you can kind of look at how the form is structured and it's not that hard to make it but I want to kind of keep it in structure so let me kind of um crease uh recursion TP I don't remember this I have to Google it because it doesn't really come up that much per se but I don't I mean it is odd to see a 10 to the six but I guess maybe someone's doing it funkily um I don't know maybe I guess it doesn't actually matter as long as you don't use it yeah I mean you know maybe it's a bit slow maybe we have to kind of optimize it but uh yeah um so you can definitely kind of well one you can definitely make it Bottoms Up and once you make it Bottoms Up you can actually do this uh in all one space I have a video on Space optimization um this is relatively a easy problem to do that for and it's good practice but yeah um yeah derangement again is a very well studied kind of problem so definitely read that up but I think the way that I would think about it is that you kind of separate them in the two cases one is with no cyclos I thought you would create multiple cyclos so I think I'm very happy that I um some and that's why sometimes you have to draw out your visualization cuz sometimes your visualization in your head is just wrong and that happens to me and actually um this is a thing where um you know Josh has a dmj contest like just last week or it ended this week or something I don't know how you describe it but in the past week um and that was my thing was that I st I got stuck um I got stuck spending 20 minutes de not debugging something but just thinking that something wouldn't work because in my head I kind of worked it out but my head is just apparently not very correct in some calculations um but as soon as I draw it out when now I was like oh wait what am I doing this is very easy this is very obvious and then you know so yeah definitely draw things out uh challenge your assumptions make sure that you know uh yeah uh you don't fool yourself cu the easiest person to fool is yourself uh anyway that's all I have for today let me know what you think I think this is a very um cute interesting thingy but and also like I said there's a lot of interesting places where this comes up so definitely study it a little bit um or like if you're into you know if you're into math and being a nerd like I am then definitely you can check that out but uh but yeah that's all I have for today let me know what you think stay good stay healthy to good mental health I'll see you later and take care bye-bye
Find the Derangement of An Array
find-the-derangement-of-an-array
In combinatorial mathematics, a **derangement** is a permutation of the elements of a set, such that no element appears in its original position. You are given an integer `n`. There is originally an array consisting of `n` integers from `1` to `n` in ascending order, return _the number of **derangements** it can generate_. Since the answer may be huge, return it **modulo** `109 + 7`. **Example 1:** **Input:** n = 3 **Output:** 2 **Explanation:** The original array is \[1,2,3\]. The two derangements are \[2,3,1\] and \[3,1,2\]. **Example 2:** **Input:** n = 2 **Output:** 1 **Constraints:** * `1 <= n <= 106`
null
Math,Dynamic Programming
Medium
null
1,537
hey everybody this is larry um yeah maybe i only do well in the dynamic program forms but let's go over today's problem uh get the maximum score today uh the contest 200th um hard question uh so yeah so basically you could choose from the problem assess you that you can choose from any uh you know you could choose from numbers one or nums two um and you could have an index of um you know you just go for the index from left to right and you could jump from the same number right and the score is the sum of the unique values in the path and you have to mod it by 10. so i think one thing to note is that it's actually really tricky to uh for in the general case to return the max number by after modding it or like you have to do some math about the proofs but the thing is if you look at the um the constraints uh each number could be only be ten to the seventh uh the length can be only be ten to the fifth so that means that the maximum number is going to be 10 to the 12 which fits in a 64-bit integer the 12 which fits in a 64-bit integer the 12 which fits in a 64-bit integer which means that you can actually store the maximum as a 64-bit integer and then mod it at as a 64-bit integer and then mod it at as a 64-bit integer and then mod it at the very end uh it's a little bit nuanced but that's the way i would think about it um yeah uh and then for dynamic programming what is the states right they're only a couple of states um the thing going from so basically you add a cell every time uh and you're given the index and you're either under numbs one or nums two so that's pretty much your state and that's the way i think about it i have some lookup tables so that i could look up going from numbers one to numbers two and so forth uh and backwards um and then i have the score function that okay if i'm at the end of the first array uh return zero if i'm at the end of the second array returns zero and the first is just you know indexes index first is um which uh which are value in and of course there's two times n unique uh inputs and each of them does all roughly all one work so that means that this is linear time or two times n which is good enough uh so i did this recursively in retrospect i should have done it bottoms up maybe because i ran into issues with recursion limit in python i added this and it worked out okay but it did cost me five minutes which dropped my rank from seventh ish to 25th which is i don't know just for bragging rights it'd be nice to be in the top 10 because it's been a while but uh but yeah but the thing here is okay so what are the transitions right so the transition is okay we're in the first array uh first element we just add the score to go from current index to the next index right so that's what this line does and this that's also what this line does but for the second uh array right and then the thing to model the jump from the arrays is that now we have a lookup table um and we don't want to we just want to make sure that it doesn't um jump back and forth so what we do is that we change the array that we're in and then we just use the lookup table assuming that it is in the lookup table and then we just go to one right of that and because um and then the scoring is just that every time you go from left to right it is always going to be unique value so you just add that score uh even if you jump to the other way well you just have to make sure that you don't count the same index twice and because the you can only jump render the same value that means that by definition um by definition if you move one to the right and just kind of once that'll be okay so that's pretty much all i did and i kicked it off by making sure that we'd start from this uh the first index and the second index and that's pretty much it uh the issue that i have again is because 10 to the fifth and i ran into recursion limit which cost me five minutes uh kind of sad actually but uh but yeah and now you can watch me solve this live right about now so what's the kind of way some of the unique oh geez just so i don't forget is that even true oh some of them oh geez okay let's turn to 7 that's 10 to the 12th that's just a long okay that's not true this is not what we need to do and jump to the other one you oh you hmm okay come on oh you gotta be what is that thing again foreign um uh what is solu mistake
Get the Maximum Score
maximum-score-after-splitting-a-string
You are given two **sorted** arrays of distinct integers `nums1` and `nums2.` A **valid path** is defined as follows: * Choose array `nums1` or `nums2` to traverse (from index-0). * Traverse the current array from left to right. * If you are reading any value that is present in `nums1` and `nums2` you are allowed to change your path to the other array. (Only one repeated value is considered in the valid path). The **score** is defined as the sum of uniques values in a valid path. Return _the maximum score you can obtain of all possible **valid paths**_. Since the answer may be too large, return it modulo `109 + 7`. **Example 1:** **Input:** nums1 = \[2,4,5,8,10\], nums2 = \[4,6,8,9\] **Output:** 30 **Explanation:** Valid paths: \[2,4,5,8,10\], \[2,4,5,8,9\], \[2,4,6,8,9\], \[2,4,6,8,10\], (starting from nums1) \[4,6,8,9\], \[4,5,8,10\], \[4,5,8,9\], \[4,6,8,10\] (starting from nums2) The maximum is obtained with the path in green **\[2,4,6,8,10\]**. **Example 2:** **Input:** nums1 = \[1,3,5,7,9\], nums2 = \[3,5,100\] **Output:** 109 **Explanation:** Maximum sum is obtained with the path **\[1,3,5,100\]**. **Example 3:** **Input:** nums1 = \[1,2,3,4,5\], nums2 = \[6,7,8,9,10\] **Output:** 40 **Explanation:** There are no common elements between nums1 and nums2. Maximum sum is obtained with the path \[6,7,8,9,10\]. **Constraints:** * `1 <= nums1.length, nums2.length <= 105` * `1 <= nums1[i], nums2[i] <= 107` * `nums1` and `nums2` are strictly increasing.
Precompute a prefix sum of ones ('1'). Iterate from left to right counting the number of zeros ('0'), then use the precomputed prefix sum for counting ones ('1'). Update the answer.
String
Easy
null
329
hey guys welcome back today we're going to solve lead codes problem number 329 longest increasing path in a matrix so given an integral matrix we need to find the length of the longest increasing path so remember that the directions we can move in are left right up and down we cannot move diagonally so this would be an example this would be the longest increasing path so you can see that the path can go backwards you can turn clockwise and both clockwise and counterclockwise so i think what makes this problem so hard is that people think that there is some kind of smart or intelligent way to go about this so that you don't have to try all of the combinations but actually it's just like that you just need to go through each cell and try from every cell to start a depth first search that branches out through the cells of the matrix and tries to find a new maximum length so the way we're going to go about it is first of all i'm going to store in a variable the possible directions in which i can move from a cell so these are the deltas so this is the delta row and this is the delta of the column then what i'm going to do is i'm going to set up a base case where i'm going to say if my matrix is empty then i just return to zero because i can't build any path then i declare a new variable max that stores the current maximum increasing path that i've found so far and later on obviously i'm going to have to return this maximum variable so now we need to compute and to update this variable to reflect what actually is the longest increasing path so to do that we're going to have to loop through all of these house and start a depth first search from all of them so the way to loop through each cell in a matrix is to loop through each row down like this and then loop through each column like this and now i'm going to have to update the max variable with the mathematical maximum between the max variable and an expression and my expression is going to be my depth first stir search starting from this row and this column the current cell so our depth first search and function is also going to have a third parameter which represents the value of the previous cell in the current path that we are exploring so since right now we are not exploring any path the third parameter is going to be minus infinity meaning that any value that we find is okay we can consider that to be increasing because there is nothing before it so it's always increasing in a way so now we just need to implement the dfs function so that's going to take in the row and the column and the parent and what i'm going to do is i'm just going to return 0 if my row and column are out of the boundaries of the matrix so these are the conditions rows negative or it's greater than the matrix length or the column is negative or the column is greater than the amount of columns that there are in a row now there is a third condition that i can use to return zero and that's if the current cell value is less or equal than the parent because if this condition is true then what happens is that the path that we are visiting with this depth first search is not increasing because the current matrix value is less than the previous apparent okay so now that we have this out of the way what we can do is instantiate a max path from this cell so initially it's going to have the value 0 and later on we're going to have to return this and now we just simply loop through all of our neighbors and we start a new depth first search from all of our neighbors so this is how we use our directions array here so for every delta rho and delta column we add it to the existing row just like this and we add it to the existing column so what this formula is doing is the maximum for this current cell this node of the matrix is one plus the depth first search of row plus the delta rho column plus the delta column so these two things are going to essentially go through all of our vertical and horizontal neighbors and this is just our current value so this is going to be used as our third parameter for the depth first search function so now this the current cell becomes the previous cell for the next depth first search calls and so then what we do is uh if we have found a path that is greater than the current max path we update the max path with the greatest uh path that we ever found so far and then we just return the path so this would already be working but the time complexity would suffer a bit from the fact that when we call this depth first search here we don't have any checks in place to prevent the same depth first search to from happening later on like here so what we can do is uh prepare a memo so this is going to be a two dimensional array filled with empty arrays and when we run a depth first search in acell we memorize the value that is going to be returned in this memo so that we don't have to do that same depth first search again so what we need to do is check if the memo of this row of this column is defined so if it is defined return the memo value and now we just need to remember to update this value whenever we return a value from this function so the way we can do this very rapidly is to just return the assignment because the assignment returns the right value of the expression of the assignment expression so that's it we can submit the code and verify that it does indeed work and that's it for now so bye thank you
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
748
oh hey everybody this is Larry this is me doing an extra problem because we haven't uh how do I do this do a um yeah because we've already done the prom I guess we could have done the algor because I always worry about getting a random well it is or going be RNG it is day 18 or something like this I mean it's technically the 17th here in New York but hit the like button hit the Subscribe button join me on Discord especially if you like these kind of um extra problems and today we get a easier one with a lot of dam mod so we'll see uh how much we'll hate it but you know but as professionals you got to do work that you hate along with the work you hit like I mean you know uh don't have to be that entitled but uh but today's problem is 748 shortest completing work give Shing light and pray in a way of string words find the shortest completing words in Words a completing word is a word that contains all the letters in license play ignore the numbers and spaces in license player and treat letters as case and sensitive if a letter appears in more than once in license that must appear the word same number of times okay what is the ignore numbers and spaces okay and this is uh I so spst okay so shortest completing word con but only contain One S okay so steps contains it okay so basically huh so it doesn't have to be in the right order or anything that's kind of awkward I don't get the license plate idea like what does that have to do with anything I don't know maybe there's a story behind it and I'm curious but um all right well in any case uh yeah let's actually try solve the problem oh this one is a Yeezy H okay I mean I guess there's only a thousand words and each one only has 15 characters and the licensed player only have seven I was actually thinking about trying to think about like a more tougher scenario um I don't know if it's observable because given the Yeezy like it's not always like maybe there is just um like maybe it is really like if you have an N Square l a bang solution right like you know there's nothing you can do about it is just a easy and that's why it's n square or something like that right and yeah but this one I mean you know it is a easy app all so it is going to be just Pro Force um and just like follow the rules is what I would recommend doing right just like in real life I suppose um it may not be an interesting problem but it should be okay but uh yeah all right so basically I mean I think the first thing that I would do is given this license plate we would normalize the words um other or normalize the license play other words or lowercase huh so yeah so that's even better so we only have to nor normalize the license plate we can do something like um uh we'll keep track of it in the counter and then for see in license F uh we can just do like maybe already we convert it to lower and then if C is Alpha that means if it's from a to zed then we can do oh jeez I meant this as f as it's in frequency that's why I try to keep everything you know the same thing and then now uh for word and because we only have a th word each of 15 characters we can Pro for Bo Force this right so then here we can do maybe word frequency is equal to collections. counter of word and then basically the idea is that if everything in here uh n WF if um basically we want this to be a super set of F I think this is the this should be right as um a correct thing as super set then we can oh do we say the shortest completing word so if uh if this is the multiple return the first one that occurs okay fine okay so then here we have the shortest is equal to I don't know right like Z times 20 CU and I pick 20 because this is uh most 15 right so this will be the um like wor case so length of word is less than length of shortest then we can definitely choose shortest is equal to word else if length of word is equal to length of shortest then we don't do anything right because we do the first one that comes into place so we can actually skip this and then we just return shortest that should be good and let's give it a submit hopefully I didn't make a silly mistake and we look good we look Gucci um yeah what is the complexity here well this is going to be all of I mean let's just call this n maybe I don't know so this is O of n uh o of L maybe L could be also be the lame so it's a little bit awkward but yeah o of L this is O of n uh this is O of L also for each length and this is over um technically Alpha for the size of the alphabet because you only have 26 things at most but L is actually smaller than Alpha so inferior is also all of L but if you want to you know um par parametrize it'll be all of L plus Alpha right so but still very smaller right um but that's going to be all of n * par L plus Alpha Let Me Wait It hour * par L plus Alpha Let Me Wait It hour * par L plus Alpha Let Me Wait It hour what we doing oops uh a for Alpha maybe I need a quick keybo for time right and for space this is also just uh oops o of L plus Alpha space right same thing here right this is only has 26 elements at most or L elements and this as well so yeah um pretty straightforward I mean it is a easy problem whoops what did I click on uh it would be curious to think what it how to do the harder one um I don't know that I know how to do a harder one maybe you can do something like with a try or something like that um because no I mean I don't know that you I don't know that it um I mean there's some pruning that you can do but at the end of the day it's still all like o of alpha is not that expensive and even if you do like a hashing thing of on o of Alpha and even if you kind of like have a perfect try which like if you have a tri algorithm it would still be o of alpha so I don't know that you can do anything better than this I don't know that this is the lower bound um but it I don't have a easy way to think about a more optimized solution that isn't um yeah I guess there is actually um no but that was still no I mean I guess in that case it's not all of alpha cuz I guess like if you do if you're really careful and um you can kind of keep track of it for example you have frequency here so this is going to be all of l plus Alpha and then here we do it character by character and then we kind of almost like no that'll still be all of alpha space but it'll be all of L time but like but yeah but this being of L time it will still be I don't know I don't think you get away from all of n * don't think you get away from all of n * don't think you get away from all of n * L because oh yeah why am I saying it like that's silly like um the alpha is not the important part the fact that is of n * L is the lower the fact that is of n * L is the lower the fact that is of n * L is the lower bound because that's the size of the input I kind of confused myself the size of the input um because that is the number of total n * L roughly speaking number of total n * L roughly speaking number of total n * L roughly speaking is the total number of characters and words and we look at each character once so that's going to be lower bound right nothing about it I mean that is the lower bound you have to look at the input once okay so maybe I'm satisfied now U but yeah that's all I have for this one let me know what you think I mean there is some shorthand with this uh with these set notations um let me actually write a add a comment so WF is super set of F and that's pretty much it that's all I have for this one let me know what you think and yeah if you enjoyed this uh the extra problem please leave a comment I don't know if I want to continue doing these especially if no one cares about it right I mean maybe I still get a little bit out it but I don't know let me know uh but yeah thanks for watching stay good stay healthy to mental health I'll see yall later and take care bye-bye
Shortest Completing Word
largest-number-at-least-twice-of-others
Given a string `licensePlate` and an array of strings `words`, find the **shortest completing** word in `words`. A **completing** word is a word that **contains all the letters** in `licensePlate`. **Ignore numbers and spaces** in `licensePlate`, and treat letters as **case insensitive**. If a letter appears more than once in `licensePlate`, then it must appear in the word the same number of times or more. For example, if `licensePlate` `= "aBc 12c "`, then it contains letters `'a'`, `'b'` (ignoring case), and `'c'` twice. Possible **completing** words are `"abccdef "`, `"caaacab "`, and `"cbca "`. Return _the shortest **completing** word in_ `words`_._ It is guaranteed an answer exists. If there are multiple shortest **completing** words, return the **first** one that occurs in `words`. **Example 1:** **Input:** licensePlate = "1s3 PSt ", words = \[ "step ", "steps ", "stripe ", "stepple "\] **Output:** "steps " **Explanation:** licensePlate contains letters 's', 'p', 's' (ignoring case), and 't'. "step " contains 't' and 'p', but only contains 1 's'. "steps " contains 't', 'p', and both 's' characters. "stripe " is missing an 's'. "stepple " is missing an 's'. Since "steps " is the only word containing all the letters, that is the answer. **Example 2:** **Input:** licensePlate = "1s3 456 ", words = \[ "looks ", "pest ", "stew ", "show "\] **Output:** "pest " **Explanation:** licensePlate only contains the letter 's'. All the words contain 's', but among these "pest ", "stew ", and "show " are shortest. The answer is "pest " because it is the word that appears earliest of the 3. **Constraints:** * `1 <= licensePlate.length <= 7` * `licensePlate` contains digits, letters (uppercase or lowercase), or space `' '`. * `1 <= words.length <= 1000` * `1 <= words[i].length <= 15` * `words[i]` consists of lower case English letters.
Scan through the array to find the unique largest element `m`, keeping track of it's index `maxIndex`. Scan through the array again. If we find some `x != m` with `m < 2*x`, we should return `-1`. Otherwise, we should return `maxIndex`.
Array,Sorting
Easy
2274,2327
336
Ki A Hello Everyone Welcome To Date 30th June List Challenge And Aspirations Thailand Grand Prix Race In This Western Wear Giving Energy Of Words And Into Identifying Na Dharo Mix Subscribe ABCD One With Difficult To All Subscribe Follow Rock Play List Suzy 6 And Saffron Approach Problem All Possible And Weather Or Not Getting All Subscribe Skin Ko Subscribe That Time Complexity Is Point Red Chilli Anil Tried To Reduce The Complexity So The Solution Can Be Accepted All Its Limits Value And The Question It Subscribe Third Fourth Subscribe Id As Salads That First This Trick Sad Song Hydride All Others A Split B C D A B C D You Will Get DC Baby Straight Mid-2012 Unofficially Will DC Baby Straight Mid-2012 Unofficially Will DC Baby Straight Mid-2012 Unofficially Will Not Possible Acid Possible Solution Subscribe A For Example H L Du Bihar Impotent Similarly E Will Be Interested in This Possibility of Bird's Pencil Drawing of Bird's Pencil Subscribe Now to Identify the Subscribe Video That If Second Test Cases Pending Something Important To The Effigy and 1000 Test Cases on Thursday Minutes Ago That Anti Specific Report and MTS Suffix After Some Will Read Them Separately or that were similarly good in freedom struggle with phase they all want to learn to subscribe to play list that vijendra plate S1 into two parts left and right per diet part of S one is reversal of two cash withdrawal part of someone you will get to Five withdrawal person part subscribe and subscribe the Channel and subscirbe 's enemy this island of but not for telling them 's enemy this island of but not for telling them blind second condition states the white part of this lineage of birth of to do subscribe to who hear it matches chief verification of leadership sexual considering this 220 Vrat And Logic Of The Solution Now Electronics And Another Example Vihar Phase Pet Subscribe And Third Subscribe Inside Check Weather The Right Part Of One Is Reversal Of Students Not Withdraw It's True And Don't Thing Can Be Generated In Some Diploma Ki Tedhi That Aunt Being And should not be in the middle part of the mind Subscribe to I want special F1 price man slide I want special as descent reversal front part report as one ride with nothing but s2u I hope you understand this logic and without much Difficulty Section and Explain The Gautam Back Report Singh Top Down Did You Find My We Will Do the Answer List of Winners and Monitored Middling Removal Define a Map of Springs Commented That Will Produce Pair Input Mode The Video then subscribe to The Amazing Subscribe The Effigy Of A String Actress Cinema Expected To Blank IAEA Of Scientist Media Forget Her During Any Time Created Over All The Rings By Important Ise Zameer World Combination Subscribe School Side Per Subscribe Button Click The Just And Rest In The Second Half Just Reflection Case Do I Want To What Are The Advantages And All The Rings To Be Impotent Is Replaced Reverse Swing Of The Con Is The River In The Idy I'm Just Death Rudolph Case 2 Tricky Gas That Darkness Again He Was Treated With All His Words Very Important And Started Meeting Cut Certification Going After The Length Of The Thing Is Extracted Certificate Check On Website Weather Heart Fat This Year Android Notice Board The White Part Ko Subscribe This Video Hain Inke Is The White Part One Switzerland Roaming In The Nature Is Calculated The reverse part of the left wing and id in the map Drawstring subscribe Video in the middle that the one who purse me good songs soft power myth best friend its length terminator and note that end time complexity of this approach should be border of are in their swap instituted Aaf Ki In Square Ke Subha Reduce Time Complexity Of Difficulties Ki Android Price Of Ki Akshay Updated On 128 Watching This Video If You Are Interested Please Don't Forget To Like Share And Subscribe Our Channel Hai Ab Hridaya Ek And Thanks For Giving Me A Hua Hai
Palindrome Pairs
palindrome-pairs
You are given a **0-indexed** array of **unique** strings `words`. A **palindrome pair** is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return _an array of all the **palindrome pairs** of_ `words`. **Example 1:** **Input:** words = \[ "abcd ", "dcba ", "lls ", "s ", "sssll "\] **Output:** \[\[0,1\],\[1,0\],\[3,2\],\[2,4\]\] **Explanation:** The palindromes are \[ "abcddcba ", "dcbaabcd ", "slls ", "llssssll "\] **Example 2:** **Input:** words = \[ "bat ", "tab ", "cat "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "battab ", "tabbat "\] **Example 3:** **Input:** words = \[ "a ", " "\] **Output:** \[\[0,1\],\[1,0\]\] **Explanation:** The palindromes are \[ "a ", "a "\] **Constraints:** * `1 <= words.length <= 5000` * `0 <= words[i].length <= 300` * `words[i]` consists of lowercase English letters.
null
Array,Hash Table,String,Trie
Hard
5,214,2237
827
hey everybody this is larry this is day one of the august league daily challenge hit the like button hit the subscriber and join me on discord i'm gonna be doing this all month so you know do it with me and let's do it together i haven't i think i'm on um let's see 12 15 or 16 month streaks so you know let's keep going anyway today's problem is making a large island so i'm going to do this live so if it's a little bit slow or whatever just watch it 2x and 2x skip forward whatever you need to do because i am doing this live so okay so you have an m by n grid you could change one zero to one return to the size of the largest island and grid after applying this operation okay um this is an annoying problem bit but this is going to be a connectivity problem if you do this naively where you do you change every element knowing that any one side is going to be 500 so 500 squared and then that square so 500 to the cube is going to be too slow so you want something that lets you do this in uh n square where n is the number of sides or something like that and i think the for connectivity so the thing that you would think about is either first breakfast search that first search both of them i don't think it's going gonna be yeah both of them i don't think it's gonna be gucci and then in that case it's gonna be uh connected components but oh sorry union fine for connected components i think it doesn't really matter to be honest i think uh if you do breakfast search endeavor switch naively by changing every zero to a one then yes that's going to be the case but we can actually do a bit of a hack right um we can not a hack but you can solve it another way which is that we can do a connected components on the grid so count all the islands and then for each zero we just look up down left right and then do a set some of the islands and i think that should be good enough and what i mean by that is if you go up and then to the left and it's and these two things are at the same island then you don't add them twice so as long as you'll be being careful about stuff like this i think that should be okay so let's get started let's just do first by start doing um you can do this either using a different social preference search i don't think that matters um but yeah but they say first i'm going to color the grid um yeah i'm going to color the grid into basically without that first search you could do i mean very often actually do this with a breakfast search but let's try something new today maybe i go back and forth it really depends to be honest on how i do it so here let's just say one for rage okay and then now we just do that first x y and then a color right and then if colors of x y is equal to color and we return because we already changed the color if this is equal to one we return otherwise oh sorry if this is equal to zero we return otherwise we set the secret to color and then we have a directions this is just you know a standard thing i say it is a standard but this is basically um that's how i always write it because it's easier to write you could also just write two for loops to be honest um but it wouldn't matter so the way that i do it is that it is like two follow-ups into one array follow-ups into one array follow-ups into one array so i just do something like this and then you know this is just delta x delta y and then we check that and actually rows is equal to columns but i very often will just do the same thing anyway because right not and colors of x y is equal to one uh oh i guess actually yeah it's actually meant this to be great not colors so we want to make sure that the grid of x y is equal to one before we go then otherwise we just do this and then color yeah and that should be good i think so let's just start by you know current color is it going to see well do we want zero let's just do one right now let's start with one so it's less confusing for y in range of columns if grade of x y is equal to one and colors of x y is equal to negative one that means that we have to start coloring it then we color x y and then the kernel color and then we increment the color okay let's just kind of see how this goes first it's as we expected all right zero so this is one two because they're two colors so that's good let's also take this time to copy on more test cases i would say it was this it's a very it's a problem that is on the difficulty that is on an interview so definitely be sure to for your family will just get practice and so forth um yeah okay so this looks good these are the same color everything is the same color okay and then now we just have to count the colors and the buckets so you have done this with all these colors yeah let's do that here i think that should be good color count not just let's just do a counter too lazy too i mean you could put it in a way and then modify the size of that array but this is fine as well yeah so then now let's just print out color code counter is it counter color count okay so this looks good so far so then now we just have to go through um you know each way again this time looking at the zeros oh yeah um the largest item so let's actually get the largest island so far uh again it's just max of color count that value color counter again what i use um yeah and those there's no colors this may fail so we should double check that yeah because if you have for example i think this will give you a max cannot take something value whatever it's called okay we'll also give you think we didn't finish this so too soon yeah see so we could just do this plus zero say so this is just two arrays um i think that it's a little bit weird but i think that should be okay so that the answer is zero otherwise oh dick type values is not a list i guess that's like an in another type but okay fine this is very yucky now but that's okay uh yeah okay it doesn't crash so that's probably good enough okay now let's go back to here if the grid if this is zero then we can use this as a possible addition so that now we want to look at all four directions we have here so let's do that so for dxd ui and directions and x and y d same logic here which is that if this is a one then we want to add this current number to the thing um we're gonna uh let's just say use as you're gonna set i'm a little bit uh let's actually put this here instead so then now we have to get the color right so the n the color of n x and y is not in use that means that we haven't used this color yet otherwise we want to use this color uh this is so basically do right you don't want to add the same color multiple times hope that makes sense and then count is equal to this plus the count of the color i keep on writing color counter you always account a little bit and then at the very end we do max is going to max of max cow and then we just return past that should be good let's give it a spin one three four oh well okay that's weird isn't it maybe no well it gives us an opportunity to oh i see because i don't add to zero that i add so okay so given that this is zero this is this so this starts at one i don't know if that solves it because i think this answer is still wrong uh why is this so this is used that's weird okay let's take a look at the debugging actually mostly confident about this one but clearly sometimes confidence don't matter all right zero one why is this one did i make a typo somewhere oh yeah i did this is nx ny do i have it right here no i have it wrong here too so yeah wow huh mistakes were made uh oh yeah this color what is the color colors of nxmi okay so like i said typo aside this should be okay so let's give it a submit i think i got most of the edge cases just some of these the one that was adding this one actually a good one but yeah i think we're okay so let's give it a minute hopefully we're good a little bit slow down me okay so it's accepted so where's the complexity right uh with this depth research um you can see that even though this default search goes with this these two for loops and there's a lot of follow-ups here um you can see that each follow-ups here um you can see that each follow-ups here um you can see that each cell can only be colored once and because each cell can only be called once we only look at each cell constant number of times so that's going to be o of n squared where n is the size of the length and n squared is the size of the input so this is going to be linear time for this just that first search right and then here this is also linear time because us for x times y we do this thing and this is only you know direction is four so we only do four lookup set only has only up to four items and this is over one so this is going to be o of n squared which is linear time because linear because the size of the input is n squared so n squared is linear time so this is all of n squared um in terms of space well the way that i did it we did we select a color because we don't want to modify it i know that probably in the form of something someone makes a comment about um you know you use the grid so you don't have to use extra space but even in that case your that first search or your breakfast search is going to be you know in theory can go all through the entire matrix so it's going to be n squared which is again the near time so this is going to be linear sorry linear space so this is going to be a linear time linear space algorithm and what i mean by that is n squared time and square space just to be clear um that's all i have for this one let me know what you think um yeah i think that's what i have let me know what you think hit the like button to subscribe and drop me a discord again if you're doing this for august come hang out come on discord uh let me know what you think have a great day have a great rest of the weekend i'll see you later good mental health bye
Making A Large Island
expressive-words
You are given an `n x n` binary matrix `grid`. You are allowed to change **at most one** `0` to be `1`. Return _the size of the largest **island** in_ `grid` _after applying this operation_. An **island** is a 4-directionally connected group of `1`s. **Example 1:** **Input:** grid = \[\[1,0\],\[0,1\]\] **Output:** 3 **Explanation:** Change one 0 to 1 and connect two 1s, then we get an island with area = 3. **Example 2:** **Input:** grid = \[\[1,1\],\[1,0\]\] **Output:** 4 **Explanation:** Change the 0 to 1 and make the island bigger, only one island with area = 4. **Example 3:** **Input:** grid = \[\[1,1\],\[1,1\]\] **Output:** 4 **Explanation:** Can't change any 0 to 1, only one island with area = 4. **Constraints:** * `n == grid.length` * `n == grid[i].length` * `1 <= n <= 500` * `grid[i][j]` is either `0` or `1`.
null
Array,Two Pointers,String
Medium
null
1,721
how's it going everybody in this video i'm going to be walking you through a solution to leak code problem 1721 and it's swapping nodes in a to list so if we read the description real quick you're given the head of the list and it wants you to return the head of the list after swapping the kth value node from the start and the end of a one indexed linked list and by one index linked list they just mean instead of starting at zero they start at one this time so we can look at some of the input examples for this head we want to swap with k equals two which means we are going to swap one two we're going to swap this node with the second node from the back too so two and four are going to be switched and as you can see they're switched here if we go on farther k equals five we'll count one two three four five the seven and one two three four five from the back these seven and eights are going to be flipped so we can look at the resulting linked list that is the expected solution and we will see that instead of seven eight it is expecting eight and seven so there's a few ways to do this if you look into the hints they tell you that you can transform into an array and that should ease things up one solution would be to add all of your values into a list or an array and then you're going to need to map your one index to the zero index as most languages are zero indexed arrays just swap those two values and then rebuild the list this video is not going to cover that solution i'm going to go over i'm just doing it in place on the list as i think that it could actually be an easier solution um one thing that was pretty interesting to me when i was completing this problem is it seemed like it was going to be a lot harder than it should have been until i started programming it and i think the solution is really intuitive and once you see it you'll be able to understand it so getting started with this one thing that i think makes it a lot easier is just getting the overall length of the list you um if you know you need to swap like the k-th nodes the k-th nodes the k-th nodes it will help if you know the length of the list so i'm going to write a helper method at the bottom i'm going to call it get length and we are going to take a list node from this and return an integer and simply all we are going to do with this is create a pointer to our head and create um a size of the linked list we'll start at zero and i'll just say while temp um doesn't equal none and we're gonna go and iterate this and each time we iterate it we will increment the size and then at the end we can go ahead and return its size we can return the size so now at the top if i was to do length equals self.getlength with our head self.getlength with our head self.getlength with our head we can go ahead and print out the length of the length list just to double check that this is running properly so the length of the linked list says it's five and we'll see one two three four five so this is properly returning the size of the linked list with um with what we need so now that we have that it'll make it easier to um go through the list and be able to find our kth index from the beginning and the end this length really helps us find the end index since we kind of need to know the overall length of the list to know what the k-th node from the end is going what the k-th node from the end is going what the k-th node from the end is going to be so we can find that out doing um taking we'll take the minimum and the maximum for the first node and the last node index to get the position of the nodes so i'll just say get position of nodes to swap and i'll say something like um node one index and this will be the minimum of the k value so um the kth node and then we are going to take that with our length minus k plus one and then we're going to do the same thing too with our node two index the one from the k position to the end and we are going to take the maximum of k and the length minus k plus one so um we there's some adjusting for this that we're going to have to do uh for example right here because our list is a one index versus a zero indexed linked list so moving on from that we are going to create a pointer for both node one and node 2 and we're going to put them to the head so we're going to do node 1 equals head node 2 equals head and all we're going to do next is we're going to loop through the list and get the pointers into position so if you were to look at this input example right here we want to have a pointer we want to swap node 2 and node 4. so all we want to do is iterate this list and get one pointer sitting on this node and then iterate the list again and get another pointer sitting on this node and then once we have that we can simply swap the values between these two nodes and the process is already complete it is a lot simpler than it seems like it should be but it's actually not so we are going to loop lists for position of target nodes so we'll just run um a for loop and we're going to do a for loop in range node one index minus one and all we're going to do is node one equals node one dot next and then we're going to do the same thing to get our second note in position so then we're going to do a for loop for node 2 index -1 node 2 index -1 node 2 index -1 and we're gonna go ahead and iterate that too so like i said once before we are getting the position now that we know the length of this overall list we are getting the position for where our two nodes need to be so we know we need this node this two node and this four node so we're iterating a pointer for this node and then we're going to go over the list again and iterate a pointer for the number 4 node and then once we have that we can simply swap the values in between so lastly what comes up is swapping the node values i can do some debugging real quick to make sure that we are at the correct values so i'll go ahead and do that so we'll say print value of node 1. and no two just to make sure that we are doing everything correctly so the value of node two is or node 1 is 2 and the value of node 2 is 4 so everything is running smooth so far so all to do last is to swap the values in between with python you can use um kind of the swapping syntax i'm going to use if you're using another language you might be able to use a swap function from a standard library or something else or you can simply just create a temporary value of whatever the type is and then swap them over but for python i'm just going to do node1.val no 2.val node1.val no 2.val node1.val no 2.val equals no 2.val comma equals no 2.val comma equals no 2.val comma 1.0 and all this is doing is putting the 1.0 and all this is doing is putting the 1.0 and all this is doing is putting the contents from node one into node two and the contents of node two and the new into node one and then lastly all we have left to do is to return the head of the linked list well since we are using pointers pointing to the head we have never even moved the head of the linked list so we can just return the head so this is the code um i'll go ahead and run it and we have saved space doing this is constant space this is one space and this is big o of n complexity since we are simply running a for loop through um the range of the loop we never have to do any sort of nested for loops we don't have to allocate any memory to hold all the contents so this is a clean and simple solution to solve this problem if you have any questions feel free to drop them below if you have any particular leak code questions that you are stumped on and want a solution for drop those below in the comments otherwise have a great day or great night thanks for stopping by you
Swapping Nodes in a Linked List
maximum-profit-of-operating-a-centennial-wheel
You are given the `head` of a linked list, and an integer `k`. Return _the head of the linked list after **swapping** the values of the_ `kth` _node from the beginning and the_ `kth` _node from the end (the list is **1-indexed**)._ **Example 1:** **Input:** head = \[1,2,3,4,5\], k = 2 **Output:** \[1,4,3,2,5\] **Example 2:** **Input:** head = \[7,9,6,6,7,8,3,0,9,5\], k = 5 **Output:** \[7,9,6,6,8,7,3,0,9,5\] **Constraints:** * The number of nodes in the list is `n`. * `1 <= k <= n <= 105` * `0 <= Node.val <= 100`
Think simulation Note that the number of turns will never be more than 50 / 4 * n
Array,Simulation
Medium
null
160
hey guys rob here from brevity and in this video we're going to be solving one of amazon's most favorite questions the intersection point of two linked lists first of all congratulations on making it to week three glad to see you didn't give up are you enjoying the song for learning environment on youtube and discord if so do let us know in the comment section down below week three is going to be really exciting as we delve into more two-pointer algorithms two-pointer algorithms two-pointer algorithms and you have more of those oh my god moments as you realize how useful they are in the upcoming need problems if you haven't subscribed yet do hit that subscribe button to make sure that you don't miss it so the problem that we're solving today has been asked in amazon microsoft and oracle and the first step to solve any problem is to carefully read the problem statement and understand it so let's go to lead code and see what this problem statement is so here we are in lead code and we can see the problem statement is as follows write a program to find a node at which the intersection of two singly linked list begins for example in the following two linked lists a1 a2 c1 c2 c3 and b1 b2 b3 c two c three they begin to intersect at node c one now visually this is very easy but how can we implement an algorithm to make this work fire boy and water girl will meet again if you have no idea what i'm talking about check out this video where vignesh is going to talk about this algorithm in detail and is absolutely necessary in order to understand the code which i'm about to write go watch it i'll wait exactly are you back okay let's continue so the first thing i have to do is declare two pointers which point to head a and head b let me say this node point a is equal to head a and this node pointer b next while these two pointers are not equal so while pointer b is not equal to pointer a we are going to um go inside the while loop now what you have to check is if currently pointer a points to null or not so if pointer a equal to null then we have to make pointer a point to head b as discussed earlier so pointer a will now be equal to head b and if pointer a is not equal to null then all we have to do is uh make pointer a point to the next element the next node so that's going to be pointer a equal to pointer a dot next all right so that's all we have to do for pointer a and now we can just copy paste this and we can do a similar thing for pointer b so pointer b is now pointing to null then we have to say that point of b equals head a similarly uh if it's not pointing to null then pointer b equal to pointer b dot next right and if we get out of this while loop that means that we have found the intersection point so all you have to do is return either pointer b or point array let me return pointer a in this case and let us try running the code okay we can see there are no compilation errors let's submit the code we can see that the code passed with a very good time and space complexity now if we had to discuss about it the time complexity for this solution will be o of n where n is the sum of the lengths of both the lists because that is the worst case time complexity at the same time the space complexity is going to be of one this is because we did not allocate any special memory for any sort of data structures we did not use a hash set we didn't use an array list so we have only used constant space because we have declared two pointers and whenever we declare only pointers keep in mind that we're using only constant space memory this means that we have an o of one space complexity solution and that's it for this video hope you guys enjoyed it tomorrow we'll be dropping the more zeros problem which is another interesting application of the two pointer algorithm stay tuned for that and more on that note this was rob you're watching brevity thank you and goodbye
Intersection of Two Linked Lists
intersection-of-two-linked-lists
Given the heads of two singly linked-lists `headA` and `headB`, return _the node at which the two lists intersect_. If the two linked lists have no intersection at all, return `null`. For example, the following two linked lists begin to intersect at node `c1`: The test cases are generated such that there are no cycles anywhere in the entire linked structure. **Note** that the linked lists must **retain their original structure** after the function returns. **Custom Judge:** The inputs to the **judge** are given as follows (your program is **not** given these inputs): * `intersectVal` - The value of the node where the intersection occurs. This is `0` if there is no intersected node. * `listA` - The first linked list. * `listB` - The second linked list. * `skipA` - The number of nodes to skip ahead in `listA` (starting from the head) to get to the intersected node. * `skipB` - The number of nodes to skip ahead in `listB` (starting from the head) to get to the intersected node. The judge will then create the linked structure based on these inputs and pass the two heads, `headA` and `headB` to your program. If you correctly return the intersected node, then your solution will be **accepted**. **Example 1:** **Input:** intersectVal = 8, listA = \[4,1,8,4,5\], listB = \[5,6,1,8,4,5\], skipA = 2, skipB = 3 **Output:** Intersected at '8' **Explanation:** The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[4,1,8,4,5\]. From the head of B, it reads as \[5,6,1,8,4,5\]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. **Example 2:** **Input:** intersectVal = 2, listA = \[1,9,1,2,4\], listB = \[3,2,4\], skipA = 3, skipB = 1 **Output:** Intersected at '2' **Explanation:** The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as \[1,9,1,2,4\]. From the head of B, it reads as \[3,2,4\]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. **Example 3:** **Input:** intersectVal = 0, listA = \[2,6,4\], listB = \[1,5\], skipA = 3, skipB = 2 **Output:** No intersection **Explanation:** From the head of A, it reads as \[2,6,4\]. From the head of B, it reads as \[1,5\]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. Explanation: The two lists do not intersect, so return null. **Constraints:** * The number of nodes of `listA` is in the `m`. * The number of nodes of `listB` is in the `n`. * `1 <= m, n <= 3 * 104` * `1 <= Node.val <= 105` * `0 <= skipA < m` * `0 <= skipB < n` * `intersectVal` is `0` if `listA` and `listB` do not intersect. * `intersectVal == listA[skipA] == listB[skipB]` if `listA` and `listB` intersect. **Follow up:** Could you write a solution that runs in `O(m + n)` time and use only `O(1)` memory?
null
Hash Table,Linked List,Two Pointers
Easy
599
171
hey YouTube welcome back today we have this problem um Excel sheet column number uh given a string column title that represent the column title as it appears in an Excel sheet return its corresponding column number for example a equals 1 b equals 2 C equals 3 Z equals 26 A equals 27 a b equals 28 so on so forth um and basically if we have like column A I guess to be in the first one a B I guess would be on 28 and so on so forth so although it looks quite easy but it's not that easy at all because uh if we put let's say that we are putting um the for example we put in the let's take an um a string for example like a z c how we can know that how can we know the which column this one is there physically and I guess it looks quite hard but it's a pretty straightforward but once we understand this table so basically we have this table that we already said that first we have a table that from one column it's uh it's so like ABC and the other one from a b AC until is it and b a b uh b c and so on so forth so basically that just to understand this column the first one the first column the green one it's about it's from one chart it's 26. the other one is from two charts so it's 26 multiplied by 26 okay and the third one it is um it will be this number 60 multiplied by 26. and this one because it's one chart and this one I guess it will take this title it will be 1 7 5 uh one seven five seven six multiplied by 26. and the thing that we should see here is that um each um physically each character category it's just it's a part of its previous one so the electronics motorbike electronics and the other one it's its previous one multiplied by 26 and the four characters is basically the Third characters multiplied by 26 and um basically it just um and physically that's it's physically about how we can get like right now you understand how the table works basically so how we can get this the position of the string so we got the position in this string by break it basically into four different uh characters so basically we start from uh for from four things first a it's we have four characters so a it will be in the in it's a four character uh it's in the full Niche so to get it actually it will be a um at Plus uh Z and we have other two characters Plus Z plus c what that means basically uh so basically it will be I guess uh we um like it basically here actually we are representing is it's physically we go with from block to the smaller blocks basically and um basically um for each block we have multiplied by 26 so yeah basically that's it like we have um if you want to scan this one it will be C to get the value of C we start from the innermost the smallest one so C and this will be uh the C position is three multiplied by um uh I guess C it's multiplied by three by one I guess it will equals a three so as the results it will be let's see that we have or it will equal zero plus three because it starts with 0. and I guess um Zed the second this one it will equals um I guess it will equal uh 26 uh multiplied by uh um 26 because it's the second one and India basically because actually it's in the Lost position so it will be 600 sorry is 600 176 and this the second did it will equal um 26 multiplied by um uh multiplied by let's go back here it will be multiplied boy 676. yeah it's because it's the third con and basically it will equals uh it will equals 1 7 . . . 5 7 6 and I guess the last one it will be the a let's just do that here we have the a the AIDS have a third it's in the third block so it will be um uh we have let's just see again it's multiplied by this number it will be there is first so it's one multiplied by uh um one seven five seven six we take this number each one if you see each one will take this number from here so it will equal um you know it looks a big very big number it's just a three five uh eight three one and basically we add all of these numbers to R specifically Plus plus six seven six plus uh one seven five seven six plus uh three five eight three one three five three eight one and we will have our own number which will be uh wait a minute no it's [Laughter] [Laughter] [Laughter] one seven five six seven six this is not right it's because of multiplying by one this number it will be the results I made a problem with my calculations three five eight three one so basically how we can do that how we can do this calculation because this is how actually we will build this calculation so basically one of the things that we can do we will first of all we create a table and restore all of the this we will store this in it and basically what we can go through we will get the character from the from right and after that we get its position and uh we when we get this position we basically um if you see this one we have 26 okay and we have here 62 and 60 676 and 676 basically it's a 26 multiplied by 26. so basically if you are in the third or the second basically you have 26 and we multiply it by your index like if we have two uh for example uh give it like 26 and we put the power of your index so it will be two or three or four whatever it is based on your index so let's just go to here so first of all let's just start with the lit result equals zero and we return this result okay return and we say let's just start I will say the const the alphabet map which equals a new map end of the what is the colors is not good in the mid yeah I guess this is much better um it's equals a new map I will say that I'll make a for Loop first I wanna store the map so it will be four let I equals zero uh um I less than 26 because we only have 26 numbers just I plus and let's just put the I will say const c for character will equals I plus 65 uh basically this is the dimensional but like each character has uh has a unique number for example a is 60 65 B is uh B is um is uh is 66 things like that so basically we give each character its number basically so I guess the Alpha map wool that's it we'll put the we put the actual string dot four character code of C and we will have it will be oi plus one basically if you want to get the character so basically if I equals zero and the code it will be equal to 65 this one will be a basically that's what we're doing and um yeah that's it basically in the saving the table and let's just start to add to basically find the actual uh character so let oil equals zero okay I less than is Dot length minus this is an insta length minus one all the less than length no I guess it will listen is because we will get all of the characters basically and I will say I plus all right or okay I will say uh const I will get the current character I'll just current const the current and as we said we start from the right so it will be s dot a character ads add and it will be um n minus 1 minus I because we're going to start from the far right you know what I can just say is minus one like there is no need to make it and I will say um results or it will equal we will add to result is that first of all I'll take the alpha dot get the character and the character number physically because we add the character number and what we do right now we add we have the character number and actually we multiply it by the 26 and it's a block so if we looked at this one again here for this one we had 26 the position of Z is 26 okay and it's a plug it's it has the first block so it will be 26 and was in The Power of One so you get this one you get this why we did it like that so basically it will be um math dot poll um 26 um in power of OI and I guess that's it's not the function why ah it's a form not from sorry double m ah why wrong answer length a kiss maybe because I guess this will not work although wait a minute what in actually what animals do minus one not just you well it's not working why okay let's just give it um give it a quick look we have um first of all I will be less than length because we want to get all the numbers and because when I get the least most one so it will be oh minus less minus one and uh and we have the current and we have this one and ah we multiply it sorry I just not good this one not good oh sorry because I'm sort from the far right look okay so there's something weird with lead code like right now I'm beating 81. the same solution was 34. just it's just sometimes liquid has the same things that I don't understand but however we find the solution and um the thing that if someone doesn't understand why we did it like that basically because when we get the actual strings we're getting from the far right and basically we don't want to make a minus one because if one minus one I will not uh um physically because when we stored the actual uh titles and we add one because we don't we can have zeros for this one because in the multiplies it will screw all of things up so what we can do is just we add one so basically we do we don't uh go with zeros anymore so we just s dot length that's it and so that's it for this solution I hope you like my solution and uh if you like my solution just subscribe to the channel and make sure to give me a thumbs up and then hit the notification Bell so you will never miss a video and that's it for today's video see you soon
Excel Sheet Column Number
excel-sheet-column-number
Given a string `columnTitle` that represents the column title as appears in an Excel sheet, return _its corresponding column number_. For example: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... **Example 1:** **Input:** columnTitle = "A " **Output:** 1 **Example 2:** **Input:** columnTitle = "AB " **Output:** 28 **Example 3:** **Input:** columnTitle = "ZY " **Output:** 701 **Constraints:** * `1 <= columnTitle.length <= 7` * `columnTitle` consists only of uppercase English letters. * `columnTitle` is in the range `[ "A ", "FXSHRXW "]`.
null
Math,String
Easy
168,2304
1,171
Hello friends, today we are going to solve a problem. Today's question was asked. What is the question of the problem? What is the question? Today's question is given below. The test tells us how to approach the question. Think about the code. What kind of code should it be? Let's understand what we have to do, let's assume that we have given zero, the head of which is starting from N, whatever sum inside it is coming to zero, let's say Apple on Y. This one we grab t min y because if you do 1 p that is and 3 min 3 f e equal t 0 the sum of these three i's till zero index is zero so we get the output. We have to provide the internal one s output and that too in the linklist form and we can also provide two. Even if you have a different approach or algorithm then you can provide that also or you can see how the two came or what did they do in mine and 3 if If you sum and come to zero, then two will be proper link. If we talk about the example in this, then it is the same. If you sum and minus, if you sum and come to zero, then this will be the final output. So let's discuss its approach once. Let's do it, how is it going to happen, so once I show it in paint, how to make it OK in paint, oh, this is end, and this is end, that is connecting the tap, and the one that is on is head, basically that is the parameter passed. You can see that this link is listed and parameter one is passed on zero, so what to do to solve the approach, so what we have to do for that, simply, to do this approach, we take it from zero. The elasticity man will do it while doing it while the team is trying to reach zero. The point will show whether the connection is broken or the connection is broken, then again the connection is broken again till we do not get it, so what we have to do is to make it and connect it with it. Hey, let's curt it, let's give it OK, let's take it to zero, let's say we have done it, don't do it, OK, now do it, and inside the current, we can easily do curt and let's do it, if we do it. It's done OK, now it's here, it's next, it's going to go back to where it's going to be, as if it's done, then it's going to zero, so what we have to do is simple, if it's head right, then head's which is next. Yes, it will be equal to the next of m, the middle will break, connect OK, so now or then we have to check back, this is the sum of both of them until the current is not equal to the tap hack tap, the current is also not equal to zero, again and again we While pushing the curve, write the code below to push it. Okay, so first what we have to do is to create a list node. Create a new list node by customizing it, clean the end dummy with one and define it to be a and name it. O A I have made a dummy so I have to connect with the lead ok so yes ok mummy to connect sate current dot next equal to head connected to the head yes the code is telling current is current about to be connected to connect To do this, we have to go straight till the current which is equal to its sum. If we do not find zero then there is current inside it. Current is not equal to two. Then run this sum. It will be equal to zero and ok, so the sum is done, so what do we do to run the item and check this sum, I have defined this and the current also has to keep moving forward, so for that, I have to add the sum to move forward. What to do is to make current equal to current next or I have done it and there is one thing like what should we keep for that, we should not make a single list, we should also make equal to two equal to where we are going to keep it. Will put it in front of current, so current should be next. Now the one going from current to tap is done. Now I am not getting even value in between while going from m to tap. I will have to make wa for that also and make another wa loop. Inside this, we will have to keep moving further and this means we have to write this is sum is plus equal to, what will happen if a is equal to here, how if we get the dial, start the semicalculation and In the mean time, if I am equal, I get s, what do I have to do, current is next, I have to do, if in these cases, suppose y, at y, my value is equal to zero, because this is what is happening. If my current is current ok then current will run on ya from ya it will run ya will make the connection otherwise if there is current then this connection will be made then what should we do if the connection will be made We have to wait because if it comes then there is no other chance, if the sum becomes equal to zero then this is the proper answer, so what do we have to do here, the final output will be coming something like this is zero is connected to three and It is connected to one and one is connected to the tap or from the tap to the tap. That's it, I have already done it, just fix it, what do I have to do, what should I return, do the next step, just run it and see if it is cooked. I would have done three tests to see if the code is running or not, ok so, but an error is coming, number 39, dummy, first check it, ok, capital hell, now submit and see what comes out, ok so. This test run has also been done and passed and this is a kind of best approach also, many of its approaches are simple approach but this is simple through linklist, do not keep any extra space and bust and easy code ok thank you bye
Remove Zero Sum Consecutive Nodes from Linked List
shortest-path-in-binary-matrix
Given the `head` of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0` until there are no such sequences. After doing so, return the head of the final linked list. You may return any such answer. (Note that in the examples below, all sequences are serializations of `ListNode` objects.) **Example 1:** **Input:** head = \[1,2,-3,3,1\] **Output:** \[3,1\] **Note:** The answer \[1,2,1\] would also be accepted. **Example 2:** **Input:** head = \[1,2,3,-3,4\] **Output:** \[1,2,4\] **Example 3:** **Input:** head = \[1,2,3,-3,-2\] **Output:** \[1\] **Constraints:** * The given linked list will contain between `1` and `1000` nodes. * Each node in the linked list has `-1000 <= node.val <= 1000`.
Do a breadth first search to find the shortest path.
Array,Breadth-First Search,Matrix
Medium
null
1,512
i'm going over a number of good pairs and uh we will use a same input given here which is here blue is index red is value and i use the mem is 101 i mean size is 101 but to make life simple i'll just use five so uh let's start um it's okay first visit um index zero right okay i have a value on and do i have any pairs so for zero okay no okay value one i'm gonna map to index one of man and now add one here okay next one right here second one okay do i have any pairs in the second one i mean uh index two okay i go here uh no i do not but let me record i had a value too and the same thing here okay three no appears okay now this one if i go um index one of men i already have one which is coming from this guy right so yes we found a pair which is index zero three uh sorry it's black and black you're gonna see but i'm pointing here uh because index zero and three right so we will get we will add a one two some uh i'm so lazy let's do this all right okay and let me uh change uh what was it uh here let me change okay we had a value of once twice now okay now i'm going to next one okay if we visit um mem1 okay we have two we have to add two reason is um okay so we already have uh two ones right this is index zero and what was it index three okay new guy whatever it is index four right so reason why we add um two is okay we can get two new pairs this guy and this guy's new right so that's why we add two here and then okay let me update this table to three and i go to um three here right oh i already have one and which is coming from this guy right so let me add plus one now let me update it to two then you get total return of a 4. let's just output this for that and uh just extra let's say we have one more and um let's say we have one again so what's gonna happen is we get one here right so we get three new pairs here and here then it'll be plus three uh that's pretty much what's going on uh hope you guys uh get it um thank you for watching
Number of Good Pairs
design-underground-system
Given an array of integers `nums`, return _the number of **good pairs**_. A pair `(i, j)` is called _good_ if `nums[i] == nums[j]` and `i` < `j`. **Example 1:** **Input:** nums = \[1,2,3,1,1,3\] **Output:** 4 **Explanation:** There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed. **Example 2:** **Input:** nums = \[1,1,1,1\] **Output:** 6 **Explanation:** Each pair in the array are _good_. **Example 3:** **Input:** nums = \[1,2,3\] **Output:** 0 **Constraints:** * `1 <= nums.length <= 100` * `1 <= nums[i] <= 100`
Use two hash tables. The first to save the check-in time for a customer and the second to update the total time between two stations.
Hash Table,String,Design
Medium
2285
1,896
hey everybody this is larry this is me going with q4 of the bi-weekly me going with q4 of the bi-weekly me going with q4 of the bi-weekly contest 54 minimum cost to change the final value of expression so this was a very really hard problem um i have solved this before which is how i am able to solve and even then i actually solved another version of this or at least an incorrect version of this that i had to spend some time kind of uh changing it into it but the cool thing to notice for this problem um and the first thing that you should do for is to hit the like button hit the subscribe button join me on discord where we talk about contest problems right after the contest so if you're into doing contests um join because the more the merrier because i like chatting about these things as you know as a nerd would but um but yeah so yeah uh for this problem the key thing to note is that every step of the way the only two solution right there's only you can either get a one or a zero so that's the key thing to notice and then the second thing is that um and then after that it the other um the other prerequisite for this problem is just trying to um it's knowing how to solve a problem using infection notation so that's a prerequisite i'm not going to get into that part that much um i use the stack implementation um if you look at other top people's solution they have done it with uh that first search and that's fine as well um and these are things to kind of google and look up because i you know uh it's a little bit tricky but the idea and this is a very easy this is a relatively easy it's not a easy one but it's a relatively easy um expression uh in fixed expression to pause which is that you know you have these things and then you go from left to right other with parentheses so every time you see a left parenthesis you can match up with the right parentheses and then match and then do it and then solve the answer for everything in the middle and then after you do all that you go from left to right on everything as well uh the key thing to know again is that um is that the only two possible solutions for every expression no matter how complicated which is a zero and one so the idea here is to keep track of the cost of flipping the answer from zero to one um it's kind of like dynamic programming but it's very um in the sense that you know um you keep track of okay what's the minimum cost to go to one and what's the minimum cost of going to zero uh or the other way around and because um so you're gonna get two answers at the end um one is just your original answer like whatever this thing would have evaluate to anyway and then the other answer is the number is the cost that it would take um i did this in a funky way because i was hacking a solution that i had which was a little bit off so i don't know that i would do it this way if i had to do it live again um but um let's go over the code right i did it again with a stack you can do this with a recursion so an implicit stack as well which is what i see a lot of people did and probably i should have done uh because going from left to right i had some issues there but that said it's a you know let's go for it right so now this is already exp um yeah if this looks confusing to you like i said you have to practice in fix notation parsing so that part like there's a lot of um understanding and they were true about it so i'm not gonna get into it that much but yeah for each character in these in the expression um this is the meat part so we're gonna skip for a quick second but if it's a zero or one we put it into the array we put it in the stack and what does this mean right like i said so the stack will contain two things um which i haven't talked about yet so not like i said but one is um the cost of going to zero and the cost of changing to one so if this is if the number we see is zero then you know it costs zero to go to 0 and it costs 1 to change it to 1. um now in uh conversely or inversely if this is if the num if the thing that we're parsing is a 1 then it causes one operation to change it to zero and zero operation to change it to one right so these are our base case if you want to call it that um and if it's a left paren i so i added this in a little later it looks a little bit funky i know but yeah but otherwise we put the opera either the operator which is an n or an or that's a really weird statement uh basically the two operators that the bitwise operators that we have we append it or we append the left parenthesis wow that's a mouthful anyway so then this is the meat of the problem right which is the right what happens when we process it right so the thing that i do is that okay so i have a thing to process um so until we see the left paren i push everything into the thing that we have to process now um and then we pop because this pop is just to get rid of the left parens at the very end so okay so basically we're going from left to right and again because i'm uh copying code from a previous thing so this is a little bit awkward because the original one uh they're all binary like all the operations are binary instead of this like chain kind of thing so it's a little bit awkward it's my so yeah so i do it backwards with respect of popping but if i go from left to right this would have been um the way to go pretty much uh yeah because here like i inverted this one intentionally so that i could invert it again because like i said the this is just me doing it the original way so that's a little bit awkward um yeah anyway and i have my video of me quote unquote solving it during the contest i did solve this one during a previous contest so it's not like i'm cheating by copying someone else's code i'm grabbing my own code like so you know with my comments as you can see but yeah so now as we see um now that now we have a binary operation right we have the operation that's in the middle which is the up and then we have the number of edits to get the zero on the a side and then on the oh this is on the b side whoops yeah so now you have some operation you know a of b and yeah and this is basically is self-explanatory with respect to i is self-explanatory with respect to i is self-explanatory with respect to i have comments so this is just as we said before in the stack uh the number of edits to get to a to zero the number of edits to get to one of these should be zero of course um just by what we talked about by default um but that shouldn't matter in either case so we have the operation here and then the same thing for b and then here we just have the new answer i don't know why i said it to none i don't think i think it's just so that i don't get confused but yeah but and then at this point it just becomes rick sausage and what do i mean by exhaustive it means just going through the cost of every possible way of going to the cost because there's three things that you can change given this thing right you can change you can either change a you can either change b or you could change the operator and that's basically what i do here um is that yeah so this is the new number of z uh new number of zeros so if um if our new digit is zero so the minimum way to get to zero is either gonna be okay the number of edits to get oh yeah let me step back a second so this is for the or operation right so everything is or so if you have zero or zero then you already you're gonna get a zero so that means that you don't need any operation so that's basically the way that uh you know we go how do you get a one well yeah and this is i think the comment here talks about it pretty deeply which is that okay we take the cheapest way to get to a one by okay if we have you know the uh yeah the cheapest way to get to the one is you go two if a is zero and b is one so that's the number of costs here that's the cost of a getting already at zero b already at one um or a is equal to zero b is already at zero oh sorry a is equal to zero a and b are both ones so a or b is equal to one so that's just the cost there or you know this thing right um so these are our base cases if you will um because that requires no edits that's just taking the minimum path uh and then here this these are the paths with edits so yeah this is a lot of things to say so but this is just going for all the possible cases uh literally so i don't do anything fancy here you can maybe add some for loops to make this easier but this is how i did it um so yeah so now news the number of zeros is equal to well what we had previously here or um yeah if a is zero b is one then to get zero you have to change b of zero uh you have to change b to zero so the cost of that um is going to be equal to b zero right also here uh i'm saying it incorrectly so the cost of that is equal to b1 because um yeah because that's the cost so you have to change all the things there to get to one right um because if you have to change every number on the b side um this is going to be the cost uh conversely um yeah if a is 1 and b is zero then it costs a of zero to change it to zero that's basically the idea i don't know that i'm going for the explanation really correctly but hopefully uh it makes sense uh but basically we're just going for every possibility like i said i'm going for it really uh in this video uh but yeah and then if we want the answer to be a one then either it is already a one that we get from here or uh if they're previously zeros so if a then we have to change either b to a one or a to a one so that's the cost because that's literally how we define it right that's the minimum cost to change it to that digit in that place um yeah and of course lastly we can also change the sign we can get the zero if we change the or to an n and it will cause one to change the operation right so that's just you know if um yeah i think this is obviously i kept this part for symmetry reasons but yeah if you have uh if you want to change to an or to an n then what happens well if they're both 0 then 0 and 0 is still 0 and 1 is equal to 0 and 0 and yeah and one and zero uh is equal to zero this is just bitwise things and then if you change it to an or oh sorry yeah if you change this to an n then that would be your cost of doing zero and of course you take the min uh otherwise uh this is the same which is that um yeah this will never be true because this is by definition um this is by definition here so this is always going to be bigger but as i mentioned in the comment i'm here for symmetry because i do something similar on the because on the n side you do something similar that's basically it but uh but yeah i'm not gonna go over these logic here but that's for the n side but yeah so basically it is dynamic programming in the way that you just take the minimum of all the possibilities on the transitions so that's basically the idea uh i hope that i explained it okay um but yeah uh and because you know um because we keep track of and at the very end we processed it and we put the number of so now this is the number the minimum number of changes or operations or changes edits to get to zero and this is the number of uh edits to get to one and then we add that to the process uh we push this back into the stack and then we keep on processing while we are processed and then after all the process is done we should have one element left and then we put it back on the stack and then we loop again on an on a kind of like a recursive kind of way um that's all i have uh let me know what you think it's very long it's very hard but uh but i think the core ideas i explain even if the code is a little bit yucky and maybe confusing i hope that makes sense so to go over again the core ideas is that notice that every step of the way you know keep track of the minimum number of edits to get to zero and one and then just kind of do the infix operation based on that um so what is the complexity of this right i know that i have some while loops here and a for loop here but it is going to be o of n in linear time and you need to because n is 10 to the fifth this is linear time because for every element you only push and pop a couple of times uh you push a pop on this stack once and you push and pop on this stack once so you're only doing a constant number pushing and popping per eliminate per element so that is going to be linear time and for space it's linear space because we have two stacks um again you don't really need it the way that i did it but yeah uh that's all i have for this one uh yeah that's all i have for this one let me know what you think you could watch me kindness of this live next but i think i actually spent about 40 minutes on the original prom and then i spent about 20 minutes uh making it work for this problem so if you want to say i probably took an hour on this one so i would not been able to solve this uh only because i spent too long on q3 but i mean i had the idea for this one but i've even during the original contest but i think it's just very easy to get this wrong as you can kind of see um but yeah that's all i have if you like it please hit the like button or subscribe button or whatever you need to do i will see you later uh you can watch me stop it live or hack this live next in two minutes okay let's see if i could get this real quick oh my what i wrote a tutorial on this so on binary search i think maybe i wrote it i don't know i don't so yeah answers dynamic programming and binary search changed the way that they did stuff no just give me my what give me my editorials so we've gotten this really quickly actually but assuming it's the same problem but i cannot get this one so hmm i mean i think i did it pretty okay during the contest too but okay so this is wrong maybe this is not the same statement what are we doing hmm do maybe i misunderstood this one no i mean why is this through a do they change the cost function why is this not two here's two under binary search so i don't even know i can't get anything right today even when i have to answer why is this true so maybe i have a typo and this is a this gets ac on binary search maybe the binary search solution that i had is incorrect but this is going to be impossible to debug man i cannot do anything right today okay so okay this is a struggle fx2 okay it takes two to shift here huh why do i have an extra finger what okay so this is mostly right but it's just not combining in a good way but why is that like why does it have two things oh man i am really bad today even copy and pasting code my old code is wrong but i don't get it oh i see the reason why my code is wrong is because they have a thing where they don't prevent parenthesize everything okay so that's what's different about this one um they changed it just a little bit annoying enough okay how do i fix it so in the original solution they would have something like parenthesized like this so i think i just had to hmm so it's only those when we append this okay how do i debug or how do i make this thing so on this we only takes two operations but we need to keep doing this until it is the thing right i hope that's right okay so here we have pent so this will mess up that's fine um um maybe not um maybe it would have been faster if i just start from scratch okay well that's fun but not quite the answer i'm looking for sadness so hmm why how oh how okay oh this is small this is one so that's a choice to do okay now it is more correct what's my print statement i have another print statement here that's kind of funny though that actually my solution was wrong and the other one i just yeah well oh and that doesn't even have to have operations wow i guess this is a tough tougher variation than i expected but i think the idea is right it's just i am not going to get this one probably huh it's kind of funny yeah could have gone this way quickly if i uh yeah poop serve all these things and to combine them right but okay so it does get combined just not in a good way well i think the reason is because now we have to do it left to right within the parents um but i'm not doing that i'm doing it from right to left which probably gives me the wrong answer as a result um this is going to be a mess okay let's do something a little bit funky you so okay so i think i fixed it i don't know if it's gonna be fast enough but at this point i have nothing to lose okay um i
Minimum Cost to Change the Final Value of Expression
maximum-score-from-performing-multiplication-operations
You are given a **valid** boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise **AND** operator),`'|'` (bitwise **OR** operator),`'('`, and `')'`. * For example, `"()1|1 "` and `"(1)&() "` are **not valid** while `"1 "`, `"(((1))|(0)) "`, and `"1|(0&(1)) "` are **valid** expressions. Return _the **minimum cost** to change the final value of the expression_. * For example, if `expression = "1|1|(0&0)&1 "`, its **value** is `1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1`. We want to apply operations so that the **new** expression evaluates to `0`. The **cost** of changing the final value of an expression is the **number of operations** performed on the expression. The types of **operations** are described as follows: * Turn a `'1'` into a `'0'`. * Turn a `'0'` into a `'1'`. * Turn a `'&'` into a `'|'`. * Turn a `'|'` into a `'&'`. **Note:** `'&'` does **not** take precedence over `'|'` in the **order of calculation**. Evaluate parentheses **first**, then in **left-to-right** order. **Example 1:** **Input:** expression = "1&(0|1) " **Output:** 1 **Explanation:** We can turn "1&(0**|**1) " into "1&(0**&**1) " by changing the '|' to a '&' using 1 operation. The new expression evaluates to 0. **Example 2:** **Input:** expression = "(0&0)&(0&0&0) " **Output:** 3 **Explanation:** We can turn "(0**&0**)**&**(0&0&0) " into "(0**|1**)**|**(0&0&0) " using 3 operations. The new expression evaluates to 1. **Example 3:** **Input:** expression = "(0|(1|0&1)) " **Output:** 1 **Explanation:** We can turn "(0|(**1**|0&1)) " into "(0|(**0**|0&1)) " using 1 operation. The new expression evaluates to 0. **Constraints:** * `1 <= expression.length <= 105` * `expression` only contains `'1'`,`'0'`,`'&'`,`'|'`,`'('`, and `')'` * All parentheses are properly matched. * There will be no empty parentheses (i.e: `"() "` is not a substring of `expression`).
At first glance, the solution seems to be greedy, but if you try to greedily take the largest value from the beginning or the end, this will not be optimal. You should try all scenarios but this will be costy. Memoizing the pre-visited states while trying all the possible scenarios will reduce the complexity, and hence dp is a perfect choice here.
Array,Dynamic Programming
Medium
1538,1808
1,725
so lead code 1725 number of rectangles that can form the largest square so in this problem you're given an array of rectangles and you need to return the number of rectangles that can be cut up to make a square with a side length of max len and what is max length max len is just the side length of the largest square that you can obtain from any of the given rectangles so for example here these are the given rectangles and you can map every of these rectangles to the biggest side length square that you can cut so for example from this rectangle the biggest square that you can make would be 5 from this it would be 3 from this it would be five and from this it would be five again and so you have max len equals five and now you want to return the number of rectangles that can make a square with side length five and that's just three is the first one the third one and the fourth one okay so let's implement this logic so we're going to divide the problem into two parts so the first part is getting the maximum length of any square made from any of the rectangles and then we are going to have a counter that is our result variable which we are later i'm going to return and then we're going to have a loop that goes through every rectangle and adds one to the result variable if you can make a square with a side length of max len which we have calculated previously right so now all that's left is just to implement these two functions so let's start with the get max line so get max length is going to look at every rectangle and take the minimum between their length and their width and that will give you the maximum length of that single rectangle now what you want to do is you want to take the maximum out of all of those minimums right so you just take the maximum between every rectangle mapped to the minimum between their two dimensions okay right so that will give you the maximum and now what you want to have is the second function right here so to do that you just implement what the problem statement tells you so the problem statement tells you that you can cut the rectangle to form a square with side length of k if l is greater or equal to k and w is also greater or equal to k so yeah just implement that in code and you're done so you can make a square with a side length of length if l is greater or equal to the length and w is also greater or equal to the length so that's it i'll submit a solution to show that it works and the time complexity here is o of n because you just go through every rectangle once or twice and like a constant amount of times and then the space complexity here is o of n actually because of this lazy way of doing the maximum here but there's nothing stopping you from using a better max function and that will give you a o of one space complexity as well so that's it for me thank you for watching and bye
Number Of Rectangles That Can Form The Largest Square
number-of-sets-of-k-non-overlapping-line-segments
You are given an array `rectangles` where `rectangles[i] = [li, wi]` represents the `ith` rectangle of length `li` and width `wi`. You can cut the `ith` rectangle to form a square with a side length of `k` if both `k <= li` and `k <= wi`. For example, if you have a rectangle `[4,6]`, you can cut it to get a square with a side length of at most `4`. Let `maxLen` be the side length of the **largest** square you can obtain from any of the given rectangles. Return _the **number** of rectangles that can make a square with a side length of_ `maxLen`. **Example 1:** **Input:** rectangles = \[\[5,8\],\[3,9\],\[5,12\],\[16,5\]\] **Output:** 3 **Explanation:** The largest squares you can get from each rectangle are of lengths \[5,3,5,5\]. The largest possible square is of length 5, and you can get it out of 3 rectangles. **Example 2:** **Input:** rectangles = \[\[2,3\],\[3,7\],\[4,3\],\[3,7\]\] **Output:** 3 **Constraints:** * `1 <= rectangles.length <= 1000` * `rectangles[i].length == 2` * `1 <= li, wi <= 109` * `li != wi`
Try to use dynamic programming where the current index and remaining number of line segments to form can describe any intermediate state. To make the computation of each state in constant time, we could add another flag to the state that indicates whether or not we are in the middle of placing a line (placed start point but no endpoint).
Math,Dynamic Programming
Medium
null
47
foreign is called permutations too you have your gaming collection of numbers nums that might contain duplicates which is important fact here and we have to return all possible unique rotation in any order Suite so the final output cannot have duplicates and here we are given the example one two and here all are the all uh applications without duplicates and the constraints are pretty similar to the constraints that we have uh that we have had inside the permutations problem partitions one so to solve this problem we will basically have the same modifications that we had from subsets one two subsets two so to bypass the duplicates we will first sort the array and then we will only for the current position let's say position three we will uh we will select the element if it's different than the previous element so that we don't have for example one and one uh or if it's the same we will only select it at that position If the previous element has been also selected so basically all the elements uh the Bold possible candidates uh are dependent on the previous ones if they are of the same values and we are only choosing that If the previous value has already been selected just as we had inside the permutation one problem we will Define a result which will be a list of our permutations that we are generating then a slight modification we will sort the arrays so we can use the shortness the order of the array to bypass the duplicates next we will call the helper function it will again contain the set of candidates which is our input array as the first parameter next parameter will be the perpendician which are currently generating which will be initially an empty list next we will pass our result to which we will be adding all the partition that you're generating and in this case we are using uh an array of the same length as our input array but just type Boolean and this will represent if our if we have already selected an element or not and we basically just returned the result now for the pro for the helper function we have it as basically is the same as the one that we had in the permutations one we will check if the current list the current permutation that we have generated is of the same length as the input array in which case that means that we have reached the end of the recursion tree at the leaf node basically and we have to add the current list to the final list of the permutations next as we had before we will Traverse through all the candidates so that each candidate can be placed at position one and then we will check just as we checked in the particious one we will check if we have already added it so if we have visited in the previous uh previous calls of their helper function so that we don't use it again and then we will have basically three scenarios this is the multiplication to the frontations one so it's either we are choosing the first element in which case we can we cannot have duplicates or the current element it's not the same as the previous element in which case you can just freely select it or if we have already selected uh element before which is basically the same as our current element is a duplicate so in example one we will have one and one so we will select the second one only if the first one has already been selected in the previous schools of the helper functions and then we will follow the same logic as we had for the partition one we will edit the we will add the current number to the to our partitions you're currently generating we will mark it as visited and then we will call the cursory the helper function after we are done with that call we are basically moving up from the recursion tree and going to another uh to the right children nodes so we have to backtrack we are removing the latest element that we have added before calling the helper function and uh we also have to mark it as not visited the Space and Time complexity are basically the same as implementations one uh for the generation of the partition we have n factorial and because we are copying over this uh array list that we uh the current list that presents or represents our current condition that you're generating we have a multiplier n for each of those um creature those permutations now for the space complexity uh because we are only passing the current list which is of maximum of the size of the input array we will have space complexity proportional to the linear and proportional to the size of the input sorry
Permutations II
permutations-ii
Given a collection of numbers, `nums`, that might contain duplicates, return _all possible unique permutations **in any order**._ **Example 1:** **Input:** nums = \[1,1,2\] **Output:** \[\[1,1,2\], \[1,2,1\], \[2,1,1\]\] **Example 2:** **Input:** nums = \[1,2,3\] **Output:** \[\[1,2,3\],\[1,3,2\],\[2,1,3\],\[2,3,1\],\[3,1,2\],\[3,2,1\]\] **Constraints:** * `1 <= nums.length <= 8` * `-10 <= nums[i] <= 10`
null
Array,Backtracking
Medium
31,46,267,1038
309
in this video we're going to take a look at a legal problem called best time to buy and sell stock with cool down so you're given an array of prices where prices i is the price of a given stock on life day so find the maximum profit you can achieve you might complete as many transactions you would like buy one and sell one share of the stock multiple times with the following restriction so after you sell your stock you cannot buy the stock on the same day but you have to do a cool down day for one day right before you buy a stock so basically you can see you might not engage in multiple transactions simultaneously you might not you must sell the stock before you buy again so you can see here uh we have an example of prices right so for this prices uh in this case you can see we're starting to spy at index zero right day one we buy one and then we can sell it here right in this case we'll get a profit of one right and then what we can do is that we have to take a cool down date right in this case the next day is a cool down and i'll buy at here right in this case you can see i'll buy at this position or at this day and i'll sell it in the next day and then you can see here we get a profit two so two plus one will give us three so that's why you can see the maximum profit that we can earn um you know performing these operations or performing following these restrictions is gonna be three right so you can see we can also have another example of if there's only one and uh in this case we will give us zero right because in this case we can buy one but we cannot sell on the same days right you can see here after you sell in this case you can so you have to buy one and sell one multiple times with the following restriction even though you sell at the same day the profit is still going to give us zero right so in this case to solve this problem let's take a look at the constraints first so in the constraints you can see here we're guaranteed to have positive values and uh the length of the array is between one to five thousand so in this case to solve this problem uh what we can do is that well the brute force approach to solve this problem is basically trying with all the combination right so let's say we have this array right here and what's going to happen is that we're starting to maybe like buy at this position and then we basically try to iterate each the remaining elements to see okay if i were to buy at day one and i sell it here what's the maximum profit right and then in this case to find out what's the maximum profit in this case is basically two minus one which is one plus if we have to you know wait for another day to cool down and then we're gonna start to uh you know see what's the maximum profit if we were to start buying at this position right so in this case we're doing a dfs uh basically saying hey i want to know what's the maximum profit if we were to start buying it here and when i say start buying it here i does it doesn't mean that i can buy a here i can also let's say this value right here is a crazy big value right and then we have zero right here and i can also start buying like here you know i can also start buying it here right it doesn't really matter it doesn't like when i say buying it here it doesn't mean that i have to like find the maximum profit if i were to buy the stock today right at this day i can i want to know like what's the maximum profit if we were to start buying at day at this current day right maybe it would be like day two day three or day four or so on and so forth right so basically we want to find what's if i were to start at this position right what's the maximum profit that i can earn right if we were to start buying at this position right i can also start buying at two right day two right i can start buying it here right so that's what we're trying to do right we're basically doing like a brute force approach which in this case you can see for each and every single element right if i were to buy here i will i want to figure out where can i sell i can sell it here and then i have to do what df has to say okay if i were to start buying it here what's the maximum profit right and then i backtrack and then i say if i were to start buying it here then i have to or sorry in this case if i want to sell at here then in this case i would have to start i would have to find what's the maximum profit if i were to start buying at here right and then if i were to start to sell it here which is not possible because 0-1 here which is not possible because 0-1 here which is not possible because 0-1 is not a it's not a positive value right and then what if i sell it here then i want to know what's the maximum profit if i were to uh you know start buying that here right which is out of bounds so it's going to be zero so in this case you can see like the brute force approach to solve this problem is basically going to try with each and every single combination right like for each and every single element i have a number of branches or in this case and yeah a number path that i can go down to and for each of those paths i also have a number of paths that i can go down to right i can right you can see here i can if i were to buy let's say if we were to go back to here right in this case i can start here right i can uh figure out you know if i were to sell here i can try to buy what's the maximum profit if i were to buy here and what's the maximum profit if i were to buy here right and not only that you can see i also want to say let's say if there's a situation where this value right here is 1 10 right it's really large i want to know what's the maximum profit if i want to buy here as well as i want to know what's the maximum profit if i were to start buying here right so basically that's what we're trying to do here we're trying to in this case trying to explore all the options using the sprue force approach right but that's brute force approach and you can see that there will be a lot of duplicate computation because you can see here if i want to know you know what's the maximum profit if i were to buy here but you can see when we're at here we already compute that when we do the dfs right so that's why we can be able to use like a top-down approach to able to use like a top-down approach to able to use like a top-down approach to solve this problem but if we were to implement the top-down approach to solve implement the top-down approach to solve implement the top-down approach to solve this problem you can see it will give us a time limit exceeded because of the recursion stack so let me walk you through this still because this is very important you can see here we starting at the max profit right we take the prices and then we say n is equal to prices.life right and then what we do is prices.life right and then what we do is prices.life right and then what we do is that we're basically creating this cash integer array and then we're basically trying to call this dfs function and this dfs function basically answers uh you know if i want to what's the maximum profit if i want to start buying at this position right that's what we're trying to do if when we call this dfs function we want to know what's the maximum profit if we were to start buying at this position so what we're going to do then is in our dfs we basically check to see if index is greater than n then we can just return zero otherwise what we're going to do is we're going to see if cash at index is already cashed if it's already cash we can basically return that cash value right and then otherwise we're going to do is we're going to calculate okay so we iterate so in this case when we say start buying at the index right it doesn't have to be like oh let's buy at this position and see what's the maximum profit we can also buy at the next day we can also buy at the nest day right so that's what we're doing at this loop right here this outer loop is basically saying let's say we buy at this index let's say we buy this index let's say we're buying at index and x three right let's figure out what's the maximum profit if we were to you know uh start buying at this date so in this case you can see we can also start selling right so we can also check to see okay if i were to sell at this day right what's the maximum profit that we can get and first like i said before we have a check to see if the buy price is bigger than the sale price then we can continue right we don't have to do that we don't have to do this comparison here and we don't have to do the dfs function uh because in this case the buy price is bigger than the selling price right if that's the case that'll give us a negative value we don't want that right so in this case you can see if it doesn't qualify then we're going to calculate what's the maximum profits right if we were start right selling at this position right if we were to sell at this position what's the maximum profit right what's the maximum profit if we were to buy at this position that's what we're trying to do for the max variable here so you can see max is equal to either max or if we were to get the you know the price difference plus the dfs function uh two plus cell right basically what we the cell is basically the index right like this index where we want to sell and then plus two basically means that we want to have one day of cool down and then we're starting at the day after the cooldown right so that's basically the nest started we want to find what's the maximum profit if we were to start at that date and then at the end you can see we're basically caching that value and you can see cachette index is equal to max uh value between either max or cash at index right what does it do is that uh it basically saying okay for this position right either i'm going to buy at you know the first day one or i buy a day two it doesn't matter right we're starting at buying at index right at this index right here we start buying at this position at this day what's the maximum profit that i can get at this or if we are if i were to start buying at this date right so that's what we're trying to calculate right and at the end we're going to return this is the maximum profit that i get if i were to start buying at this day right so that's will give us uh you know close to n square time complexity and there's also like a recursion stacks which uh you know affects the performance and let's take a look at the uh the top down or the bottom up approach right the bottom approach is a lot easier um or i shouldn't say a lot easier but like the code is a lot smaller right and then you can see i document these by comments so it's a lot easier to read so what's going to happen here is basically we're starting at the second last element in the array and we're working our way up right we're working our way towards the first element d-ray our way towards the first element d-ray our way towards the first element d-ray and for each and every single element in this max profit by star at right is basically trying to answer like for in this case let's say index two or index three right what's the maximum profit if i buy starting at index three or what's the maximum profit if i buy starting at index two right that's what the uh this cash already trying to uh store right so that's why we're starting at the second last element because the first element right the maximum profit that you can buy is basically zero right starting at this position is zero okay so what's going to happen then is that for each and every single iteration right first we want to find what's the max profit if i buy at this position right if so let's say for example this one this last second last element right here what's the maximum profit if i buy at this position in this case if i buy this position um is you know we have to iterate all the cell point right in this case it's gonna be by plus one two to n right we wanna iterate all the uh right sub arrays to figure out okay if i sell here what's the maximum profit if i still here what's the maximum profit right if i sell so on and so forth right let's say the start is two i will iterate three zero two trying to figure out what's the maximum profit if i were to sell at this position right each and every single position and that's what we're doing the calculation here so profit is equal to prices sell minus prices buy and then uh we check to see if we can be able to continue to buy after the uh the cool down right because in this case the cooldown it takes one day so in this case we already cashed that before right like what's the maximum profit uh by starting at after the cooldown that's what line 12 is doing right here and then once i get the profit if i buy at this position um right buy and sell at this position right and then i will try to compare that what's the maximum profit uh what's the maximum profit by starting at buy right if i were to start at this position or in this case uh day two right what's the maximum profit if i buy and sell at this position right and i will make sure that i will get the maximum profit right if i buy this if i buy today what's the maximum profit if i can what's the maximum profit uh if i sell here and here right after that this is the key part of the code is that if after i get the maximum profit if i buy at the current position right i need to know what's the maximum profit if i start buying at this current position there's a difference one is a start buying and one is buy at this position right start buying basically means that if what's the maximum profit if i were to start buying at this position maybe i don't have to starting or start buying at the current date right i can buy at the next day i can buy a nest day right like it depends on the current value right if the current value is really large for example 100 1000 right so maybe we don't want to buy at today right so that's what we're doing here is that we already know what's the maximum profit uh if we buy at tomorrow right because we're going from the bottom to up approach so what we can do is that we know you know we know that currently if we were to buy at today's stock and what's the maximum profit if i buy at today's stock right i need to know is it going to be greater than you know what we you know if we were to start buying tomorrow or should we buy today right so in this case we will get what's the maximum profit this will give us what's the maximum profit if we were to start buying at the current position and at the end that's what we're going to return at the end right the maximum profit if i were to start buying at the first day okay or in this case start buying uh or s uh buy start at day one right i can when i say start at i can buy a day one i can buy a day two i wanna know what's the maximum profit right if i start buying it day one right in this case start buying day one i can buy it day two day three so on and so forth right so this will basically bring the time complexity uh the time complex is still going to be n square but you can see the space complexity is uh in this case we're not using recursion stacks right and then you can see we're still using a one directional array so in this case the space complexity will be linear right and the time complexity will be n squared
Best Time to Buy and Sell Stock with Cooldown
best-time-to-buy-and-sell-stock-with-cooldown
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: * After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day). **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[1,2,3,0,2\] **Output:** 3 **Explanation:** transactions = \[buy, sell, cooldown, buy, sell\] **Example 2:** **Input:** prices = \[1\] **Output:** 0 **Constraints:** * `1 <= prices.length <= 5000` * `0 <= prices[i] <= 1000`
null
Array,Dynamic Programming
Medium
121,122
1,413
hello viewers welcome back to my channel I hope you are enjoying all the videos that I'm uploading if you haven't subscribed to my channel yet please go ahead and subscribe to my channel and also share among your friends today's problem is minimum value to get positive step-by-step some so given an array of step-by-step some so given an array of step-by-step some so given an array of integer noms you start with an initial positive value start value in each iteration you calculate the step by step some of start value plus elements in nums from left to right written the minimum positive value of start value such that the step-by-step sum is never such that the step-by-step sum is never such that the step-by-step sum is never less than one so basically we have we're asked to find a start value with which we will start right that is a seed value we'll have to start with and then keep on adding the values in there or adding the numbers in the nums Eric so the result of the addition should never be less than one so which positive value or which start value that we need to select is the question the positive value must be minimum okay minimum positive value okay let's go ahead and look at the example one to try to understand why it is right so here the example shown is start value is five that is one start value and start values for right so to start values are given and trying to see which one is better right so better means when this the sum is never less than one at each step right so here this nums array has five elements so start value is 4 so 4 minus 3 is 1 plus 2 is 3 minus 3 that is a third one right here so here if you add 3 minus 3 that will be that became 0 so at this point in time it became less than 1 so 4 cannot be the start value right so let's go ahead and look at 5 right when you add 5 minus 3 to 2 plus 2 is 4 - three is one it could be one but it - three is one it could be one but it - three is one it could be one but it never less than one that's what it said right it could be one so one is valid so one plus four is five plus two is seven so the minimum start value should be at least five otherwise we won't be able to have this condition satisfied so this is a good condition to keep in mind right so all we were asked to do this a minimum positive values for example if you started let us say start value anything greater than five right you would always you will still have this sum never less than one right so but we are looking for a minimum FASTA value so the minimum is in this case is five so how to come up with the minimum positive value so I have devised the solution here so the solution is and the algorithm is get accumulated some of our elements that's the first step so cumulative sum is in this case right minus three plus two minus three plus four plus two rate so it will be how much it is to write the sum is 2 minus 3 is minus 6 this is plus six it cancelled out and two right so this 2 is the cumulative sum right and why going through the cumulative sum you will have to keep track of the minimum right what is the minimum that you are going to get right it's a cumulative sum while doing that right so let's go ahead and understand what is meant by the minimum so when we have this element right so let's take that example and some array so since it is the first element it is minus 3 and minus 3 plus 2 is minus 1 minus 4 is minus 3 is minus 4 plus 4 is 0 and minus 1 is 0 plus 2 is 2 so what is the minimum of all 4 right so the minimum of all is 4 we are having the cumulative sum right so the accumulators from the minimum cumulative sum is 4 that is occurring it here so what we are going to do is since the value the sum should be never less than one we are going to add one to the absolute value of the minimum right so that is what is the answer as long as the minimum is less than zero sorry yeah minimum is less than zero we are going to add that if it is greater than zero we don't need to add anything so minimum positive value can be just one that's it you don't have to order add anything but if minimum positive value is less than zero then you have to add absolute value of the minimum thing okay so keep track of the minimum element in the cumulative sum so that is what is minus four here if the cumulative sum is greater than zero then obviously we can just start with one we don't have to add anything otherwise it should be 1 plus absolute value of the you know so absolutive so that will be what so this will be 1 plus absolute value of minus 4 that means it's 1 plus 4 which is equal to 5 which is the answer for us right so the output is 5 so it matches right that is what is the algorithm that we are going to look at right so very simple algorithm let's go ahead and look at that later right so for this sake I am creating a sum array right where I want to store the cumulative sum right so as usual the first element will be same so that's why I'm storing the sum of 0 the same as the namazi row right so minimum I am assigning it to the sum of 0 to start with red that will the minimum and then while going from 1 to n right 1 to n minus 1 basically I am going to calculate the cumulative sum and keep track of the menu so minimum will be minimum of minimum and sum of a whatever that is so minimum will be calculated so once the minimum is calculated right so if the minimum is greater than 0 you just written 1 and if the minimum II is not greater than 0 that means less than 0 right or less than or equal to whatever that is right then what we are going to do is 1 plus minus 1 into minimum so in this case minimum is negative so you are if you are converting the minimum to positive by multiplying with -1 the other ways you can just do with -1 the other ways you can just do with -1 the other ways you can just do the absolute value that's what I explained in previously read Matt dot a BS of min right that also works so once you get the maximum absolute value right then you will be able to get the conversion happening right - formula conversion happening right - formula conversion happening right - formula converter 2 + 4 1 plus 4 is 5 so that is converter 2 + 4 1 plus 4 is 5 so that is converter 2 + 4 1 plus 4 is 5 so that is where the value that is going to return so let's go ahead and look at the time complexity for this algorithm so the time complexity inference algorithm is we are going through the array like one time that is 1 2 n so this will be order of n is a time complexity for this algorithm and the space completely for this algorithm is we are creating this some array right so some array will be keeping track of the cumulative sum in here right so cumulative sum is being kept track right so one thing is you can get away without creating the some array also you can just keep track of the sum only the cumulative sum the simple variable but in this case just to show you how it is going to look and all right I have this sum as array that's why for this particular code the time sort space complexity will be order of n but if you keep the sum in a simple variable right then the space complexity will become constant that will be a single variable anyway so then you will be comparing the sum the cumulative sum variable with the minimum at in every step that will be any way you can keep track so in that particular place algorithm right it will be constant space so this algorithm could be converted into constant space algorithm also where you will convert this into here some the array to just make it as just only the in some and update this statement right and use the update this once you do this to 3 steps that's it that will get converted to or you say constant space algorithm right so you can implement over what we can say is time complexity is order of and space complexity is order of one for that algorithm once we update these two steps and this making it into some right and obviously in some is equal to we will say zero right that's the statement way they are going to do it so hope that cleared up solution your any doubts and all if you still have any questions please leave them in the comment section I will get back to you as soon as I can thank you for watching again if you haven't subscribed please subscribe to my channel and share among your friends please don't forget to click the bell icon if you click the bell icon you will get notifications for my future update thank you for watching I look back with another problem very soon till then goodbye
Minimum Value to Get Positive Step by Step Sum
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
Given an array of integers `nums`, you start with an initial **positive** value _startValue__._ In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right). Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1. **Example 1:** **Input:** nums = \[-3,2,-3,4,2\] **Output:** 5 **Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1. **step by step sum** **startValue = 4 | startValue = 5 | nums** (4 **\-3** ) = 1 | (5 **\-3** ) = 2 | -3 (1 **+2** ) = 3 | (2 **+2** ) = 4 | 2 (3 **\-3** ) = 0 | (4 **\-3** ) = 1 | -3 (0 **+4** ) = 4 | (1 **+4** ) = 5 | 4 (4 **+2** ) = 6 | (5 **+2** ) = 7 | 2 **Example 2:** **Input:** nums = \[1,2\] **Output:** 1 **Explanation:** Minimum start value should be positive. **Example 3:** **Input:** nums = \[1,-2,-3\] **Output:** 5 **Constraints:** * `1 <= nums.length <= 100` * `-100 <= nums[i] <= 100`
Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.
Array,Binary Search,Matrix,Prefix Sum
Medium
null
688
welcome back to our channel in this video let us write the python program to find the probability of thick knife to remain inside the chessboard after taking k number of steps as we know there are 8 possible moves for the knight in the chessboard as indicated in the screen they move in l-shaped in the screen they move in l-shaped in the screen they move in l-shaped direction now let us consider the board as size 3 that is n equal to 3 which results in uh index top left is indexed to zero and i am considering that knight is also positioned initially at this zero index block for k moments let us find the probability of the knight to be inside the chess for k equal to 2 let us work out how this can be achieved as mentioned uh night by original position is at zeroth index and the probability at this place that is at k equal to zero no steps were taken is one because um that knight is within the board so probability is one for this position now uh when the knight moves that is when k equal to 1 out of 8 possibilities this 2 retains the ignite within the board and the resultant probability is 1 by 8 that is 0.125 for each of these two positions which is nothing but the two probabilities two positions which results in the knight to be positioned inside the board now for the next two more that is k equal to two from each of these two positions there are two possibilities for that knight to move and their probability is 0.125 0.125 0.125 divided by 8 resulting in 0.156 um for the uh knight positioned in row one and the same thing applies for the knight position in row two also uh two possible uh moves resulting in the knight to be positioned within the board so now to calculate the probability we have to have uh at position k the sum of these probabilities will give us the overall probability for the knight to be positioned in the board and here the probability is 0.0625 which is nothing but the sum of 0.0625 which is nothing but the sum of 0.0625 which is nothing but the sum of all probabilities of the knights to be positioned within the board for k equal to 2 so with this logic let us implement our python code ah summarizing the algorithm that we have seen so far uh there are eight choices for the knight to move which is including the inside and outside the board the second point is smooth ignite and check if it is inside and the third point is if inside the probability of the taking new position is one by eight of the current probability and the fourth point is repeat the above 0.213 fourth point is repeat the above 0.213 fourth point is repeat the above 0.213 for k number of times so with this algorithm let us implement a dynamic programming in python as a first point there are eight possible moves for the knight so i have the moves list with the eight possible positioning uh two at the bottom and two to the top and two to the right and two to the left so there are eight possible moves at any time for the knight which includes both inside as well as outside the board before moving on to the second step let me import the numpy so that i can have the flexibility to use numpy array input numpy s n p and as we saw in our example let me first have again the size of the board as three and the number of steps to be taken is 2 for the knight within this board and find the probability that knight will be within the board with these values let me have the three dimensional array to store the probability of each of these positions so probability array shall be initialized with a numpy array and let us initialize this with 0 so 0.0 for a in range n 0.0 for a in range n 0.0 for a in range n as n is the board size and for b in range again n for c in bridge again we are having three dimensional array uh normally two dimensional array would be ah used to hold the row and column of our board the third dimension is included to hold the probability of the knight in that position that is in the row and column the probability value will be stored in the array hence resulting in three dimensional array and we have initialized the elements by zero as we also know when there is no movement it is of probability 1 because the knight is within the board so for k equal to 0 that is when it is not no steps were taken let us update the probability array with value of 1 that's the probability when no steps were taken at this point let us print and see our three dimensional array as expected we have the three-dimensional array and three-dimensional array and three-dimensional array and uh the position uh when that knight is not moved that is k equal to 0 is initialized with the probability value of 1 in all this arrays of position row and column so we have our three dimensional array initialize with probability for k equal to 0 now moving to the second point in our algorithm we will implement these things with dynamic programming method so it is flexible if i define the function called probability night and it shall take the parameters of initial row and column as x and y also it shall take the steps here steps is nothing but our value of k so with this as the input parameters we have to move ignite and check if it is inside so to move the ignite means move the uh knife to the possible eight positions and then check if uh the any of these things are inside so first for x in range n is the size of the board and for y in range within the uh x boundary we have to check if the new positions as defined in moose list is within the board so if the new value is between 0 and n that is x plus i is between 0 n and also y that is column y plus j new position new move position as provided by the moves is also within um 0 and n if this condition is satisfied then the mood night position is inside the chest so the next point is if inside the probability of taking new position is 1 by 8 of the current probability it also implies that if it is not inside the current probability shall be zero so let us have the variable knight probability initialize to zero that is this it means it is not inside the board now after uh the moves if it is a valid move that is within the board big night probability shall be probability 1 by 8 of the current probability that is x plus i y plus j yes minus 1 where s minus 1 indicates the current step that is before uh taking this move what is the value divided by eight so eight one by eight the current probability we have to consider it now as our dimension uh is about the probability of taking steps we have to repeat the above point for k number of steps so we have to start the uh loop for each step that is yes in range of one two steps plus one their steps is one of our input parameter which is nothing but our k value and if you also observe i am taking the range for s starting from 1 not from 0 because we have already initialized for zero steps the probability is one because uh it stays inside the board and hence the probability is one so yes ranges from one to the steps since it has to reach till steps i have taken steps plus one in the range now this move uh and check if it is inside calculate the probability as 1 by 8 of the current probability is repeated for all steps and we can return the value after each move the val probability is stored in our variable kb which has to be moved to our probability array and then we can return the value as per the input parameter that is by passing uh the initial position of the ignite in the board that is start x and y and the steps now let us execute this one and then check our result let me call the probability ignite function by passing initial position as 0 comma 0 that is 0 indexed in our board of size 3 and k is nothing but it takes the value of 2 steps as we see previously the probability should be 0.062 for a k value with initial 0.062 for a k value with initial 0.062 for a k value with initial position of that knight at 0 index in our board size of 3 let us see and confirm it on execution yes we got the probability of 0.0625 as expected 0.0625 as expected 0.0625 as expected now let us take different values let me change the initial position for that knight as one comma zero for two steps on board size three again the probability is same 0.0625 let us try increasing the size of the board and the number of steps where n equal to 8 and k equal to 3 and initially that knight is positioned at 1 comma 0 let us execute and see the probability of knight in the board which is zero point one nine two one eight seven six of accuracy level eight digits hope you liked our video in the description i have also provided the link for a minimum night moose in the chess board to the destination position please click the link to see the video also subscribe and share with your friends
Knight Probability in Chessboard
knight-probability-in-chessboard
On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`. A chess knight has eight possible moves it can make, as illustrated below. Each move is two cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly `k` moves or has moved off the chessboard. Return _the probability that the knight remains on the board after it has stopped moving_. **Example 1:** **Input:** n = 3, k = 2, row = 0, column = 0 **Output:** 0.06250 **Explanation:** There are two moves (to (1,2), (2,1)) that will keep the knight on the board. From each of those positions, there are also two moves that will keep the knight on the board. The total probability the knight stays on the board is 0.0625. **Example 2:** **Input:** n = 1, k = 0, row = 0, column = 0 **Output:** 1.00000 **Constraints:** * `1 <= n <= 25` * `0 <= k <= 100` * `0 <= row, column <= n - 1`
null
Dynamic Programming
Medium
576
337
Hello friends uh welcome to my channel let's have a look at problem 337 horse robber 3. this video is a continuation on host Global problem problems 198 and 213. so this horse robber 3 involves binary tree because the thief improved in data structure and algorithms so a binary tree actually can be defined recursively so here we could think of giving a recursion solution so the thought process is still following the previous two problems however the code format is slightly different due to the different abstract data tabs so here is a binary tree and in previous at the data structure data tab is list so first I'll read through the statement of the problem and then we analyze the problem and finally we share the code so here the thief has found himself a new place for his uh silvery again so there is only one entries to this area called the route so that this route is the root of the binary tree so beset the route each horse has one and only one parent node or parent house so after tour the smart Thief realized that all horses in this place form a binary tree it will automatically contact the police if two directly linked houses were broken into on the steam night so given the root of the banner tree the return the maximum amount of money to see if can rob without alerting the police so here are two examples so let's look at example one so in example one so if the safe drop the root and the know the two Leaf nodes so they can or she can maximize the money collected that is seven and in example two so the two nodes marked in right are the nodes to be robbed to maximize the money so that is not so we're going to Analyze This further so before we look at the methods let's look at the constraints first the number of nodes in the tree is in the range between 1 and 10 to the power of 4. so this first said that the tree as a whole is not null and the 10 to the power 4 is the upper bound of the number of nodes so this first constituent first constraint actually defines the problem size and secondly so the node value is not negative so this is actually can be important because so there each node have on couldn't have negative money so with that said let's look at the idea so here for each node so actually we're going to compute two pieces of information so not Rob or Rob so the job means the maximum money can be collected onwards if we drop for the safe drops in that node The Nut Job can be interpreted similarly but if we do not but the condition is that the shift doesn't uh does not drop that node so with this two pieces of information defined for node so the main point for this problem is how to get the information for a root if we know the information for its two substrates so this is a counterpart of the recursion relation in the previous DP Solutions to problem 998 and 213 so there we speak of DP object rule or recursion relations so here is similar right so given a root or node so we assume that for the left subtree so if we do not drop the left of tree so the amount of money we can get is left not job so if we drop the left super tree node so we get left Rob so this is the amount of money if we drop the left subtree root so similarly we Define the two pieces of information for the register symmetry so then we could get the information for the root so the if we do not drop the root then we can drop the leftover tree or not similarly we can drop the respiratory root or not so in this way so the max money we can get is that so this is the first atom the first item means that we can choose the van larger depends on if we drop the left subtree root similarly for the red so the maximum is that we the maximum money can be collected depending on not drop the resistable tree root on a rock right so this is the if we do not drop the root so if we drop the root then we cannot drop the left circuitry route and the red substitute root so then the money can be collected is root value so this is the money at the root node and then we press left not drop in other words so we cannot drop left root animal so similarly we add red not rob in other words we cannot rub the red root animal right so this is the updated rule of the recursive relation in a not so rigorous sense so here let's look at example one so for this node two so the information is the following so if we do not drop this two so we can get the money three and if we drop this two we can get money too because we cannot drop three animals so for the three for this the registered tree of root three so if we do not log these three so we can get that unit of money and we rub three so we can get three units of money so the information for two and three is three two and the last three respectively then for the root 3 here so if we do not drop the three itself then the money we can get is the max of this one plus the max of this one that is 3 plus 3 that is 6. so if we drop three itself then we should have three this is the value at the root and then plus not numbering two so we get three here and not at not lobbying uh the red subtree that is three so we get to one so we get three plus one that is seven so overall the largest one is seven so the return is seven because six and seven the larger one is seven So the plan in this video is the following first we are going to share a few recursion solution and then we will write a DP lag solution in a line with the DP solutions for the previous two problems so the two formats are actually essentially the same so now with that set so let's look at the code so first um I'm going to define a hyper function so this hyper function actually is essentially does the actual work so this function accepts a tree node let's call it root or we can call it a node so that does not matter so then first we're going to have a stop condition or base case if not root so in this case if the node is a null so we're going to return a zero right so no matter we drop this node or not there's no root three nodes Instead at all so we get 0 return 0 and 0. otherwise so we do recursion calls so first L is helper uh go to the left and the r is helper go to right so notice that L and R are two tuples right and then we want to combine the information from L and R according to the rows here right so um first we're going to return so if we do not drop the root so we can drop a left symmetry root or not or similarly for the registry so we're going to have Max L plus a Max R so this is the first item in the return Tuple and then if we decide to rob the root so we are going to have root value then plus the situation that we do not drop the left symmetry root and the red substitute root that is L 0 Plus r0 so that's the hyper function and now with this bulk of work done so actually we are ready to return so we are going to call this hyper function right um so and apply it to the root and then this is a tuple then so this actually contains two pieces of information so the money we can collect it if we do not um drop the root and if we love the root then what we are going to return is the max of the two right so in other words the max of the two elements in the Tuple so that's actually finished the first format of solution so I will change this one to the solution and then we are ready to do a special case check first yeah it passes um the example one here I guess so now let's do a generic case check yeah it passes the general cases so with that said actually we are ready to do the second uh version so here let me copy this function signature and put it here and then we'll change this function name to be drop V1 so now let's look at the second one so in the second one what we are going to do is that we write a dynamic programming Solution on dynamic programming lag solution so the purpose for this format of solution is to align with the two videos for host number one house number two right so that we can see that we can use dynamic programming to address all the three questions so with that said we are ready to do the work so for this solution format I'm going to use a memorization or we can use the use hack cache so I'm going to initialize a dictionary called memo so now we're going to define the rubber so all the worker so let's see I'll Define it as rubber and then this uh we're going to accept a node and a stage so let me make some remark so node will be the three node right as binary tree and the state will be a Boolean in others if we drop this node or not right so the return will be the money right so the money we can get onwards from the tree node right here so this function actually and can be easily written so right so first let's consider a case if node and the Stitch uh not in some dictionary so we need to do some work so otherwise we just need to you know return memorization and the node and the state all right so this is the um structure of this hyper function now let's look at the main logic if node and state is not a key in the dictionary then what we're going to do let's check if not node so we are going to return zero so this is the for sure no matter what's the state true or false and then we are going to check if the node is not now if state in other words if we decide to drop this node so what we're going to do is that we update this dictionary right so we have the node and State so it's going to be because we have decided to drop this node itself first we need to include the node value here so node value all right so this is the one part another part is that we can drop the left and the right so we can drop um uh sorry let's con uh so because we are going to drop this node we cannot drop the note left and the red Roots so we're going to drop node left so the state variable will be false and then we're going to rob node right but we cannot drop the root so it's also going to be false so this is the first case otherwise if the state is false in other words we will not drop this node so what we are going to do is we are still updating this dictionary but here so because we have decided not logged node itself then we can choose the maximum value and we can get from log node left and not the right with the option that we can uh we hope the corresponding root nodes if we lack so that is Max so job node red so let's say Source or Rob node right true so similarly we need to add the left and subtree so Rob um node left Force add drop node red true right so this is the maximum amount of money we can collect so that's actually the full Logic for this case so that's done so we just need to return um the result here so that's the full hyper function so now what's the return for the whole problem first we're going to call this function right so call this function there are two possibilities we either determine to drop the trend route and or not right so if we drop through the three nodes so we're going to have root and true otherwise we're going to have lob root and force so we are going to collect the larger one so that is the maximal of this two so that's the second format of solution so here we use memorization and this is a format of DP solution so um with that said so this is also in a recursion format for sure so we are ready to do a special case check first let's run the code so wrong answer so let's see what's the problem here so if notice it not seen so we're going to yeah if state so node value left and right so yes add me more note stage so next drop node right fourth red true so here should be left all right so we collect this setting table so now let's do a check again yeah it passes the test case so now let's look at the generic case foreign other test cases so I guess that's about it for this problem itself so let's give a quick summary so in this robbery problem so the problem involves binary search tree so first we follow the previous ideas in solving the two rubber or strawberry problem one two and then we use dynamic programming and also we use a recursion format so in the specific implementation we first demonstrate a recursion solution and then in order to align with the previous two videos we write a DP lag solution right so with that I'm done I guess that's about it for this video thank you very much
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
1,675
hello everybody this is larry this is day 30 of the um january lead code daily challenge uh oh okay second to last day um of the month hit the like button hit the subscribe button join me on discord let me know what you think about today's farm and stuff like that hope everyone's just doing well in life uh you know end of the month hope you uh kind of had a streak going if not that's okay you know life is busy life is hard um but you know one at a time and see where it takes us okay today's problem is minimize deviation in array so i usually start this live so like if it goes a little bit slow feel free to fast forward it so because i do my explanation and thought process as well um so you're given an array numbers of n positive integers you're performing two type of operations if it's even divided by two okay on okay so i think the first thing i noticed is that you can do this infinite amount of time so depending on what i'm supposed to get into um that's something to keep in mind because that means that there's some sort of greedy or something like that because if you can do something infinite amount of times then there's a patterns that you can build on or something like that i don't and i know that those statements awake but that's because i haven't finished reading the problems yet so okay that means even do i write two or you could do it by two for free okay if it's odd multiply by two okay um okay so the deviation is the maximum difference between two elements in the array hmm what is the maximal difference between any two elements right um wow this is a tricky problem i have some feelings uh some invariants that i try to figure out for this problem and i'll go you know talk about them um but i think in a greedy kind of way you for a given number you almost want to divide or number back to odd um is that good enough um no because in this case you then you will have um all the odd numbers right um wait let me think about that again sorry i don't know if that statement is true um so i think for me is try to figure out like a place to kind of find um good place um if we divide it because we i think actually i take it back so for every odd element we multiply by two and then we do some sort of um i'm just looking at n just to make sure some sort of um hmm like some sort of uh min max type thing and why say this is that because um you know this can only happen once right i think that's the invariant that i'm trying to build so if this can only happen once and it's reversible right because we reverse it by because when you multiply by two you can divide it by two later so we always want to do this for every element first that's my intuition because we can always reverse it later anyway and then now that we do this on every element we have a list of even elements right so in this case it'll be 2 6 um yeah 6 4 or something like that and then now we're trying to figure out um how to get the minimum deviations down and i think a couple of ways to do it um i one idea i have is like some sort of heap type thing where you keep on getting the max element and then you divide it by two um and because each number will be at most ten to the fifth which is um what is it a hundred thousand which is like you know 2 to the 17 or 16 or something like that um that means that you can you don't need to about 16 at first you um you divide the number 16 times and then you get your answer um and yeah you take the max element you divide it by two and then you take a snapshot of the um deviation which is the smallest number and the biggest number and then you kind of keep on doing that and i think if you do that enough times um like the answer would be one of those answers because it doesn't make sense to um because basically my idea is that you know if you have a series of numbers um you know something like that or let's have them in a sorted order because we have a heap say if you have a series of numbers like this it doesn't make sense to divide by 2 on any numbers in the middle because your biggest number is still going to be the biggest so it doesn't change the deviation except for making it worse possibly if you divide by a smallest number for example so you always want to take this biggest number and write by two take the snapshot of the biggest and the little and then kind of keep on doing that in a cheap kind of way is what i'm thinking so that's what i'm going to do um so i'm gonna keep track of yeah let's start implementing um so grab a heap uh i have a let's just say oops um yeah and then for x in nums uh if x is if it's x is even then we can already put it directly in heap let me think about this for a second actually i think maybe there's a weird case where like if the answer is two and i don't know uh five right um what does this mean right um this means that the answer is actually four and five but we might not get to it with my previous strategy of just taking the biggest number and while we can right so we might have to play around with uh multiplying by two until the smallest odd number or something like that um and play around with that idea i think uh wow there's a lot of weird cases that i cannot prove to be honest so this is going to be a little bit tricky one uh but yeah because even here if even if we you know change it to a 10 um well that's not going to be good enough be because this is too small and when oh this is not this is too big and two five but the best answer is actually four or five right yeah um oh wait did i mess that up i think no okay so never mind actually i think i have a mind confusion because only if it's odds you can multiply by two otherwise you could have to divide by two so okay never mind this is not a case um so again you guys see my dart process of trying to think about different cases but i just kind of mixed up the thing a little bit because then now this goes to ten but it can only ever go back to five and this can go to two uh one but not anything bigger um because yeah because if it's a given number you can never multiply by two so okay so doing variant holds i just got a little confused so um h so then we do a push um else um actually we also want the max number every time so let's you know just convert it to a max heap because in python it's a min heap that's why i'm doing like this uh otherwise we push um as we said we multiply by two so that it is now an even number so now all the numbers are even um in the heap right um and then we also want to keep track of the smallest number which um which comes in handy i suppose oops let's make it is uh really big um made enough small yeah uh is that true now uh here we is x times 2 and here it's x so yeah um and then now we just have to do uh go for it while we can so while len of heap is greater than zero at least but also now we have a max if the top number is going to be this the highest number so top is equal to negative of heap of zero uh heap q that he pop of heap after that so this is the largest that's quite largest and let's just have a best answer which is we want the minimal duration so best is equal to some infinity number uh let's also call this infinity just in case because i think in some cases i messed up because of that so uh you know don't repeat yourself okay so then now the best is just obviously it's going to be the largest minus smallest um and then now um okay if largest uh if this is an odd number we actually end up have to break right because we cannot divide it by two i just wanna look yeah you cannot do it by two so that means that you can the next number is going to be smaller than the largest anyway so you can divide it um otherwise if the largest number is um an even number we should be able to you push it um largest over two um and of course we have to uh make sure that we you know to keep it uh using the largest uh a max heap instead of a min heap so i kind of rework we inverse the direction as well i know by the way and we just return best i think that should be okay um it isn't code right let me i'm gonna want this just to kind of see whether uh you know any typing at risk what i call compiling errors though i know that you know you don't um in python this is not compiling per se and that's using pi or something like that or like you know i guess it compounds in the by kojima then but uh yeah this looks okay um let me look at constraints real quick uh at least two elements let's try that real quick oh i think it's positive so that's okay um and then maybe some big powers of two it's not that big but um ooh negative numbers so that's not great oh i don't update smallest that's why i knew i forgot something but then well i mean no but that's why we test um so the smallest is equal to min of the smallest of um of this thing i think so if the largest over two um then the smallest becomes that um okay so that looks good thing we tested then uh okay let's give this a quick submit and then if it's right we'll go over the complexity and it's good yay so we'll go over the complexity for each item um so okay let's go over it a little bit uh so we have n items this is gonna be of um n log n because you know we push n items to the heap so that's of n items in into um in these loops uh how about this one right well there are n items in the heap for each uh each loop we do log in here and then no wait the n items in the heap in the beginning but we also push stuff back right well how many times do we push back well the number of times we push back is actually about 16 or 17 as i said before so the number of total items that gets pushed in the queue is actually some you know something like that right some constant um except for that you know it depends how you want to define it because um as i say c is equal to say um log of max number in the array um so yeah um and then here and each of these also takes log n time so it's roughly n log n for that reason uh for that reason um yeah um and in terms of space we only use the heap so it's going to be linear because at most the heap will have n items um because at most it replace itself but yeah um that's all i have for this problem it's greedy it's and therefore it's very tricky i hope that um i hope that you know me going through my thought process and even you know making silly mistakes here and there uh makes sense and my kind of visualization on why i times by two and stuff like that makes sense uh let me know what you think about this problem and if you have any questions in general um yeah i hope everyone has a great day has a great month uh weekend is coming up have a good weekend take care of yourself if you have a chance take care of people around you um or even take care of people in general even though around you um yeah stay good uh stay well you know and to good mental health take care of your health take care you know yeah um i will see you uh next prom and have a good night bye
Minimize Deviation in Array
magnetic-force-between-two-balls
You are given an array `nums` of `n` positive integers. You can perform two types of operations on any element of the array any number of times: * If the element is **even**, **divide** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the last element, and the array will be `[1,2,3,2].` * If the element is **odd**, **multiply** it by `2`. * For example, if the array is `[1,2,3,4]`, then you can do this operation on the first element, and the array will be `[2,2,3,4].` The **deviation** of the array is the **maximum difference** between any two elements in the array. Return _the **minimum deviation** the array can have after performing some number of operations._ **Example 1:** **Input:** nums = \[1,2,3,4\] **Output:** 1 **Explanation:** You can transform the array to \[1,2,3,2\], then to \[2,2,3,2\], then the deviation will be 3 - 2 = 1. **Example 2:** **Input:** nums = \[4,1,5,20,3\] **Output:** 3 **Explanation:** You can transform the array after two operations to \[4,2,5,5,3\], then the deviation will be 5 - 2 = 3. **Example 3:** **Input:** nums = \[2,10,8\] **Output:** 3 **Constraints:** * `n == nums.length` * `2 <= n <= 5 * 104` * `1 <= nums[i] <= 109`
If you can place balls such that the answer is x then you can do it for y where y < x. Similarly if you cannot place balls such that the answer is x then you can do it for y where y > x. Binary search on the answer and greedily see if it is possible.
Array,Binary Search,Sorting
Medium
2188
102
hello everyone so in this video i'm going to explain about today liquid daily challenge so today question is binary tree level order traversal in this machine they are given the root of the binary return the level order traversal of its nodes values okay we want to do level of traversal of the tree so it is a basic type of question only if you know about tree level okay so this is the tree we wanted to we want to do level out of traversal in first level there is again element is three the second level is nine and twenty and third level is fifteen and seventy seven okay so let me discuss about how we can solve this problem okay consider this is the three it is one of the binary so in this example we are going to do a level of ourselves so there are various methods of traversal so i in this example i'm going to do in using queue okay you can also uh do this problem using a recursion call also but i'm going to solve this probability using recursion uh sorry using iterative method so to solve this problem i need a queue okay basically all levels problems need a queue so it is a better way to solve this problem you can also use uh recursion to solve this problem but my preferences is used to queue method okay i uh okay now i created q okay so first of all i'm going to put this first element into my cube so this is the answer set where i'm going to put my first element into my queue so the first element is one so this is my root of my tree so after that hour now this path is going to start okay now i check my q size so my q size is one okay so it's tell that in first level the number of element is one okay so i'm going to listen all the elements doesn't make a particular level so i'm going to pop this element from the cube now i need to check its neighbors okay the neighbors are 2 is sorry children's the children's are eleven children is two so we want to put this from left to right fashion so i first received the left child so for the left children is two and the right children is three okay now you can see in my i visited uh my first current element at current level element because my size is only one so my i used all the elements in my current level so now i move on to next to the next level before that i also added this element to my answer okay this is the owner this is the first level next i'm going to move the next level so now i'm going to check my queue size is two so my second level size is two okay so i'm going to iterate two times into my queue so i'm going to pull out last uh first two elements from my two so my first number is two so it's neighbors are four okay it's the it has only left child there is no right side and after i'm going to add this into my uh answer so the next i'm going to take that three from my queue so three is my children's are five and 6 so i'm going to add this 5 and 6 into my q okay i remove the three from my q so now i will i get lost two elements present in my queue now my again going to check my size of my queue so my size of my queue is three so this is the next level the third level in third level there are three elements in my queue uh three elements in the level so i visited all these neurons now again now my first element is fourth so i'm going to visit uh vcds so children's are seven so i'm going to add seven into my q and all children are visited now we move to five so five left now there is no left children the right one is eight i'm going to put the eight into my queue after that i'm going to remove the six which is the third element in the queue so there is no children's per sixth element so i did not do anything now i obviously did all three elements in my queue so now this level is to over okay now i'm going to write it for last i also want to finally visiting this element i also want to add this into my transfer set okay after that i'm going to visit this uh a next level element so that is that i want to find the size of the queue so the size of the key is two so in fourth level there is two elements that are present so which indicate this uh two so i'm going to launch two elements present in my queue so the first two elements are seven so there is uh in seven there is no children so and i did not do anything and remove the sound from my queue and add this seven into my answer and next eight so for eight there is no element in the cure no children so i'm going to so i did not add anything into my queue and add this eight into my asset okay so now they i removed a lot of first two elements from my q so now this q become empty so my going to drop uh start my process so this is the answer so in first level fire element is one and second level is two and three i did not add that and the third level is four five six and six plus the fourth level is seven and eight so this is the uh process to do double a direction entry so now we look at the code so in this code there is a basically a level of transfer board only so there is no difference so i did it there either i check the base condition if the root is empty initially empty i the written empty array so this is the base condition i want to check that after that i declare the answer array um two dimensional answer array and then declare the queue then i put them push the root into my queue then uh this is the other this is the section i explained in earlier the path so i tried until the cube become empty and then i found out the size of my cube okay and the anticlock is another vector which is to store which is used to show the current level elements okay i will now i try to find all the elements which are present at the current level after that i will try i'll check this the children's if they need if the children's or any uh not null i will put push the element into my queue from left to right fashion then finally i pushed the current level into my answer and finally written the answer hope you all understand so now we'll submit this solution so it's accepted so the time complexity is hardware can only be visiting all elements only one and the space complexity is depending upon the so space complexity is also order of n only because we store the answer but other if we did not consider the answer the space capacity would be at the maximum breadth of the tree so how the it's a maximum elements present in a particular level so is the space number that is for this question okay hope you all understand if you have any doubt please kindly ask in comment section we are meeting next later daily challenge bye
Binary Tree Level Order Traversal
binary-tree-level-order-traversal
Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[9,20\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Breadth-First Search,Binary Tree
Medium
103,107,111,314,637,764,1035
7
hello welcome back to my channel for uh the hanjaliko challenge and today we have reverse integer really similar to the question that we did um but i'm here to do that one more time so basically we will import an integer and output a reverse digit of the integer here's example one two three be three to one but negative one two three we have we keep the sign of the integer and the number will still be reversed it and here if you have zero and then you just ignore it in the beginning so this one is kind of tricky as i see a lot of people dislike it because uh two reason one of the reason that because this word is too long to read second one probably there's two edge cases we have to consider one is 32 bit of integer size second one is the positive and negative sign of that integer we can talk about later so for the reversing integer for example we have one two three and we need to reverse it we started having a placeholder which are not numbered starting at zero we can first thing to do is mod this number to 10 after marking this basically this is getting the last digit i will add the last digit to the temporary number after modding this one getting the last digit and the one two three number original number will divide divided by ten so get rid of the last digit and now we have twelve and three and then we do the same thing again mod 10 will have the last digit but in this time after you have the last digit 2 and come back to here so temporary is equal to temporary time 10 after time 10 you have become 30 and then you add the remainder which is 2 that will come up from here so now the temporary number will become 32 but the original number will divide by 10 again and then basically take out the last digit and the number one it will be the same so eventually it will come up with numbers just reverse version of the one two three so this is how the logic is and here we can think about the edge cases in here we use long output with zero uh why we use long i will explain later but we just go through this as soon as possible we have a negative equal to false if we keep this uh starting if it's a fast one so if x less than 10 less than zero sorry and x will equal to x times uh negative one take out the negative sign of that and now negative is true we'll keep this boolean for later uses so just keep that in mind we take out just make sure the x right now is all positive now come to the point that we uh do the inversion reversion sorry so output equal to 10 time output plus see here is x mark 10 and x is equal to x divided by 10. this whole while loop is the process that i explained for how to reverse the number after reverse and store the number to the output and now the output will have the reverse version um of the input x but you can see i just copy this number and this number is integer max value so if x is this value the reverse version will be is definitely bigger than this number like it would start with seven something seven four six three so this number is definitely bigger than the current number in that case that edge case is kind of weird bigger than integer max value what we need to do is return zero otherwise it will come up a real number so that edge case is clear so we'd have to check if negative is true or not if negative is true we'll return into we add negative sign to the output time negative one otherwise we will return you have to convert back to n output clean the code a little bit yeah hopefully that works that looks all right to me now okay yeah i really don't like this a lot of edge cases so i just give it dislike hopefully we have see we will see a lot of better lego so if you have any question please comment it below and i will get back to you as soon as possible otherwise and we'll see you in the next video bye
Reverse Integer
reverse-integer
Given a signed 32-bit integer `x`, return `x` _with its digits reversed_. If reversing `x` causes the value to go outside the signed 32-bit integer range `[-231, 231 - 1]`, then return `0`. **Assume the environment does not allow you to store 64-bit integers (signed or unsigned).** **Example 1:** **Input:** x = 123 **Output:** 321 **Example 2:** **Input:** x = -123 **Output:** -321 **Example 3:** **Input:** x = 120 **Output:** 21 **Constraints:** * `-231 <= x <= 231 - 1`
null
Math
Medium
8,190,2238
344
hey guys welcome to a new video in today's video we're going to look at a liquid problem and the problem's name is reverse train so in this we are given a character array which contains characters and we have to reverse the characters present inside the array with the time complexity in space that is often the space complexity should be constant of 1 which means that you shouldn't use any other extra memory space that is an extra character arrays to store the answer you need to place the answer in the input character arrays itself that is why we have a return type as void so you don't have to create a new character array looking at the example here the first character is now at the last index position and the last character in the input is the first character in the output so what we are going to do is we're going to follow the two pointer approach the first pointer left will be starting at the zeroth index position and the second pointer right will be pointing at the last index position then we are going to use is a while loop where the while loop will run till left is always less than right and inside the while loop will swap the characters as the two pointers that is the pointer pointing at the starting will be swapped with the character at the last position where the right pointer was pointed and where the right pointer was pointing will be swapped with the character at the first index position and that is how we are going to swap the elements and get our answer inside the character arrays itself so let's start coding it up like I said let us declare the two pointer start and now that we have the two pointer let us open a while my start will always be less than n so this means that start and end should never intersect so when start and end point at the same index position for this example that is here we break the loop and we print out and we return what is present inside the character arrays so inside this let us create a character temporary character now let us swap the two characters pointing at the point of start and end so the characters h and O will be spot and this is how they'll be present inside the output so as of start is now equal to S of n we are so up and now we have to swap S of end with start so s of n is equal to start as n but we have stored it inside the buffer temporary variable CH so ch now that we have swapped the two characters we need to increment the start pointer to the next index position start will now point to start plus and we need to decrement the second pointer starting at last index position to last minus one index position so n minus so this is how the while loop will iterate and until both of them point at the same index position this while loop will iterate and the characters inside the character array will be reversed and when you come out of this Loop the characters inside the character array will be reversed you don't have to return anything with because the return type is void so you can run the code there you have it the characters have been reversed let's submit the code there you have it a solution has been accepted that's it guys that's the end of the program thank you for watching and I'll see you in the next one
Reverse String
reverse-string
Write a function that reverses a string. The input string is given as an array of characters `s`. You must do this by modifying the input array [in-place](https://en.wikipedia.org/wiki/In-place_algorithm) with `O(1)` extra memory. **Example 1:** **Input:** s = \["h","e","l","l","o"\] **Output:** \["o","l","l","e","h"\] **Example 2:** **Input:** s = \["H","a","n","n","a","h"\] **Output:** \["h","a","n","n","a","H"\] **Constraints:** * `1 <= s.length <= 105` * `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters).
The entire logic for reversing a string is based on using the opposite directional two-pointer approach!
Two Pointers,String,Recursion
Easy
345,541
661
hello hi guys good morning welcome back to the new video I hope that you guys are doing good so firstly my MacBook is dead so I'm recording back on my Windows laptop um so like there is not much setup I tried but the OBS is not starting at all it just says the OBS shut down like it didn't shut down properly and you would like to start in the safe mode or not if anyone have you have any solutions for it please comment because we have seen this issue quite a lot in live streams it just delays in this video it also is delayed but yeah let's say the problem itself it's a pretty like it's not easy but like as in it's easy with the constraints but it has a great follow-ups and you will just has a great follow-ups and you will just has a great follow-ups and you will just learn a lot cool uh it's let's see uh we have an image smoother uh basically an image smoother is a filter of size 3 CR 3 that has been applied to each of the cells of an image by rounding down the average of these cells and the eight surrounding cells so I'll just indirectly tell you what we have to do is we have this image given to us we have to convert this image to a new Matrix basically we have this input Matrix given we have to convert this to a new Matrix now the new Matrix values will be nothing but uh if I have this value so it will be the average of all the values surrounding it plus this value so you can see I have eight values surrounding it so I will have the sum of all these eight plus this value so it will have the sum of all the values upon the count because average is sum upon the count for example if I ask you what for this specific value what is the average so you will just count all these surrounding values plus him so the sum will be 2 + 7 + 6 + 1 count will be four will be 2 + 7 + 6 + 1 count will be four will be 2 + 7 + 6 + 1 count will be four and the same goes for this value right here you will take the sum of 20 19 24 and 25 and the count will be four you will not count the outside area you will only count what is inside so you just have to build a new Matrix out of it that's the only thing which you have to do which means you have to just smooth this input Matrix now with the question itself uh the first obvious thing is you will make a new Matrix and what you can do is you can just iterate on all of the inputs you iterate on all of the inputs very simple that you have this as a cell you will just go on from this cell to this cell now we'll see what this cell to this cell means but we'll just go on to all these nine cells possible because again it can be possible that it goes out of bonds it is possible that it goes out of bonds so it's possible that it goes out of once so we'll just make sure that okay we also have that if condition that if it is going out of once and if not then we'll just take the sum and we'll also maintain the count and does we will just simply replace in the new Matrix because for sure we will need to have maintain the input itself so in the new Matrix we will just replace this values so ultimately uh this was the question for us so straight method one which we could get is for this specific I comma J I go from i- one J minus1 to I + 1 G+ one from i- one J minus1 to I + 1 G+ one from i- one J minus1 to I + 1 G+ one simple of all loop from here to here it will go and in this it will go on to all the loops so basically I can just have a X as a variable which will go on from I -1 to I + 1 and y Will Go On from J -1 to I + 1 and y Will Go On from J -1 to I + 1 and y Will Go On from J minus1 to J + one and with this you can minus1 to J + one and with this you can minus1 to J + one and with this you can actually go on and iterate on all the values of like all the cells and again this is I'm iterating but I have to again go and check for if condition that if my X lies between 0 and n m and my y lies between 0 and N with this I can just simply go on all the cells just have to check these nine cells in the worst case these nine cells and ultimately I get my answer so you will see the time complexity will be o of 9 into n into M because n into m is the number of cells nine times for every cell in the worst case and for sure nine can go away because it's just constant space will also be of M into n because you know that you are using an extra space just to make a new Matrix and that is always good practice to not modify the input Matrix until unless it is asked or you are asked to do so as you can see uh again uh we wanted to have typed but nothing as in like if I cannot show you but yeah see like nothing in this is okay this is not working but yeah uh nothing in that is working so uh unfortunately we not but cool um what this is yeah so I just got in my M and the n and then I just have a new uh AR called as smooth image a new Matrix which actually will contain the smooth values so I just iterated on all of my cells I NJ IJ all of my cells I will maintain the sum and the count for every cell now for every cell I told you I'll go on from i-1 I + 1 to J you I'll go on from i-1 I + 1 to J you I'll go on from i-1 I + 1 to J minus1 J +1 which means I go on to minus1 J +1 which means I go on to minus1 J +1 which means I go on to all of these nine cells now as I was going on to all these nine cells I told you also have to verify if it is inside your Matrix or not so just have a quick verification if it's inside the Matrix or not if it is inside please add its corresponding value in the sum and for sure increase the count by one ultimately when for this specific cell I comma J this entire thing in the worst case nine cells are seen then and for sure nine cells and this one cell itself so this nine cells all these nine cells are seen in the worst case again I'm good I can just say for this smooth and image I comma J the answer is sum by count which is the average for this particular cell I comma and ultimately do this for all the cells I comma and ultimately return the Smo image with this you will just get the time and space of M now the interview ask you sir can you please optimize it time you cannot optim opiz because for sure you will have to go to Every sale just to get its average value so this is one thing which you canot even think of optimizing the only thing that you can think of optimizing is your space but for that you will have to not make another Matrix so first question you will ask the interviewer is Sir can I do in place operation which means can I modify the input Matrix although you will say to him that okay so it's not a good practice to modify the input Matrix but still are we wanting to modify the input Matrix that is what we can ask he will say yeah you have to modify and get the proper answer okay now my task is to reduce the space now if I just look back at the at what the operation which we were doing earlier was when we were making a new Matrix let's imagine that it was our old Matrix let's imagine it is our new Matrix now with this what happened was if I am applying an operation on this cell then ultimately it will go and try to check for all these cell values right I just wanted to have all these cell values as correct but as I am going on and if I just try to think of doing an in place operation so I will be modifying these cells when I will be at this yellow cell I would have modified all the Red Cross cells I would have already modified that so if I would go and check okay for bro for this yellow cell values give me all these values sum you will see that all these Red Cross these blue Red Cross values are already modified and I did not want it that so ultimately my aim was okay I did not want it that which means I'm only concern about just one row above me and it should not be modified while I'm calculating my yellow cell value just the row above me it should not be modified so the one obvious thing is you are only concerned about one row why not just take a copy of that one row before modifying it so I'll just do simple one thing I'll take this copy of this above row named as let's say previous row so when I will be using when I will be calculating the value for this yellow cell I will go to this blue cell it is giving me the correct values and from this previous row I will go on to these cells from this previous row because it has stored the copy before even modifying the value but then you will ask byya what about this cell this is already modified yeah great so for this also what you will have to do is you will one way is you will have to maintain a copy of this row also so let's say this is my current row so I will maintain a copy of my current row also so with this copy of current row what I do I would know that okay the original value I can get it from the current row so I know one thing that I will maintain my previous row and current row with that with these two rows only with these two rows as the extra space only I will be able to modify my input Matrix itself with the correct values for example again if I just do a recap so I will have a previous row I will have a current row now current row just indicates that okay I am right now starting off with this specific row so this is the current row and it will always be having values before even modifying the current row so I will assign my current row as image of I because image is the Matrix name is image this Matrix name is image so I will assign image of I and this is the I row so I'll assign image of I to this current row before modifying my image now when and now again I'll just modify my image of I now when I will go on to the next aat row firstly I say bro your previous row will be the current row so now my previous row as you can see the current row was here so the previous row will come here so basically now I just assigned my current row to previous row so that previous row will have previous rows correct values or original values and again current row I will assign before starting to modify the current row so current row will have the values before modifying the current row now I will start modifying the current row which is the image of I will modify the image of I and my original values are stored in previous row and only current row so with these two rows only I will be able to solve it now how I will do it for this cell let's say I want the values I want the nine values I want the bottom values I want the right value I want the previous value I want the like top values right so what I'll do I can get this top values from my previous row because previous row is containing original values I can get this left value from my current row so if let's say it is I comma J so I know previous row is an array so I can go to previous row of J minus one previous row of J and previous row of J + 1 this will have previous row original + 1 this will have previous row original + 1 this will have previous row original value for the left one I can just simply go to current row of J minus one for the current value I can itself get the current value which is image of I comma J for this next value I can go to image of I comma J Plus 1 and for the bottom values again image of I + 1A j i + 1 j- 1 I + 1A J + 1 so I + 1A j i + 1 j- 1 I + 1A J + 1 so I + 1A j i + 1 j- 1 I + 1A J + 1 so with this you can get all the nine original values and then you can simply modify the current value so with this you will always be having previous row and current row as just two extra rows which will use two Extra Spaces now although uh this is this will have the time of O of M into n because that is what we cannot even think of modifying and space is just o of n so your space has reduced from o of M into n to O of n many people I have seen will jump straight off to O of one solution which is not intuitive as in like you can just think of but it will not show you that you can think of in every direction the next step is to reduce a space a little bit by giving a solution of O of n again that is a o of n into two solution because you will see you are using two again you can say in interviewer that sir I can do a bit more modification in this by just saying that I just need a previous row and rather than current row I can just take a previous value because I'm not concerned about these values I'm about just previous value so rather than two rows of size N I can take one row of size n and one variable and that will also work but that is a followup for you guys that give me a code although the space will again be o of n it's just that earlier it was O of N2 now it will be o of n itself but the followup like but the follow for you is comment down the code for space of exactly of O of N I will show you right now o of n into 2 which means using previous row and current row because that is much more like to Showcase it's much more a simple code but again exactly everything is same n m&amp;n we have got it uh we take same n m&amp;n we have got it uh we take same n m&amp;n we have got it uh we take we don't need this variable uh we just need a previous row we just need a current row uh and again we don't need the previous value because that would be required if we are using just one row but now we plan to use two rows previous row and current row so before even starting off with my image of I row I assign that to my current row because as soon as the loop will end I will assign previous to the current row as soon as Loop will end now I will actually go on to my all of the values because for a cell I need its top values I need its left like I need its previous neighbor I need its next neighbor and I need its bottom values right that is I need what I comma J so I went on to and again this is the sum and count which I want to initialize I will go on to all the bottom neighbors so simply saying if I + 1 is less than M and I if saying if I + 1 is less than M and I if saying if I + 1 is less than M and I if I have this J values like just saying okay if it is in the bounds just simply go it if I can go to this specific cell go to this cell I can go to I can for sure go to the cell because i+ 1 is less sure go to the cell because i+ 1 is less sure go to the cell because i+ 1 is less than M so I can go to this cell so go to Simply this when I say go to Simply add the add in the sum and simply get its count increased by one and again I can go to check that if I can go in the right I can simply go in the right now I check for the next neighbor just simply saying if k + 1 is less than n simply saying if k + 1 is less than n simply saying if k + 1 is less than n just simply added some and count increase I'll go on to the previous neighbor I'll go to the previous neighbor but for the previous neighbor you know that you will get its actual value from the current row so I got it actual value from the current through itself because I cannot use my image because image has been modified so far right okay cool and then I'll go on to the current cell which is for sure current cell which is the cell itself current cell so I just got go on to the current cell that's great I will go on to my top neighbors the same way I went onto my bottom neighbors exactly the same code uh you will see I went on to my top neighbors simply saying now for the top neighbors I know I will use my previous row because previous row is containing the original values it is I -1a J-1 I -1 original values it is I -1a J-1 I -1 original values it is I -1a J-1 I -1 comma J and I -1a J + 1 same i-1 comma J and I -1a J + 1 same i-1 comma J and I -1a J + 1 same i-1 comma J-1 I -1 comma J and I -1 comma J +1 J-1 I -1 comma J and I -1 comma J +1 J-1 I -1 comma J and I -1 comma J +1 I'll go on all these three values same as what we did for bottom it's just that we'll now use previous row as to get the original values and ultimately I will have my modified values which means sum upon count and then I'll simply assign that to my image of I and I can simply go keep on going forward just make sure that as you go on to the next row Please assign your previous row to the current row because this these two R are containing the original values and with this your space and time is O of like your time is O of M into n which is constant for sure like which is which will remain as it is because you're not modifying that your space has reduced because now you are using only two rows again the follow for you guys is just to use again for this I'm using a space of n into two because I'm using two rows you will use only one row and one variable to get the answer now the final method which is actually more optimized is because we will try to optimize it much more how to even think of optimizing just think of everything which the interviewer has told you interviewer must have also told you the constraints if you go and look for then okay M and N that is pretty small which makes this question easy but let's say if M andn would have been pretty large the thing which should click our mind is this value why the is this value so small as in why he has given the value so small can I use the so small value if you look this value closely it is a 255 which is nothing but a 2^ 8 minus 1 because 2 8 is 256 a 2^ 8 minus 1 because 2 8 is 256 a 2^ 8 minus 1 because 2 8 is 256 that's a standard number which we all know it's a number which is 2^ 8 - one now minus one is just is 2^ 8 - one now minus one is just is 2^ 8 - one now minus one is just indicates one I have some zeros minus one will give me all values which as one as it is so it will be I if I say I have eight values as one in binary one11 in binary form that number is at 255 that is what I have written also here which means an integer value is a 32-bit number but here I am value is a 32-bit number but here I am value is a 32-bit number but here I am only an integ again an integer value is if you just have remember um an integer value uh which is like you have written like 2 32 minus one in your like limits when you have studied your C language or any basic language you must have written like integer bounds are this values so you will see that you have the range of 32 you can you actually have 32 bits to place a number but here I'm only using eight bits which means remaining 24 bits are not used at all that is the Crux of this question that you can use those extra bits to store extra values which means I can represent my normal integer as these 32 bits but what I will see is if I just use this image of I comma J which is just maximum value is 255 it will only use the starting eight bits which means this remaining 24 bits I can use to place any values in this which means I can use this next eight bits I can use these next eight bits to place any other value I can use this next eight bits to place any other value I can place I can use this next eight which to place any other value so basically in this one value I can place four different values and they will not impact each other because all of them will be of eight bits Max so there's other thing which you got to know that in this one integer I can store four different integers and I can retrive all those four different integers anytime I want so now you know that okay the only issue which you had was you had to make another array to store the original values right so what I will do is I will not use another array I'll use the same integer to store both the smooth value and also the original value I'll store in the start 8 Bits the smoo value I will store in the next 8 Bits and again if you want to have other variables Also let's say smooth and two smooth and three then you could have also placed them in the next eight bits and next eight bits so this integer gave me options to store four different integers that's how I can place it so what I will do is I'll just use a starting 8 Bits for the actual image values and the next eight bits for the smoothing values now how by how we can do it so one thing is for sure if I give you a value let's say five which is the image value so it is 101 but I will for sure store the eight8 bits for the image of I even if it is a 0 I will still store this value which is like for the image of I still store the 8 Bits so I can just grab these eight bits and say okay this is my value and I said the smooth value smoo value now smoo like smoo value is sum upon the count let's say if I have got the sum upon count as let's say number seven so I know the seven can be represented as 111 so now I know okay I have to place my 111 eight bits from starting I cannot place it here I have if this is the value of sum upon count I have to place this value I have to place this one1 value in after this eight bits so I'll place this eight bits like this and again remaining bits for by default will always be zero but make sure you are not using the starting eight bits but by how to do that simple firstly get this value as seven and then simply left shift this seven eight times so what I mean is firstly get this value as seven and then left shift as in shift left okay shift this left eight times that is how a left shift works so this value which means I will do a seven left shift by 8 so this value seven will be left shifted by eight times to the left and that's how you will be able to place your smooth value in the next 8 Bits but byya okay uh this was the image value and this was the smoother value which we have got but ultimately I wanted to store both the values in one value right yeah simple okay you have these values you have this values simply do or operation so what we'll do with our operation or operation your image values will come in the left side because it is all zeros so it will come as one1 and your smooth value will come on the on this side which is 111 simply by the r operation you will get both the values for us so now in this one integer you have corresponding both the values which is the actual value and the smooth value right and smooth value you achieved by getting the sum upon count which is smooth value left shifting eight times because eight times you know eight times is giving me because of this thing that I have this value as 255 which is a 8 bit integer so my image value will take only eight bits remaining bits are free for me so I can just left shift completely by it and I will be safe at every moment and any moment now great uh Now by okay my everything is done my entire computation is done I have used my original values to compute every of the smooth values But ultimately my value looks something like this so my value ultimately my value will look as 1 01 so if I convert this thing into an integer so it will become as 1 0 1 which is actually a different integer I just wanted this smooth value ultimately in the end I don't want these values right so yeah simply that's correct you have this value how you achieve that by left shifting by eight times yeah so you have to remove this now simply right shift this value by eight times so you know that this is the value which you have if you keep on right shifting now how right shifting work is if this is a value it will just truncate it will just trun it will just leave ahead so if I just if I have this value if I right shift this with one time so how it will look like is it will become a 1 one and one zero so one got truncated and similarly I'll keep on right shifting this entire value eight times so ultimately this thing will come to the end and this will entirely truncate to the like it will just go away it will just truncate and this is how you will get the smooth the values right so that is a bit manipulation great technique which the interview can ask you and that is what makes this problem a medium problem so again everything exactly same as what we wrote in the above code if we just go back you will see everything you will see just have a glance at this code have a glance everything will be exactly same everything it's just that while I am assigning in my sum I need to know that in my sum I am taking only the original values in my smoo the values in my smooth the values I should know okay it should be my smoo the values right ultimately uh I need to convert this values which is a mix of smooth and origin values to just only the smooth values so I'll just have a bit modification code here in the end which will convert smooth plus original to only Smo the values by just simply doing a right shift let's quickly see that what we saw above as I showed you exactly same code I went on to all of the IG I went on to grab the sum and the count I went on to all these nine cells I check if that specific cell is in the bound of my entire Matrix now if it is in the bound of my entire Matrix I will go and say okay for that specific image value just only get the original value is in the starting eight parts now why is this value done so you remembered that your original value if this is a value your original value was only was in the starting eight parts right so you have this as the current image value because you will be doing or operation all that stuff so your current value image value is like this will look something like this you want only the starting values because starting values represent your original values so you will do a 1 one remaining by default every one will be a zero if you do a and operation between this current image value and this specific mask let's name it as mask so this will give you all the values as what were the yellow values and remaining everything no matter if it is a one or a zero remaining everything will be a zero so this by this you will get a original value only from this mixture of smoother than image values because right now image of I comma G J which is the input array you have modified this to a mixture of smoothen and actual image smooth and original values but you only have to derived the original values so as to add in your sum so that's the same thing I did I just make a mask of 1 one11 eight times and that ultimately I have just got this mask I'll do a and operation from this it is a original plus smoothen and this is the original value this is actually the mask for original value only when this is applied so smooth value entirely will be gone I'll only get the original value out of it now when I got the original value I'll just add that in my sum and increase my count Now by this I will only get the original value sum now when I have got the original value sum I know that it is the sum it is the count from the sum and count I can ultimately grab the smooth and value okay from the sum and count I can get the smoo value is sum upon count right okay I know that my image of I comma J was storing the original values I have got the smen values now I have to add in my in this image of I which was only having or original values previously I just have to add in the like Smooth value also so just simply as I showed you it is the smooth value left to shift this by eight times and then simply do a or operation in the original values to make this original value as original plus smooth on values so now this image of I will be having original plus smooth values but P previously you were grabbing original values and you were saying that original values were having original plus smooth yeah bro exactly because it will go on as we showed if this was a matrix this was the entire thing so this is I comma J so this is having these four will have original plus smooth values in image of I comma J and these five will have only the original values and right now I am only modifying this specific cell which is having original values to original plus smooth values to go ahead that is the reason for this case it I did this and for sure even if I do this for original also it will only grab the original values because it is just removing the smooth values this case is only removing the smooth values from my image of I comma J right and ultimately as I have grabbed the entire smooth value like Smooth values sum upon count I have grabbed the sum I have grabed the count now I can just add like assign my smooth value in my sum and the account and ultimately um I know that this now image which was earlier smooth like which was earlier only original now it has original plus smooth values both starting eight bits original values next eight bits smoo values now ultimately my entire stuff is done now my image of I comma J all the image of I comma J is having both original plus smooth values original in the starting 8 Bits smooth in the next8 bits but I want to remove all of these original values now I only want to have the smooth values so I'll just simply do a right shift of every of the image values to only get the smoothen values and ultimately I return the smooth Matrix sum like I'll return the smooth Matrix and with this you will use only o of fun space and time is again it's it will remain which is actually o of M into M and that's how incrementally again incrementally we saw all the variations from very start to very end in that's the only thing which I wanted to show you incrementally go ahead in interview that is what makes him show that okay you have not done a artification and you have not reached your solution just like as it is cool I hope that you guys got it bye- bye and yeah please uh let me it bye- bye and yeah please uh let me it bye- bye and yeah please uh let me know that how this can be solved that's a issue which has occurred a lot and I just wanted to get this issue done cool bye-bye thank you
Image Smoother
image-smoother
An **image smoother** is a filter of the size `3 x 3` that can be applied to each cell of an image by rounding down the average of the cell and the eight surrounding cells (i.e., the average of the nine cells in the blue smoother). If one or more of the surrounding cells of a cell is not present, we do not consider it in the average (i.e., the average of the four cells in the red smoother). Given an `m x n` integer matrix `img` representing the grayscale of an image, return _the image after applying the smoother on each cell of it_. **Example 1:** **Input:** img = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[0,0,0\],\[0,0,0\],\[0,0,0\]\] **Explanation:** For the points (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0 For the points (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0 For the point (1,1): floor(8/9) = floor(0.88888889) = 0 **Example 2:** **Input:** img = \[\[100,200,100\],\[200,50,200\],\[100,200,100\]\] **Output:** \[\[137,141,137\],\[141,138,141\],\[137,141,137\]\] **Explanation:** For the points (0,0), (0,2), (2,0), (2,2): floor((100+200+200+50)/4) = floor(137.5) = 137 For the points (0,1), (1,0), (1,2), (2,1): floor((200+200+50+200+100+100)/6) = floor(141.666667) = 141 For the point (1,1): floor((50+200+200+200+200+100+100+100+100)/9) = floor(138.888889) = 138 **Constraints:** * `m == img.length` * `n == img[i].length` * `1 <= m, n <= 200` * `0 <= img[i][j] <= 255`
null
Array,Matrix
Easy
null
881
hey everyone welcome back and let's write some more neat code today so today let's solve the problem boats to save people we're given an array of people and each value in this array represents a person of course but more specifically it represents the weight of that person we're also given an infinite number of boats where each boat has a max weight limit that's also given to us as a parameter of the function so each boat will have the exact same weight limit and there's another restriction that each boat can carry at most two people but for us that's good because it actually simplifies the problem but also of course the two people the sum of the weights of the two people can't exceed the limit of that boat which is straightforward our goal is to determine the minimum number of boats it would take to carry all of the people and it's always going to be possible to do that because we're also told that every single person is going to be within the weight limit of you know the boat so since we are given a weight limit and we're trying to get the minimum number of boats how should we go through the list of people and their weights suppose the limit was something like 10 and then you know we had one person whose way is four now and we still have our entire list of people left so who should we pair this person with well we maybe we could pair them with someone who weighs one that's a valid choice maybe there's another person who weighs two maybe there's a person who weighs six wouldn't that be the ideal person to pair this person with because we're reaching as close to the limit as we possibly can we're carrying two people per boat so that's kind of what we want to do right we might reach the exact same solution with pairing them with the person who only weighs one but we don't know for sure yet it might turn out that in our array there's a one a six and a nine right if we use the one and the four together then we're gonna need one separate boat for the six and one separate boat for the nine because they can't both be on the same boat because they weigh too much so this is really leading us towards a greedy solution so for every person we have we want to pair them so that we get close to the limit as we possibly can so on that train of thought of being greedy it would probably be better to get the heaviest people first because using that same example if we start with the heaviest people we will still have the least heavy people to pair them up with and that's exactly what we want to do of course we'd want to pair the heaviest person with the least heaviest person if it's possible so this is very much a greedy solution now the question is how are we going to find the heaviest person and also the least heaviest person if we were only looking for the heaviest then we could probably go with a heap approach but since we want the heaviest and the least heaviest then we probably should sort the input array because it's not really sorted for us necessarily so this is very much a problem that your intuition can actually lead you to the solution there's not a ton of fancy stuff going on here so we're going to be greedy we're going to sort the input array we're going to start with the heaviest person and then check can we pair them up with the lightest person in this case yes we can so we're going to use one boat and you know carry both people we can't carry three people no matter what we do even if they're within the weight limit but in this case carry these two people so next we would start with the next heaviest person and then also with the next lightest person so as you're kind of seeing we're really going for a two-pointer approach this is a for a two-pointer approach this is a for a two-pointer approach this is a pretty standard algorithm hopefully you've seen it before where we sort the input array go with the two pointer approach and then decrement our right pointer accordingly and increment our left pointer accordingly when we need to now it could be possible that maybe this one is actually a two in that case we would need a dedicated boat for this nine then our right pointer would be here our left pointer would stay here we couldn't necessarily take them in the same boat but that's kind of the algorithm we would just continue it at this point this six can we pair them up with someone yes we can so in this case we'd use one boat for these two and then we would increment our two pointers in this case they'd be at the same index so we'll have to watch out for that when we actually write our code since both our pointers are here then we can put you know just this one person in a single boat we'll have to make sure we're not adding the same value twice but all in all it took us three boats in this case and so that's what we're going to return so overall our time complexity is not really bottlenecked by the two pointer approach it's based on the sorting that we're doing before that which is n log n so with that said let's jump into the code now so now let's code it up we are given our people array and that's what we want to sort before we actually start this problem and then our result is going to be the number of boats now i probably should call it boats but i've always called it results so i'm kind of just stick with that our two pointers are going to be initialized in a pretty straightforward way at the beginning and at the end of the array and then we're going to go while the pointers have not crossed each other they can be equal to each other because that means there still is one person left which is fine but they can't cross each other because that means we ran out of people now we're always going to start with the heaviest person so what we're going to do is just take our limit and then subtract from it the heaviest person who is going to be at the right point so this is basically the weight that is remaining for the current boat that we're using since we took this person and put them on a boat let's go ahead and decrement our right pointer and increment our result but the only question is can we take the lightest person now and also put them on the same boat that's the case if the remaining weight is greater than or equal to the person at the left index but also let's not forget that edge case what if the left and right pointers are equal to each other that means there's one person left that means maybe this was the last person so let's check that in our conditional before we even check if there's enough weight remaining let's check that there still is a person left we know that if the left pointer is less than or equal to the right pointer because remember we just decremented our right pointer over here so if there's a person left and enough weight to hold them let's put them on the boat we can do that pretty easily just by incrementing our left pointer we don't have to do anything else after that's said and done though we can go ahead and return our result and let's run it to make sure that it works and as you can see on the left yes it does and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
Boats to Save People
loud-and-rich
You are given an array `people` where `people[i]` is the weight of the `ith` person, and an **infinite number of boats** where each boat can carry a maximum weight of `limit`. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most `limit`. Return _the minimum number of boats to carry every given person_. **Example 1:** **Input:** people = \[1,2\], limit = 3 **Output:** 1 **Explanation:** 1 boat (1, 2) **Example 2:** **Input:** people = \[3,2,2,1\], limit = 3 **Output:** 3 **Explanation:** 3 boats (1, 2), (2) and (3) **Example 3:** **Input:** people = \[3,5,3,4\], limit = 5 **Output:** 4 **Explanation:** 4 boats (3), (3), (4), (5) **Constraints:** * `1 <= people.length <= 5 * 104` * `1 <= people[i] <= limit <= 3 * 104`
null
Array,Depth-First Search,Graph,Topological Sort
Medium
null
1,498
hello hi guys good morning welcome back to the next video is a problem number of sequences that satisfy the given some condition no matter what if you have solved this problem no matter what just watch this video because see the logic would be for sure same if you have solved it logic will be for sure say but the number of approaches to code that same thing will be different and specially for the different languages also without further Ado let's start with this Anya before that can you if you just see that package so yeah it came yesterday in the night but I was tired so I could not open it but it is something related to the last lead code contest stream so if you have watched it you can just guess what would be inside that package just guess if yes you would guess is right then no worries yeah also do let me know if you want unboxing of these kind of tech stuff in this channel like just a normal unboxing not a Hi-Fi inboxing yeah unboxing not a Hi-Fi inboxing yeah unboxing not a Hi-Fi inboxing yeah before further Ado let's have this problem uh it says that a number of sequences that satisfy the given some condition you are having an array of integers called as nums element subsequence which means any element in the order any element number of subsequences remember this word number I am not concerned about this subsequence I'm concerned about number of such subsequences number thing is please remember because it is very helpful cool number of subsequences non empty subsequences of num such that the sum of minimum and maximum element on it basically uh the subsequence is minimum and maximum element sum it should be less than or equal to the Target value remember minimum and maximum element of that subsequence I am not concerned about rest of the elements I'm just concerned about the minimum and the maximum element since the answer will be very large which means the number of subsequences can be pretty large return it Modular One and per seven it is standard cool first thing I'm just concerned about the minimum and the maximum element of a part of an array right if C for now let's forget okay it's a subsequence basically subsequence says the elements needs to be ordered right but I am not concerned about these subsequence itself I'm just concerned about number of such subsequences which I mean is if I have anything like x 2 3 4 right let's say one two uh one four two cool up number of subsequences of this 142 and number of subsequences of one to four are they both same or not same tool so one thing I can for sure say that for number of such sub number of subsequences maybe the order might not be important maybe it is just an intuition which comes in our mind we will verify it later but it is first thoughts which comes in our mind okay maybe the order might not be important but let's see what we have to do okay when it says okay just concern about the minimum and the maximum element now while evaluating a subsequence let's say if I choose some uh subsequences one two four six two five three one now while evaluating a subsequence let's say I choose this particular whole part now I choose two six five three Now isn't it very bad for me that I have to go okay go on the entire array and see okay what is the minimum is this I have to own the entire ad and see what is maximum energy maximum in this maybe it can't be very easy for me if I just can't choose okay the starting element is the minimum and the last is the maximum as simple as that so for that what can come in handy for us is sorting because I just want I'm just concerned about the minimum and the maximum element what if it can give me in the start and the end itself so it is okay one thing comes okay I just want minimum maximum element maybe I can just sort it out and I also saw earlier that sorting won't affect me as such because I just want the number of such subsequences and number would remain same because I just want minimum the maximum Elemental maximum element of that subsequence an element will fall shortly remain same so maybe intuition one is that okay I can sort maybe it is a few thoughts which comes in person's mind by solving a problem it may be wrong it may be right cool now it is the thought which came in while reading the problem itself I have not even started to see the example I get now let's see the example three five six seven and the target is nine uh one thing I got to know that if you see the constraints the number of elements are 25 so you have to find the number of such subsequences in either o of n or o of n log n at Max you can't go beyond that which means if I just go to Brute Force way of finding the number of subsequences let's say if I find number of all subsequences which is power n then find the mean maximum Element no worries for let's say now I just sort it so I can find okay minimum maximum in just o of one cool and this to figure out okay how many such numbers it will be bullish for n Only provided I sorted it initially but it is still more which means I have to find subsequences but because one thing I for sure know I have to go on to every element which means I have to find what this element can contribute to me in number of subsequences such that the condition which follows minimum uh and maximum sum is less than this target it follows how much this Con this element can contact because one thing of for sure now I have to go and go on to every element which means o of n is for short gone so I have to find what this element one element can contribute in number of subsequences I have to find okay what this three can contribute what this five can contribute was the six can contribute what's this 17 contribute I have to find this in over one anyhow okay now I've got to one thing for this array when I'm in trading on this array I land at three I have to find okay what if this three can contribute in the number of subsequences okay cool no worries uh for that what I can do is uh for three okay I'm standing at three let's consider three as the minimum element itself now what maximum element I can take in my subsequence I can take okay if 3 is the minimum element then I can and three plus something which means the maximum element it should be less than equal to nine so maximum element should be less than equal to 9 minus three maximum should be less than equal to six so I think I got one thing for sure okay maximum should be less than equal to 6 which means in my subsequence I know 3D will come for sure because it was said I want to choose a non empty subsequence and I consider let's consider 3 as my minimum element for the one element and let's use the rest of this subsequence one of my element now let's see okay what can be the um number of subsequents but if I consider one of the element then it can come in minimum also maximum also so let's for now let's say okay let's consider 3 as one of the minimum element itself and let's try okay what all subsequences can be possible such that my other number is the maximum element I can go okay I first found out that my aim is less than equal to 6 so it can be maximum element I can take in my subsequence now I just for sure okay 3 is my one element I am taking right now and six it can be the same element I can't take which means more than six I cannot take less than six how many elements are there less than six elements are two so basically with 3 with the 3 with a 3 I can take either five or six or no one else also because I am also grabbing three as well right three I am for sure grabbing for the other options five and six I have okay I can grab it or not my main condition you saw what happened my main condition was I need to grab an element less than equal to 6. I'm just grabbing that element which is less than equal to 6. now for this I saw there are two elements which are less than equal to six three I for short grabbed no worries for that I have four two elements there are always four options for one element you have two options just grab it or just not grab it two options for the next element also you have two options just grab it or just not grab it so it is just two options that is the reason I just say okay no worries you can just say that okay for this grabbing five and six you have four options so with this three number of subsequents I can form is actually Four you can see one is with three one is three and six one is three and five one is three five and six and anyhow the maximum element is bounded by this particular six because it can't go beyond six because I always choose the numbers less than equal to 6 and for sure it's bounded by this three because I'm starting with this 3 itself now comes interesting part you saw what happened while I was choosing okay I want the number of elements less than six won't it be good if I had already sorted my array so that I could get number of elements in less than six very fast maybe in O of one or maybe in of login because if it is sorted and you want the number of elements less than something then you can just apply binary search and get okay number of elements less than something that is okay one intuition which we thought of would actually help us that we will just sort it just so that I can find number of elements in less than a bigger number in just over one cool so basically to get the maximum element okay one thing was I was standing at three I need to choose what element I can get a six for that I just thought okay I will just sort it down so that I can just get it okay what is the location of six and I'm standing here so I can just grab this range for me which means these two elements I can choose okay opted or not opted so ultimately I just need to find the position of this particular six which is nothing but I need to find the position of what is the maximum bit I can get for this particular eye right now I considered three is considered which I'm considering right now as the minimum element for this add two options I can just use binary search or two pointers are in uh binary search looks fine but like you said okay you want to find okay you know already you need to find a six so you said that it is sorted I can find a six in my binary search because it is sorted finding a location of an element it can be remove login but how two pointers are in I could not understand it just see like this if you have this number three and you have this number six let's see in the beginning both the pointers of three five six and seven in the beginning the pointers are ing always two pointers is used because see you have a limit that the sum of the nums of I plus nums of J it should be less than equal to Target this condition is satisfying for short the range will always collapse it will never go okay if our eyes standing here now I will say three plus seven is it less than equal to 9. so I'll just decrease my J cool now six plus three is it is less than yeah it is now when three is evaluated when number of subsequence is possible for three are done I will just increase the I you remember one thing your Gene never went forward because for sure I is increasing and for three plus six it was the condition okay it was less than equal to 9 then for sure for five plus six it may or may not be which means for three plus seven where J was here it was more than nine right if I increase this three to five it will for sure be more right so if I'm just decreasing it which means now 3 plus 6 is at a brim of let's say goodbye is that a brim of mine if I increase it so for sure it will just increase the left part will always increase it can't decrease that is the reason the number of subsequences possible it can always just go this I am just using two pointers to find out okay how many number of numbers are there initially you will see I and J are here so the numbers of numbers possible are in this subsequences I can just choose three five three six and three five six it is how I'm choosing a subsequence like this I'll show when I'm just actually throwing this two point of approach that how it is being done but now we just got to know that for every element when we just choose okay I just choose right now I'm at index I just choose okay it is index I maximum enable it can be at index J I will just choose okay number of elements it can be let's say number of elements which can I can think office 2 which is 5 and 6 so number of possible options are for me four for this element three right here number of possible options number of possible subsequences it can be four which is uh two raised to power 2. this 2 right here is nothing but these number of elements which are two elements so if you just clearly look it is nothing but if the index is I and the index is J so it is J minus I it will just nothing but 2 minus 0 which is nothing but 2. so basically J minus I returns number of elements here right here that is the reason I can just find okay for this particular index the contribution of number of subsequences will be nothing but foolish over J minus I now let's see what we got the intuition first intuition we confirm it will sort why because for one index I want the maximum element J login such that I can find the number of subsequences possible for this particular I index in just open or overflowing okay one thing I got for sure know that I will just sort it now next intuition which we had was the intuition right here that to find this maximum element we just need a two pointer or a binary search approach and that for sure will work because I just wanted R actually thing to work in open or off login thus to find this maximum element a basically number of elements in the range from minimum to maximum it can be turn my two pointer or the binary search because the array is sorted because of the intuition one we had cool now comes interesting part now you remember what we have to do what we simply do is we will just start our inj I'm just using a two pointer approach you can also use a binance approach which means it will just start from this I you know what is the maximum element you know what is you know you want six so you will just point it to six and we'll find okay number of elements in this range which is J is pointing right now here now to find out the contribution of number of subsequences because of this I it will be uh J minus I and it will be done same you will just go on to the next element and then again do a binary search and so on and so forth but the better way is not to do binuses again and again you can just start from this pointer Ing and just keep on reducing the range and as you keep on reducing the range I and J you know okay this ing is valid so for this I the range actually it can be three to six so the contribution will be J minus I and same we will just keep on increasing your eye and keep on decreasing your J and for every of this element at every I increase you will just check okay what is the contribution of this I right now so you can just easily do that let's see the code with this how it is being done first find the 2 raised to the power J minus I as C it is the indexes it can go up to n which is the length of the array you just can't compute it by the normal method because see for every of your eye movement you have to compute this which means every of the two pointer movement because your eye is moving your J is moving so for the this movement you need to compute two raised to the power I or J minus I should say which is which can be around o of n which can be around n big so if you just compute it linearly then you are done you are gone thus I told you that just watch this video so basically to compute our exponential number which means a raised to the power n we have a binary exponentiation which can compute this a raised to the power n in log n time it is a very standard technique used to find exponentiation you might have seen this in Fibonacci series also and other problems also but it's a very sound problem to compute the exponents of a number thus you will see right here I am using by the exponentiation it is a very simple it is nothing but if the number is odd which means if your power right now is let's say 5. you will just simply let's say you have a raised to the power of 5 so what you will do is let's say the result is right now one but a rishaba 5 is there so you will do a result is equals to whatsoever result is there okay 1 into just multiply by 8 once so now the power will reduce by this number one because you just multiplied one times only but as soon as it becomes even what you will do is rather than just decreasing by one again which means you have done a raise to power R3 which means one in a was already there so like res is now a into a again right but rather than decreasing it by one you will just decrease it by two which means you're 4 you have the power as 4 right now it will just decrease by two which means a will just which means n your n is power n will become 4. by 2 which is 2. it is decreased by half rather than decreasing one as soon as it becomes even just decreased by half which means a becomes a which was already a into a that a which was your this existing a it becomes a and mod P is just to make sure that okay mod b is happening again and that is how you will see your result it was just like nothing but sorry your result your just a is basically see it is one thing that result will be result into a in the all operation only but I'm just making sure rather than just making multiplying by a how about I just increase this a twice which means you will see in the even time our result is not changing but our a is becoming twice and what will happen next time is as okay it becomes a 2 then it becomes it is in the next situation it's again even so it will become a one so your again a is now a square so it will again become a now in the next iteration when n is 1 what will happen is it will just go on and multiply with this arrays which was already I so a into a raised power 4 which is nothing but a raise power 5 that is how you will get a rest to the power 5 where your five was gone no worries it was four it was decreased I guess okay it was five it was decreased to four and then we had this when initially it was a just make sure that it is at all operations I am just increasing my rest into a in the even operations I am decreasing my n which means any if n is even so now I am part of the whole power which is even I am decreasing it by half which actually in turn increase my base component is a it is being increased which means a into a next time will be let's say it becomes a square so it will be a square into a square next time it becomes a raise power 4 so it will be a raise power 4 into a power 4 and as soon as again my odd power comes this area everything which is already my a has been computed it will just go on multiply balance which was already being computed for odd thing that is how you will just get it because you are just doing a half every time thus you are getting the computation in of login if you're not got it just go and watch the binary exponentiation but if you just go and try run this you will just easily get it's actually very easy Now by exponentiation I just took a bit time to actually explain you my inspiration but it should not be this case but yeah let's see what can be done now as you know that it is we have to sort now to sort we can use apply a two point approach or the bind search approach by such you will not apply for sure it's a higher competition path two pointer we can easily apply its lesser because buy and such to do the same stuff to find for I to find the J it is using of login time while the two pointer will use o of one time that's the reason I'm just using a two pointer approach now the standard two-point approach which comes in two-point approach which comes in two-point approach which comes in people's minded but see one thing firstly I'll just show you a bit long code but it is more intuitive to write and think then I'll just move on to a short report which is actually short to write but it is more complex for many starter people if you just start off writing a two pointer thing now to write a two pointer it is for sure good that you move your eye once step you move your eye and in The Next Step you move your J while you can to do the same file you can do the same thing parallel also which means if you just here you will see in the next step I will show you how you can make it parallel but here I'm just showing okay in the fun for Loop you will say your eye is only moving here in this for Loop your eye is only moving until your eye is less than equal to J it is one condition because I and J are moving like this so I is moving J is moving so you should need to make sure that they should move until they don't overlap each other or basically surpass each other in the next loop I am just moving my j i is fixed now I'm trying to move my J such that the condition is followed which means nums of I plus nums of J if it is more than my target I need to reduce if it is more I need to reduce as it becomes equal I will just go and say okay I have landed on my J I have my I initially because of the above for loop I have my because of the below for loop I have my J and it is just I is moving like this J is moving like this because above for loop I is moving like this because the below for Loop while loop my J is moving backwards now when my J is done I should firstly make sure my J should be at least more than equal to I because you will see the condition is I is equal to J and J minus so if I and J are equal then still my J will increase so it can happen that my jsr passes I so I'll just say okay if my G is less than more than equal to I then firstly I will just compute the path because I just want as I said for this number right here if my I was here G was here 0 1 2 the number of numbers right here which are impacting my particular I R2 which is nothing but J minus I 2 minus 0 so I need to compute 2 raised to the power J minus i j minus I are these numbers and every number has two options grab it or not grab it now I will just grab it is power J minus I now with this I will just add for every I am just adding okay what this power can compute what this power can contribute to my answer and ultimately I can return the result it is one option to code now if I'm not if I don't know binary exponentiation still I can solve this problem in O of n login how firstly the same exact same thing I just sorted the thing out it's the exact same part I am moving my eye and I am moving my J here it is exam part if my J is more than equal to I now the exact same part that I am adding my power in my result by the only thing now you will change is that I one thing for sure no if I just don't know by the exponentation I can't solve this I can't compute this power again and again which means I can't compute storage one two spot two to four three two is power 4 up till 2 power 25 I can't compute because it will be to actually compute this I need to go on like linearly which is O of n as it is already o of n so inside this if you compute this o of n so it will not work it will be of n Square which will which won't work thus you have to just pre-compute it pre-compute it pre-compute it now how to compute 2 raised to the power 6 if I have I just multiplied that by 2 I can simply get a 2 reference X so I will just keep on Computing like this one two square two Cube 2 is power 4 2 is power five which means at this value I will just say okay what was the last value multiply that by 2 and get the current value what is the last value multiply that by 2 get the current value as simple as that what I will do is you will simply see firstly I have this one because I will for sure start with one then I will just grab what is the last value is nothing but one multiply that by two multiply that is nothing but a left shift operation is much faster than a multiply operation all the both are same although I can just write the same thing as three dot back into two again the same thing as this but a left shift is a faster operation because it's a binary operation it's faster operation then a multiplier by two cool I'll just grab it and I will just push it basically I'm just trying to make this particular pre-computation like this with this help pre-computation like this with this help pre-computation like this with this help I can just grab okay the power of every element after four is power N I will just grab all the elements and will be computed in this P array which means purify 0 to 25 and so on I will just use that pre-computation of I will just use that pre-computation of I will just use that pre-computation of J minus I which is nothing but 2 power J minus I and will return this value in O of 1 time that is the reason how I can actually optimize it now as you saw we are just moving our I forward and J backwards right so as I showed you that it looks a bit bigger code but it is a more intuitive code to write you move your eye you move your chain right while many people write it much shorter that I will just move my Ln R which means inj until they both are actually less than equal to them which means while my L is less than equal to R I'll just move my Ln r and it was also the same thing which you were which we were doing we were moving until it was less than equal to so basically it is converting this whole thing into a while loop but it's much shorter and looks cleaner how what we can do is the condition was that okay move L move R when your condition okay the sum of Ln R if it is more than Target then only move your r same thing what we did move R firstly the condition I should be less than equal to J which is actually the while loop move R move j with it is more than equal to my target then you just moved your J now if it is not the case then just add that contribution of that 2 to the power R minus l in your result as simple as that added the contribution in my result as simple as that and also increase your R which L which means in the next iteration your I will increase that is the same thing which we performed right here in this particular code part if you just see this code part exactly the same part of precomputation exactly sorting part this part it become more it became more shorter thus it's a two-pointer push which is thus it's a two-pointer push which is thus it's a two-pointer push which is shorter one but it's a bit hard to actually write in this way and it's also hard to debug if it goes wrong but in this case it is easier to debug many people may understand this but according to my experience uh of teaching many people have got this method as much more faster and easier because it's more intuitive to actually see okay here I is moving here J is moving now ing has reached now let's compute what ing have to do and let's move your eye further that is how you will do you can do also line like this just have L is less than equal to r or is less than equal to j i n j l r looks more of binary search thing but it's not binding such it's a two pointer approach cool uh complexity I have shown you already but I will still show you that this part which is binary exponentiation it is login part which will happen you will see that firstly sorted so n log n while doing this two point approach I is moving like this J is moving like this ultimately it will just move o of n Only here while doing the pre-comp here you here while doing the pre-comp here you here while doing the pre-comp here you will see while doing this power thing it is O of n log n for this any Loop is of n log n and this is to find over result it is over one so ultimately it's O of n log n this whole part it is ofn login which means that complexity will be o of n log n for my sorting I know of n log n for this particular Loop which is two pointer approach space is open because I'm not using any space it is the interesting part many people will say that and C plus and Java are the space used will be o of n because they have to do pre-competition because they have to do pre-competition because they have to do pre-competition but they don't know that in C plus version Java we have in Python we also have that we can compute very big exponent very easily but in simplest Java we don't have so we have to do a pre-computation part we have to take pre-computation part we have to take pre-computation part we have to take that route but it's not necessary we take the precomputation part we can also use the binary pronunciation many people don't teach this part maybe they know maybe they don't while in the case of precomputation firstly you will just use your of end time to actually pre-compute your of end time to actually pre-compute your of end time to actually pre-compute space will be also open because of this pre competition login part same as the previous part this pointer two point approach IE and J for sure then to actually get this power it's O of 1. to get it's also offered to actually compute it's entirely o of n which was earlier o of n log n it was earlier of n log n now it is O of n because of this precomputation of O of n so ultimately the complexity will be for sorting Over N log n for pre-computation sorting Over N log n for pre-computation sorting Over N log n for pre-computation of n for actually two pointer approach o of n but space will also be for sure of n because you are using the precomputation part thus you will see that spaces go often that is what you have and just lastly if you had used binary search in place of two pointers which means here in this place if you would have used a binary search to actually find the location of this particular JS so basically your login path would also have come in picture so it was O of one it was O of n to actually move on to every element so it would have been o of n log n so it would have been a o of n log n here it's basically a login contribution sorry of any login here so basically rather than n it would have been of in login if you would have used a binary search that is the reason uh I would not recommend to use a binary search to find your J here because ultimately the complexity will be of O of n log n also here also it was O of n login here also it will be here also it was of n login but it was n log and l login it was earlier n log n Which is less than n log n plus n log n but here it will be o n log n plus n which is more than the earlier approaches which we saw that is the reason just not recommend I'll to use bind search that's the reason I'm not sure that approach also but you can also use the binary search part Java and python code is down below python code is actually faster than all the goals because I am just using pre-computation because I am just using pre-computation because I am just using pre-computation in Python also while python can compute the power itself but this pre-computation is actually faster than pre-computation is actually faster than pre-computation is actually faster than the inbuilt thing which the python can compute so it you will see that it will be faster than the standard if you just access your tourist power J minus I by the function of python so yeah that was all I know the video has gone a bit longer so but I want to show you every approach by exponentiation to pointers by and search everything so yeah it's all from me I hope that you guys like this foreign
Number of Subsequences That Satisfy the Given Sum Condition
find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
You are given an array of integers `nums` and an integer `target`. Return _the number of **non-empty** subsequences of_ `nums` _such that the sum of the minimum and maximum element on it is less or equal to_ `target`. Since the answer may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[3,5,6,7\], target = 9 **Output:** 4 **Explanation:** There are 4 subsequences that satisfy the condition. \[3\] -> Min value + max value <= target (3 + 3 <= 9) \[3,5\] -> (3 + 5 <= 9) \[3,5,6\] -> (3 + 6 <= 9) \[3,6\] -> (3 + 6 <= 9) **Example 2:** **Input:** nums = \[3,3,6,8\], target = 10 **Output:** 6 **Explanation:** There are 6 subsequences that satisfy the condition. (nums can have repeated numbers). \[3\] , \[3\] , \[3,3\], \[3,6\] , \[3,6\] , \[3,3,6\] **Example 3:** **Input:** nums = \[2,3,3,4,6,7\], target = 12 **Output:** 61 **Explanation:** There are 63 non-empty subsequences, two of them do not satisfy the condition (\[6,7\], \[7\]). Number of valid subsequences (63 - 2 = 61). **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 106` * `1 <= target <= 106`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
null
131
in this video we're going to take a look at a legal problem called partition palindrome so given a string s partition as such that every substring of the partition is a palindrome so return all uh possible palindrome partitioning of s so a palindrome string is a string that reads the same backwards forward so here you can see we have an example of aab right we can have partitioning a b like this and each and every single string are all palindrome or we can have aab right this is palindrome and this is also a palindrome as well so both of them are all palindrome so another example is that if we can have a single character in this case we have a single uh element in the string we can just the partition um the result list is going to be a just a single partition right so another example will be let's say ef efe right so in this case we have this is a palindrome so in this case at the end we can have e f e like this is also a palindrome or we can have e f e right so that's also a palindrome right so in this case we have two results right so how can we solve this problem so one way we can do this is we can use brute force and then try for each and every single um combinations that we can find to see for each and every single combination or each every single um partition substring we check to see if it's a palindrome if it is then we're just going to add it to the result list right so this is not the most optimal solution so to solve this problem basically we're just going to implement backtracking and then for each and everything for the current strain that we're given we basically have a couple decisions that we can make right let's say we have a b right in this case we're going to have a list empty list that we're going to um have to store all the uh palindrome partition right in this case and then for the current list is empty right we didn't have any elements in there yet we didn't have made any partition yet i should say so we're gonna have a couple of decisions right we can either partition after a or between a b or between or i should say after b right in this case the entire string we can partition here right so in this case the first partition we have three decision so in this case let's draw it out if we were to partition here right in this case if we were to partition here we're just going to add this element onto our list because we know that this element is a palindrome right only if this element is valid right so in this case what we can say is this we can say if a is valid we're just going to add this onto our list now we left with a and b okay so now what we can do is we can also have another path where we can partition f between a and b so in this case we know that a is the palindrome so we can add a to a list and then we're going to have b we're left with b okay and then the other path we can take is we can partition after a b but we know that a b is not a valid palindrome so we're not going to go down this path so then what we can do is we can see there are two ways to partition this left over string right in this case we can partition after a between a and b or we can partition after b so both ways works so in this case sorry not both way works um a b in this case is not a palindrome so we're not going to go down this path we're going to go focus on going down this path in this case we're just going to add a onto it now we're left with b right and we know that b is also a palindrome right b then we can just add b onto our list as well so a um in this case a and b right onto our list then we just add this onto our result list right in this case we're going to have a result list that we're going to return at the end and then here for this path same thing we know that this b is a palindrome right we can partition right here after b so if we were to partition here in this case we can we know what b is a palindrome so we can add b onto our result list then we're on the uh where partition or pretty much the current index is the traverse the entire string then we can just add the current um list onto the result list right so in this case we have two examples right in this case so let's take a look at another one where let's say we have ef right in this case what we can do is we can have partition between e and f right we can we know that e is a palindrome so we can add e is us to the list and then we have left with f and e and then in this case we can have um partition between f and e or we can partition between after e in this case f e is not a valid palindrome so we're not going to go down this path but in this case f is a palindrome so we can just add f onto the array right onto the list then we left with e right so now we know that e is also a palindrome so we can also add this onto our uh onto our list right see now we can just add it on to our result list right and then we can focus on going down different path this case we can partition right in this case we can also partition after between f and e right so in this case but f e f is not a palindrome so we're not going to go down this path now in this case we can also partition after e so we can have e f e add on to our list right so in this case we know that we're on the end we there's no more strings left over right so in this case we partition last element already then we can just um add this current list onto our result list right so this is pretty much how we solve this problem and let's take a look at how we can do this in code so to do this in code i have a method called is palindrome which takes a string and then check to see if it's a palindrome using two pointers and then here you can see we have the partition method takes a string and then we're just returning um in this case a list of this string in this case right list of lists of palindrome partition strings so in this case what we're going to do is we're just going to have a string right so in this case the current sdr we're going to make it a global variable we're going to say sdr is equal to s and then we're just going to initialize our um or call this that for search method so in this case we're just going to pass in a current empty list right in this case we haven't partitioned anything so we have an empty list and we're starting at zero um and then at the end we're just going to return the result list right so for each every single time we found an element that is a palindrome we're just going to add it onto our current list and then once we reach to the end of the string we can just return the current list that we built onto our result list so that's kind of like our base case we're going to say if start like the um the index that we're starting to partition is equal to sdr dot length in this case then what we can do is we can just add the res we can just add the list onto our results okay but the thing is that we have to create a new instance of it okay so then we're gonna do is we're gonna start iterating starting from index plus one and the reason why we do index plus one is because we're going to get our substring that starts at start to i right in this case start plus one right so in this case start to the current index which is going to be our current partition and i is going to continue to iterate to get all the different partition eyes basically give us where to partition this the start is basically where we start the partition right so i while i is less than sdr dot length and what we're going to do is we're going to get a partition string so substring is equal to sdr the substring uh dot sub string starting from start to i and we check to see if the current substring is palindrome if it's not we don't have to add the current element uh current substring onto our list so it's palindrome so we're going to see if substring is a palindrome if it is we're just going to add the current substring onto our current list so let's add substring and then we're just going to perform our depth search pass in our list and our current uh index right and at the end once we do continue to do the backtrack we want to make sure that we remove dot remove the last element that we added it right so in this case it's going to be list dot size -1 and one thing that i forgot to do is -1 and one thing that i forgot to do is -1 and one thing that i forgot to do is i have to make this equal because the reason why we do um in this case like i've said remember i said that i is basically where we want to end the partition so in this case it's gonna um what we want i reached to the end of this like the last like the index that is one bigger than the um the last element so that we can partition the last element right um in this case we're just going to say reach to the string.length so i to the string.length so i to the string.length so i is going to equal to the straight string that length right so now we're just going to run the code um in this case we have a illegal startup expression so 13 okay so let's try to run the code again and let's try with a different example okay so let's try to submit and here you can see we have our success so this is how we solve this um palindrome partition problem and the time complexity in this case is the time to be exponential and um but we also have this um is palindrome method which is linear so it's going to be n times um exponential right 2 to the power of n so there you have it and thank you for watching
Palindrome Partitioning
palindrome-partitioning
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`. **Example 1:** **Input:** s = "aab" **Output:** \[\["a","a","b"\],\["aa","b"\]\] **Example 2:** **Input:** s = "a" **Output:** \[\["a"\]\] **Constraints:** * `1 <= s.length <= 16` * `s` contains only lowercase English letters.
null
String,Dynamic Programming,Backtracking
Medium
132,1871
199
welcome to lead programmer today we are going to solve the question binary tree right side view uh so essentially you have a binary tree imagine that you're standing on the right side of it you'll have to uh return the values that are visible from the top to the bottom so imagine uh you are standing to the right side of the tree you are able to look at the values of the binary tree you notice we have one which is like the rightmost value of that given level we have three we have four so uh this is the first level of the binary tree this is the second level of the binary tree this is the third level of the binary tree uh when you notice a binary tree you will look at the rightmost node of that level so over here You observe one over you here You observe three or here You observe four so one three four is essentially what we have to return so how do we solve this question so one way is obviously a traversal uh now what type of traversals do we commonly use we either use a BFS or we use a DFS in this case what are we trying to achieve we are trying to get the value of one node from each level again this is one level we want to explore all the levels and get the rightmost node value from each level now how do we go through each and every level going through a level means exploring the breadth first because going in depth might mean okay going from one to a two and then two to a five and then processing three and four respectively but that's not what we want be on a first process one and then go to two and three for we want to explore its neighbors before we go in depth so that calls for PFS obviously you can solve the question using DFS but DFS would be an easier way to solve this uh so the way I'm going to solve this is going to be similar to a question level order traversal where we uh essentially go level by level and print out all the nodes we see the only difference over here in this question is we go through each and every level we see the nodes at each and every level but the only node we care about is the last node of the rightmost node so that's what we append to the results array so definitely check out the question level order uh traversal uh before solving this question because those two are very similar as you might notice here um so uh yep it's a direct BFS implementation where we go level by level take the rightmost not so let's look at uh there's an action so we have a code so if the root is empty we just returned empty string that's what is desired by the question and we have a queue as we do for BFS and to that queue we want to append the root we also have a results array that's what we return at the very end um we keep going till the queue is empty so and then over here we have a size we create a snapshot of the queue and we go through each and every elements for of vehicles with those many elements so size number of elements so if we want to visualize this let's say we take the example uh given so in a BFS we'll our queue might look like this so we first have a one in the queue so that's what we appended to the queue so at this particular stage we have a one in the queue and then we come here we take a snapshot which means okay we see uh that the size of the queue is one and then we execute this particular Loop one time so there we first pop the element so we pop this and we see if uh if I is equal to size minus 1 which means if it is the rightmost element in the queue then we want to append it to the result so in this case yes it is so we append one to the result and we also see if the left and right nodes are not null so if they're not null we append to the queue so here we append um two and three to the queue uh and that's it the four Loops as execution ends and you might have noticed that each for the for Loop pertains to the entire level because that's what we create a snapshot of now we go back to our Cube we check is the queue empty no the queue is not empty so we move on to the next line we uh take a snapshot of the cube which means we keep track of the size we see okay the size of the queue is two so our level contains two elements we go to the for Loop we want to run it two for two times uh we first check that is it The rightmost Element it's not because I is not equal to size minus one so okay so that's good uh oh we also had to pop it so yeah we pop it and then we see uh it's the rightmost element no it's not we also want to append its children so with the child of uh the child of 2 would be five so we put that in the queue and that's it uh in the second execution of the loop we see that I is in D equal to size minus 1 because the size is two uh size minus one would be one and I over here is one so it is the rightmost element so we put that into the result and we add the children of three which is four and the story continues we can take a snapshot we exceed five as no children that we execute four has no children performs the rightmost element so we put that into the result and when we are done uh so after this the queue becomes empty so we break out of the while loop and we return result the time complexity would be linear as well as a space complexity uh since we use a queue I hope you enjoyed it please subscribe to the channel thank you
Binary Tree Right Side View
binary-tree-right-side-view
Given the `root` of a binary tree, imagine yourself standing on the **right side** of it, return _the values of the nodes you can see ordered from top to bottom_. **Example 1:** **Input:** root = \[1,2,3,null,5,null,4\] **Output:** \[1,3,4\] **Example 2:** **Input:** root = \[1,null,3\] **Output:** \[1,3\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Medium
116,545
66
hey what's up guys Nagoya tea already checking Kodi stuff on twitch in YouTube this problem is called +1 oh yeah check this problem is called +1 oh yeah check this problem is called +1 oh yeah check the description bro man formation premium problems on patreon reach out to me via discord if you want to +1 is easy me via discord if you want to +1 is easy me via discord if you want to +1 is easy problem and it is given a non-empty problem and it is given a non-empty problem and it is given a non-empty array of digits representing a non-negative integer plus 1 to the non-negative integer plus 1 to the non-negative integer plus 1 to the integer the digits are stored so that the most significant digit is at the head of the list and each element of the array contains a single digit you may assume the integer does not contain a leading zero so this array represents a digit so this array would represent 123 so this is the most significant digit on the left and least on the right and no leading zeros so we have to add 1 to this number and in this case we just do 1 to 4 we just add 1 to the last number that's it in this case 4 3 2 1 4321 we just return 4322 so it's pretty easy the basically here's the problem the it's not even really a hard problem that's probably why there's some dislikes but if it's 1 2 3 all we have to do is find a number the only difficult case is like if this is a 9 right when we add 1 this becomes a 3 and then this becomes a 0 right 131 or 29 becomes 130 but it's still not that big of a deal basically what we have to do is we set we find not the only hard cases 9 because the site that every case is pretty easy except for 999 because you have to increase the size of the array by 1 because it becomes a 1000 so basically what we're gonna do is we're just going to loop backwards and look for a number less than 9 so in 1 2 3 this is less than 9 but if it was 9 we would wait until we get here and then we add 1 to it and then until we get there we may every digit zero so we just you know if it's two that's less than nine so we change it to a three and every digit we change it to a zero so that's pretty much it and if it's all nines we have to make a new array so we just will do this we'll say okay and is equal two digits length for int I equals n minus one so from the last index to the first index of the array we will do I - - if digits of the array we will do I - - if digits of the array we will do I - - if digits of I is less than or no less than nine we are gonna do okay that's good we can just add and we can add one this adds one to that number and we can just return that's it all we had add we just had to add one to the number overall so we can just return digits otherwise we haven't found a nine yet so we I mean we haven't found a number less than nine so it must be all nines so any nine we see we have to turn to a zero because eventually later in the array or earlier in the right we have to change we have to increment a number so all these are zeros so if we see nines like one two three nine you know this nine we were looping backwards from the end and we see it's not less than nine so we have to change it to a zero not less than nine changed to zero not less than nine change to zero less than nine so we just changed this off by one and that works perfectly right because all we had to do was increased by one and you know that number one whatever number twelve thousand no 123 thousand nine hundred ninety nine plus one is 124 thousand so it works perfectly in the case it's all nines that's the case we had to worry about that's the only one is you have to make a new array for that so you have to do okay new number is equal to new ants and you have to increase the size because it's gonna be four instead of three so you just take the size of it you add one and you just make the first number I mean the first number has to be a 1 because it was all so it's gonna turn into a thousand like in this case so you increase the size and you just make the first number one and then you return the new number so that's it's just until you find a number less than nine you loop if you find one you increment it you return making all the zeros before that if there were nines and then if not you make a new ones increase the size that means there were this is the case they were all nines so this problem is really easy the only thing is the digits of 0 is equal to I mean digits of hop sorry digits of I is equal to 0 I don't want to redo the video or edit that so please bear with me with you know I know that sucks that I did that but whatever so I'm thank you guys for watching a pretty easy problem let me know if you have any questions about it hopefully that didn't mess you up you're making each number a zero if it's a nine because you have to change the one before it I think I explained it and I did enough example so thanks for watching and I'll see you guys in the next one love I love you too bye that alright getting weird alright bye
Plus One
plus-one
You are given a **large integer** represented as an integer array `digits`, where each `digits[i]` is the `ith` digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading `0`'s. Increment the large integer by one and return _the resulting array of digits_. **Example 1:** **Input:** digits = \[1,2,3\] **Output:** \[1,2,4\] **Explanation:** The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be \[1,2,4\]. **Example 2:** **Input:** digits = \[4,3,2,1\] **Output:** \[4,3,2,2\] **Explanation:** The array represents the integer 4321. Incrementing by one gives 4321 + 1 = 4322. Thus, the result should be \[4,3,2,2\]. **Example 3:** **Input:** digits = \[9\] **Output:** \[1,0\] **Explanation:** The array represents the integer 9. Incrementing by one gives 9 + 1 = 10. Thus, the result should be \[1,0\]. **Constraints:** * `1 <= digits.length <= 100` * `0 <= digits[i] <= 9` * `digits` does not contain any leading `0`'s.
null
Array,Math
Easy
43,67,369,1031
337
hi guys welcome back to my channel my name is radhika and today we are going to solve house robber problem three i know this is too much of a house robber but believe me this is different from the last two problems that we solved obviously this is an extension of that problem but the structure is totally different so let's get into the video so uh the problem is that the thief has found himself in a new place for his thievery again there is only one entrance to this area called the route besides the route each house has one and only one parent house after the two thief this realize that all the houses in this place forms a binary tree it will automatically contact the police if two directly linked houses were broken into on the same night that means and they determine the maximum amount that the thieves can drop without letting the police yeah so the problem is that this time the houses are arranged in a binary tree and the constraint here is we are not allowed to rob the houses which are direct directly linked right so if we have uh robbed four suppose we cannot drop one or we cannot drop three uh or we have if we have robbed three we cannot drop four and five and we can drop one uh three in one okay so we have to find out the maximum amount that he can make uh while dropping so what approach can we use here is we will use recursion so what i'm thinking is what we'll do we have two options either we rob the root or we do not drop the root so if we rob a root like if we think of only this if only our tree is supposed only this three four and five so if we choose to drop three then we can't drop four and five so uh what we have to do is we have to choose from either robbing the root or not robbing the root the maximum of that so if we rob the root then we get 3 and if we do not drop the root then we can drop left and right so 4 plus 5 which is 9 so maximum of 9 and 3 which gives me uh 9 so we will draw 4 and 5 and not rob root right so this is the logic that we are going to use so we have to obviously write another function that will recur so we only pass root fine so this returns me an integer value that will be the maximum value that can be robbed and it takes a parameter which is the root of the tree okay so first of all the base condition if root is equal to null that means we have reached uh the end somewhere so we return 0 because that will not be added anywhere sorry return 0 okay now so as i was saying so we return maximum of either we drop the root or we do not drop the root so what we do root value right plus now this is going to get a little complicated so please pay attention what we are going to do is the left of root and the right of root can be present or cannot be present so we have to take care of that so how do we do that we check if root we are using ternary operator here if root of left is present then we take that into consideration so what we do is we rob util root left of left now why is this let's say uh we are taking uh this tree and we have chosen to rob three so that means we cannot drop four and five but after four like one three and one we can draw so if you see it is a recurring problem for one uh tree rooted with one and four three uh for tree rooted with three it's the same problem right the same thing we can repeat so that's why raw butyl we are called the same function with value root left of left that means we have dropped this we cannot drop this now we can drop this one right this plus we can draw the right of it right so raw left sorry and left right now pay attention this is the ternary operator that we were using so if roots left is there if it's not null then we do this or we take 0 like in this case there is no left of this right so we add zero yeah so we have added root value we have added roots left's left and what is left we have to add roots root right matlab so we just put a plus sign plus so let me line this in another line so that it's more clear okay it could be a log line molecule now if root same will repeat the same step if root right is present then we rob root right left and we rob root right oh i have written your rob okay otherwise we add 0 because we have to add something right otherwise it will throw an error so yeah so this is what maximum of either this comma if we are choosing not to rob root then it's very simple we have to just take we have to rob the root left plus rob root right simple okay let me see just check it once ah correct right okay let's just run this code and see let's just put this in bracket let's just submit it now as expected our time limit is getting exceeded that is fine uh there is no problem with the logic only a time is uh getting exceeded so we need to do something now the next step like if you are doing it with recursion you want to optimize it you can what you can do is use memoization uh so how we can do that we just need to store uh whatever result we have got and use it later if we want to use map uh tree node and dust integer because we will be storing it as a pair of tree node and the integer like the maximum you can drop if you are at that node right uh dp from that node it will be stored now we'll just use it now if there is like if whatever we wherever we are right if that is already uh calculated so that from that root if it's already calculated it's not equal to dp dot end that means we have already filled this right then we return dp of root right otherwise what we do is we save this dp of root is equal to max of this oh sorry and we return dpos simple let me check yeah it's fine look go let's just submit confidence not run it we have directly submitted okay so it's getting accepted so now it's getting accepted so that's it for this video i hope you enjoyed it now this is the end of house rubber problem from the next video we'll do some other problems do suggest me in the comment section below what problems do you want me to pick i will be back with another video very soon till then bye happy coding
House Robber III
house-robber-iii
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called `root`. Besides the `root`, each house has one and only one parent house. After a tour, the smart thief realized that all houses in this place form a binary tree. It will automatically contact the police if **two directly-linked houses were broken into on the same night**. Given the `root` of the binary tree, return _the maximum amount of money the thief can rob **without alerting the police**_. **Example 1:** **Input:** root = \[3,2,3,null,3,null,1\] **Output:** 7 **Explanation:** Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. **Example 2:** **Input:** root = \[3,4,5,1,3,null,1\] **Output:** 9 **Explanation:** Maximum amount of money the thief can rob = 4 + 5 = 9. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `0 <= Node.val <= 104`
null
Dynamic Programming,Tree,Depth-First Search,Binary Tree
Medium
198,213
1,887
So in today's video, we are going to solve the question number 187 of lid code, reduction operation to make the array elements equal. In this question, we will be given an array named names, we have to return how many number of operations will we have to do. And to equal the elements of the array, as you can see here, first of all we have to find the largest value and then the next largest value and compare and equalize the largest value from the next largest value. But you can see that if we give 513 in our example, then the largest value will be f and the next largest value will be r, so we will reduce f to three, so here it will become three. You can see that it will be 313, after that the largest value of ours will be three for pe and the next largest value will be one, so we will reduce it once, here it will be one, 11 3 and again Our next largest value will be one, the largest value will be reduced to three, then here our output will be three because we have done the operation three times, so let's understand it once in the copy. After that we will come and code it. Here for the example we are using this array. If the proposal is such that the values ​​of the array are If the proposal is such that the values ​​of the array are If the proposal is such that the values ​​of the array are not sorted then all our methods will not work. So what are we going to do that First we will sort it, here it is already sorted, so we can write it directly here, after that we can see, what we have to do is to tell the number of operations to equalize all the values, so the approach for me is like this. It came that we can either increase it or decrease it but it is given that we have to replace this value with the mean which is the largest, we have to replace the next largest with it and doing the same we keep on increasing the value of the mean. If the values ​​of the array we keep on increasing the value of the mean. If the values ​​of the array we keep on increasing the value of the mean. If the values ​​of the array become equal, then the approach here is that we will sort it so that all the values ​​which are equal to each other come next to each other, values ​​which are equal to each other come next to each other, values ​​which are equal to each other come next to each other, after that we will run a loop from the last one because if it is sorted then the last value will be that. Will be the largest and the value just next to it will either be equal or different, if different then it will be the value below that, mean and the next largest value, so we will keep checking if both of them are equal. If we use continue directly there in the loop then it will move ahead and if it is different then we have to do something like replace it, then instead of replacing it, we can do this operation of replacement. If it is going to happen, then we can do the values ​​plus we can do the values ​​plus we can do the values ​​plus means. We can tell that the operation is taking place. As the operation is going on, values ​​are being added to it on, values ​​are being added to it on, values ​​are being added to it and with this we will store its count. And to come out of the loop, we can see that if this value and this value both will become equal, as soon as m which is the largest and which is the smallest, both will become equal, mean which is our number of zeros. It will be equal to Nums of Aa because we are starting from the last one, so in Nums of I, we will break the loop there and return whatever operation we are doing, but here the main question of ours. How will we tell in the operation how many number of operations will be required, so there is a simple way for this that we can check that whatever elements will be bigger than this one, means whatever elements will be bigger than this one. How many elements will there be, how many times will there be, whatever will be the number of operations we will need to do, so we can do a mean to find out the last index which will be n-1. We will come to minus because we have n-1. We will come to minus because we have n-1. We will come to minus because we have started the loop in reverse and will turn it to plus one so that the same value is added to it, then the operation will be done by us like this. Let's go into the code and let's see by coding it. So here I am going to code this, first of all we create a variable named operation, let's assume OT and now we start it with zero, we take n as the enum dot size for the size of the array and again numbers. Instead of writing the dot size, here we will sort as we have understood in the copy that numbers dot begin means the entire array from the beginning to the end will be our shirt. After this, what will we do after that, we will run the loop from the last and then for. Int a equal to last index a greater than equal to because we are not taking zero because we will compare it with whatever the zero value is and that will be our lowest value so there is no need to take it in the loop here. We will make I minus, after that if the number of zero of ours becomes equal, the value of the name of I is what I want to say and the whole is equal, then we will come out of the loop at the middle. If we break this then we will come out of the loop. If it is not so, if it is so that the number of which has come is equal to the number of the same, meaning the value is the same next to the other, then we will look for different values. So here We will continue this and then after that if nothing like this happens then we should get the number of operation from here, then to get the number of operation which we did, operation e is equal to operation plus equal to two which we did. The last index will be minus a plus one means while covering this index, all our counts will be stored here. Means in our operation, all the values ​​will be stored as many times as we will values ​​will be stored as many times as we will values ​​will be stored as many times as we will do the operation. Then here we will return. We can run our operation, which we will name as OT, run it once here and see that all our three cases have been accepted and submit it. Here our code has also been submitted. Thanks for watching. In the next video and its time
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
41
hey guys welcome back to another video and today we're going to be solving the leakout question first missing positive all right so in this question we're given an unsorted integer array and we want to find the smallest missing positive integer so uh one more thing you want to notice is that we only want the positive integers so in other words it only starts anything from one all the way to a positive infinity okay so in this case we're just gonna ignore the number two so we have one two and zero but we will we really don't care about the numbers which are equal to or less than zero so in this case we have the number one and we have the number two and technically we actually do not have any missing positive integer so in that case what's going to happen is we're go we're just going to give output the next uh positive integer so in this case the next positive integer is going to be the number three right since we already have one and two there's nothing in between of that so the next possible value is three okay similarly let's look over here so we have three four negative one and we're always going to ignore numbers zero which are zero or less than zero so we're ignoring one and so you can just think of it as we have the numbers one three and four so now in this case what's gonna happen is that we have one but we do not have the number two so we're gonna end up outputting the number two so hopefully the question does make sense now so in order to solve this question we wanna understand one thing which is the fact that our answer cannot be smaller than the number one so our least possible answer is always going to be the number one because uh there is no smaller positive integer than the number one so let's just write that over here so our answer is going to be 1 or anything up to positive infinity but there's actually a limit to that as well so we have two conditions over here our first condition is do we actually have any missing values for example over here we do not have any missing numbers so in that case we just output it as a next number which is the number three so let's just uh take a quick look at that so let's say we have one two three four five six now in this case obviously we do not have any uh missing numbers and the number that we're going to output is going to be the next number which is the number seven so this over here is going to be one of our extreme cases and the other case that we have is that we do have a missing number so let's first deal with this case over here so this answer is always going to be the length of our numbers so in this case how many values do we have so we have one two three four five six it's gonna be the length of our numbers plus one and that is going to be the maximum or the highest possible answer that we can have so that is going to be our upper bound for our answer so length of nums plus one so that's kind of like the upper bound of our answers nothing is going to be greater than this value and well by the way this value is inclusive okay now every other value is going to fall in between of one and the length of nums plus one the reason for that is because let's say we have something with a length of three and in order for it to not have any missing numbers it has to have the numbers one two and three and let's say it does not have the numbers one two three and it has the numbers ten a hundred and twenty then in that case our answer is always going to lie in between of the number one and the length of numbers plus one our answer is never going to go outside of that boundary okay so hopefully you understand how that works and keeping that in mind we can actually come up with our solution so this over here is not going to be our final solution but let's just take a quick look at it so keeping what we just did in mind so our answer is going to be in the range of 1 or it could be the length of nums plus 1. now in this case the length of nums plus 1 is not going to be inclusive of length of numbers plus one right so in order to make it inclusive of that value we're gonna do plus two over here okay so now that we're over here we're going to check if this x value is inside of our nums and to be more specific if it's not inside of our nums then we're just gonna directly return that value for example if we do not have the number one that means that we're missing the smallest possible value and we're just going to return that as our answer similarly in this case over here we have the number one right but we do not have the number two so we're just going to end up returning that value so this over here is going to be our answer and if you submit this it should work so submit so as you can see our submission was accepted but the problem with this solution even though it does work and it is probably pretty fast as well uh it does not follow this over here which is that we want our algorithm to run in linear time and we want it to use constant extra space so let's see how we can actually apply these rules into our algorithm over here all right so let's just start off by going through the step by step and let's just look at our area over here which is the numbers 3 4 negative 1 and 9. so first let's kind of understand what are our possible answers so our answer can either be 1 or it could go all the way up to the length of our array so 1 2 3 4 5 so 5 and plus one so our answer could be one through six inclusive of both the numbers and the answer the reason we added plus one is because let's say everything was perfect so if you had the numbers one two three four five then in that case our answer would be six okay so now what we want to do is we kind of want to clean up our area over here and the way that we're gonna do that is if anything is less than or equal to our value of zero or if anything is greater than the length of our number then in that case we're going to go to that specific element and we're going to change its value so now the question is what are we going to change its value to so in our case we're just going to change its value to one more than the length of our area and the reason that we're doing that should be clear really soon so let's just go through our area so over here we have three and three is in between of our range so we can just skip that then we have four that's fine but then negative one is going to end up becoming the value six so that becomes six over there one is going to stay the same and nine is also greater than this so it's also going to become six so this over here was kind of our first step so now that our area is cleaned up what we want to do is we're going to kind of change the way that we look at our list so over here we're going to think of each of the index representative of a certain number so for example the 0th index would mean the first number this would be the number two three four and five and we can use that in order to kind of tell us which numbers have already we've already come across so how we're going to do this is we want to use some sort of marker which tells us that we've used this number so what we're going to do is we're going to be iterating through each of our numbers here so currently let me just copy this over here so we have our area over here and we're going to be iterating through each of these numbers so currently we're at the number three so now what we're going to do is we're going to go to the index of three minus one so that's the second index so over here we're at the second index of zero one and two and at the second index what we're gonna do is we're going to make this into a negative value so by making this value negative we're kind of telling our program that the number three we've already come across the number three so we don't need to worry about it again so let's just go through this one more time so now we have the number four so now we're gonna go to four minus one so the third angle so zero one two and three and we're gonna make this number negative so all we're doing is we're kind of using a marker to tell us that this certain number at this index is being used now we're gonna go to the number six and one more thing so this actually became negative six so we're going to be taking its absolute value so in this case we're just gonna take the number six so six minus one is five and that leads us over here so this over here becomes negative similarly over here we have the number one so we want to tell our program that look we already have the number one so we don't need to account for that so in order to do that we're going to go to the first index remember we're taking the absolute value so 1 minus 1 sorry 0 with index not the first index and we're going to make this value negative okay and over here we notice one more thing so at negative 6 right so that's its absolute value is the number six minus five one gives us an index of five but this over here is already negative so if something is already negative that means that we've already come across a number once so in this case we're kind of dealing with our repetitions so in this case we already came across with the numbers so we're just going to let it be as it is so what this is basically telling us is now we're going to go through our array and over here we have the number negative 3. so this over here is less than zero so that means we have a marker there and that's telling us that so basically at the zeroth index that represents the number zero plus one since the index plus one so this represents the number one and since it's negative it means that the number one we've already come across but this over here is positive so when it's positive it's basically telling us that we've not come across this number yet so this is index one plus one so that gives us a number of two and as you can see we did not come across the number two similarly over here we came across the number three as you can see here and we also came across the number four now the part that is might be a little bit confusing is why is this over here negative right we did not come across the number five yet this value is negative and the reason for that is because let's say everything over here was negative then in that case we wouldn't actually be returning anything so when everything is negative we're just going to return the length of our numbers plus one so when everything is negative that's basically telling our program that we came across each of the numbers starting from one up to the up through the length of nums so now we're just going to end up returning length of nums plus one so let's just go back to this question over here and this over here has a value of four which is positive so we came across the first positive value and we're going to directly return that so currently we're at the index of one so we're gonna do one plus one which equals to two and two is the number which we want to return so we're gonna end up returning two and just for the sake of an example so one comma two comma three then in this case uh we're actually gonna output the number four so when you go through this uh this is going to become negative this is also going to become negative and so is this so now we have all three negative values and when we have all negative values like i said earlier that means that we've accounted for all of the numbers and the next number that the number that we're going to output is going to be the length of nums plus one so in this case it's just gonna be the number three since that's the length plus one and we're gonna output the number four over here so hopefully this does make sense and i'll just go through how we can write the code which should be the easy part once you actually understand how this works so this over here is going to refer to our first pass where we're just cleaning up our area so cleaning up let's just do that okay so over here we're gonna go inside of a for loop so for the index in the range of our length of nums okay and over here what we're gonna do is we're gonna check if that current number so nums index if this number is greater than sorry less than or equal to the number zero or if this number numbs index is greater than the length of our sorry length of our nums then in either of those cases we're going to change its value so we're going to go to nums index and now we're going to give it the value of the length of our nums plus 1. so that over here is the ending of our first step so now we have our second step which is we're kind of placing our marker so we're adding we're going to make the values negative in order to kind of say that over here we have a value so to do this we can just do for num and nums so now we have each of our numbers and we want to change this into its absolute value because it could be negative so our number is going to be the absolute value of our number so if this number over here is less than or equal to the length of nums then in that case we're going to go and make it negative so we're going to go to nums and then we're going to go to its index so nums minus 1. we're going to go to that index we're going to make that value negative so into equal to negative 1. so we're multiplying that by negative one but over here the problem is what if we come across the number two times then when we come across a number two times it will first become negative and since we're multiplying a negative number with negative one it will become positive so in order to kind of make sure that doesn't happen we're going to go to nums num minus 1 in order to check if this value is a greater than or equal to 0. so if it is greater than or equal to 0 that means it's positive and in that case only and then only then are we going to go inside over here and make that number negative okay and that's going to be it for placing our marker and this over here is going to be our final step for getting the answer okay and over here all that we're going to do is we're going to iterate through each of our numbers so let's do for index in range length of nums and over here we're going to check if the current number we're on so nums index if this number over here is greater than zero then in that case we're going to return the index we're on plus one since that's what the index is representing so index 0 represents a number zero plus one which is one okay and that's going to be it but what if we don't end up returning anything over here that means that all of our values are negative then in that case we're just going to return the length of nums plus one and one more thing the reason uh i kept calling the length of nums instead of a variable which holds that value is because we want to do this in constant space and that should be it so let's submit this so sorry uh this over here is not nums it's supposed to be num so we're referring to the variable over here not nums the list sorry okay so submit and as you can see our submission was accepted so finally hopefully this did make some sense i'm sorry if it was a little bit all over the place but thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
First Missing Positive
first-missing-positive
Given an unsorted integer array `nums`, return the smallest missing positive integer. You must implement an algorithm that runs in `O(n)` time and uses constant extra space. **Example 1:** **Input:** nums = \[1,2,0\] **Output:** 3 **Explanation:** The numbers in the range \[1,2\] are all in the array. **Example 2:** **Input:** nums = \[3,4,-1,1\] **Output:** 2 **Explanation:** 1 is in the array but 2 is missing. **Example 3:** **Input:** nums = \[7,8,9,11,12\] **Output:** 1 **Explanation:** The smallest positive integer 1 is missing. **Constraints:** * `1 <= nums.length <= 105` * `-231 <= nums[i] <= 231 - 1`
Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space? We don't care about duplicates or non-positive integers Remember that O(2n) = O(n)
Array,Hash Table
Hard
268,287,448,770
1,007
hey everyone nitish's side hope you are doing well so let's start with the question so the question is minimum domino rotation for equal rows okay so you have in a row of dominoes you have top eye and a bottom eye represent the top and bottom halves of the ith domino okay domino is a tile with two numbers from one to six one on each half of the tile okay so you have to rotate it domino so that the top eye and bottom eyes swap values okay and you have to return the minimum number of rotations so that all the values in the tops are the same or all the value of the bottom are the same okay so you have given two arrays and you have to basically do the value like you have to do same value for either for top or either for bottom and you have to give in the minimum number of rotation you have to do ah if it can't then you have to do written minus one okay so let's see with an example okay so let's under and take this example so we have given this top array which is 2 1 2 4 2 and we have one bottom which is 5 2 6 2 3 2 okay so what you have to do either you have to convert the top array into the same element or either you have to do the bottom if any of them you just have to give the output and it's also like if you can see the input like either one digit can be converted like if you can see either two will become all the same element either one or either like i have the possibility inputs like the digits are only one to six okay so if we see the input either one of them can be converted okay so let's take for this so as you can see like we have two here we have five here okay for here we have one we have two but here we have two where f6 okay for four we have two for this two this we have three for two we have two okay so if you count the twos from the top it is one two three four so it is four and for the two in the bottom if you count two it's three okay so if we see the size of this array it is six and if we do the sum for this it is four plus three equal to seven and if you can see these two are common so either like we don't have to swap this number because if we swap like they will become the same so if we reduce the same number like they are same so it will be six so two is the possible input which can we give like which we can convert okay so if you can see this is having top as four and the bottom has three okay so whoever is the lesser will give us like if i convert this into two then this two so i will take output of three but i can also do it like i can convert this to it here and i will give the output in only in two so this is the minimum input like why i take only two because if you take other numbers like one if you can see for one in the top it is only one but in bottom it's zero so this number can't reach like this number can't be converted all once so we need to take only that number that is possible okay so let's take this example also so we have three five one two three and we have three six three four okay so this number are same so we will just skip it okay so let's take it from here so as you can see this is one three here and if we assume like this three will come at here this three will come out here but here there is no any number which we can't take so for this case we can't make any array which is equal to either top or either bottom all elements are same so for this case we just written the output s1 okay minus one so let's see how we can approach this question okay so let's take the previous example so as you can see here like 2 is the only possible because you can see like at every element if i come from here 0 1 2 3 4 5 at every index i have to present it so i can swap the element okay so for like checking whether the number which i have to take so i can take a count area okay so and i also know like the maximum numbers or the range of number is z it's one two six okay so let's take an array for that also so let's take uh you can say a top and a bottom okay so this will be like it one two three four five okay and let's give it let's take a six also because the number range from one to six okay and what we will do we will count the frequency of each number okay so we will start from here and let's take one more array for let's say a same because uh at this position we don't have to swap it okay like there will be many other option also so we will start from here we will take this element and we will increment at here okay so this will become one and we will go for this bottom also and this will become one and if both the elements are same we will update the same also so we'll move further we'll comment here so we'll update one and we'll update bottom two and both are not same so we will not do anything we'll move further we'll update two so it will become two now we'll go to six and we'll update it we'll move further we'll commit here we'll update four and we'll update two so this will become two okay now we'll move further we'll come back here will update 2 and 3 so 2 it this will become 3 and this will become 1 and will move further again we'll update it so this will become now 4 and this will become you can say uh three and if you can see the element are same so we'll update the same also so all elements are zero here okay so we have created three array of six size array after this what we will do we will loop over this array okay and wherever we found like top i plus bottom i and minus this same because this element is con count twice so we don't need it same i is equal to n like the final input length or the top length if it is equal to you just have to return from here so you will get the output as n minus whoever is maximum you will take it max of t i and bi okay and that will give the output so let's debug it we will start from here so we will do one plus zero and minus zero so it's become one and one is not equal to n is equal to six for this case and this is not equal to this condition we'll commit here we'll check for this so 4 plus 3 minus 1 7 minus 1 equal to 6 and this is equal to n so what we have to return n is 6 minus maximum of 4 comma 3 i have taken maximum because we need to return the minimum output uh by swiping it so i take the maximum and i will subtract it from the our number so this will give us the output so this will be six minus four and this will be two and if over reaching to the end and if i don't receive any kind like this condition is not true so i will just return the minus one okay so let's write the code for this okay so let's take the three errors which will be of like indexing from zero so let's give a seventh size this is top let's create a bottom size also this is also seven and let's take a same okay so we have created our array let's count and so let's take a variable top dot length i will less than n i plus okay so we have to count at top also the tops of i incremented similarly increment the bottom counter also bottoms of i plus and the condition for same if tops of i is equal to bottom of i you just have to increment your same you can take tops or bottom this is your choice you will update same so we have updated our count array let's solve the function now so we have created the array so what we will do we will go over this area so 1 from 1 to 6 will go and what we have to do if p of i plus b of i minus same of i is equal to n just written from here n minus math dot max t of i comma b of i okay and if there is no condition meeting uh matching this condition so we just return minus one from here okay let's run the code let's see so this is accepted let's submit it so as you can see our code is submitted the time complexity for this it's basically a order of n for the tops or bottom length and the space we are taking uh you can say a seventh size of three area and that's a constant size we have take hope you like it thank you for watching my video and do join the telegram group if you have any doubt any concern thank you
Minimum Domino Rotations For Equal Row
numbers-with-same-consecutive-differences
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.) We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values. Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same. If it cannot be done, return `-1`. **Example 1:** **Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\] **Output:** 2 **Explanation:** The first figure represents the dominoes as given by tops and bottoms: before we do any rotations. If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure. **Example 2:** **Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\] **Output:** -1 **Explanation:** In this case, it is not possible to rotate the dominoes to make one row of values equal. **Constraints:** * `2 <= tops.length <= 2 * 104` * `bottoms.length == tops.length` * `1 <= tops[i], bottoms[i] <= 6`
null
Backtracking,Breadth-First Search
Medium
null
1,816
Hello hello ok let's start a new question attract sentence it is given that we have a list we have time only space and capital word and resolve all small letters only involve so what we have to do is that in that smell length is given number of words same number of words We have to attend that weapon till the words and that means it has to cut us and turn off the new street light like the example given here is hello how are you at the contest tent here so here is hello how are you got forwarded till here okay So, this is all we need to appoint and forward it, so let's start with how to start it. What I do is that as soon as the space comes, I feel that one of my Once the word is complete, we have to comment it by adding plus to the account and adding the word to the new street. You will understand quickly through the code. So let's start by making bill account variable and starting from zero. Create a string variable Okay and that this note size was to run till here Effigy of this is a positive equal to that if there is space then what do we have to do STR class physical activity that apke teacher cult kya kar dena I have to back What to do, I have to break the mails on people, what to do? l Make time that we have this tube of ours, we are going to add a letter to it once, when our word is complete, then he will add arm resting to it, okay, so we have to add it here, then I will add it to this as team plus. By adding water to it, the word was 'cheese' and the last word here, I add the word was 'cheese' and the last word here, I add the word was 'cheese' and the last word here, I add the string ' string ' string ' Aadha' and ' Jhaal', on Jhaal', on Jhaal', on this occasion, this is ours, it is something simple, very simple and everyone's health has been achieved, thank you.
Truncate Sentence
lowest-common-ancestor-of-a-binary-tree-iv
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a sentence `s`​​​​​​ and an integer `k`​​​​​​. You want to **truncate** `s`​​​​​​ such that it contains only the **first** `k`​​​​​​ words. Return `s`​​​​_​​ after **truncating** it._ **Example 1:** **Input:** s = "Hello how are you Contestant ", k = 4 **Output:** "Hello how are you " **Explanation:** The words in s are \[ "Hello ", "how " "are ", "you ", "Contestant "\]. The first 4 words are \[ "Hello ", "how ", "are ", "you "\]. Hence, you should return "Hello how are you ". **Example 2:** **Input:** s = "What is the solution to this problem ", k = 4 **Output:** "What is the solution " **Explanation:** The words in s are \[ "What ", "is " "the ", "solution ", "to ", "this ", "problem "\]. The first 4 words are \[ "What ", "is ", "the ", "solution "\]. Hence, you should return "What is the solution ". **Example 3:** **Input:** s = "chopper is not a tanuki ", k = 5 **Output:** "chopper is not a tanuki " **Constraints:** * `1 <= s.length <= 500` * `k` is in the range `[1, the number of words in s]`. * `s` consist of only lowercase and uppercase English letters and spaces. * The words in `s` are separated by a single space. * There are no leading or trailing spaces.
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Tree,Depth-First Search,Binary Tree
Medium
235,236,1218,1780,1790,1816
1,283
in this video we will solve a smallest divisor problem so first let's see the problem so we have an array of integers and there is a threshold given to us so we have to find numbers starting from smallest number such that if we divide all the numbers in this array by that number which we choose and which we are supposed to return finally so we divide everything by that number and then we find out the sum so dividing individually and not summing first and then dividing that's not uh allowed so you have to divide each number individually and then sum them and it we will take the ceiling of everything so uh for example let's say if we have 3 and we want to divide by 4 so it's zero point seven five but we will take it as one similarly if you divide three by three also again it will be one so you see that multiple numbers can result in same output so three by four is also 1 3 by 3 is also 1 and we have to do it on each element so you can see that multiple such numbers can result in same sum so this is the problem and the sum should be less than or equal to threshold and it's also given that it's guaranteed that there will be an answer so let's see this example we have one two five nine and threshold is six so in this case output is five so let's see so we have to return the smallest divider so clearly smallest can be 1 because divided by 0 is not allowed so smallest is 1 so when we divide by 1 we get 1 plus 2 plus 5 plus 9 so what is the sum here it's 14 plus 3 17 which is more than threshold is six so we will go higher what is the higher two so if we divide by two one by two is one we take the ceiling so 1 plus 3 plus and this will be 5 so it's 8 plus 2 10 still more than 6 now we go to 3 so it will be 1 plus 2 plus 3 again it's 3 plus 4 7 more than 6 next we divide by 4 so 1 plus 2 plus 3 same thing equal to 7 so more than 6 so you see multiple uh divisors resulting in same output so this was for 4 this was for 3 it also did not work so next we look for five so it will be dividing by five one two by five one five by five one nine by five two now it's three plus two five which is less than six you can even if we got 6 it would have been fine but it should be less than or equal to threshold so 5 is fine but anything less than 5 it was more than threshold and we want the smallest so we see that if we increase the value of divisor so if divisor increases sum decreases because divisor is in the denominator of all the numbers and we want the smallest one so clearly for one it will be large for two it will be smaller and we should stop just at the right place obviously if we take the maximum of these like 9 and divide everything by 9 then it will be same as number of elements and there is a solution always so that will always work but we are not interested in the largest we are interested in the smallest so you can see that theoretically upper limit is the maximum element for anything beyond a 9 it will be just 1 follow everything because it all the values will be less than 1 and more than 0 so we will take it as 1. so we have to search from 1 to maximum of this so we can do a binary search here so uh we can also proceed linearly but calculating the sum will take off and time so first we will calculate the sum which will take o of n time n is the number of elements because we have to divide all elements and sum them and if we have to search from 1 to n max and max is the maximum element in this array then using binary search it will take log n max time so let's denote by small and each iteration will take on time for calculating the sum so overall we can do it in n log n max time uh we can also do it like this so we search for one if it's more than threshold we double it search for two still more double it four we look for four still more eight so we are doubling the value and calculating for this value so if it's less than threshold for four it was more than threshold for eight it's less than threshold then we know that it lies in this range so we will get a smaller range and we can search in this range and this will be nmax will be somewhere in this range it can be even 8 it can be 4 plus 1 so n max will lie somewhere in this range so straight away you can search from 1 to n max or you can keep doubling it and then you will find a smaller range and within that range search for that actual value both ways are fine and this doubling will not take very long time because we are doubling it so after log n max steps it will cover the n max because we are doubling it all the time so 2 raised to the power log base 2 n max it's equal to n max so in log n max steps we will find this interval where we want to search or straight away we can do it both ways are fine now let's write the code for this and here we will use binary search but there will be a very small difference from our normal binary search so in our normal binary search when we are searching for value one of the checks is that so first what we do l less than r l is the smaller range from where we want to search r is the rightmost range first we calculate mid then we calculate the value at mid and if it's equal to the required value we return the mid and then we check if it's greater we greater and less we increment or decrement the lower range but here this mid equal to value even if it's mid is equal to threshold we will not return mid because we saw that for different values we get the same output for example for 3 and 4 both we got 7. so let's say mid was 4 and we got 7 and let's say in this case threshold was also 7 instead of 6 so we would not return this mid 4 because even for 3 we will get the same value so it does not guarantee that mid is the optimal so mid can be optimal but there can be smaller divisors also possible so this will be the slight difference from normal binary search so here we will have just two cases one will be more than threshold which is a definite no so if it's more than threshold we will strictly look past mid plus one so we will increment our lower range to mid plus one because mid is not accepted anything below that is not accepted and else everything else will be made so if it can be the solution or anything less than this can be solution so these are the only two cases so let's quickly jump to the solution we have already seen the time complexity which is n log n max is the maximum value in this array n is the number of elements and a space it will be of one we will not use any linear array so you can go through this problem and they have also given the solution but i felt it was slightly it might be slightly confusing for some less experienced folks so i will try to write a simplified solution here so let's see both of the approaches so first we can start from n equal to 2 and here end will be this value so we are doubling it so when it's less than threshold this will denote end and we are starting from 2. and let's define a function to compute the sum and in this case i am using long because for some cases it can exceed the limit of integer n divided by x but by default it will uh do the floor and not the ceiling so we need to do the ceiling so if n modulo x was a perfect divisor then 0 else 1 you can also use the ceiling function so now this function is ready for computing the sum so while compute sum of nums and let's pass it by reference nums end is more than threshold we keep doubling the end so left shift is same as doubling and when this loop ends end compute sum of end will be using end as the divisor is less than threshold is not more than threshold at least so we have found the end value now where should we search so if this is end what was the previous value it was half of that for that it was more than threshold so we have to search from end divided by 2 to end so we know the previous value already using just this variable so let's do a binary search from end divided by 2 which is equivalent to right shift no need to store start every time we do it we know that already it's half of that now we will do binary search so while start is less than end first thing calculate the mid and i have told it multiple times why we do it like that and not like start plus n divided by 2 because start plus n can be a large value and it can go past the range of hint if for mid it's more than threshold then for anything less than mid also it will be more than threshold and mid is invalid so we are looking in the right side of mid strictly right side so start is mid plus 1 else end equal to mid can be a solution so as i explained here we are skipping that third check which is when this sum is exactly equal to threshold for mid we don't return mid because we can get the same solution for multiple divisors as in this case so that's why we are still searching from beginning till from start till mid and finally we return start and let's see its nums undeclare in so it should be okay so there is a repeat here let's make one of these so time limit is exceeding so we are doing something wrong here so sum so this is fine and this two while compute sum is greater than threshold then end so this is left shift so end was never changing this was less than equal to which was so this was the mistake now it's working so let's submit and the solution is accept accepted and we it's taking 76 milliseconds which is better than roughly 43 percent of the accepted submissions now as i was saying that we can this end and n divided by 2 so n max will lie somewhere in this range so we can directly search from 1 to n max straight away and that will also work so let's change here so end we already know anything more than nums not begin nums dot end and start we can take as 1 and this we don't need and let's see so let's see if we get a better or better solution or not so it's slightly better but we cannot say it's much better it's similar even memory is similar runtime is similar so you can do either of these runtime is same for both so let's write this in java also not much change is required and the java solution is accepted and in this case it takes somewhat smaller time 18 millisecond
Find the Smallest Divisor Given a Threshold
reformat-date
Given an array of integers `nums` and an integer `threshold`, we will choose a positive integer `divisor`, divide all the array by it, and sum the division's result. Find the **smallest** `divisor` such that the result mentioned above is less than or equal to `threshold`. Each result of the division is rounded to the nearest integer greater than or equal to that element. (For example: `7/3 = 3` and `10/2 = 5`). The test cases are generated so that there will be an answer. **Example 1:** **Input:** nums = \[1,2,5,9\], threshold = 6 **Output:** 5 **Explanation:** We can get a sum to 17 (1+2+5+9) if the divisor is 1. If the divisor is 4 we can get a sum of 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2). **Example 2:** **Input:** nums = \[44,22,33,11,1\], threshold = 5 **Output:** 44 **Constraints:** * `1 <= nums.length <= 5 * 104` * `1 <= nums[i] <= 106` * `nums.length <= threshold <= 106`
Handle the conversions of day, month and year separately. Notice that days always have a two-word ending, so if you erase the last two characters of this days you'll get the number.
String
Easy
null
285
That Welcome Back Print Ubuntu Solid Problem Foods And In Order Successor In Bst Aa Saw You Might Already Know Data Offer Create List Code And Your Daughter Solution Videos In Java J2ee Technology Advisor For Recording Problems Jewelers J2ee Interview Related Videos To Help People You Know What Kind of Frequently Asked Questions Sad Which Tips Ideas are Important for Java Interview Cellular Data Structures and Algorithms Sour Similar Any Other Preparing for Job Interviews Coding Interviews For And If You Are Looking for Some Kind of Your Problems for Targeting and Skin Interview So Please subscribe to the Channel This Channel Has Jab Laut Good Material Related To The Interviews According Interview Schedule For Java J2ee Telephonic Interview Se And Inhale Screening Interview So Please Check Out The Play List And Sub Chotu Channel So Will Look At Details For This Problem Nau Sugriv Winery Search Tree And can not find in older successor of the node in the best I want to give not have nowhere successor in the string in return for this is the problem statement and was basically you have been given binary search tree so let's discuss this problem here Test One Sample Minor Research 300 Discount Offer Tree Will Be Given To A Person Who Has To Find Out The In Order Successor On Prototype Superhit Sampann Twenty-20 On Prototype Superhit Sampann Twenty-20 On Prototype Superhit Sampann Twenty-20 Notice 122 Notice Given To Husband In Order Traversal For Inverter Successor For The Note 21st 2822 This Years Old Collection of But Whose Sector-28 to 154 ftu Solve this problem is you can do the inorder traversal of busty and even when you are doing dabia research traversal preorder traversal you will just keep adding notes in to-do list right adding notes in to-do list right adding notes in to-do list right and left Royal Complete Inorder Traversal Eastern Day You Can Just Believe in Christ and Final Successor for the Giver Not Let This One Way of Doing Good 100 Villages Where First Viewers Discuss a Little Bit About What is Recorder's Driver Son of Finance Ministry Should You Get Some Kind of background for the question and they will discuss how to solve that question encoding a details side so let's first let's look the inorder traversal for this finally Bigg Boss you can see you can start with the root of the channel subscribe and what not To traverse is you always go from like loop rule for example Give one search tree is loot from like this channel like this order traversal will always go like this basically in this direction first visit to be seen in you visit the right nine clicks on this water Drop in the order traversal Latest best for you and you will go to the love you will go to the left news you can right so you visit and when you visit for so you are and left most known for its viewers edit in to-do list say you have at least for example edit in to-do list say you have at least for example edit in to-do list say you have at least for example viewers edit powerclip clear right day after death at you will go crazy discuss you know from this point you will go and visit fruit showroom tube well add three days you will go to the right side of the tribune you will not Very clear after this you will also be done with extreme right to even done with legitimate light software done with this marine sun will go on and off track 250 investments will print 15th is the form basic and will go to the right all the trouble sure that Guna 12218 Is The Love Notes Will Printing And Will Editing And List And You Will Go Up The Route Some On * * * This Day Will Go Ahead A Right Side On * * * This Day Will Go Ahead A Right Side On * * * This Day Will Go Ahead A Right Side Into Disuse 2424 Will Have To Go And Will Print Blocked No Deep Cause This Here's what we do it is here's what you've done in order to travel for the lift subscribe school this benefit 50 Bluetooth of attraction for this right subscribe The Channel traversal 900 right side 40 give back to probably not wrong subscribe and you will go To the 60 thing two three order traversal swadesh mein you can do the inventor of northern travel sir phone to complete binary search tree and you can and values ​​into all equally aside for values ​​into all equally aside for values ​​into all equally aside for example users considered and especially after just a discussion on futures think that is a linguist and you have instructed to death in our list night so 5022 notice given for years old and how to find the in all the success of window withdrawal is entry find the twenty-20 dear and in the next month the twenty-20 dear and in the next month the twenty-20 dear and in the next month will return is the Inventor Sabse Service 3533 One approach to solve this problem but this approach is too easy to use and limited to learn data structure of Thursday * data structure of Thursday * data structure of Thursday * Using Additional Storage Space Musically So Our Space Complexity Will Be Increasing Its So There Is Any Better They Can Do It Well Using Any Kind Of External Storage Space Show Tuesday Reservation Cannot Be Seen After Success Aavi Jhon Fine Inverter Successor In Binary Search Tree For The Giver Not Without Using Any External Data Structure So Let May Show You Data Professional Attitude A Actually Going To Implement This Is One Of The Proselytizes Just Wanted To Show You Before They Can Start You Know Explain In The Cockroach Hai Sonam Let Say What We Will Do You Will Create At Reinhard Call Themselves Not So Far Right Swadeshi Chapter Note That Was Given To Has Issued At Footer In What Is The Class And Get His Left And Right Hand When Life So Everyone Notice Implement A Like Share Discovery No 2515 Everything But Not Rates Will Just Create One Product Object Hair Conditioner When Not So Far And What Will Give U Will Attack Value And will start doing so finally search traversals and write the best for the value of solvent 100 visit daru at first site in binary search traversal 520 500 1000 is mode and anti 200 will just producer of values ​​mode on the given when will just made tower values ​​mode on the given when will just made tower values ​​mode on the given when will just made tower profit Zaroor Suparshva Is Updater Is Lar Jo Not Saunf Us From An Old Divide And Rule Things Will Have 822 Is Model 128 In The Brain Research In The Left Side Values Will Be Destroyed And Drut And All The Rights And Values ​​Of Truth Village Water Rights And Values ​​Of Truth Village Water Rights And Values ​​Of Truth Village Water And Fruit Sun Has Been Spent With Smaller Than Twenty Five Will Go On The Left Side Right Software Now Would Not Pass And Who Were Looking For 2215 Is Not Bigger Than Twenty 20 Will Not Update Amla Which 96200 More Than Fifteen Will Go On And On The Right Side Of Different Software And Women Found No 22892 He Will Not Get Proper Results Vikas 2012 Is Not Greater Than Twenty Two So In That Case How You Will Go On The Right Side To Yudh Ko Dancer The Same Time So You Will Understand So S You Can See Hui Compare the value of the target note ufff how to write man tree does not need and twenty-20 develop 6700 will go on to the twenty-20 develop 6700 will go on to the twenty-20 develop 6700 will go on to the right side software doing so will visit 359 on the highest 2422 fennel do hua hai to aam will visit country note 0404 is more than twenty 21 so they will be updating next and when note sofa 22424 is the value of the end after 10 hui the not practice or in that case will be written as you can see clear shot this is the recursive function on In Solving Square Meter Not Victory Body Of Foreign Investment Is Main College Muzaffarpur Disawar Me Khas Aap Mera That Recursive Function Returns Right Loot Or Equation And Specifically For Others Hui Just A War Value Is Less Leather Like Value Of Notes Is Greater The Target Value Day Will Go On to the website software doing act like they are going to the left side that and gifted not lose give the value is not less than in that case you want to right side on tomorrow in this case whenever you are done with red question what Ever Is The Largest Node Super Villains Written As The Successor Rights On This Portal 10 We Will Return Air India's Server He Raw Created Dalal Journalists Were Initially TV Channel And SV Travels In Aankh Ajeeb Drivers Ludhi Retreat Life Vikas Function Hair Day Will Just Keep Going Left and Right based on the node velvet you have seen and they will keep updating lar when not so far when ever will see any value is more the validate were looking like share and looking for 2012 cm and validate 2525 will just keep updating date will Not so far right Guddu in here a is and now that point man someone inside right side like oo will not updating the only they will update you are the implementation of implementation subscribe share and value 150 hundred liter fuel data structure where you can 151 the0 S U P S M Ranbir Working O 56001 N C T Output Is 200 So Our Solution Work Point And Work Has Changed His Whole Solar Gift You Want Like c16 Late To 2016 Year 900 Vacancies Sixty Is Hair Soft Ansh Value Mithila Region Value Se Jakham Where Running Program I Swayam Can See A Hundred Is Coming Years Without Points Collect So Viewers Submit This And Make Us Updated On Ki Suraj Which Power Solutions Getting Accepted By Liquid Soap We Want More Time And They Should You Like Them With T Solution 34 Lal Jatt Notes Then Oil Creator Known To Visit Outside Its Object The Symbol Of Power Is Jatt Club 's Class Levels With Accessible From The 's Class Levels With Accessible From The 's Class Levels With Accessible From The Method And Poor's Calling And Recursive Function Were Passing Route And The Target Node For Straight Search On This Occasion Secretary Function 100 Base Cases Gift Notice Nothing Will Return For Example You Rich Chironji 40 Going Right You Are Fitting Lights Vindheshwari Corruption Will Return Difficult Advised Hui Chief Cover Note Key Value Is Crater Valid Were Looking Like This For Example 2501 Wb Is Greater 1022 Work Shop In That Case will just update power lies not so far to that node and you will gain convert receive function but will go inside left side for example ago your website Sudhendu you will do life for twenty five went to the lips of software engineer if chief and notes value is on not likely in the novel is greater than two years will this rate you find value so this day for example clear 5909 values ​​and you will go to the right 5909 values ​​and you will go to the right 5909 values ​​and you will go to the right side of the software's lap doing clear right side they are doing and you have Only of the Largest Notes25 Value is Bigger Right for Example When and Values Bigger Twenty-20 Big Bash Twenty-20 Update Bigger Twenty-20 Big Bash Twenty-20 Update Bigger Twenty-20 Big Bash Twenty-20 Update Airplane Mode to Twenty-20 Big Bash Airplane Mode to Twenty-20 Big Bash Airplane Mode to Twenty-20 Big Bash Twenty-20 Will Update End 8th End What Ever Twenty-20 Will Update End 8th End What Ever Twenty-20 Will Update End 8th End What Ever Value is There in Our Lal Chowk Saunf Just written exam answer right to that will be and in older successor in GST for the vinod ji 202 aam ki is one more time hai yes your view or tu ghr sixty already so let's sabse zor - sp singh ko subscribe shyam the answer is basically a 131 Comments The Answer So Our Chords Working Point So When You Thank You Can Create Your Own Tree Dried Air Tight Solm This Is The Way You Can Create Your Own Trees And In You Can Just Click On Data Structure Which You Will Be Able To See Your Country So let's you want to adv2 notes after this for 108 viewers trial show you how to do the time din so you will also know for example after 1000 1282 more notes for the children of the life and adventures and 40 sure water drink which children 900 vacancies In foreign twenty-20 coming soon you want to see the In foreign twenty-20 coming soon you want to see the In foreign twenty-20 coming soon you want to see the successor of twenty-eight success of successor of twenty-eight success of successor of twenty-eight success of winters pair right needle and destroy don't want time 20000's voice successor of twenty skimming on duty so this is the way can implement in order successor in tasty and The Year To You Have Not Used Any External Data Structure Quote Simply Using Recursive Function And One Tree Not To Us Used This Tree Not To For The Largest Not So Far So We Half Explain In Detail Dissolution Show Police Checking This Court In To Make Every Politician And Sharing With You Guys So You Can Take A Look At Some Noise Pollution And Trousers Here This Nice Data Structure Description So You Can Create And See How Your Brain Research Things Looking You Know And When You Can Pray With Different Not How Are Different Just Is Give New Of A Successor In The Binary Search Tree Soft Already Open Ko Subscribe To My Channel Please subscribe To My Channel Bhai Always Create Likea Videos For Java J2ee Interview Coding Solutions Please Take Off The Playlist Have Created A Lot Of Good Places For The Two Help lighter person on these java j2ee interview service will give you really a good one that you can subscribe to our channel and thanks for watching the video.
Inorder Successor in BST
inorder-successor-in-bst
Given the `root` of a binary search tree and a node `p` in it, return _the in-order successor of that node in the BST_. If the given node has no in-order successor in the tree, return `null`. The successor of a node `p` is the node with the smallest key greater than `p.val`. **Example 1:** **Input:** root = \[2,1,3\], p = 1 **Output:** 2 **Explanation:** 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. **Example 2:** **Input:** root = \[5,3,6,2,4,null,null,1\], p = 6 **Output:** null **Explanation:** There is no in-order successor of the current node, so the answer is `null`. **Constraints:** * The number of nodes in the tree is in the range `[1, 104]`. * `-105 <= Node.val <= 105` * All Nodes will have unique values.
null
Tree,Depth-First Search,Binary Search Tree,Binary Tree
Medium
94,173,509
1,637
hello everyone welcome to another video now in this video we are going to look at another Aries medium level question but it says medium but it is really easy so what the question is that we need to find the wildest sorry the widest vertical area between two points containing no points now what does this mean so widest vertical area is nothing but uh if you know that the area of any rectangle is length into breadth okay so we need to find that but if you can see uh in the question it is given that the length of the array I'm sorry the length uh is infinite okay we are not given but we are given breadth okay so we need to find that so how are we going to do that such that no two points no points are inside the area now what does this mean so we will go to that as well and another thing that we need to go here is that the widest vertical area is the one with the maximum width okay that is the maximum distance between any two x coordinates so what does this say is that let me show you here okay and let me look at the example 879974 eight seven nine seven four and the last one is nine seven okay now if I write this in a coordinated system our x coordinate will be it let's say over here the 9 is going to be here the 7 is going to be here and the 9 is okay we have we don't need to look at the y coordinate because we don't care about that right now because we need to find the widest uh area with like I'm sorry the maximum width right now where it comes from uh bread okay so wheat and bread they are similar and that comes from the x coordinate now if you will see here the widest area is right now from seven to nine but we have an 8 between them okay which um in this condition it breaks the uh the constraint that we are given that is we do not want any point in between any two points right so for that I'm sorry uh so for this condition uh our maximum width is going to be either 728 or 829 because they are both one but how do we find that okay so for this we are going to have three steps the step one is that we will be filtering out our x coordinate okay so it will look like this 8 9 7 9 okay the second condition is that we will sort we'll sort this temporary array that we have found now why is that because if you will see here after this differences we find okay 9 minus eight seven minus 9 UM nine minus seven then you will see here that in nine minus 7 we are getting 2 okay but if you will see here we cannot take a width from seven to nine because we have another position here another point over here okay because of which it violates the given condition so for that what we'll do is that we will sort this okay now we have the points in a continuous order and for that what we'll do is that we'll simply take the difference so 8 minus 7 is 1 okay now we'll find the maximum we need to find the maximum width right so for that we'll continue 9 minus 8 that is also 1 so as it is 9 minus 9 that is 0 but 1 is maximum in between 1 and 0 so that is going to be like that only and this is going to be our result okay and we will be returning this okay it is really that simple and if you have understood this then you can continue to code this otherwise you can I will be coding and you can compare your code later on so the right so right now uh the first thing that we require over here is our result so let me create that okay another thing that we really require here is our temporary array where we will be storing all the x coordinates okay so for that let me create a vector over here and it will be integer and let me name it temporary so now we need to add our values our x coordinates over here right so let me do that for integer I foreign we need to add this we need to add in our temporary what point set index I and index 0 because x coordinate is always going to be the zeroth position now our first task is done that is the filtering out of the x coordinate our second task is sorting the temporary array so for that what I'll do I'll simply sort this from beginning till end okay now sorting is also done now we need to find the difference how are we going to do that okay I equals to 1 is there temp dot size I plus uh now our result that is going to be maximum of result and temp of I minus 10 of I minus 1 okay and let me simply return this result our code is done it is really that small and simple now I hope I did not make any mistake over here okay so you can see it's really that simple and the time complexity that is going to be Big O of n log n because the costliest part of this algorithm is the Sorting part otherwise the all the other Loops are going to take only because of n where n is the size of our um points Vector okay so yeah that's it for this video I hope you like this and understood this and learn something new and do let me know if you have any other problems for me to solve from any other platform I will see you in the next one till then keep coding
Widest Vertical Area Between Two Points Containing No Points
string-compression-ii
Given `n` `points` on a 2D plane where `points[i] = [xi, yi]`, Return _the **widest vertical area** between two points such that no points are inside the area._ A **vertical area** is an area of fixed-width extending infinitely along the y-axis (i.e., infinite height). The **widest vertical area** is the one with the maximum width. Note that points **on the edge** of a vertical area **are not** considered included in the area. **Example 1:** ​ **Input:** points = \[\[8,7\],\[9,9\],\[7,4\],\[9,7\]\] **Output:** 1 **Explanation:** Both the red and the blue area are optimal. **Example 2:** **Input:** points = \[\[3,1\],\[9,0\],\[1,0\],\[1,4\],\[5,3\],\[8,8\]\] **Output:** 3 **Constraints:** * `n == points.length` * `2 <= n <= 105` * `points[i].length == 2` * `0 <= xi, yi <= 109`
Use dynamic programming. The state of the DP can be the current index and the remaining characters to delete. Having a prefix sum for each character can help you determine for a certain character c in some specific range, how many characters you need to delete to merge all occurrences of c in that range.
String,Dynamic Programming
Hard
null
201
hey guys welcome to day 23 of our decode challenge and please problem is problem but 201 that is bitwise anding of number numbers range which means given a range of numbers you need to do bitwise and on each of the member right you have M to n in the range and you need to return the end bitwise and of all the numbers in this range let's look at five to seven and some closure between all numbers from five to seven needs to be bitwise ended so let's get the bitwise representation of five one zero one six one zero seven one right we need to end all these bits to ending one fatal gives you 0 and then 0 and 1 here's your 0 again wait I'm ending all these fits on the same position here it gives you and then take all these 1 bits will give you one but this is actually comes out to be 4 in decimal representation of the number line so this matches answer one thing we can do is if we go by the brute force approach of course we need to purchase from four numbers from M to n plus 1 we ingest to like answer equals to answer bitwise end and number right but if you see the range of the numbers this is pretty huge well this is pretty huge and it will surely give you time limit exceeded what you can also do that once your answer becomes zero that means you cannot that there is no point in ending in two more numbers you can return those answers but those are like small optimization and it won't actually improve the time complexity of your algorithm by much so it will I can give your TLD okay so what does what we'll do is we'll analyze this by few examples and see if we can find any Python members but if let's say we have the example s is too close wait turn lemon to it okay there it wasn't the presentation of these numbers oh yes now see that if you were to attend this so you get a 1 in your answer only if all the columns and these range of number is a 1 right so this is one thing we have learnt all columns should have a bunch for the answer to have the one in simply right first of all in order to reach from 8 to 12 all the numbers in this range the bits should flip somehow this bird should increment to 1 right and this list would change to 1 is 0 and a 1 and a 0 audience the numbers that change anything and since the numbers only zeros N 1 if the best change any time then the answer would always have 0 for that position if the bed do not change on any position then you can safely assume that bit would retain its position in the final answer if you see a longer example let's say 1 0 1 so 1 right this is all emphasize our n we need to let down all numbers from this to this into a bit wise and wait but let's say the difference in the number isn't it this persuade for these m and i taken from n to n this particular bit needs to flip 2 over 1 right so there will be a point in time where this particular bit h increment to 1 and the remaining this will become 0 with peaceful positions way and you will like it something like this hey until this point one there one more but gives that do give this do not change at all from M to n right so this felt perfectly fine and any bit that changes from 0 to 1 or otherwise could be substituted at zero and Ansel and all the remaining which would also be need to be zeros because there will be a point of memory this which happens in all these zeros come right so come m2m all the numbers would have a common prefix in bits and these are the only bit that will remain stable in the answer and all the remaining words from M to n will get to 0 okay so what we need to do in our solution is get bit wishes presentation of em get bitwise representation on in and find the common cleavage now I will show you my code that I just see what I did there following that if it comes I had trusted the bitwise representation of both M&amp;N the bitwise representation of both M&amp;N the bitwise representation of both M&amp;N and I should get the common purpose on top of that I will show you a better way to do this using the shift operator the bit ships of theta you so let's result the code now what we need to define a bit representation function which village is the bit representation of any given number put the bit seminary rectangle a little bit while then as a lumber left then what I do is I'd shut out the last rightmost bit surf it's modular 2 as 1 then I need to append one Indian if it is 0 the remainder divided by 2 we'll see within I need to open this view right and then I need to divide it by 2 okay that function well actually gives the reverse interpretation so the worst way so if you have four then it will give you clear 0 1 now we just need to do work the words on this to get the 1 0 right so that stuff the first look ok now let's get the presentation bit representation of em they said better presentation of n all right and so once we get it so let's say you have for a new title and M is equals to 4 and n is equal to 8 ok then you see that we don't have a way to represent or to pad for with a leftmost feeling so if this padding is needed which means we don't have any common profit but the length of the better presentation is not same so they're ending up on the virtually zero its length of B M is not equal to length of B N then returns view okay if they do match suppose this were to be 7 then this will become 1 now what we need to do is we need to fill our answer for I in range then I threw it over the bridge and see if they are equal so this is where we extracting the common profit okay now if p.m. power is not equal to okay now if p.m. power is not equal to okay now if p.m. power is not equal to BN or 5 then we need to break here right LF BM of the same of HP no.5 right but LF BM of the same of HP no.5 right but LF BM of the same of HP no.5 right but if it is 1 which means BN is also 1 then we need to construct our answer wait so either we can construct our answer in batch and then convert to decimal system or we can directly convert it into decimal here so what we'll do is I'll do the direct construction of the decimal answers here right and we need to define what power we need here right so we turn on so here so we need exactly how much we need to increment our answers with our power right so the power is actually sent of BM minus I minus 1 right so forth first bit in 4 &amp; 7 we should add forth first bit in 4 &amp; 7 we should add forth first bit in 4 &amp; 7 we should add the answer with it 2 to the power 2 L 2 which is 4 now here this power 2 is actually length 3 minus I it is actually length 3 minus I which is 0 minus 1 and this equals 2 so let us run this code and see ok I think that is we need integer division here otherwise it will just go on forever okay good but this is not the actual solution I wanted to show you so you can do this thing but you can also do this by a bit shift operators so what we need to do is since we need a common prefix right what we'll do is well M is not equal to N and we reduce the N until it becomes equals to M right so will take up the rightmost bit from end the rightmost bit 2 n becomes 0 we take out rightmost bit from M so the so once this is over answer should be equals to M or end shifted by how many number of pi loops we have done here right so what we'll do is we'll also count the shifts here and we'll say shift plus equals and that is pretend this answer okay let us run this good okay so you tell you how it works on the examples we have seen 1 0 1 and 1 0 1 this is the example we had right so the first three bits are the common perpetuate so in the first iteration these two bits the last two bits goes into it goes into null right so this M is not equal to n still right so we'll keep on iterating in the while loop but I shift become 1 here wait now does this go chef becomes 2 this let's go just become 3 this red curve just becomes full this what is I should ensure us become 5 so I'll M equals equation in here right but what we need is our answer should be equal to 1 0 2 okay something like this ok so we need to open 5 zeroes in the end right so that is why we are shifting the M by this number of shows right I hope you like our approach to this video we have first shown you our solution which is more intuitive and then we have shown you how to optimize your coding skills to implement the algorithm you have you know much better way I hope you again like the video please share if you do subscribe to our channel for more daily videos like this thank you so much for watching you
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
91
That in this video you will see Lord Number is Way Two Decades Ago When Called So You Must Have Died of Mine in Coding and Decoding Scheme Sudhir Visit Unicode Encoding Share It's Very True Love Can Join Coding and Become Difficult Decoding Suid Twitter Account How Way Can Give Video subscribe to subscribe our ki election lad deposit one possibilities patience individual characters tutu 6 two means b fat you two 62 f subscribe 602 16 the family unit test 201 sudhir way kal subah hai next six pieces da That Sudhir Person Send Recording Get Any Other Positive A This Tube School English Subscribe Now To Receive New Updates Reviews And Eggs Subscribe 4,320 E And Eggs Subscribe 4,320 E And Eggs Subscribe 4,320 E On Karo Hua Hai E Will Not Right Disbalance You Can Just Think That You Should Be Between One 06 2010 को subscribe The Channel subscribe this को subscribe The Channel subscribe this को subscribe The Channel subscribe this Video not valid notes will be seen here 142 here 123 sudhir wedding day saavan fluid mp3 ke din aa vikas bhawan floor notes23 sudhir will not come into force on ki sudhi zindagi zero one two three do it se z f and Navami decoding sir possible yo stress se 010 is not valid notes will display decoding number 1200 this is not valid only apps digit 232 subscribe notes143 subscribe jo person lips radhe-radhe wear jo person lips radhe-radhe wear jo person lips radhe-radhe wear solving from left to right key and current wear 800 till hair what is the number of wales 142 108 value for 2nd sudhir way 4219 tv24 2nd id clear reminder subscribe to and listen for the current character its quality is character dirty politics with british 04851 09 and jagadish camp if individually only zero karnataka and individual visits to come and Finance Dip Sweets 125 Thoughts This Subscribe Deol Will Be Valid In It's An More Positive 123 Tomorrow Morning Ulte Positive And Negative Very How Leave A Gross Violations 1423 Take 400 And A Co 143 Loot Services Naveen Shirt Validate Se And To Take Medicine From 1292 Everything That THIS NUMBER SOLUTIONS REMAINS THE SAME AS A DISTANT VOICES HAVE LEARNED HER A KI AND IT CAN ALSO WORK AS A CANDIDATE FOR THIS IS THE K Swimwear Continue Julian Knoll Solutions Won By Loud 9 News Part-1 Next By Loud 9 News Part-1 Next By Loud 9 News Part-1 Next Will Check This Note Positive If Individuals and acid subscribe next subscribe this Video not value between 6 and boy that * apple very stink schezwan other sudhir and that * apple very stink schezwan other sudhir and that * apple very stink schezwan other sudhir and only individual subscribe notes14 that and you two to that and shameless value later to go hua tha under what are the solutions It Will Again Hai Officer 142 The Fourteen 204 328 That And One The Four Is This Is 142 Secretary Hua Hai That To A Deer With All Its Effects On That If Units 90 Do Not Accept Individually So Just Take All Solutions Will Remain Valid Newsstand 32 Solution Have A Suitable Boy Account Hair Doctrines And Wickets Galaxy S8 Services Fluid 6 And More Than 100 Years Will Send You A That This Year One Day Before This Is Today's Redmi 4 Sweater Solutions Loop System 142 So A Well That And Porn More Solution Key Knowledge To Sudhir Voice Mail This Point That In This Person's View Chhut Will Up And Distorted Subscribe To All Of You Jai Hind Second Part Subha Total Dispur Plus Is To-Do List 6 Total Classified.in Plus Is To-Do List 6 Total Classified.in Plus Is To-Do List 6 Total Classified.in This Is Not Want To Listen To All Of You Can See Hidden Away Due To Subscribe And You Can Not Exist Individually 0 Is And Single Digit Not Allowed On Hua Hai I Suresh Sirvi 234 For Isa Did Not Wish That Can We Do It Together With This And Directly In The Past Me Su-30 Did Not Blind This Range In The Past Me Su-30 Did Not Blind This Range In The Past Me Su-30 Did Not Blind This Range And Member That Sachin Part Will Also Not Be Added Soon But Will Result In This Thank You Can See But They Ca n't Get Any Decoding To This And You Will Need Not Whisper Subscribe School A Bright Inch Plus Job In Python Improve Explaining this foreign pimples given goldie scene from pearl that this is note length 80 tips mp09 decoding and that this zero is equal to 1000 decoding 100 feet can only are it candidate but very first chapter this is Z2 and ninth slot length that this one A sweet K90 body account for which this will return even before going to next line that fees just 112 from 12951 Only one decoding possible advantage will keep track of values ​​on that values ​​on that values ​​on that distorted values ​​depending on weather The can exist distorted values ​​depending on weather The can exist distorted values ​​depending on weather The can exist individually The bell adds the great value Benefits Can Just Opposite Role Play The Solution Till That Eye - Too Sundha Minus One And Five Eye - Too Sundha Minus One And Five Eye - Too Sundha Minus One And Five Minutes Solution Terrorist subscribe and subscribe the Like Snacks Details Account 1.2 Like Snacks Details Account 1.2 Like Snacks Details Account 1.2 Which Equal to One Account Too Equal to One Sims Points 151 The 0 subscribe solution from the point is 21 a high standard length a plus i soft minute to check which takes lessons to deal with r current value is i - 0 deal with r current value is i - 0 deal with r current value is i - 0 220 is the current you will need the and combined value of current digital print digital and BJD Singh Research Scholar Defomed Is This Is I - One I - One I - One 8 - 02 Convert Which Character 80 Subscribe 8 - 02 Convert Which Character 80 Subscribe 8 - 02 Convert Which Character 80 Subscribe To Do Not Wash Indiscriminately Previous Multiply vide0 And Current Events Welcome Switch On Two Digit Number Is This Is From One 226 Days Villa Discount To And View Til Solution Til Please Visit And Asked One Is The Current Of Solutions Decoding Still Previous Year To Is Superhit And Current Account Is Jio Phone That Is Ki D Ki Is More Than Zero That Shirdi Ke MB Hai And This Note V2 Did Not Win More Dan 982 Single Digit Swift Mon 08 Feb 123 Person Solution Net Is Account To Set Karna Individual So Will Just Up And This To All Solutions Will Disappoint Video then subscribe to the Page That And Gift DOEACC Is Mode On Is Equal To One Hai And Italy Morns nickel 210 not one seams a the feet lets electronic 3080 sid and head sudhir wa porn video clip subscribe 6 a sor please correct the ajay ko kar do ki and after death at nine extradition will right shifting live with a account to become account vansh ki And what is the current account vikram account to 159 how to is the previous solution encounter one is the previous to previous that and finally it will return who to sind latest value decorated last visit that i that and works so let's driver time Complexity is 2009 and 142 228 ghee 4 hua tha hain yes and easy 8086 solution which hair chief but ch 100 a gift two-seater car individually so let's tree a gift two-seater car individually so let's tree a gift two-seater car individually so let's tree liquid Chhath festival example so it's 69 electronic tuesday lagengi 4 yo honey 80 decoding possible due To this was Shyamveer with and digit 3204 12000 karen 9 we will do the same thing in java in item that sequence pims solution acid last time space was not good to all during time wear consistently getting your sake da ki and next is javad ko share Bhi neend is carat hai ko anjaam Voice of its good Let's try MP3 Free Kar Do Hua hai kar do hai Ab hum ki Surjeet ne temporary value body ki and here ons again e thought hua tha ki and pattern solutions also accepted oh
Decode Ways
decode-ways
A message containing letters from `A-Z` can be **encoded** into numbers using the following mapping: 'A' -> "1 " 'B' -> "2 " ... 'Z' -> "26 " To **decode** an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, `"11106 "` can be mapped into: * `"AAJF "` with the grouping `(1 1 10 6)` * `"KJF "` with the grouping `(11 10 6)` Note that the grouping `(1 11 06)` is invalid because `"06 "` cannot be mapped into `'F'` since `"6 "` is different from `"06 "`. Given a string `s` containing only digits, return _the **number** of ways to **decode** it_. The test cases are generated so that the answer fits in a **32-bit** integer. **Example 1:** **Input:** s = "12 " **Output:** 2 **Explanation:** "12 " could be decoded as "AB " (1 2) or "L " (12). **Example 2:** **Input:** s = "226 " **Output:** 3 **Explanation:** "226 " could be decoded as "BZ " (2 26), "VF " (22 6), or "BBF " (2 2 6). **Example 3:** **Input:** s = "06 " **Output:** 0 **Explanation:** "06 " cannot be mapped to "F " because of the leading zero ( "6 " is different from "06 "). **Constraints:** * `1 <= s.length <= 100` * `s` contains only digits and may contain leading zero(s).
null
String,Dynamic Programming
Medium
639,2091
250
hello guys uh let's solve count uni values of trees today uh so this question we are given the root of a binary tree and we simply just need to return the number of uni valued subtrees uh and they're defining a universal subtree as a subtree where all the nodes of the subtree including itself uh have the same value right so let's see example one uh so in this example clearly there are four Univision subtrees uh marked in blue uh because the nodes themselves and all the nodes within the subtree all have the same value right and in second example it's an empty tree so we just turn zero and in the last example is the same as example one but instead of one here we have a five so you can see why the answer is six right all the nodes are now unevalued because they all have the value 5 the node has a value file and all its subtrees also has a value file so all of these nodes are individually univated subtrees as well so we return six right uh so let's see how to solve this problem uh so we have a slightly more complex example here so that we can sort of understand the algorithm better uh so one obvious observation here is that the leaf nodes are all definitely uni valuable right because they just have one node and that subtree has just one value so that is definitely going to be univalued so it sort of gives you an intuition as to we need to build the solution from the leaf to the root right like the information is there in the leaves and that sort of has to be propagated upwards towards the root right so let's first take an example where you want to evaluate a specific node so how do we know that if this node is only valid or not um so for a node to be univalued the left subtree must also be univalued the light subtree should also be univalued and the value of the left sub tree and the right subtree and the node should match right so that's how you sort of build the um solution from the leaf and propagate it towards the root so let's try to track the algorithm for the entire route entire tree and see how this works yeah um so in this example I've also marked the null nodes uh because it's sort of important how you uh process the null nodes as well so let's recurse through this tree um so you do a typical uh like a post order traversal where you first propagate recurs through the left subtree then the right sub tree and then you sort of evaluate the current node right so let's go left and then once we reach the null node um we know that there's an unload so for every node we return true two values right one indicating whether it's a sub tree it's a universal subtree or not a Boolean value basically and another indicating the corresponding value for it so for the null case we are going to return true followed by a wild card X uh I'm calling it a wild card because uh for a null node it doesn't really matter what the value is it just matches with all the other values as well this probably would make more sense one same write down the code so again you go down here it's a null node then you return true alert by the oil card X right and now it's time to evaluate five so to evaluate a node we need to check if ah the left subtree is univalued the right sub tree is unevalued and if the value is match so they are both true and since we have a y card we know that the values actually match like any number would match a wild card right so we know that 5 is definitely going to add it so let's mark that and once you're done with the node we need to propagate the information towards this parent so what would 5 return to one so it's going to return a true indicating that 5 is indeed univalued along with the value of 5. uh which is the value for this univalent subtree right uh and then from one we go right now and the same thing happens here they both return true along with the wild card and then we know that 5 is even evalued uh and then five would basically now return a true along with the value fight right and now it's time to evaluate one um so we check the left subtree and the right subtree they are both true indicating that they are univalued but the value that is being returned from the left and right are five while the value of the node is one so since this is not matching we can immediately say that one cannot be a unevaluate chapter right and then now we need to propagate the information back to its parent uh since we know that one is not univalued you can just send a false um along with just like a null value so once we know that it's false you don't really care about what value this is uh it can just be null or whatever right and let's recurs down the right sub tree yeah so for the right subtree let's go right and then we'll go left and since this is a null node it's going to return true followed by the wildcard X and then we go right again and then we'll go left and then the same process is going to happen this is going to tell us that 2 is a univ valued subtree and this is going to return a true followed by 2 and the same thing happens on the right sub tree as well so this is going to return a true followed by the value of true and now we know that for this particular node the left subtree and the right sub tree they both have the value to both have booleans true and their values are matching so they're all two so that way we know that this node is also uh univalence artery right so we can mark them as basically count them so when you reach this point now this two would return a True Value followed by the value 2 here and now it's time to evaluate this node this two and now we can see that for this two the left Boolean is a true the right Boolean is a true uh but the value from the left subtree is a wild card uh value from the right sub tree is 2 and the value of the node is 2. so since now we know that y the Wild Card makes sense here because we know that a wildcard matches with any value so this would return true because all the values sort of match so we can Mark and count this as a univalent sub tree as well and finally we return to the root with the t under the true under 2 and for 5 we can see that the left substrate it on the false so we can immediately mark this as false right so the total number of univalence of trees was this two these two and then these two fives so that's gonna be four plus two six right so hope you got an understanding of how this algorithm works so let's quickly see how to code this yeah so let's start with first defining the value for the wild card that I was talking about uh so I'm just going to give it a value 2000 because I know that the values of the node ranges from just minus thousand to thousand just to make sure that no node actually has this wildcard value right uh and I'm going to have the research variable defined as an array of bond integer this is just to make sure that when I increment this index since I implement this value inside the recursive function there is no problems because of like you know local variable Global variable issues like that you could also do assign it as a class label and then increment it inside the function but I just used to do it to say right let's define the request a function so it's going to take a single argument which is the node itself so first let's handle the null case so we saw that when it's a null value with a null node we return uh true forward very wildcard X right so that's how we handle our values and if it's not null we basically do like a post or a traversal right so we're gonna reverse left and right so we're just gonna do because none dot left and because not DOT right and um they're gonna return a Boolean value followed by the Boolean variable followed by uh followed by the value so it's going to be left move come on and here it's gonna be okay right now is the time when we need to evaluate the current node right so um so this condition is probably going to be a little bit so I'm just going to split it across a few lines just for clarity so what was the first condition that both the left and right of these needs to be true right so let's first Define that and what was the second condition the values from the left and right sub tree should match the node value right so the left value can either be the body card value or it should be clear to me right and I'm gonna just do the same thing for another example and I do I like to be the welcome value or the null value right so all these conditions need to be true for the node to be univariable right so if this is all true I can go ahead and increment the counter and I can also return a true along with the current value right so this is the case when node is universal tree and in the other case all we have to do is just return false along with me value can be just none because once we know it's a false we know that it's definitely uh not your Universe update so that's about it for this function now we just need to start the recursion to say recursuit right let's see if not any issues looks good awesome so let's quickly see the complexities for the solution so this is a standard DFS traversal so the time is going to be just o of N and we aren't really using any extra space apart from this one variable so the space is going to be of one right so I felt this was a pretty interesting and unique problem to solve because you don't typically like return like two values from a recursive cons which I thought was pretty unique but yeah I hope you guys understood the solution and thank you for watching
Count Univalue Subtrees
count-univalue-subtrees
Given the `root` of a binary tree, return _the number of **uni-value**_ _subtrees_. A **uni-value subtree** means all nodes of the subtree have the same value. **Example 1:** **Input:** root = \[5,1,5,5,5,null,5\] **Output:** 4 **Example 2:** **Input:** root = \[\] **Output:** 0 **Example 3:** **Input:** root = \[5,5,5,5,5,null,5\] **Output:** 6 **Constraints:** * The number of the node in the tree will be in the range `[0, 1000]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
572,687
145
Hello everyone, friends, now I will solve problem number 145 reverse traversal of a binary tree So reverse traversal of a binary tree is called Traversal in order left node right node root Let's look at this diagram How it works, that is, we start from five We go along the left nodes we reach zero we add zero then add two right node then one then return to three add four after that three then add five and move in the same way And in the right node relative to five, let's start here the order of adding zero added moved to two added one then moved to four added three and five now Seven six eight nine ten Yes eight later Of course yes and five too that was a mistake first here we go through then eight five right So I will solve this problem in two ways The first is recursion the second is an iterative method using the IR stack So let's get started first, with my help, as the simplest way to solve the problem, let's create a variable result, it will be an empty array. Now we will return result in the response. Now let's create a new function that will recursively call itself, let's call it travers. It will take it will have one parameter, the current node, so we need this function. by default, we need to run it once, pass our root node there, as we said, first the left node, then the right one, and then the center, that is, we do it quite simply, the function starts itself, we pass node Left there, then node wr, and then we add the root, that is, the result Push Note value and we need to do all this by wrapping it in an If check, that is, or If noe is not equal to Nal Why Because when we get to the last node noe will be equal to Nal Yes, because the last node has no descendant nodes and the Left and Right link will refer to Nal then yes we add like this m Let's check So great Let's think about what's happening here that is, look we our function calls Left yes that is Left will call the same function then again Left and at the end Left will be cash yes in the end we will get there to zero Left and Right will be cash and we will push this value So let's think again, yes, that is, the last one we will have cash They will be executed at the last one and these functions will be executed at the node, they just won’t functions will be executed at the node, they just won’t functions will be executed at the node, they just won’t do anything since there will be cash and we can say this function will be executed in vain, we will move on to push and then the previous functions will be executed recursively So let's think about the complexity of the algorithm, the first from memory is Linear complexity because ultimately all the values ​​of our binary tree will be written in the array, all the values ​​of our binary tree will be written in the array, all the values ​​of our binary tree will be written in the array, all the values ​​of all nodes of our binary values ​​of all nodes of our binary values ​​of all nodes of our binary tree and therefore the length of the array is linear depending on the number nodes of our binary tree Now let's think about time is Linear complexity Why Because each node of the binary tree We traverse once we check it once in our recursion and actually A push the Answers variable result now Let's write iterativeness leave the variable result and we will continue as before return in the response we will create a second variable we will call it k it will be an empty array We need a stack here and also Let me think We also need the current one but we can create it both here and in the loop our loop will be entirely based on the length of the stack And we will go to the stack push entire nodes and not just their value greater than zero yes and the stack We need to add our root node by default, that is, there will be one element in the stack and this is our root node link to the root node So what do we need to do here as I told us we need to create an auxiliary variable current node and each time we will get the head element in our stack That is, it works on the principle of last in first out Yes, now it’s interesting we will add Yes, now it’s interesting we will add Yes, now it’s interesting we will add the current node value to the unshift method. The Shift method in a Java script adds the array as the first element. the first number For example, we had an array like this 2 3 4 and we want to add one to the very beginning, that is, Shift will add it to the very beginning Yes, that’s it, to the very beginning Yes, that’s it, to the very beginning Yes, that’s it, why do we need this, now you’ll why do we need this, now you’ll why do we need this, now you’ll understand, that is, we write the current noe value added now we do a check If current node if it has a descendant of the node on the left then we do then we push onto the stack Push curent Left and if it has a descendant on the right So now I’ll think about whether on the right So now I’ll think about whether on the right So now I’ll think about whether we did it in the right order We sewed up the stack We took the stack Yes the order is correct that is, first on the left then on the right So let's size our T How will ours be Yes And what will they look like And what example to take now I'll think about everything So let's take this example just let's say when here If we only started construction to simplify the task Yes we have here such a small binary tree, it has a root node of three and the Descendant node is only on the left. Well, let’s and the Descendant node is only on the left. Well, let’s and the Descendant node is only on the left. Well, let’s let it be on the right too, that is, this is the tree. Let’s just imagine this is the tree. Let’s just imagine this is the tree. Let’s just imagine 3 4 1 02 the rest does not exist. That is, she has a Descendant on the left again on the left. one is on the right and here there is a four, how we will bypass Let's look at this example So, the root node Root is on our stack by default, that is, there is a three, yes, that is, what we did We took the three from our stack and pushed it with the first number its value that is, began began began to contain a three for us and the stack is now empty Yes, because we cleared the only element using the pop method Now what do we do if there is Left and Left is there, then we push the stack one If there is, then we push the four too Yes Only This is not just a value and here the nodes are located But for example, I will write the value and this is just a value, that is, numbers So we move on to the next iteration on LT we do the Pop method, take the four, take out the four and push it with the first number in using unshift Yes four So now And we did it now we have l 43 stack one Now again we take Left from one Left is zero we push the stack and push yes Right is ours Two this is our two Yes we move on to a new iteration our cycle is working for now something there is in the joint we remove the two using the pop method and add it as the first number to ours. Now this doesn’t work for us ours. Now this doesn’t work for us ours. Now this doesn’t work for us because it’s all zeros. Yes, because it’s all zeros. Yes, because it’s all zeros. Yes, we have everything, that is, curent is a two. And for a two, left and right are that. That is, it doesn’t work, let’s move on is, it doesn’t work, let’s move on is, it doesn’t work, let’s move on our method takes out zero, pushes it with the first number, also does not work, take out one, push one with the first number, look, what did we do ? then I made a mistake here, let’s quickly ? then I made a mistake here, let’s quickly ? then I made a mistake here, let’s quickly go over it again. So we had to check the logic again, the logic is correct, but I just missed something. That is, we started construction. Yes, this is Root, that is, the stack is empty here, the value t is now And the triple has 1 stack 1 4 First, we push from the left, now we take, we get a four on the right side, we push it with the first number here, we add a Yes, the situation is like this, that is, we took a four, Yes, and she has a Yes, she has these things, we don’t execute this code for the next we don’t execute this code for the next we don’t execute this code for the next radio, we already get a one we push e with the first number and now it’s a one we push e with the first number and now it’s a one we push e with the first number and now it’s already at one. Here’s where my mistake was, already at one. Here’s where my mistake was, already at one. Here’s where my mistake was, we take and add 0 ID in c but then it doesn’t work there will be then it doesn’t work there will be then it doesn’t work there will be values ​​we take two values ​​we take two values ​​we take two A we delete and add with the first number and then we delete zero with the first number Yes, look a 0 2 1 4 3 That is, now we have the correct answer, this is how it works, we added 0 2 1 43 That’s right, this is how the works, we added 0 2 1 43 That’s right, this is how the works, we added 0 2 1 43 That’s right, this is how the iterative method works Let’s iterative method works Let’s iterative method works Let’s think about the complexity of solving the system The first is time, linear time is the same We go through each one once node in our binary tree and the second is memory Let's think That is, we have already discussed and the res array will contain all the values ​​of all nodes Ro That is, this is all the values ​​of all nodes Ro That is, this is all the values ​​of all nodes Ro That is, this is Linear complexity at a minimum, now we need to decide what will be on the stack and on the stack we have the following situation we need to parse the worst case, yes, that is, it may be that there are no descendants of nodes and we do not add anything, but the point here is that the worst case is a balanced Tree in which each node will have two descendants. Yes, and then for each walkie-talkie of the two descendants. Yes, and then for each walkie-talkie of the two descendants. Yes, and then for each walkie-talkie of the cycle we will remove one element from the stack and add two, but in any case, since at each iteration we subtract One node, we add two, that is, it will still be less than the number in the stack, there will always be a smaller number of elements than the number of nodes, so from memory, as if we are rounding here Although of course It takes up some space in memory but we are still rounding here and the complexity is linear o So we solved this problem in two ways using recursion and interactively using a stack Thank you all for your attention Goodbye everyone
Binary Tree Postorder Traversal
binary-tree-postorder-traversal
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_. **Example 1:** **Input:** root = \[1,null,2,3\] **Output:** \[3,2,1\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Example 3:** **Input:** root = \[1\] **Output:** \[1\] **Constraints:** * The number of the nodes in the tree is in the range `[0, 100]`. * `-100 <= Node.val <= 100` **Follow up:** Recursive solution is trivial, could you do it iteratively?
null
Stack,Tree,Depth-First Search,Binary Tree
Easy
94,776
212
Hello One Should Appear give a like And subscribe The Amazing spider-man More Subscribe My Channel Subscribe Button Hai That Boat Less Lessons and Miscellaneous Tow Ring to Indore Train Subah Subh Virudh subscribe our Channel subscribe to the Page if you liked The Video then subscribe to the Page Loota Container Startd Aaoge Sudhir Vidmate Vidmate subscribe this Video plz subscribe Queer Vitamin Map To Avoid Vid Ooh ki naav par attention Pimple on this coat Far hence but is tight on were inner contentment rydell training on dual personality bulletin midding and subscribe diy ocean 's explanation cutting subscribe and star 's explanation cutting subscribe and star 's explanation cutting subscribe and star root tender housing difficult function pimply calling pimpy function in hair cutting half the fuel subscribe toe is in gooseberries a new delhi cricketer Root And Its Root Will Continue To Lead Us In This That Aditya Pack Singh With Words Insisted Its Function In More Subscribe To A Love Affair's Traversing Diet Watch Later Ofton Here With Attention Deficit In The Pointer Current President Rule In Thought Word And Subscribe To Our Channel Subscribe that in this school entry alone in middle aged person half inch width subscribe to ki maze done nine comes the part updated on ki padi hai only but I don't David Pauly please do n't forget to subscribe and subscribe to a fight for a day that end Have Advertised Dresses Available On Website Acid Play List Avoid Giving Vid Oo Hai Na Her [ __ ] Path Ab Doing Hai Na Her [ __ ] Path Ab Doing Hai Na Her [ __ ] Path Ab Doing Hai Then That Only Interest Karnataka Ko The Raven Milti Thi Simple Width Particular Actor Will Continue To Market Me Sleep subscribe this Video Please subscribe And subscribe The Amazing spider-man spider-man spider-man Vid Oo Main Jaanta Required to Give Its Opinion Can Withdraw Radhe Maa Subscribe Tave subscribe and subscribe the Channel subscribe and subscribe this Video Subscribe Questions Sexual Friends Questions Page One Act International Friday Questions on History Duddy Questions Special Tips Questions Will Welcome Much Easier For Electrification Subscribe Skin Ko Vid Oo Main Hoon Thank You
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
212
Everyone, today we will make a playlist of Try Data Structure, so today we will do the first question, okay and this question is very popular and famous Now let's come to this question, what is the question and how to make it, so before that, let me tell you this. There is a question called word search. Well, this word question is a bit simple. What is there in it? You will be given only one word. You will be given one word and it will tell you that you have. That word of Tu Tel Me is present in this grid or not. If you have to return True or False, then it was quite simple. If you see, whatever word has been given to you, it will be created. Now let's come to this question, keep the word in it. There are many of them, look here, a list of words has been given and a grade has been given, asking you to return which of these words are present in this word. So see, look here in this word. The first one is at here, that at here, I saw it here, at is it, I got it, after that, what is ot, the post is also here, look, isn't it, and is it rain, is it not rain here, because you go from one cell up and down. You can go right or left, so here I don't see rain anywhere. Okay, so I have understood this question, there is nothing in the question, it is ok, so what now is that you can make this also like right. Like take each word, now do DFS and search in it. If you find it, then put it in your result. Ok, but this is a very costly operation because you are doing DFS for each word. What will be the year case in DFS? Let's use M is the cross, what will happen in this, the whole grid, the whole cell, we will explore M, okay and here we have man, let's take N words, okay, so for every end word, do DFS in you, this is done with DFS, M and This is a very costly operation for every N years, the best way is that the trade structure is fine and see what is try in general, after reading the question you understand that this is general, it is okay, so in this it is clear. It was decided that DFS will not work. Okay, so the best method is that you can search for a single word or not all the words, that is ours. In which data section can you search for a word best, is n't that ours? Now in tri questions there are many terms like prefix six and many other things by which you can immediately know that it is a tri question but I don't think you will understand the terms. OK, now look at the question, you will be able to figure it out yourself, this question of yours is from TRAI, okay, so let's see how to make it from TRAI, see now the implementation of TRAI is fine in it. Insertion happens in it, what we search in try isn't it, how to define from try, I will make a separate video for that but when I will code in it, I will also understand it, okay and here I will tell you now. But for tri, I will make a separate video in detail about search and insert. Okay, now let's see, let's take man, I have made a tri. Ok, the inverse of these words, if I have made a tri, how will it look and will it help us? Solve this question. Okay, so see what happens in try. There are many notes and each note has some details. Okay, that note is of a character. Okay, so let's keep making the notes so that we can understand them better. Okay, so I want to make it due to main, so first I got the post, okay, I try to put it in try, so this is the first note, let's take it as the root note, okay, let's take this main that is my root note now. Look, is there a place for O near the root note? So the first thing we will see is there a place for O near the root. It is not there yet, so what I will do is create a pointer near the root, okay, I will create a note, which will be for okay. Now I went to A and said, brother, do you have space for A? If not, then we will make space for A. Okay, now our point here has gone to A. Okay, now we have gone to A, so we will ask from the point. Which will be for t, man lo, you are traveling in tri, okay, you should know, not good, but which word was completed, is n't it, which word was completed, okay, so I have told this. I will write that whatever is in this word is true. Okay, there was a word here, there was a valid word and date it is o a t h is d and of word so similarly for t What will happen in this world will be false because till now we have not found any such word which ends in 't' which ends in 't' which ends in 't' which we do not have. Okay, so you must have understood the structure that every tree which I am making is based on There will be a structure, what should be there in it, first of all the brothers give the character group, which character will be there, okay, after what I told, will it be Indo-English words, will it be dialects, okay, Indo-English words, will it be dialects, okay, Indo-English words, will it be dialects, okay, after that, each one will have a list of children. There should also be something to point to the children, there should be something to point to the children, okay, now if I take man, now more words will come from the root, right now I will enter at, okay, so a lot of alphabets, a If we can, then what will happen in children? We will make a 26 size children's pointer because any word can come out of each note, it can be A, it can be B, it can be C, it can be D, it can be neither, nor all the alphabets. We should have children like ' We should have children like ' We should have children like ' On' is derived from the root, ' On' is derived from the root, ' On' is derived from the root, ' A' is derived from the root, 'A' is derived from the root, ' A' is derived from the root, 'A' is derived from the root, ' A' is derived from the root, 'A' is derived from the root, ' B' is derived from the root, then from here some words named 'A' and 'T' are B' is derived from the root, then from here some words named 'A' and 'T' are B' is derived from the root, then from here some words named 'A' and 'T' are formed, 'BAT', from here 'AB' You understand, C is formed, 'BAT', from here 'AB' You understand, C is here, B is T, now from here, Ba is one and here if G comes out, then you are seeing that everyone has one, we will keep the vector to store more characters, it is of 26 size isn't it, so you will get this. So it is understood that okay, what should be there in each of our notes, its structure, okay, till now I have understood and you can automatically add one more thing to sample your work. You can also do this by not storing characters in each node, you can store words in each mode because which word is there, okay, so like man lo, now I am at the top, here at the top, no word has been formed yet. There is no, isn't it? Now it is on A, so is there any word named O and A? Is there any word called O and A? We don't have any word, but the ending is there, we will write it with the word, isn't it? So this is a better way, you can use direct word. Well, people, you will not need to store the travels, so now by storing the direct word here, people are getting clear till here. Okay, what did we do, we stored the cover and while making noise, we came to know that what we have to do- What that what we have to do- What that what we have to do- What elements have to be kept on the notes of your Mr. Okay, children, it is true, it means that a word has ended here and which word has ended, I will store it in this word. Okay, okay, now we come to it, make it noise. Let's try to do it, okay with Blue, is it okay, right now I will do the route from the beginning, right now, if I start again from the route here, then I will ask the route, brother, do you have it now, am I near the road, do you have A because Now I am going to fill the brick, here I write this A T Now I am going to fill A, so what is the first character, if it is A, then do you have A, it does not have A, so what will it do, its children nodes. If there are children in I then what will be the index of If I store a pointer to the unit index of I, then it will work because you need to know the index or find out that it is the index of I, okay, there should be information about the word in all, like what will be the word here, is there any word ending here. If it is not there then it will be empty. Similarly here also the word which will be there will be empty because till now no word has been finished here, whatever word will be there in me, whatever word will be there is equal, you will be covered isn't it because here The word is empty. Now we come to A. Now our pointer here is A. Okay, I ask it, brother, do you have any note to point to the child A, so it will not say, so we They say, let's make it, okay, so AI will also have a vector named Children, right, AI will also have a vector of children in its eight indexes, so how will eight indexes come out A - A i.e. 0 how will eight indexes come out A - A i.e. 0 how will eight indexes come out A - A i.e. 0 in the index, we are the team. Okay, we will give a single note team. Okay, now our pointer which is here is A. Okay, otherwise, okay, let's make a note, made a T for you and now the pointer which is mine here. But it's okay, now look, we have traversed the brick completely, its meaning is P, it is Indoph word, is there any word which has this end, we will mark it as true and which word is it, brother, okay, I have taken the team, okay now. Let's insert ren from white here near the root, now I am here near the root, so R is needed for ren, neither is R, so no, okay, for I have made a note for I, okay and which one? The word is brother, there is rain here so that we can find out directly. Okay, okay, now let's move ahead, so let's start that whenever I have any concept of DFS, sorry root, you have a child named O, then root. If he says yes, then I will say, ok, great, ok, now I have passed ok, now look at the grid, where can you go on the grid, what is given in the question, you can go right, left, up or down, right now? Look here, now you can't go left, it's out of bounds, okay, you can go right or down, now I have gone right, I have to explore down also, otherwise I will leave, explore the right also. If we do, then let's assume that I am just exploring the right side first, so where have I been? I am here, my point is, brother, do you have a child named A, then he will say yes, I have a channel named A, then I will say, okay, let's kill the pointer and take the pointer here. Okay, so now. Let us pay attention to one thing here, when you start opening the O, it has already been visited, you will go back to O for a while, now you cannot go back to the open from this A, let's mark it green, okay, so there is no one in it. Give the dollar sign. Ok for now, so now you are at Meaning, if that is the state, then I will not go left, okay, I still can't go because it is out of bounds, I can go right, don can also go, so because of the man, now I have gone down, okay, I have gone down, I did that, I am tk. I am close, let's go, okay, then when we do it again, we will do it after that, okay, we are still storing it, so now I have come to the T, okay, now I ask my driver, brother, I am asking him because the pointer. Mine is here right now brother, do you have a child of three M's then A will say yes I have it then I will say okay let's go there then let's pointer here A has gone to T's okay and see I also ask from each note. I will say that brother, your end of word is true, meaning that you had a word ending on you, what will he say? He said no, I did not have any word ending, meaning someone is right, now this is how I asked, I am asking brother. Did you end up with any word ? No brother, I did ? No brother, I did ? No brother, I did n't end up with any word. Similarly, I will ask T, is T the dialect of yours a variable in me, but I didn't end up with any word? Okay, there is no word named Teen. It was in our input and we had not even put it. It is our time. Okay, where did it come from? Okay, we have kept T. Okay. Now look, now we are on TV, so where can we go from T? Right Left. Now I went down. I am okay, so I went here to H, okay, so I will ask the try pointer now, I will ask him, brother T, do you have a child named H, then he will say, brother, Han, so I am okay with my children, let's go to the child named Achcha. If you go then it is gone here, okay here it is gone, now look, should I ask, brother, do you mean in me, a word was finished, okay, so I will ask, ok, which word was finished, tell me about the note. Remember, in the structure that I have, I had also stored a variable named ' I had also stored a variable named ' I had also stored a variable named ' world' in which I had world' in which I had world' in which I had stored the word, here the word 'word' had stored the word, here the word 'word' had stored the word, here the word 'word' had ended and it is correct that it was in our input, so our In the result, I will enter the camel that brother Oath is correct, it is clear till now, ours was in the right place, so I checked all the words starting with O, nothing else was found, I entered the input, ok now. Let's come to the next cell, A came but I asked Root again, okay if my net is in the cell now then I will start from here again, A went to the next cell, Root will speak otherwise I will speak, okay let's move ahead, I am A Gaya zero does n't even have a child named N, let's ignore this too, okay, now we take man while increasing like this, here we go to A has a child, and root has a child named A, okay, where do I go? I can go up and down here, so I take it, when I go up, it is there, the phone numbers go to I, here there are no numbers to come down, which means this is also no less, we have returned from here. Okay, we returned from here too that brother, I don't have a child, so leave this too, now when we come to A here, the root will say brother, I don't even have anyone named A, okay now look here, pay attention. Here A went to A, okay, the root is saying, okay, I have a child named this, so I said, okay, I have a reward, if you have style, then go to A, went to A. Okay, now here I am at A. Where can I go from here? I can go up, I can go left, I can go down. Okay, so man I went left. Okay now when I go left, I came to A. Right, now I will try to point the pointer at the eye and ask him, 'Brother, do you have a child named A?', he will ask him, 'Brother, do you have a child named A?', he will ask him, 'Brother, do you have a child named A?', he will say yes, I have a child named 'A' and I have asked him, ' child named 'A' and I have asked him, ' child named 'A' and I have asked him, ' Brother, do you have a child named A?' If the word was coming to an end, then Brother, do you have a child named A?' If the word was coming to an end, then Brother, do you have a child named A?' If the word was coming to an end, then it would not say, I was not getting any word, so okay, I will go to A right now, who is his child, okay, A has gone to A, now look, now here we have come to A. I have guided it and marked it with a dollar mark for now so that it can be considered back. Okay, now see where I can go from this A. Up here and here, I cannot go to the right side because there is a dollar mark, it is widgetized, so I take it. It has gone to the right side, meaning it came here near this T, okay, now I ask the point about the try point, like brother, you have a child of three M, then it will say yes, I have a child of three M and on this There was no word being uttered, so I said, okay, he goes to his child, T is fine, now when I came to T, I would ask TCB, brother, if any word was being uttered to you, then T would say yes. If my variable in this world is true, then I will ask. Come on brother, tell me your word quickly, then it will tell your word at, isn't it? We have made at noise in it, we have stored hit in it, okay, so our Oth and at us. Got it, okay, we will move ahead like this. If we don't get any more words, then we will backtrack and go back to our old cell from where we started. Where did we start from? We started it, don't mark it. Let's do this, we will go to R, if we go to R, the root will say, I have R, ok, R is there, but if you go up from R, I will not go, look near R, there is no child named A here, on the left. If you go down, you will get K. R has no child named K. If you go down, you will get C. R has V name, which means this one is also no less than I. Come on F. Come on L. Come on C. Nothing is found. We have traversed the grid just once. You see, we have got our output. Okay, we have got our output. This is the specialty of TRY. You see, you do not need to do DFS again and look at each letter. Is there a word in try? And so on, what do you put in whatever you get? Are you okay? So I hope you have understood this story here, now I am completely Sorry, I will remove it now, when I will write the code and even while saying sorry, I will code, you will understand it very easily, okay, so let's start coding it, so let's start the director solution, the question is this, it is okay to understand, so first of all, define above. Let's make our global some global variable like vector of string in which we will store our result. Okay, there will be more moles and there will be N columns. Okay, let's go, okay, M is equal to you, what will happen Okay, till now it is clear, now we are not. Let's first create our tree data structure. Okay, so what did I say that TRAI's note will look like? What will TRAI note look like? What did I say that the bids will be the variable of End of the World, which told me that there is no word in this note. Is there an end or not? Okay, and if there is any word ending in this note, then which word is it? Okay, and every note has children. Okay, there will be children of 26 sizes. I am asking from the note, is n't it yours? Is there a child named A or not? Is there a child named B? Otherwise, if it has 26 characters, it is lower case, so it is 26. It will have this and all the pointers will point to the pointer of its type, that too will point to one note only, okay till here. It is clear, okay, this is ours, we have to create a note, try it, which will make us a new note, okay, it will create a new note, so we will create a variable named new note, okay, which is new new note, I Do you know a little about whether any word is ending here or else it will fall at the beginning? Okay, and if you don't know which word is the word of the new note, then we will leave this also black. Okay, and those who are children, do not slice them. Let's start with null, so I don't know which children will be there, I don't have it, so let's initialize it as foreign with null, give it equal to zero area, 26 i plus, okay, so the children of new note will be children of I am giving null command to all of them, till now it is clear, get try node is ok, we have also written this, after that now we are inserting in the tree, how will we insert all the words, let's see, insert is ok from the root. So let's start and which word has to be entered, that will also be passed, brother, add this word, I used to say root, not brother, root, add this word in your data structure, okay, so I will create a crawler, okay. Meaning, if the root has no children, then we will make it a child of the character, then we will make it a channel, how will we make the children of the crawler, right now, this one's children are null, so we will give it a new note, get note, it is simple, ok. Now the note is A, now let's go to the note, like man, take my try, B was, sorry, this was the root, it was not even near the root, so B is given, BSA is given, okay, now our point will come to B. Na, initially the pointer was near the root, A will go to B, now A will go to its child, till now it is clear, okay, in the same way, we will add all the letters in our tri, all the letters of this word will become clear, so these people All the letters of the word will be gone. Okay, which word is the one which came to me in the word input? Here, which word is this word which came in the input which I inserted, it is clear till now, we have inserted it. I hope you must have understood. Okay, now remember what I told you, okay, we have created our structure, we have created the trade data structure, now what will we do, we will start searching for our words. And find all the worlds. Okay, okay, so first of all, remember, right now I am on the I Kama K character root, do you have this child named 'f' or root, do you have this child named 'f' or root, do you have this child named 'f' or not, I will ask the root, okay, we have not created the root yet, sorry. Create a root Make Make Make it equal, you get a new note, okay, we will get a root, now think about this, now we have put all the words in try, where is it, okay, so first of all we have created the root. Do this also for string and word in word. Okay, insert all the words in the word. You will call the root, brother, root, you insert the word in it. Okay, we have inserted it. Okay, let's come back from here. What do I know from root? Brother root, is there any place for this 'f' in your children? You have made it meaning any place for this 'f' in your children? You have made it meaning any place for this 'f' in your children? You have made it meaning when you insert it, you have a note for this children. Not equal, you null means note. If so, then let's explore. Let's do it, okay, let's write a function to explore. There is the word find, right, what will be traversed in try, what will I send in it, I will send it to the board, which is the index, okay, what else will I send to the root, write the word find and The word fine is also very easy, it is nothing, what I told you is simple DFS, isn't it, the word fine is fine, vector and factor of string and word, sorry &lt; 0, if it is done then quietly brother, close your eyes and return, you cannot do anything. No, okay, it is clear till now look, we will do exactly the same things which I told, it is fine, just like the story, just like sorry, Han, now you have to check this too, brother, the board you have come to is fine. Is it widgetized somewhere, is it a dollar sign, is it detailed or does the root have no children of the character, isn't it board i k in which I am right now from the root of board i I will ask every time, no brother board izz Do you have the character root? Even if it is not there, will you return it? What is the benefit of going further? Are you looking for the meaning of root's children? If I is null then you do not have that character. Otherwise, what is the benefit of going further? Then return. We will return the group, okay, if there is no case in either of these two cases, that is, C is good, you go for D, that one is okay, then what I will do is, let's go, okay, the children of the root have it is okay, I will pass the pointer to the root. Took me there, now see, now I will ask him, brother, where is there any word and what is happening, are you watching the story that I told you, is there any word happening on you, is it true, that is, this is our world, isn't it the result and Push underscore back quickly, which word must have been stored on the root, we have that one right and what I said about it, let me show the end of the word to this world as the first mark, okay man, low bed, it was your word, okay so you After talking to the root, came to B, A is on B, and T on the end of the word was true, so I gave it to my bed. Okay, now this is a little in this, now you will stop here, you will store it in future as well, right? Because look, when we had added a wait named 'A', there was when we had added a wait named 'A', there was when we had added a wait named 'A', there was also a word ending on 'A' whose also a word ending on 'A' whose also a word ending on 'A' whose name was wait, isn't it, sit here, then that too will come, that is why there is no need to stop here, moving forward, end of off. Got the word true, do n't stop here, further words can be found so that you can get wait. Okay, so you don't have to stop here, it means okay and Han like man lo, when you got this word, okay. You have found this word, you mark it as false, okay, I have found this word, you mark it as false, it is fine, then you come to wait, okay, if you have understood, then explore further. Okay, so mark the current letter with a dollar mark so that you don't have to visit it again and again. Okay, so let's store it in temp now. Board of I, K, okay, and Board of K, I, dollar. It has been marked, which means it is visited. Marking it visitor for DFS. Now from here onwards I am marking the state for the DFS. Okay, now after that, what can we do for DFS? You can go left, you can go right. Now we can go down, so remember, to do DFS, to go up, down, left and light, we had taught a method that we create a vector called directions, vector of these directions, okay, which we The top index will help, the left index, right index and down index are fine, so one earns zero, it is fine Now again let's do the same by calling the function from the key brother, now you explore further, we will send the board this time. Will send it to New York where the new one has gone and will send it to the route I am currently on, okay now when it gets explored, okay I will unmark it again, unmark it as widgetized, okay we had stored it in temp. Shared, sorry, I was doing a show, returned the marking as unvisited, ok for next time, this is our thing, tell me how are you doing, then how are the words coming out, this is such a simple thing, now just run it. Let's see I hope we can pass all the cases What's wrong Value Line 23 Ok here we are not returning our new note We have colored the spelling of the sorry for tha children somewhere No problem let's run it Ok, here also we will run, we have made a wrong spelling, no problem, I hope it should be done immediately this time, here also we have made a wrong spelling of run, very good, now let's run, my brother, now select, now submit, actually if you see. What mistake did we make? Our board is a vector, it is fine and the word find is already the name of the question, we should have kept a different name for the function, so we keep it as find private, it is fine, find driver and here we are calling it. Fine driver ok, now let's run it and see I hope ok now let's submit it and see I hope we pass all the tests and it gets submitted Grade They have sort of this question C has sold a very good question very Hard question ok I hope you have understood everything like step by step story ok anyone you have doubt anywhere doubt please reside in comment section I will try to help you out so see you gas in D Next Video Thank You
Word Search II
word-search-ii
Given an `m x n` `board` of characters and a list of strings `words`, return _all words on the board_. Each word must be constructed from letters of sequentially adjacent cells, where **adjacent cells** are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. **Example 1:** **Input:** board = \[\[ "o ", "a ", "a ", "n "\],\[ "e ", "t ", "a ", "e "\],\[ "i ", "h ", "k ", "r "\],\[ "i ", "f ", "l ", "v "\]\], words = \[ "oath ", "pea ", "eat ", "rain "\] **Output:** \[ "eat ", "oath "\] **Example 2:** **Input:** board = \[\[ "a ", "b "\],\[ "c ", "d "\]\], words = \[ "abcb "\] **Output:** \[\] **Constraints:** * `m == board.length` * `n == board[i].length` * `1 <= m, n <= 12` * `board[i][j]` is a lowercase English letter. * `1 <= words.length <= 3 * 104` * `1 <= words[i].length <= 10` * `words[i]` consists of lowercase English letters. * All the strings of `words` are unique.
You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first.
Array,String,Backtracking,Trie,Matrix
Hard
79,1022,1433
141
Today we will solve the next problem of Blind 75 whose name is Detector Cycle in D Link. So first of all let us see the problem statement that Jivan is the head. We remember the last problem we had discussed if we have given the head and date mains has given us the hole. Linklist is given and de head of de link is determined if de link has en cycle devar is en cycle in de link list if devar is some note in de list date can they rich again same continuous following de next painter internal position is used tu Days D index of D node in D return jal So basically we have been given the head of a link list and if at any point we traverse the note over it means it travels continuously so that we can maintain the story late in some way. Whether we have made a note of taking it or not, then if we traverse the note for the second time without reaching the end of the link list date mains this link list has a cycle, then this thing can be understood with an example. I have seen that this is your point 32 01 from late and this is the point from late and I have given you the head, so clearly we know that there is a cycle right here because when I go traversing from here, for the first time I did move two and after that when I will next traverse to one I will again go to move two and this cycle will continue so I will never be able to exhaust the list and I will be able to move elements from that multiple times after that. I am repeating from right, I think that what could be an easy solution to this could be that if we maintain one map from late, our map right or our table and we just keep this note that we have made in the first travels. Whether it is working or not or right to maintain the set, whenever we travel the note for the first time, we will insert it in the set and when we come to any note, we will check whether it does or not, then we will say it is cycle. Right, another vice, we will try to travel the entire list, right, and if we reach another place, and Dileesh and we also told the story, if the cycle has not been detected yet, then they will pay the bill for the return of water. We have not found the cycle yet, other vice. Bill Return True If we are traversing the amendments later, then what will be its complexity because we are trying to traverse the entire list once and what are we maintaining simultaneously? The write which can basically tell us whether this note has come before or not and the runtime of inserting it in the handset and reading it will be constant because if we write it from Hastable then it will be order of phone or it will be a constant time. Note, our overall and time complexity will be order of one, then it will be order of n, so first of all we try to write this solution and after that, first of all, write the basic check, if our head is actually in it will be automatically calculated. After that we can check the return water, we have not even inserted it in the set, we have discussed the run time complexity of the solution, but what will be the space complexity, order of and right because we can have space for all the elements. If it is okay in this table then can you reduce it a bit? Let's see on the oven, so for this we will do whatever is there, so I will try to move fast to maintain it at double speed, so and then Later on here at some next point my goal is to maintain this is my cycle in D link list because I am maintaining fast with double speed moving and double speed it is nothing but if I start from here fast and slow Right, after racing, my fast will be here, my slow will be here, give my fast will be here, in the second address and my slow will be here, in the third hydration, my slow will be here, a fast will be here and in the next hydration, both of my will meet here, so if Cycle exists in that list. Right, our pointers will meet at some point or the other. So if our fast and slow painters meet on the story, then we will return. Cycle exists in our list of True Men. If we don't get it, okay, now let's see, let's try to write its code. Right, first of all, what will we do? IF D list, if our head is null, then we will return Jal date mains, none, our cycle does not exist. Right, after that we will slice the slow painter, no one, after that we will initialize our fast point and correct it, after that we will see that fast and fast next low bill b slow next now our slow one is moving. So how much will our fast move? Right next, we will move the pass twice and while traveling to any point, if it passes by us, then the main path will return true if we exhaust both these points. Let's see the bill return details. Okay, yes, it will work if we have set this check, then segmentation fault will not occur here because we are moving the fast twice, so it can happen that if only one item from our list is element or there are three elements in our list right so when we come to second iteration for the second time then only one painter can move fast and we will move next to the next one how to do this thing right so we will move the next one to the null So, this segmentation fault will occur, so to avoid this thing, we will put this check, so if it is working then it is okay, see you in the next video.
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
205
welcome back everyone we're going to be solving Lee code 205 isomorphic strings so we're given two strings s and t and we want to determine if they are isomorphic two strings s and t are isomorphic if the characters in s can be replaced to get t T okay all occurrences of a character must be replaced with another character while preserving the order of the characters now two characters May map to the same character okay so we can create a mapping and let's go to example one so we'll map e to a and G to D and then we can just Loop through um Loop through the characters in our mapping and then print them out and if we get the same resulting string as s we should return true so let's do that let's create a mapping where the what do we want to map the character in T to s yeah so let's say 4i and range length of t what do we want to say if well if we want the T to map to a it's going to have to be if t of I is not in nothing then we are going to set mapping of T of I equal to S of I otherwise we won't do anything and then we are going to want to build a new string at the end let's just call it res now we should be able to Loop through t every character in t we're going to print out the resulting character from our mapping so we're going to index into the mapping grab a whatever it's mapped to append it to our string and let's make this an array and return to string giant instead so we'll say four character in t if a character is in our mapping we want to Res dot append mapping of that character and we want to return a string join of our res and if it is equal to S our um beginning string if it is then we should return true if not it'll be false so let's run this and see what we get test case 2 fails so let's see Foo and Bar false it's not in there okay so we're adding in our to our mapping when a has already been mapped to O So I think instead we should be able to check if s of I is not in mapping dot values this should fix it and it does so let's submit okay it works it's not the best time complexity let's see if we can fix that so this is running o of n that's fine this is running o of N squared how can we fix this well instead of checking Estefan and mapping down values okay so While We're looping through T let's add let's create a set we'll call it Triple S is going to be equal to a set and when we Loop through T we'll check we won't check if the character at the ith position is in our mapping values we'll say if it's not in our set that'll give us an O of one lookup time instead of O of n if it's not in there we want to obviously add it so we'll do triple s dot add the S of ith character and then we will update our mapping accordingly so this should give us o of NS of an O of n runtime for this Loop instead of 12 and squared so let's run it see if it even works and it does submit and it does and there we go better time complexity so again I just said time complexity is going to be o of n this for Loop will run o of n the space complexity is not the greatest right or creating a mapping which is going to be o of whatever the length of this mapping is and then we're also going to have a set this is always going to be equal to the length of our unique characters in s so o of s dot length where it's only the unique characters and then obviously we will have a resulting array but since we're rebuilding the um the S string and then just comparing it right here right so this is just going to be o of s dot length essentially and that's it so the space complexity like I said not the greatest but we did speed up the time complexity so mapping dot length Plus um unique characters in s as the length unique plus s well so you guys don't get it confused we'll say res dot length and that'll do it for leeco 205 isomorphic strings
Isomorphic Strings
isomorphic-strings
Given two strings `s` and `t`, _determine if they are isomorphic_. Two strings `s` and `t` are isomorphic if the characters in `s` can be replaced to get `t`. All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. **Example 1:** **Input:** s = "egg", t = "add" **Output:** true **Example 2:** **Input:** s = "foo", t = "bar" **Output:** false **Example 3:** **Input:** s = "paper", t = "title" **Output:** true **Constraints:** * `1 <= s.length <= 5 * 104` * `t.length == s.length` * `s` and `t` consist of any valid ascii character.
null
Hash Table,String
Easy
290
791
you guys this is your husband going in this video I'm going to take a look at seven nine one it's meat medium not that difficult I think I'd cast custom sort string s MTS trains can post up for it for case letters in S is order so no letters a Christmas at once s was sorted in some custom order huh we want permute the caption of T so that may match the order so cba so C should be before BB should be before a so we need to sort it like this so Steve's not peering s it can be at any position in T this is okay also valid output cool okay so how should we do it well we could just do sward B huh we could do we could just do sword right use the sword and pass any compare function compare would be compare function would be getting the index of the character and compared there's compare there the in number so I think we should you first get a map between the captor and these index the order index and then we pass the compare function to the sort so that's it so the step is gets the map actor index and then you create compare something and through a third step is you ask I'm using your sword and that's it let's do it so the first one is order map for less okay this is we got the next and then create I'll come here counselor you return folder map and get a with autumn and get feeding right so it's just this minus negative it means these character should do it before this character so cool so now we catch the actors should be we split it and then pattern swatch okay and then we returned actor stroke I think this is it submit ah there's a case that this is a case that the numbers may not be in a D the captures might be something not in the map like the exv we output XV e where's e no wait a minute from even if okay so if order map if he does not exist then we could put it to the left okay it has a if a does not exist which in -1 if B doesn't exist map asking return -1 now we return 1 we map asking return -1 now we return 1 we map asking return -1 now we return 1 we return yeah I made a mistake Nereus might be some cases that yeah the character is not even on your map cool so this is it let's see if any better solutions mm-hmm okay mm-hmm okay mm-hmm okay this time complexity for this would be compare so here sward actually is o and mug and this approach actually says we couldn't preview it with media type mm-hmm well we first write our answer to mm-hmm well we first write our answer to mm-hmm well we first write our answer to the elements of T that occurs in yes in order of s after we will write any elements of TV to the right the second right you know doesn't matter because okay the trick is to count the elements of T after we have some count character we can write some new elements in order you want ah the order is yeah ah I see so we just account the t4 1a 1b 1c and then we just move through as fine if there see we write it if it has B we're at it a we I write it and then the rest write the rest we just put it anywhere Wow cool so that's actually a better entry solution let's try to in a minute it's not that difficult okay I know what happens now so we create a cow map for that capture of tea gift count ass textured bounce it actor and get actors plus one else bounce it back to one right cool and now I'll just move through distraint the result left personal and for lead actor of s if count has it has actor the result will be plus ah okay did you repeat right so for its like Nam equals counts we can't capture while num if it as four three two one to start and you should end at want result clause right yeah and then we need to delete it after we rewrite it we count we will delete intact it super map so the fine after all the travel soul the map will contain only the letters that is not in our the order string right so and then yeah we own before let character now look at the case of anomaly I'll count what do the same so while num is bigger than zero actor yeah and then result this should also work up since now there's something there's some problem where is it oh man Katie asked Hector said care to get passed on this is no problem result isn't a string we do through the cat has it then num we get the town ah cool so it works yeah it's actually much better than our previous solution and okay so that's all for this the problem will be helps us in exam bye
Custom Sort String
split-bst
You are given two strings order and s. All the characters of `order` are **unique** and were sorted in some custom order previously. Permute the characters of `s` so that they match the order that `order` was sorted. More specifically, if a character `x` occurs before a character `y` in `order`, then `x` should occur before `y` in the permuted string. Return _any permutation of_ `s` _that satisfies this property_. **Example 1:** **Input:** order = "cba ", s = "abcd " **Output:** "cbad " **Explanation:** "a ", "b ", "c " appear in order, so the order of "a ", "b ", "c " should be "c ", "b ", and "a ". Since "d " does not appear in order, it can be at any position in the returned string. "dcba ", "cdba ", "cbda " are also valid outputs. **Example 2:** **Input:** order = "cbafg ", s = "abcd " **Output:** "cbad " **Constraints:** * `1 <= order.length <= 26` * `1 <= s.length <= 200` * `order` and `s` consist of lowercase English letters. * All the characters of `order` are **unique**.
Use recursion. If root.val <= V, you split root.right into two halves, then join it's left half back on root.right.
Tree,Binary Search Tree,Recursion,Binary Tree
Medium
450
73
hey guys welcome to a new video in today's video we're going to look at the lead code problem and the problem's name is set Matrix zeros so in this question we are given a m by an integer Matrix called Matrix and if our element is zero set its entire row and column to zeros and the most important thing is we have to do it in place which means that you shouldn't be creating a new Matrix and we have to edit the input Matrix itself so let's take a look at this example and see how this can be solved so let's take a look at the example here I've taken the same example one and drawn it here so I've given indices to The Matrix so this is the zeroth row and this is the zero score of adjacent to Z are its next columns 1 and 2 and this is the first one the second row this element will be denoted by the intersection of row and column that is 0 and each cell has its index written at the bottom right now we need to iterate through the Matrix from left to right starting from zeroth row and zeroth column the outer for Loop will represent the rows and the inner for Loop will represent the columns now we have to check if the element in each cell is a zero we'll start from here it is not a zero next row it is not a zero this is a zero we take that element and check its row and add it into a set I've created called row set so this row has a 0 and we take the column for that element which is one add it into another set I created Now we move further now we'll check if this is having zero no it's not a zero and we reach the end of The Matrix now we have these two flags row set and column set now we need to change the input Matrix in place so that we don't have to create a new Matrix now we again iterate from the zeroth row and the zeroth column till the end of The Matrix this element has zero is not present inside this Matrix so we move further so 0 1 0 is 0 but we have 1 as the column has one here so we change that element to a zero Now we move further it is 0 to 0 2 is not present in either of the sets so we move further one zero now we have rho as one so row is one here so we change that element now we have this element having one as rho and one as column so we change that element now we go to the next element it has one as rho and 2s column one is present as a row so we change that element Now we move further to one zero two is not present in row 0 is not present in column so move further 2 1 2 is not present in rows one is present in row and column so we can change that element to zero now we go to this element 2 is the Row 2 is not present in either of the sets so we don't change that L and we reach the end of The Matrix and here you can see we got the expected result so this input Matrix will finally look like this and this is the final answer now let's code it up now that we have seen the example let's code it up so this is the function given to our set zeros and this is the input Matrix name the Matrix and the return type is void which means that you don't have to return anything let's start off by finding the number of rows and columns in Matrix so in close and in columns we find the first rows length to find how many columns it has now let's declare the two sets row set and column set which will hold the row and column which has zeros now let's use two for Loops to iterate through the rows and columns the outer for Loop will iterate through the rows starting from 0 till how many rows are there the inner loop is for columns which will start from zero now we have to find if that element at that row and column is a zero so if Matrix of i j is equal to 0 then we add that row and that column in its respective asset rows will go inside row set and columns will go inside column set row is represented by I and columns represented by J we are adding the row inside row set and adding the column inside columns now this is the for Loop which will give us how many rows and columns have zeros now we have our flags indicating the rows and columns inside these two sets now we have to set zeros inside the input Matrix itself so now we have to modify the input Matrix let's iterate through the rows and columns again now this is representing the row and this is representing the column it will start from the element here until the element here in this example so it will go in this way so each time we have to check if the row or column is present inside our flag so if row set dot contains I all right if column set dot contains J then we set that element as 0 so inside the input Matrix itself we set that element to zero so this will happen for all the elements until we reach the end of The Matrix here and it will set the respective element to zero and once this Loop ends the input Matrix has been modified according to the requirement and we don't have to return anything because the return type is void now let's run the code here it is J plus run the code the test cases are passing let's submit the code there you have it our solution has been accepted the time complexity of this approach is O of M into n where M denotes the number of rows and N denotes the number of columns and the space complexity is O of M plus n where again M represents the number of rows and number of columns because we are using two sets to store the row and column numbers as a flag that's it guys thank you for watching and I'll see you in the next video
Set Matrix Zeroes
set-matrix-zeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it [in place](https://en.wikipedia.org/wiki/In-place_algorithm). **Example 1:** **Input:** matrix = \[\[1,1,1\],\[1,0,1\],\[1,1,1\]\] **Output:** \[\[1,0,1\],\[0,0,0\],\[1,0,1\]\] **Example 2:** **Input:** matrix = \[\[0,1,2,0\],\[3,4,5,2\],\[1,3,1,5\]\] **Output:** \[\[0,0,0,0\],\[0,4,5,0\],\[0,3,1,0\]\] **Constraints:** * `m == matrix.length` * `n == matrix[0].length` * `1 <= m, n <= 200` * `-231 <= matrix[i][j] <= 231 - 1` **Follow up:** * A straightforward solution using `O(mn)` space is probably a bad idea. * A simple improvement uses `O(m + n)` space, but still not the best solution. * Could you devise a constant space solution?
If any cell of the matrix has a zero we can record its row and column number using additional memory. But if you don't want to use extra memory then you can manipulate the array instead. i.e. simulating exactly what the question says. Setting cell values to zero on the fly while iterating might lead to discrepancies. What if you use some other integer value as your marker? There is still a better approach for this problem with 0(1) space. We could have used 2 sets to keep a record of rows/columns which need to be set to zero. But for an O(1) space solution, you can use one of the rows and and one of the columns to keep track of this information. We can use the first cell of every row and column as a flag. This flag would determine whether a row or column has been set to zero.
Array,Hash Table,Matrix
Medium
289,2244,2259,2314
354
hello everyone welcome to day 25 of lead code made challenge today we have question number 354 russian doll envelope in this question they have given us 2d array of integer envelope where envelope of i is equals to w comma h represent the width and the height of an envelope one envelope can fit into another if and only if both the width and the height of one envelope are greater than the other envelope width and height and we have to return the maximum number of envelope we can put one inside the other in example one these are the envelopes given to us where the first five represent the width of the envelope and four represent the height of the envelope and the output is three that is they are putting these three envelopes we can put inside each other we can see this the width of the first envelope is smaller than the width of the second envelope and the height of this first envelope is smaller than the height of the second envelope so 5 comma 4 so 2 comma 3 can come inside 5 comma 4 like we can put 2 comma 3 inside 5 comma 4 and similarly now the width of the second envelope is five and the width of the third envelope is six so the third envelope with is greater and similarly the third envelope height is also greater so now both of these envelope we can put inside six and six comma seven that is this third envelope so that is how we get the maximum size we can get is three in example two they have given us some envelope but all of them have the same width and height so only one envelope we can put we cannot put these all envelope inside each other because all have saved width and height that's why we are returning one so let's understand this question more betterly this question is more like we have to put box in a box and we have to find the maximum number of boxes we can put inside each other so in this question is somewhat related to longest increasing sequence if we can find the longest increasing sequence then after this we can put how many boxes we can put inside this box and then we can return the maximum box so this question is more like this so first let's understand largest increasing sequence by this example like how large is increasing sequence work so suppose this is the array given to us just let me convert this to pen yeah this is the array given to us and we have to find what is the maximum increasing sequence we can make using in from this array so from this array maximum increasing sequence we can make of 10 12 17 and 22 that have the length 4 but how are we going to achieve it so the first thing is we will create a dp and we will find using this 9 using this particular number what is the largest increase in sequence we can find till this index so using this particular in this is the 0th index and using only 9 the longest increasing subsequence we can perform will have the only one length that is 9 so we can perform only one longest increasing subsequence using this number coming to index 1 this is 2 and we have to find the longest increasing subsequence which we can perform using this number or the number before it so as 2 is that means the our longest increasing subsequence should end at two so nine is greater than two nine cannot be end at two so the longest increasing sequence we can form using the two is two itself a number starting with 2 itself now coming on the index 2 the largest increasing sequence which we can form using 9 2 and it should end on 10 so we have 2 option it can be either we can form you can we either we can go with two or ten either we can go with nine or ten and both ways our length will be two so here we have to restore the length so the longest increasing sequence length ending or 2 is 2 so ending on 10 is 2 now coming on the index 3 we have to see the longest increasing sequence should end on 12 and should take all these maximum of all these numbers like on 12 it has the option to go with 9 we can form 9 and 12 because 12 is greater than 9 we can form 2 and 12 because 12 is greater than 2 we can form this it already have the length 2 that is 9 10 and 12 or if we can consider if this would have gone with 2 then we can form 2 10 and 12 so the longest length possible longest increasing sequence possible if the that particular sequence is ending on the uh index 3 or the number 12 is of length 3 so this is of length 3 this is the answer we are storing like till here the longest increasing sequence we got and that is of length 3 similarly coming to one now one we cannot put like we cannot put uh anywhere because every number on its left hand side is greater than one so one can perform the longest increasing sequence only with itself because to form the longest increasing sub sequence this number should be greater than the left part but it is not so the longest increasing sequence which is ending on 1 is 1 itself so its length is 1 for this was for index 4 for index 5 we have the number 17 and for the number 17 it can form the longest subsequence with 9 that could be 9 and 17 or it can go with 2 that could it is of length 2 and the other it can form with 2 or 17 that total length of longest increasing subsequence ending at 17 length is 2 or it can go with 10 again it will have the possibility either it can go to 9 10 17 or it can go to 2 10 17 and the other possibility that 17 has is let me raise this so that i can write the other possibility when was 9 and 17 let me write this 3 sequence 1 that is 9 10 12 9 10 and 17 and the other it can have is going to the 12 like take any one of these let's go with 9 10 12 and 17 so the longest increasing subsequence ending at 17 is of length 4 so that is what we are going to store here so here we have stored the length 4 and similarly we are going to 22 we can store the longest increasing sequence ending on 22 is either we can put 22 at the end of it so it will become the length 5 or we can put at the end of it i'm not writing this whole over here so just to explain you so it will become the length 4 or i can add 22 over here this can give me length 3 so out of 3 4 and 5 the longest increasing subsequence which i can form is of length 5 yeah i have given here 4 this is wrong this is 5 because the longest increasing subsequence we can form from this array is 9 10 12 17 and 22 similarly this concept we have to use in inside the russian dolby envelope because if we suppose this has this weight and height if this width and height is less than the this width and height then of course this 9 can come inside this 9 box can come inside the box which has the value 10 and this 10 can come inside the box i'm making the circle but consider it as box this can come inside the value 12 similarly we can have some similar other box 17 can come in like these all can come inside 17 so the maximum and this is like 22. so the maximum possible length is 5 that what we have to written so that's where lis uh concept is very important for the russian dolph envelope and now we can form the russian dolph envelope problem very easily now the thing is they have given us this is the width and this is the height so after sorting this on the basis of the width we got this sorted envelope array so we here we have the sorted envelope array and now we will similarly use this lis concept and over here and we will find the maximum number of envelope we can fit inside one another so this is one comma two so this can fit inside one another so this length is by default one now two comma three first we will check is its width greater than the left hand side width yes like we have to find the maximum number of envelope that has this end that has this largest value 2 and 3 till here we have to find first still here so this width of the um width of the envelope present at the index 1 is it should be greater than the width of the envelope present at index 0 and the mandatory condition is height of the envelope present at the index 1 should also be greater than height of the index present at the envelope 2. if this condition is true that means we can fit this is one comma two box we can fit two comma three inside it so now the length become two so that's why we are writing it over here and which box we fit it is one comma two and then two comma three now we are moving to the next index we have five comma four so now we will check to both of these is five less than two yes is four less than three yes so one way is it has the length two and plus is one length we can basically what we can do is we can take the maximum of these both length that is two and then we can do plus one but the cases it should be less like the width of the width because here we have check so they are already sorted so over here width of the uh second like envelope width present at the index 2 should be greater than envelope width present in the index 1 which is true 5 is greater than 2 similarly for a height 4 should be 4 is greater than 3 so its length will become 3 and which all the envelope will come inside each other 1 comma 2 comma 3 and 5 comma 4. now we have the other index now we are on the index four index sorry three so what we will see is six less than four uh sorry is six less than five yeah six is less than 5 so this is true width of this is less than 3 width of this but is this less than 4 yeah no these are equal equals are not allowed so 6 comma 4 cannot come with 5 comma 4 so now we will see to 2 comma 3 is 6 is less than 6 is greater than 2 yes 6 is greater than 2 4 is greater than 3 yes 4 is greater than 3 so one pair it can make the pair with one comma two because it all it can come down to this it has one comma two it has two comma three and it has then again six comma four so the maximum uh russian doll uh length we can form which can come inside each other using six comma four is three we can go with one comma two also but it will not make any sense like if we put uh six comma four back of one comma two but it is of length it will only form uh it will only give the maximum length that is two so and this is giving three so the maximum we will take so three like till three using three envelope we can make a russian doll one inside another basically this is like this is one comma two this is one box and then we have the other box which have two comma three and then we have a bigger box which have six comma four in russian doll also a smaller doll will be inside a bigger doll and then bigger doll is inside another bigger doll so this is what is happening over here also now we are moving to the next index and now we see is 6 greater than this no these are equal so this we are not going to use we are going to see all the above we are going to loop all the left side element then we are going to of course we are going uh to loop from the zeroth index but here i am showing you this way so first it's going to loop with the one comma two so it will get the russian envelope of two length one comma two and six comma seven so using this it got the uh russian envelope of two length then it will come to this using this yeah 6 is greater than 2 and 7 is also greater than 3 so using this it can form the russian doll of length 3 1 is 2 is of both this and then 6 comma 7 will come here so it can form of length 3 now we are coming to 5 comma 4 using 5 comma 4 6 is greater than 5 correct 7 is greater than 4 correct so now it can form the russian doll of maximum length three is of this and this is also going to join them now so it will become four now we are coming to this is six and six no they are equal so equal cases are not allowed it has to be perfectly greater than both width and height so out of this two 3 4 what is the maximum 4 is the maximum that we are going to store here and that is the maximum russian doll we can form using 6 comma 4 that has the biggest element that is the biggest box 6 comma 7. now we are coming on the next index eight comma eight now again we will check from the starting is eight greater than one yes is great greater than two years width and height of this index is greater than this so the maximum uh length of the russian wall it can form is one of itself and one we are adding this so two similarly for this two of itself one we are adding this because they are great greater it's clearly visible so this is of three and then we can go to five comma four clearly visible they are greater so this can form the russian doll of length four three like these three itself and eight comma it will join them and the other we have six comma four they are perfectly greater three of this and plus one of eight comma eight and then we have 6 comma 7 it is also greater so it can have the length 5 so out of this what is the maximum length is 5 so we will add over there like using this as the greatest uh like if we find this russian doll has the greatest width and height so the maximum doll can come inside is unlike of this index that is 4 and it itself is 5 so that is the maximum we can get now we can come to 9 comma 7. now we will again check for this we will go to loop going to loop from the left i mean this i am making the wrong direction we have to find of 9 comma 7 so we are going to move from 0 to this index if this index is this is index 6 so we are going to loop till 5 5th index 0 to 5th and then we will check for the maximum russian envelope we can form 9 comma 7. this has the one length this is clearly greater so this can form of length 2 then we have 2 comma 3 clearly greater 2 plus 1 like using 1 comma 2 comma 3 and then we will get this 9 comma 7. so it will form the russian envelope of maximum length three five comma four three itself and one this make the length four then we have six comma four three itself and one this it will also make the length four then we have six comma seven four this and one this length five because it's clearly greater so okay this will not happen this is a good case i was just making a mistake over here the length is seven and over here also sorry over here the height is seven over here also the height is seven though the width of the this index is greater but width of the dix is this is smaller so this is cool but they have the same height so this we are not going to consider and then we will move to this index its width is smaller than this index yes but this is greater height is greater so this is also not acceptable so these both is not acceptable for nine comma seven so we have to choose the maximum it can form from this that is 4 so if we have to return the maximum russian doll we can return this 5 on 8 comma 8 like okay i'll just draw this is like one comma if we are putting one comma two inside the envelope russian doll two comma three because it has the greater size then if we are taking five comma four then we are taking six comma seven and then we are taking eight comma eight so these are the russian doll we can uh it can fit inside each other and which has the length five and that we are going to written as an output so now the thing is i think why the lis concept is used here we can get it while i was traversing through this array i think i made this point very clear now let's code it up so first we will create a maximum we will initialize it with one because if we are having this envelope and if we are having this envelope itself can make one russian doll so at least one is the mags so that's why we are initializing it with one and now what we have to do we have to sort the envelope based on what we have to sort them based on the length sorry based on their width it's not length it's width over here so we have to sort them based on their width so this is the small function and then we will take out the length of the envelope and we will create a dp that will store our answer and we will fill this dp by one because every each and every particular envelope present inside it can form a russian doll one with itself so that's why we are filling it with one and then we are looping it for l i s this is for we have to this loop is same for l i s like for here we were this particular as we can see over here this particular index can form the longest increasing sequence with itself this two can also form the longest increasing sequence with itself this 10 can also form the longest sequence with itself so everyone can have the length one that's why we have initialized everything with one and the other thing is lis is why we are using this because we are checking if this is smaller than this so means these are forming the increasing uh in these are forming the increasing sequence so that's why that's where the lis logic is coming so we will write the same lis logic so that is it will go still the length end of the envelope but the second loop will only go to the left side till the left side i mean wherever the index is minus one position left to it will go over there and then we will compare what we will compare envelopes width should be we are on the envelope it width should be okay let me just copy this envelope bit should be less than the left side envelope if this is strictly less similarly there should be one more condition if its height should also be strictly less its height should be envelope of j comma yeah so this is like we are on currently on this envelope and we on which envelope vr on the left side of it its height should be strictly less and we are on the envelope and its width should be and the on the left side which should be strictly less if this is the condition holding true then we are going to increase its length that is mad dot max of i and dp of j plus 1 maximum off in itself if it is having the length let me take this example like over here with itself two comma three is forming the maximum uh maximum russian doll inside this one like off length one with itself but now at the left of it have width also less and height also less now it can form the russian doll of length two that is one comma three and two comma three so out of one comma one and two which is the maximum length two so that's why we are returning and that what this loop is doing this is done and then we have to find we have to written the maximum so maximum of the maximum which it contain or the dp of i we will store the maximum and then we will simply return the maximum this is done let's run this code it's working let's
Russian Doll Envelopes
russian-doll-envelopes
You are given a 2D array of integers `envelopes` where `envelopes[i] = [wi, hi]` represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return _the maximum number of envelopes you can Russian doll (i.e., put one inside the other)_. **Note:** You cannot rotate an envelope. **Example 1:** **Input:** envelopes = \[\[5,4\],\[6,4\],\[6,7\],\[2,3\]\] **Output:** 3 **Explanation:** The maximum number of envelopes you can Russian doll is `3` (\[2,3\] => \[5,4\] => \[6,7\]). **Example 2:** **Input:** envelopes = \[\[1,1\],\[1,1\],\[1,1\]\] **Output:** 1 **Constraints:** * `1 <= envelopes.length <= 105` * `envelopes[i].length == 2` * `1 <= wi, hi <= 105`
null
Array,Binary Search,Dynamic Programming,Sorting
Hard
300,2123
1,092
Jhaal Hello friends today's juice welcome shots comment super scenes with strings given that you have to return shot test lab test year 1st year to s subsidies if pimples wrinkles if anyone can return then let's take this example, this is also like this And cb2 strings have been given, even more than easy S, E and C. Now make this shortest possible super sequence. Super means that all the characters of these two are included in it, you will become a very simple super singer, hello, but this problem is this is the largest. I was the youngest, so all of them are present here in the quarter of the present chief, so all the characters are there, if one is not small, how can we make it small, see only one note, this C is repeated here and this one is here. It is not being repeated nor is it being repeated here, so if I remove this just for example, it is fine and even if AB was guarding it would still remain, my super sequence would remain pure, all the characters of BSE. All the characters are coming exactly as per the correct telecast of ABCL serial. All the characters are coming exactly. So this is also a super sequence. Even if it is one less shorter than that water, it is even better and it is a good thing because all the characters are coming. Okay, now suppose I do something else, that is, suppose how can I make it smaller than this, some super sequence smaller than this is becoming possible, what will have to be thought, how can I make it smaller than this, okay? So look at the IGST from a super chicken and this is the smallest answer located here. Its smallest, it will not get smaller, it is ABC, all the characters of BSE are ok, CLB is from all the tractors of SEBI, exactly and this is its length. This is the shortest one. Now how will we reach the answer. I have understood but how will we reach the answer. Look, if any shooting has taken place then the first thing to do is to record the examples. Let's answer this. This is the answer. This is the shortest answer of 23rd April. It will go from later onwards, it is okay, it is easy if you don't write the answer, then test it, you can put it custom, put it OK, UP, I think it is fine and the second one, I have taken UP is the smallest of these two. There is a super sequence of which is the shortest, what will be its effect on this year, what will happen in it and I am imposing it first in Arrest UP and then it will be imposed like this later. Now see here is the recipe like this, it is being repeated unnecessarily, repeat and If not, then what will I have to do, I have to make you small, I will write UP in such a way that there is something common in both of them, so I took it like this, now what do I have to do, I have to put an accused and put it in the order because suppose I have put the art here. If I put the art here then RST UP here will not be in the order. Leg in the order will be wrong. You were coming in 9th, which was in this roti. In the same order, in the cases, I have not put it in the roti. It has become the smallest. Super Chicken, its length is 500, look, RST UP is complete with all characters, RSTV is absolutely like this, UP is available, it is spread in the sequence as well, it became crispy, it was a small morning ticket, so let's take its simple logic as an example and the logic Jhala, accept AB TDS, anything, health, now other people, second, this left, there is something like this, okay, there is something like this here, me and the tractor, there is something like this between these two, okay, so I am the longest, put this here, then after that, this in this. I click add comment, I will write once in a week, first I am a guest, then why will I write this twice, I have to make a short dress, why will I write unnecessary, then after Aggie, I will write this hormones, once I have written it, that's it, now what is the problem? I have to put the rest in 9th, I have to put the rest in B. If I put the rest in quarter, then my answer has come. I have put the test. There is no problem. Now how will I put the rest in the order. There should be diors in the middle of Agri. Here too, now it should be between and otherwise I am this and before this, if I had not subscribed to this then this problem is not there, so I did not understand the problem and this is the simple method example again instead of the screen. Take it and now how will I make the score, what will be the answer, I have commented on it, rub AB, even with this, I have to keep it and keep it in the order, so later I will keep it in the flood like this, so that I can get like this from all the characters too, okay. So it is in such a bar but similarly, C is ahead, so learn that you will have to keep C ahead, so that from here also I have got it in 9th. Okay, so this is your answer. Now let's find it. The simple way to find it is Long Scarmant. Whatever code is there with sequence, we take the same, then how to write it, first we write it with vacation, once the question comes, then once we optimize it and do it with dynamic programming, then I write the code for sexual programming, here that too. It is simple, once you understand it, the logic is simple, so first of all we will make the matrix, here there are four, here there are three, A B C D A B C and this is also from the test, it is considered as Distic here, now we study every year. We will see that till now I will come in the sequence of longs for me, why do we need long comment sequence because whatever is common, for example, here I will write it only once, if we see the thing that is common. We will write it once, we will write the rest of the characters again, we will write the rest of the characters once, we will write it once and we will put the remaining characters again. This is the only logic, so we will have to find out those who are common, how will we find out who is who, there is another question to find out its length, they first select such people and make them diplomatic, then in every year, even in this year, what do the examples do? Even if I have a knife in A, B and C, I have nothing, then zero will come in this year, okay, and then like find and find who is in the chest, who is who, is a common one here, it will be considered in this category, just like this. All the sequences have been worked out, when we have reached the last place then we will get the answer here that China needs patience rangoli, what we have to do, then the answer should be said here because the comment is correct in both of them, so we fill the DP matriculation quickly. First of all, if anything is valid with MT Spring m30 team, then it will be complete amity, so fill zero in all here, MTS India, if there is no comment, then zero in the column, if it is not there, then zero has to be done in ROM also because the first one. Is it anti-shatter, there is because the first one. Is it anti-shatter, there is because the first one. Is it anti-shatter, there is no comment, very quick, ok, now let's go to a sale, and in a short time, I will not fill anything, I will fill zero, this is a common one for railways, I have got it on one side, now this is in the previous one. There is nothing in my last few films but this is a character here. Okay, now we will not come here in Sadio because there is nothing else in between but we have filled it here we are seeing that this What is there in the will, do this, I am fine, it does not mean that first do it with someone, here is how to do the match, so if I am matching with someone else, then what is this, then I am doing this from here. We had filled neither I have nothing in simple logic here so these two have nothing in the soonest one is different it does n't mean that some comment in the whole string because but baby and white some match in the posting details It is happening okay, so if it is possible that this is here and this is here, they got the input from above, they should have this here, then I, if there is no problem in the last one, I will try this here. If I am getting anything then should I try this? If I am getting anything between these two, then we will see in the top and left cells, after filling the maximum of both of them here, it is okay, then this case is done, now if we do the next one, then this How does it happen and here is already matching cast and also see SIM AB and C B Singh is his first here Bhar memorandum A B and C have arisen Now there are more characters in common Ber is also the same wife agrees Aman has got a text, na for battery, if you want to add and the rest and what is soft in the chest, that too will have to be seen, then from where to see in the final, I have done one, I have dialed the value and the chest has been found. What am I here, this chapter, I have one and I have one plus money here, two characters are in my mind, both of them are humans, neither when the characters are matching, they will go to the side and see, they will add it, okay now, next care. What have I said in C? There is no comment in this and Neighboring is just some deficiency, so zero will be filled. Now what have I said in this? An egg, this is the same, isn't it? In this case, we will write 'diner' and the revenue of Rs 1000 plus one will go, write 'diner' and the revenue of Rs 1000 plus one will go, write 'diner' and the revenue of Rs 1000 plus one will go, now this will be even more. If there is nothing less, then here we will look left and above, what is its max two, dha, no, but what is happening here, then you check this, then this, if there is a match between these two, then if you ask Khan, then this will go to Mittu. Okay, so till here two caters are going softly and neck to neck, now quickly turn it to the last volume, I have made it to C, the zero plus will be closed, now if you don't feel like going to sea, then look at the top and refill, become maximum. C and B are not interested in you but they will come out in the option Maximum Toot from the plan means they know that two characters have become soft, now those two characters are okay, that character is more than that, okay this is its super sequence Sanam, that battery saver. Now this trick is telling everything that two character comment, now how will it go from here to here, how to convert it into this because we have to return our fold, this organization has to be done, okay it is good to find out the length but we have to do the spring button. Look at the mind, this is the trick here, look at this, if it is two, then it has to be done last because all the character planets will start from the back, okay, we will set from the back, this trick will be folded and we will keep building on this, now the second set has to be done. Okay, so we will start from our last value, now this is value two, now look at ABCD and also from Lenovo, B.Sc. first ABCD and also from Lenovo, B.Sc. first ABCD and also from Lenovo, B.Sc. first year, this is value two, that from all around here also, I am looking at 2 characters, but now look, okay and Here, if you have both of these, then both of these, still Puri and in this, two characters will be coming from behind, so that one above and the one above in the lab, the maximum above, meaning where did we come from, which is the maximum, if from both, then I am one. Here in Delhi, we were posting news, where did we come from, ads from above, go to our higher salaries and see where we came from and overall, we will keep going with such dreams, where to go back here because two are bigger than one, isn't it? If you don't feel like seeing it, if you don't have the same, then what will you do? Let's watch the match of these two. Where did they come from? If Titu's lineage increases, then only 210 are big, so what does it mean? So what does it mean? When you wrote your sting, ABC and CAB in Who are the two collectors in both of them, but if you look at yourself, the character is soft in that too, that means this is even more than this, who are the two characters in the above film, now the character of this, what kind of users will cut it, okay, print it, why use SIM? Look, there is something else after man. RO why does the coastal heathen become sad? All this you have to tighten your sleep, you are not giving anything in common, because even till here, character time and beyond this too, there are two characters that are common, our and then I. This Bittu, what does it mean to you that these users, Hussain, have to be printed last and the rest of the work will be found here first. It is important to understand that we will learn some more, even if the party matters were set. What to make of this super chicken, its morning band, AB, you write C in front, okay, now after that set the alarm, set three, you all write backwards, otherwise what will you do with these characters, you print them, I will write these characters here. Print it, okay, let me print this character, all these characters are the characters in it, print them along with the additional director, okay, so if C and B did not feel like it, then I have to go to Pangu, go to the butt. What will we do before going up, we will print it on the seats, this is additional, this is user guide, what is the President, war, anything, it does n't matter, he does n't like it, this is common, this will come last, so what will we do now, these are the characters. Okay, so learn it, we will print it in the last, okay, what will we do now, go up, go back, this is more and again, I don't feel like it. A beta testing girl and a character of CB Singh in Swiss Open. I printed it and finished its work, now what is the reason AB, what is this in Servi Spring, again Apna saw that one more is also equal, the share is also not less, what does it mean, Apna had come from somewhere. Either where did the tabs come from above, if you increase the bittu in it, then what can you do, where did you come from above, meaning high court is to be used like this character was used instead of dancing, so even without this, if this would not have happened If this was not the case then the character here has a mind, now it is here, so it doesn't matter, you also cheat Vitamin A, B and C, now I also have a mind for two characters, so set what you have to do, print it. This is not common, print this and move on, okay delete this, print this, now I will go to my springs and then go back up, what happened to your spin, now you have come to your cell, okay, start from your place with love. I had done this from below this year ago, now I have come to this channel, what is your skin, girl, AB and CB are ok, B and C are two characters of luxury, they have got AV and SE also, now look, plum is also common, plum. If it is also soft, then print it. A plum is also soft, isn't it? These are two common characters. You will have to put the man character there. Okay, now you have put the common character. Now what is left of your spring. You will put the chakmak character. You will also decrement the i. Will you also delete this one, where have you gone now, delete both of them on this one, you spring, girl, one girl, ladder, okay friend, this matching has come here now, what will you do now, who is this one again, delete both of them here. Print it out, delete both of them, okay, now what is left of painting, save C, okay, mantra to both of them, let's go here, now stitching and nothing could be soft with it, like MP Singh, set it, make the loop faster, okay. Yes, Kapil has got the characters behind. Ajay Singh will be MP. If there is a girl, then add her character as she grows. CBSE has become your CBSE is ok, this chicken has gone to your CBSE, so when you keep adding yours, you are setting yours behind but in the West. Pushp will add first CR, then added again, Singh, I had written this in reverse, but if you will access back for free, then you have to return the PAN in reverse, right, that means here I am Pentro, you have not understood. Rah but means look mand, the longest comment sequence of yours is economic, what were you doing in the last, panpi dala, then tila, then hand, but in the spring, how will you do it in the cord, in the court, then we pushback PTR Karan, nothing gets printed. Then I ask, if there is a little front, then after researching it, you have the button, okay, after returning from this trick has been made, now he can see the code, okay, how will you write the code, okay, if you feel that it is difficult to make it diplomatic. Messages are made quickly, first size is definitely ok, what is the side of this youth, anything in these, 1ST year two's tablet was taken at 9am, okay baby, if matriculation is done quickly, vector is okay these days, what size will it be in plus one Why because we will take the third one, that's why in plus one of the various co from zero but with Edison nothing is reduced now quickly Imitrex bar to I love and plus will make cyber space will come ok points bright to Mandsaur railway employees world It will be available, okay, the pigmented banana has now become the defeat matrix, now fold it, what stops you from doing it quickly, if two characters feel like it, how the diplomats were filling in front of the simple condition, see the cases, two characters, time, what do I have to do to the wife? If you want to see in vaginal then the first condition is this, if the characters have a mind in this youth then come - Monday, now here I am have a mind in this youth then come - Monday, now here I am have a mind in this youth then come - Monday, now here I am starting my one, but in the string, if there is indexing by sending zero, then take care of minus one, it is equal to two tiers. Two off spinal, both the cricket matches are done, what to do and it is simple, both the characters are mature, our people are also this is anything, it is Arabic, okay, if there will be a wife match, then what to do, ignore them, look back, the previous one is steel me kitna ko. I thought it's okay, it has cumin in it, so zero one tenacity is okay in this movie and still add a lotus for more Hmm yours, simple logic is okay, simple logic GPF IJ what is 2D PFI - 100 - One Plus One Just 2D PFI - 100 - One Plus One Just 2D PFI - 100 - One Plus One Just believe that it was so solid, what would have happened if it was here, now you are seeing the one without one, see this one, how much time till now, ignore the morning, write, for these workers, that Got a soft one and how soft it was, a common one, so in this case, many places, how many customers in OnePlus Month Baby and AB * The character had a minute here, * The character had a minute here, * The character had a minute here, if the character does not feel like doing this, then it is good, then the characters match. Don't do it, assume that by doing this it would have happened, look at this and delete the cases matching with the car. Okay, meeting sweets, owner had added how much comment in the car rate, we the accused do n't feel like you, comment, it means this is a little, some other character. Look at the comment with and rotting hormone, this is what you will do by removing one strip and you will see that he can be a car, I can get some comments, keep meeting here, the character is getting it, okay and now one more thing, what will you do by removing the R and see in C. Already. What is the comment here, I am not getting one and I am not there for a minute, see this once, remove that tire once, remove this once, remove that tire once, ok remove the quality, remove it once and fool the rest in the tune, what is my simple condition deposit? It came to Cardiff - simple condition deposit? It came to Cardiff - simple condition deposit? It came to Cardiff - One G. Okay, here you will get something bigger, either way, here I can get the SIM, there is no problem, so whatever is the maximum value, you have to save it in one and a half, okay didi, it is a trick. It's great, now how to make a screen, my trick is done, now how to convert stringers into spring, now see what we were doing, we are starting from the last character, N, start from the back, okay, Answer Skin Yellow Answer Timli Now start from the last character, it will come in5, if you look towards the side, it will get jammed, start from the corpse character in the last activity, ok, put a bye loop, how long do you have to go, where will you get anti setting, where will you get MT setting, where will you get equal 204 check 120 love third Will you get the first column near Nashik, keep walking boldly till you get Pantin, okay inside the matrix, now check first of all the characters have a mind, this character is the same, that means it is okay, then return to the same path from which the characters came. We have to go here, these people have to go back on the same path from which they had come. Okay, they came from here, didn't they come from here is our final answer, so where from, whatever mixture of your 182 was written here. How will that author of Maths in all his defeated creations, One or Two, know that wrestling and I are no less, it means that it comes from your hands, you have to go from here to here, you too will get characters, so this is the first thing. Check 1st R1 of My - Mother is Equal to Check 1st R1 of My - Mother is Equal to Check 1st R1 of My - Mother is Equal to APR 12th Chapter Comment If there is one common then it is as if I had meditated on the character, like on example, here the plum is also common, when what was done, one plus one, took the bag entry. Had I set mine here, see what? So, if I simply go there, then see if the caterers are common, then what to do in the answer, then ask back. Hero character, if you have found the phone, please back something, anyone. I will take this one, take this youth, Edward Jenner, both are equal, okay, the answer has made the mind happy, if you call, then simply answer plus is equal to, Modi ji can write the sentence C plus here, dance plus 2, the adapter will go easily, we will add the character. Okay behind everyone, now Kumar go back to the same place, how should WhatsApp come I - - - - to how should WhatsApp come I - - - - to how should WhatsApp come I - - - - to - do that you came from the triangle behind, the - do that you came from the triangle behind, the - do that you came from the triangle behind, the thick paste which was Me Max, you have to see it as if it is here, then if both the characters are not the same. What to see if it was at maximum then either two make soya one would be max ok it can be both beans so in that case you can go anywhere but if one is big then you will have to check then DPFI - 1GB If Greater Healthy DPFI - 1GB If Greater Healthy DPFI - 1GB If Greater Healthy PFIR - Mandal What does it mean? It means PFIR - Mandal What does it mean? It means PFIR - Mandal What does it mean? It means you came from above. Okay, this is big. You came from above. What does it mean to do with yourself? If this one is a character, then printer is also Kareena. This has to be done because if you go up on this channel, you will come to this channel, then you have to print it, we will friend you there and go up, okay, the torch for printing is turned off, we are adding it to the answer, Answer Plus is Gold Answer. Plus is equal to whatever your character is, your getup is your Sapna character, this is tier one solution - but this character Panap will one solution - but this character Panap will one solution - but this character Panap will print the last one and what will you do with it I minus plus What will you do, maybe you increase the last one. In that case, you will print the Asian Tour Order - but In that case, you will print the Asian Tour Order - but In that case, you will print the Asian Tour Order - but I will add it - Bank I will add it - Bank I will add it - Bank is ok, now the last character left has to be printed, what did Tej Raftaar do, in this I have put my secret here above. If there is no same above, then I printed it and put it on top, after printing again, click on continue. Now if the accesses of both above match, then I made a blueprint and went to my dial. Tiger will also be a test match for both of them. What time is it printed and the faces will run on the dial, okay now it used to be trending but this answer is a little ABC answer is a little that they left the face directly here left front all this is printed but C is left, so you will have to write it, you will have to write that too, so whatever is left in the last, you will also have to write it. Okay, so it is boiled, now what is left in the last can be. Come, what can be grated ginger? The check return is zero. Okay, so whatever is left will have to be printed. If you print it, then STR people came - do you feel like print it, then STR people came - do you feel like print it, then STR people came - do you feel like adding it to your answer? I had added it inside - - may have done this one, added it inside - - may have done this one, added it inside - - may have done this one, children. Who saves in his style, this one was left, the character of the second film is fun, this also saves from great danger, an answer has been added, Asian Tour 6 - Part is ok - - done, it is good, 6 - Part is ok - - done, it is good, 6 - Part is ok - - done, it is good, got it, return your system. The hanging plate will come in because you forgot to debit. Okay, it is necessary to reverse. We are making it from the back, so if you are putting plus, some creature happens, push back happens, then this is the pack. Ask A R Rahman what to do, reverse it. So quickly answer digit answer and Android and now remove it okay that fruit should work let's see quickly reduce it and submit it like okay thank you but patient and son
Shortest Common Supersequence
maximum-difference-between-node-and-ancestor
Given two strings `str1` and `str2`, return _the shortest string that has both_ `str1` _and_ `str2` _as **subsequences**_. If there are multiple valid strings, return **any** of them. A string `s` is a **subsequence** of string `t` if deleting some number of characters from `t` (possibly `0`) results in the string `s`. **Example 1:** **Input:** str1 = "abac ", str2 = "cab " **Output:** "cabac " **Explanation:** str1 = "abac " is a subsequence of "cabac " because we can delete the first "c ". str2 = "cab " is a subsequence of "cabac " because we can delete the last "ac ". The answer provided is the shortest such string that satisfies these properties. **Example 2:** **Input:** str1 = "aaaaaaaa ", str2 = "aaaaaaaa " **Output:** "aaaaaaaa " **Constraints:** * `1 <= str1.length, str2.length <= 1000` * `str1` and `str2` consist of lowercase English letters.
For each subtree, find the minimum value and maximum value of its descendants.
Tree,Depth-First Search,Binary Tree
Medium
null
357
today we're gonna be working on lead code question number 357 okay account numbers are the unique digits so you have been given an integer n written the count of all numbers with unique digits so 1 2 3 are not gonna be considered unique so if n is equal to 2 so what he is saying is like from 0 to 10 raised per 2 which is 100 Within These numbers what uh how many of them have unique digits so the answer is going to be 99. so it boils down to be like um a very simple question in the sense that when the N is going to be equal to one so there is 0 to uh 10 days per one which is 10 0 to 10. right 0 and less than 10 so the unique numbers are gonna be 10 0 up to 9. right uh when the N is equal to 2 uh where it comes to is like it's basically uh like it's basically is that it's gonna be um it's gonna be 9 multiplied by nine uh the reason being is like uh n plus so the formula comes out to be okay so if you have n right so basically it is gonna be like for f of 1 is like how many of them are when n is equal to one that would be the answer is 10 right F of 2 is uh F of 2 is basically 9 multiplied by 9. why because like think about how many of them are gonna be uh we have to use choose between I and J so uh if I'm using one I'm not going to be using uh one here but I'm gonna be using two three four five six seven eight up to uh nine and when I have two here I'm gonna be using one less than uh 10. so that's why it is like that so when it's when the numbers are going to be between uh like 100 to 999 it's gonna be equal to the previous uh the answer the previous answer multiplied by 8. multiplied by eight so every single time it's gonna be uh it's gonna be decreasing one so let's say and we can we won't be able to create anything greater than 11 2. so the basically the N can only range from zero to uh 0 to 11. and the reason for that is after that everything is going to have repetitions in them so for f11 it's gonna be basically uh F sorry f11 it's going to be equal to zero so if 11 F12 anything greater than F uh 10 is going to be 0. so it's always going to say up to 10. so it's always going to be like uh so we have limit limitations in there so for an F of 10 it's F of n which is it is going to be equal to 9 multiplied by 8 multiplied by 7 and so on up to multiplied by uh multiplied by 1. so for all of them that's how it's gonna turn out okay just writing that formula and uh in the code here so the base condition is going to be there sorry the sanity check would be if n is equal to 0 uh we're gonna say that return one right okay return one and then and result is equal to 10 we're going to start with 10 and then the unique digits R9 and the available number are going to be 9. and all we have to do here is and while and when we decrease it stays more than one right and available number is greater than zero now you're gonna say that the unique digit is equal to unique digits multiplied by available number and then we're gonna update our result equal to the unique digits and available number is Gonna Keep decreasing every single time and once we are done with it we can return the result basically we are just trying to write this formula every single time uh the available number is decreasing right but we have to start with uh with nine So based on that if it is 10 we're going to be starting with uh they are always going to be starting with the nine so every single time you're gonna start with nine and then keep decreasing until uh like depending on however many number of ends we have so this is the formula we're gonna calculate okay this is gonna be earned looking good and it works for all the test cases
Count Numbers with Unique Digits
count-numbers-with-unique-digits
Given an integer `n`, return the count of all numbers with unique digits, `x`, where `0 <= x < 10n`. **Example 1:** **Input:** n = 2 **Output:** 91 **Explanation:** The answer should be the total numbers in the range of 0 <= x < 100, excluding 11,22,33,44,55,66,77,88,99 **Example 2:** **Input:** n = 0 **Output:** 1 **Constraints:** * `0 <= n <= 8`
A direct way is to use the backtracking approach. Backtracking should contains three states which are (the current number, number of steps to get that number and a bitmask which represent which number is marked as visited so far in the current number). Start with state (0,0,0) and count all valid number till we reach number of steps equals to 10n. This problem can also be solved using a dynamic programming approach and some knowledge of combinatorics. Let f(k) = count of numbers with unique digits with length equals k. f(1) = 10, ..., f(k) = 9 * 9 * 8 * ... (9 - k + 2) [The first factor is 9 because a number cannot start with 0].
Math,Dynamic Programming,Backtracking
Medium
null
725
hello hi guys good morning welcome back to the new videos split linked list in Parts it's a very not very if you have watched the last three videos last three daily videos then you should be able to solve it why because you didn't like the concept of linked list is not much but the concept actual behind concept is the main Crux of this problem cool let's see the problem uh we are having the head of a linked list and integer okay cool we are having a head an integer K now we have to split the link list into key consecutive linked list parts so we have to spread the English into key consecutors so in total I should have let's imagine the nodes of this linked list as the balls and K as some integer and we have to split into K consecutive ball so basically I will put some K consecutive balls in some box and I will just say okay I have all these K boxes in which I will be placing these balls right so I just want cake quantitative linked list as in I will have K boxes with me and in this box I'll be placing these balls as in I'm referring to the linked list notes cool the length of each part now you saw that okay we have K parts or as in K boxes with us now for each part or each box it should be as equal as possible and when I say as equal which means it should be as equal as possible to the every other box now when we say as equal it means okay I can just say completely equal if not completely equal then a difference of one if not a difference of one then a difference of two and so on and so forth so it just says okay as equal as possible so first thing comes in our mind is okay it should be completely equal which means all these K parts are exactly equal and how we can do it let's say if I have a balls as nine and I am asking you to put them in three boxes so for sure you will put three balls in each box and with this you your all the boxes have equal walls so as it's completely equal now you just say okay no two parts should have a size differing by more than one now if not completely equal he is saying that at Max you can now Place one ball so basically the maximum size difference it can be one so you saw okay here it is four here it is three so maximum size difference is one heads for here it's four okay it's zero but yeah maximum size difference is actually a one so that is the worst possible stuff which can happen again up till so far we have actually built the entire solution that season just line by line and keep understanding what's happening good um and it may also lead to some parts being null what it means is okay let's say I've asked you I have five boxes and three balls so for sure you will keep on you will firstly make these five boxes in every box you will place one ball then the remaining two boxes will be empty so for sure it will just say that and it's the same example as you can see here itself so it will just UK some part it can be empty or as well which means some boxes can mean Another Empty as well now last part is the parts should be in the order of cons order of occurrences in the input list now as you saw above also we were placing four in the like in the first box so four it should be the four consecutive nodes of the linked list and then the next four consecutive model of the linked list and then next three conjugate mode of the linked list it should be the consecutive nodes of the linked list itself and uh Parts occurring earlier should have always size greater than that of the equal to the other parts occurring and always it should be um in the increasing in the non-increasing order which means in the non-increasing order which means in the non-increasing order which means it is it should be in the decreasing order which means more number of balls in the earlier and then the Lesser as like this it should happen cool now let's see the main Crux was how to place the ball so now we know that okay we need to have K parts for sure let's have examples so that you understand that pretty well I am saying my n is 11 which means my length it is saying my length is 11 which means the number of balls the number of nodes in moleculars are 11. I have to distribute them into K parts now again I am saying I will have three parts for sure three boxes for sure in this three box we have to place these 11 balls again if I want to if I ask you let's place them equally ah if I ask you let's place them equally no worries at all let's place all of them equally all of them should be equal so what you will do is you have 11 balls you know you have three boxes 11 balls three boxes each box will have three balls it's a simple division 11 by three say okay I will have three balls 11 balls three boxes each box will have three balls or you can simple say okay uh three boxes should have 11 balls one box should have eleven by three balls now eleven by three it should be half every box should have it now we are having a simple division so three balls should come in every box that is it okay so with this we know okay each box should have three balls okay great three balls will be equally in every box so I'll just Place one two three boss in your watch box three balls in each box but uh you know that okay if a few balls were remaining because three into three is nine still two posts are meaning so I'll just snow okay what are the number of Walls remaining number of balls remaining are eleven more three which I actually do just see okay how many number of poles are remaining because it is not completely divisible by uh three okay two balls are remaining now you have to place these two balls but you also want the difference at Max should be one so you just do one thing okay place the first book now five first of all I place in the first box because it was said that I cannot place the more number of balls in the end I should have I should place the more number balls on the side and then I should keep on reducing the number of Walls so I just did okay place the first ball here again place the next ball here again and it will just keep on going so you saw number of Walls remaining by two so first ball in this box first ball next ball in this box and then it's gone that is how now when I see you have a link list of these 11 notes so what you will do is you will just simply say okay uh Aaron I know that every box which means I have K boxes K box which means for every box I will have nothing but these n by K N equals to length by K number of nodes so I know I need to put in any nodes okay I will put in the nodes which is the three nodes but I also have a remainder empty so okay one remainder use now one remainder is gone one only one ball is main because one remainder is already used again I will just go and ask you bro the next N Balls I will take in okay cool next N Balls you should take in plus one remainder also you have to take in okay one remainder you have to take in because one remainder was remaining because remainder you have to take in and for sure one box one remainder only so as to just get it as close as possible and that's the concept which I've taught earlier also if you want to have some numbers as close as possible in some boxes it is the only way just firstly have the equally divided and then keep on placing one in the end cool and then uh okay it was two more again sorry four more again four eight plus four so a three more again cool now uh you know that okay one remainder was there so I just use one more ball and it is one consecutive thing okay I wanted consecutive four nodes I want consecutive four notes I want constitute of three notes right so ultimately these will be my K parts or k boxes and that Circle simply get it solved again for this question you have length as 10 okay has three simply n which means okay in every box how many number of Walls will come in it's actually three but remainder also I have a one so for sure uh the first box will have three balls but one remainder will come in okay uh next ball will have again three balls we've got three balls is for sure in every box will come in it's just a remainder will help us okay to know how many number of extra balls to add it can be either one or zero now the remain until unless the remainder you have just having eight one as soon as the remainder goes away so have it zero okay it's zero again for third box it's three and then it remaining is zero cool um as you will see that again to get the n as the number of balls in each box so you got uh the number of balls in each box which is length by K now it is length by number of boxes case number of boxes or number of parts and it is the balls in each box cool let's quickly have a look at the code it's exactly easy as what we discussed here itself um very easy firstly we have a vector of a pass which we like which will have the start of Link let's start off every part of our linked list now first we have to get the length so as to know okay because I know that okay how many balls should come in each part for that I need to have a length by K which means length by number of parts so I need to have a length first right so I'll just simply get a length although you can just get the length while trading on this entire linked list up to just half but it's not a much worry because I have to any outgoing entire link test again so it is O of n plus n if you had used a slow enough fast so it would have been o of n plus n by 2. although you can just optimize this initial part by using a Slim Fast pointer uh to us so as to get the entire length of the link list but that's not much of a concern for us because it won't affect our complexity as much cool uh then as we saw above that we will have a n which means a number of which means saying okay N Balls should for sure for short come in each of those scale parts or key boxes and what is something about the remainder it will say SDK until this I have R I will keep on placing one ball in the starting R boxes one volume starting our boxes okay cool now my n and R is done now I will just start building my entire like linked list kind of parts right so for that I just went on from zero to up to less than K because I know I have to make for all key boxes okay parts right and then firstly for start of the linked list I have for the first part because I have to go for K parts for the first part simply pointing into the parts of I and keep pointing the starting in order of the link list but uh English I should know up till when I should go or up till where I should go I know okay I have to go up till n and plus r as in one plus one but one only and only if R is there right plus one but only and only if R is there so I just did same thing I just I know okay I've started I have got the starting note but where I have only where to go because if I get the first linked list but after that link list and I have to place a null so I should know okay up till where I should go that okay after that I will place a null so I just went on uh up till n and then I just placed okay if R is 0 then use that R and ultimately you see I am using that R when I will go up I have used that R also so if the r is there I will be using that R and for sure I will just go into n plus 1 or n plus 0 length and that one or zero is depending upon the r remaining or not now when I have got this first is assign just moving on the next node next to next node ultimately in the end when n plus r length or basically n plus one length or n plus 0 length is done then I will just simply press ok this previous next pointer points to my null and that's how you have got the first part of your English and now your node is actually pointing to the this end of this link which is the next node it is pointing to so now you can start off your next part with this next node and simply keep on dependent type process again and that's how you can simply get resolve cool uh
Split Linked List in Parts
split-linked-list-in-parts
Given the `head` of a singly linked list and an integer `k`, split the linked list into `k` consecutive linked list parts. The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. Return _an array of the_ `k` _parts_. **Example 1:** **Input:** head = \[1,2,3\], k = 5 **Output:** \[\[1\],\[2\],\[3\],\[\],\[\]\] **Explanation:** The first element output\[0\] has output\[0\].val = 1, output\[0\].next = null. The last element output\[4\] is null, but its string representation as a ListNode is \[\]. **Example 2:** **Input:** head = \[1,2,3,4,5,6,7,8,9,10\], k = 3 **Output:** \[\[1,2,3,4\],\[5,6,7\],\[8,9,10\]\] **Explanation:** The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. **Constraints:** * The number of nodes in the list is in the range `[0, 1000]`. * `0 <= Node.val <= 1000` * `1 <= k <= 50`
If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.
Linked List
Medium
61,328
808
Hello guys welcome to me youtube channel so today we are going to solve today's link code problem 801 auspicious serving so we have two soups given two types of soups type and ml are given both the quantity is mentioned. Maa ok, so if I have a tax operation then I will give you 100 rupees and zero rupees, then what is the soup super, then 75 rupees, 25 rupees will also be stopped, I have to do the operation like this, so what are you saying that when we all If we do this, then we will not have the thing that we served, that means after serving, that much will be lost, okay, that means if we give 20, then 20 will be subtracted from there, okay, the probability in that is equal to 0.25, okay now what? He is saying, if mother, I have 75 children and I have to serve 100, then we will do as much as we can, we will complete 75, then he is saying that if there are less children, then we will complete as much as we can, okay. When neither of the two or both of them will remain super with me, the quantity of both will become zero, like it was 100ml, both of them become 100, or even one of them becomes zero, then they will stop. Okay, what are you saying written probability of you pay? Bill will be B, tell its probability and tell it half, both of them being empty means if both get eliminated then its answer will be in the range of 10, tu di power-5, okay if it is be in the range of 10, tu di power-5, okay if it is be in the range of 10, tu di power-5, okay if it is accepted then okay then how to do it, now mother take N's. Value 50 both and what is the fourth choice then what will we do then zero in this way zero becomes 25 in this first 25 is mined from 75 - 50 then 25 now if 25 is mined from 75 - 50 then 25 now if 25 is mined from 75 - 50 then 25 now if both of them are 50-50 then both of them are 50-50 then both of them are 50-50 then zero becomes zero. Okay, then how much is there in this, both of them are zero, so what did you say, if you want to give half, then how much will you return here you will return zero point five, so here probability will return zero, I just have to calculate, A and A B together, which is It's over, okay, now when we returned from here, see it was one by four, then why is it one by four, then how much will be the return of both, one, multiply it by 1/4, now see, it has multiply it by 1/4, now see, it has multiply it by 1/4, now see, it has not become zero yet. Then there will be further tomorrow also, tomorrow there will be this also, yesterday this also tomorrow, then now it is 1/4, isn't it again four by four, now it is 1/4, isn't it again four by four, now it is 1/4, isn't it again four by four, now if it had gone ahead and by four, then how much is there from here too? So see, here and here too, turns are being made from three places and here, how much is here, both are zero, here, 0.5, so this total will be as much as the sum, how much will be the 0.5, so this total will be as much as the sum, how much will be the 0.5, so this total will be as much as the sum, how much will be the total, as will be the mission, the same probability will be here, when n. If we increase the value of then see the probability that it is reaching one more times means more times one is ending like one two three and here also and if we had left these two then we would have done these two also and so on. If it also ends, then it is ending more often, then the value of N, the bigger A we are, the higher is the probability. Well, one is the value of a time, where the value of N will be such that the probability of one ending is 100%. If we go then tell the same time, then like 100%. If we go then tell the same time, then like 100%. If we go then tell the same time, then like we first got this value for 4000, then for 5000, 1.3 something 4000, then for 5000, 1.3 something 4000, then for 5000, 1.3 something came, then from now on, even if we increase it will always be 1.3 something, there increase it will always be 1.3 something, there increase it will always be 1.3 something, there cannot be more probability than one, so one is fine, isn't it? Give a greater value of N, if it is 5000, then we will make the return band. Okay, so what I meant to say is that as if it is happening tomorrow, then look, it becomes 1 2 3 4, so it becomes 1/4 * 4. Will 1/4 * 4. Will 1/4 * 4. Will do it again and again, if we do this then give the value of first n greater than 1/4 * 4 do it again and again, if we do this then give the value of first n greater than 1/4 * 4 do it again and again, if we do this then give the value of first n greater than 1/4 * 4 * 4.250. Five A and B both are fine. Now see, now take mother, both are zero, meaning half probability was to be returned. Look here, it is 0.58 meaning in these. Like first we mined hundred and zero out of B is ok which will run repeatedly in loop and we will do this tomorrow after doing this sir mines and what we said at the time of doing it yesterday, that much will be the answer sir answer will be plus, this will be more. What will happen is that it will be multiplied by 0.25, it is 1/4 then multiplied by 0.25, it is 1/4 then multiplied by 0.25, it is 1/4 then 1/16, further its probability is 1/4's four by four 1/16, further its probability is 1/4's four by four 1/16, further its probability is 1/4's four by four probability, then 1/16's four by probability, then 1/16's four by probability, then 1/16's four by four is increasing like this, so in this way when we do it tomorrow. See what has been done here, Max is zero reminder. Now see here, if I have mined it then how much is it - 25 mined it then how much is it - 25 mined it then how much is it - 25 - if - if - if 25 is gone then we will take it means it is finished. See, if I do not have that much quantity then back it. If it is there then we will take it as much as is maximum possible, it is said here that see, how much is the maximum possible, we will take it is okay, if we do not take that much then the whole will not be left because if we had to take 100, then if we take the entire seventy-five, then it will be zero, take the entire seventy-five, then it will be zero, take the entire seventy-five, then it will be zero, hence the max off. Take it, if negative value comes then zero will be stored here, okay and like this also zero and reminder too, now we will return the same quality as the answer that comes, now one more thing here, now this is many times from A to A B. Like if you look at this diagram, Zero Hundred Calculator has been done, then Zero Hundred has been calculated for 75, so if we keep doing it with those too, then we will return it back, so we are doing the same vector dynamically. If there is a vector then you can also do it or you can create it with the new operator. Okay, I already have it, we will return it and if your state is not calculated, we will calculate it and do it from that and then return like this. Will give 5000, this will be very high time complexity, its 5000*5000 but its time complexity will 5000*5000 but its time complexity will 5000*5000 but its time complexity will not be that much, why not because see tomorrow, it will be very less number of times, like we used to do mines one, we got relief in most of the questions, so mines one mines you. It used to be said that there are many tomorrows, but see how many tomorrows I have for 100, for 50, one tomorrow, two, three tomorrows for 50, because there will be a lot of tomorrows because we are doing Mines Hundred, Mines 75. If we do -25 then it will be very less tomorrow, if it Mines 75. If we do -25 then it will be very less tomorrow, if it Mines 75. If we do -25 then it will be very less tomorrow, if it goes to zero quickly then it will be less tomorrow, hence this solution will work because if it is very less tomorrow then its time complexity will not be that much, it will be very less tomorrow because the value we can mince more and more. If you do then whatever state will come, less state will come, like this state was looking at 75 or 50, it was going to zero at once, 100 was back, like this 25, by mincing it by one, it will be less tomorrow, so we used this solution. If you can, then this is your solution. See you in the next video. Please like and subscribe my channel.
Soup Servings
number-of-matching-subsequences
There are two types of soup: **type A** and **type B**. Initially, we have `n` ml of each type of soup. There are four kinds of operations: 1. Serve `100` ml of **soup A** and `0` ml of **soup B**, 2. Serve `75` ml of **soup A** and `25` ml of **soup B**, 3. Serve `50` ml of **soup A** and `50` ml of **soup B**, and 4. Serve `25` ml of **soup A** and `75` ml of **soup B**. When we serve some soup, we give it to someone, and we no longer have it. Each turn, we will choose from the four operations with an equal probability `0.25`. If the remaining volume of soup is not enough to complete the operation, we will serve as much as possible. We stop once we no longer have some quantity of both types of soup. **Note** that we do not have an operation where all `100` ml's of **soup B** are used first. Return _the probability that **soup A** will be empty first, plus half the probability that **A** and **B** become empty at the same time_. Answers within `10-5` of the actual answer will be accepted. **Example 1:** **Input:** n = 50 **Output:** 0.62500 **Explanation:** If we choose the first two operations, A will become empty first. For the third operation, A and B will become empty at the same time. For the fourth operation, B will become empty first. So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 \* (1 + 1 + 0.5 + 0) = 0.625. **Example 2:** **Input:** n = 100 **Output:** 0.71875 **Constraints:** * `0 <= n <= 109`
null
Hash Table,String,Trie,Sorting
Medium
392,1051,2186
1,712
that's french for hello how are you doing friends i'm sure you're doing great but you will do even better once you solve this problem that i'm going to explain you right now the feeling the satisfaction i know sometimes you doubt yourself you're like all those people working for google and facebook and amazon and twitter and whatever how can i be like them how can i achieve this you doubt yourself and i was where you were at right now i had my doubts then i started elementary school things got better but still sometimes this feeling can be a bit crushing so let's pick ourselves from the dust clean ourselves free our hands stretch them stretch the fingers and let's jump onto let's jump onto let's jump onto try to solve a problem together 1712 ways to split array into three subarrays a split of an integer array is good if the array split into three non-empty if the array split into three non-empty if the array split into three non-empty contiguous subarrays left mid and right respectively from left to right the sum of the elements in left is less than or equal to the sum of the elements in mid and the sum of the elements in mid is less than or equal to the sum of the elements in right meaning the first is the smallest the middle is the middle and the last one the right one is the largest given nums an array of non-negative given nums an array of non-negative given nums an array of non-negative integers return the number of good ways to split nums as the number may be too large return it modulo 10 to the ninth plus seven and we have had a similar problem before where we had to apply modular operation so that we don't have an overflow of our result the logic here is as follows you solve the problem as if there was no overflow issue and then you apply the modulo operation to any place in your code where you believe the operation can result in an overflow let's now think of what the brute force solution for this problem would look like you have an array split in three that means you have indices i and j at the split points of this array and if you go through all possible eyes that split your first array from the rest and you go through all possible js that split your last array from the rest you will eventually have exhausted all your options and so in quadratic time you can generate all possible splits and verify if they are preserving the invariant that the first array needs to be smaller than the middle which needs to be smaller than the last one sub arrays with the help of prefix sums we can answer the question of whether one sub ray is smaller than the next one in constant time so we should definitely do that still that solution would be quadratic because all possible i and j pairs are n square where n is the length of the array the number of the elements in the array is 10 to the fifth so unfortunately quadratic doesn't work for us how can we do better than quadratic meaning how can we do let's say and log in an obvious candidate well the idea that you need to do n log n should force your thought towards binary search solution and in fact yes there is a binary search solution the idea is for every left subarray you have a certain index at which the middle subarray becomes large enough to be larger than the leftmost subarray so for a given i you can iterate after this i and find an index j at which that array that second array becomes large enough to satisfy the condition you can in exactly the same way find even further towards the end another index k at which that second array stops being smaller than your right subarray in other words there is an interval between j and k in which your middle sub array is just about right it is bigger than your left subarray and it's smaller than your right subarray and for any index between j and k that condition would be true once you pass k that second sub array will be too big won't satisfy the condition that needs to be smaller than the rightmost subarray and for any index before j the middle subarray will be too small therefore not satisfying the first condition to be larger than the first subarray and now the question becomes for a given i where we have split our first array what is the range what is the interval what are the corners of that interval in which we can pick end of the second sub array and it will satisfy both of the conditions meaning being the middle subarray that can be done with a couple of binary searches one for the beginning of the interval and one for the end of the interval all right how does the solution the binary search solution look like first we'll calculate all of our prefix sums and that's very standard if you are not familiar with prefix sum calculations i encourage you to look for a problem discussing just this but what we do here very shortly is we'll calculate for every element what's the sum of all elements up to and including that element so for the first element that will be just the first element for the second element the prefix sum at index one would be the sum of zero and one elements for prefix sum two will be the sum of zero plus one plus two and there is a very simple linear way to do that prefix sum for i equals to the prefix sum of i minus 1 plus the current element nums i after we have calculated our prefix sums we'll iterate through all possible first subarrays i being the beginning of our second subarray and for every one of those we'll count the number of possible splits the number of possible and indices for our second subarray that requires a couple of binary searches here we find a range in which we could pick the second split point and because all of the positions within that range are valid this is actually the number of valid splits that we can add to our result so we go through all possible first splits and for them we find the ranges of possible second splits we add that to the total and we return it so that's the binary search solution i won't go into detail of how the binary search is implemented that's the solution i went with that's what i implemented during the competition last saturday however there is a better solution there is a linear solution and it looks like so here's the idea about it we have the binary search solution right for every i index as a first split of the array we would have a range for the second split when this first array gets larger when i shifts to the right what happens with our range for our second array if you think about it the second array can never become smaller right we are only working with positive numbers which means the beginning of that range can also only shift forward the end of that range can also only shift forward if all the three indices can only shift forward that means they can go from 0 to n only once which means our solution will become linear right in the previous case we had for every i log n because of the binary search here now even though we have three indices we actually don't have them jumping back in any scenario they only progress forward so that gives us linear time you will see in the solution two loops here but if you reason about it's linear armed with this amazing insight first we calculate again the prefix sums and this time we've used the same array we've overwritten the initial values with the prefix sums just because we don't really need the original values we could have done that in our previous solution as well what about aubergine then we'll iterate over all possible first split points where our left array finishes and for all of those we'll find two things j and k the beginning and the end of our second arrays split point range meaning what's the minimum index at which we can put the second split point and what's the maximum index at which we can put the second split point this is the condition for which we'll check this statement is a bit convoluted num j less than two times num psi but what it means really is the second sub array is smaller than the first one remember nums j and numsai are right now prefix sums the moment this is not any more true then we found our j that's where we can start putting the split point between the middle and the right subarray we'll do the same or similar calculation for k we'll try to find the position at which k preserves the invariant having the last sub array num n minus 1 minus nums k that's the sum of the last rightmost subarray is more than or equal to nums k minus nums i as long as this is true we'll keep it rating k when that stops being true that's where the end of our valid range is once we have identified the beginning and the end of the valid range we'll do what we've done in our previous solution we'll add the difference we'll add the number of possible positions for our second split to the final result because this is all the possible splits of the array in 3 for that i next we'll move to the next i and we'll again find the range the only difference between the previous solution and this one is now we know that our j and k only will progress forward from where they have been until now so we won't have to binary search we won't have to brute force search the whole interval it will be just forward iteration and it will guarantee us linear time at the end we'll return the result and we're done good job well done fantastic you guys made it again up to here and that probably defines your future as tether we solve the solution we solve the problem and we're done we nailed it we solved the problem or read the solution somewhere and explained it after this problem has been asked by robin hood so if you want to enter the brokered space by the way the founder of robinhood is a bulgarian guy is it that random is that a happenstance i don't think so keep coding keep solving problems be like robin hood take from the rich give to the poor hopefully that will get you on the right path but if it doesn't then comment below let me know about it i'm curious to find what can take you straight from the path you've chosen until next time see ya
Ways to Split Array Into Three Subarrays
unique-orders-and-customers-per-month
A split of an integer array is **good** if: * The array is split into three **non-empty** contiguous subarrays - named `left`, `mid`, `right` respectively from left to right. * The sum of the elements in `left` is less than or equal to the sum of the elements in `mid`, and the sum of the elements in `mid` is less than or equal to the sum of the elements in `right`. Given `nums`, an array of **non-negative** integers, return _the number of **good** ways to split_ `nums`. As the number may be too large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nums = \[1,1,1\] **Output:** 1 **Explanation:** The only good way to split nums is \[1\] \[1\] \[1\]. **Example 2:** **Input:** nums = \[1,2,2,2,5,0\] **Output:** 3 **Explanation:** There are three good ways of splitting nums: \[1\] \[2\] \[2,2,5,0\] \[1\] \[2,2\] \[2,5,0\] \[1,2\] \[2,2\] \[5,0\] **Example 3:** **Input:** nums = \[3,2,1\] **Output:** 0 **Explanation:** There is no good way to split nums. **Constraints:** * `3 <= nums.length <= 105` * `0 <= nums[i] <= 104`
null
Database
Easy
null
1,695
welcome to may's lego challenge today's problem is maximum eraser value you are given an array of positive integers nums and want to erase a sub array containing unique elements the score you get by erasing the sub array is equal to the sum of its elements the elements of the subarray that we deleted anyway so return the maximum score you can get by erasing exactly one subarray so essentially we want to find a contiguous subsequence inside here that contains all unique elements with the greatest sum and we just want to return that sum not the array itself uh and that would be it so they give you a few hints telling you to have like two pointer solutions and we can certainly go that route but what i'm going to do is a sliding window technique it's very similar what we'll do is start off by having some sort of pointer point to the very beginning now what i'm going to do is have a lookup that's just going to contain a dictionary with the integer as the key and the index number as the value so what's going to happen is we're just going to iterate down our list and sum up all the values here so starting with 4 we say 4 then 6. but whenever we see that we've seen this number before by adding it to our scene what we'll do is move this pointer ahead to the point at which uh four is plus one so here four is at zero so we just need to move this pointer here and each time we do that we wanna subtract all the values as we move along so that's kind of like the sliding window so here we at this point we had six but now we're going to subtract four so now it's at two and then we're going to add back this four so now it's at six now this is ten now this is eleven and if you can imagine if we had like five here what we'd have to do is move this all the way back at this point subtracting all the values from our max value and each time we'll be storing the max sum at each index number and hopefully that makes sense so let's go through this all right so first we're going to have a look up i'm going to call it scene and this is going to have the integer value as well as the index number as its key next we'll have our max that we'll be calculating each time in our loop as well as final output both starting with zero and we also need to have our left pointer which is going to start at zero and we'll have a while loop to increase that whenever we've seen this integer before okay so for index number and enumerate nums we want to do let's first check to see if we've seen this number before so if n and scene we're going to do a while loop while l is less than seen n plus 1 remember we want to get to the point where we're past this number and each time we're going to subtract from our for our max the let's see nums l and we will decrease our l by one i'm starting to increase our l by one and that should be it now um if this isn't the case we're going to put into our scene here we'll update it each time with the index number and we'll always increase our max by whatever this value is and finally we want to record the actual maximum here so that's going to be output equals max of output and max finally after this point we want to return the output not the max okay so let's see if this works okay that looks like it's working so submit it and there we go accepted so this is essentially the two-pointer technique essentially the two-pointer technique essentially the two-pointer technique but i didn't quite use two-pointers it's i didn't quite use two-pointers it's i didn't quite use two-pointers it's more like a sliding window so time complexity is of n but we do use oven space as well because of the scene um i don't know how you can avoid that though so alright thanks for watching my channel remember do not trust me i know nothing
Maximum Erasure Value
maximum-sum-obtained-of-any-permutation
You are given an array of positive integers `nums` and want to erase a subarray containing **unique elements**. The **score** you get by erasing the subarray is equal to the **sum** of its elements. Return _the **maximum score** you can get by erasing **exactly one** subarray._ An array `b` is called to be a subarray of `a` if it forms a contiguous subsequence of `a`, that is, if it is equal to `a[l],a[l+1],...,a[r]` for some `(l,r)`. **Example 1:** **Input:** nums = \[4,2,4,5,6\] **Output:** 17 **Explanation:** The optimal subarray here is \[2,4,5,6\]. **Example 2:** **Input:** nums = \[5,2,1,2,5,2,1,2,5\] **Output:** 8 **Explanation:** The optimal subarray here is \[5,2,1\] or \[1,2,5\]. **Constraints:** * `1 <= nums.length <= 105` * `1 <= nums[i] <= 104`
Indexes with higher frequencies should be bound with larger values
Array,Greedy,Sorting,Prefix Sum
Medium
null
54
when i first came across this problem it looked at first glance to be quite easy i thought you know you just start at the zero point in the matrix and go across the first row down the column back from that row at the bottom up to the column you're at and then continue the traversal in a spiral fashion as you collect your values into an array and it turns out as you'll see is how it plays out is it's a bit more complex than it seems at first glance and what makes it so complex is all the moving parts so let's see how this plays out as always whenever we have a grid or matrix we want to take the dimensions of that grid or matrix by saying mn equals lenimatrix and then len of matrix 0. so that is m by n matrix right rows and columns then we need our resulting array res equals the array and here is probably the most i guess meticulous tools that will help you solve this problem right we need three pointers i j and k so i and j to traverse the matrix and then k to help orient our i and j pointers and you'll see how that plays out shortly so first we want to traverse the first spiral in that matrix that is if you look in example one two three six nine eight seven and four and we'll continue to traverse down our matrix diagonally after collecting the first and second spiral and so on using the k pointer so we say while k is less than m and k is less than n and matrix k is not equal to v and the reason we're doing that is we want to eventually tell our have our program stop processing when it sees that a cell in the matrix has been visited i use v for visited right and then for each traversal at the end of the spiral we want to say i j or equal to k right and the reason is we'll start if you look in example 1 when we start at 0 when we increment k is going to be the thing that helps us go diagonal to increment the next spiral in the matrix okay and so back to our code on line 10 we'll say while j is less than n and matrix i j is not equal to v to make sure that it hasn't been visited res.append visited res.append visited res.append res.append matrix res.append matrix res.append matrix i j and now we want to say i j matrix i j and now we want to say that cell matrix i j is visited v and then we want to increment j and when we exit that while loop we say j minus equals 1 i plus equals 1. a lot going on here so lines 10 through 13. let's take a look so we're going across the row if you look at example 2 on the left 1 2 3 4 and eventually we'll get to j equals n which is outside the bounds of our matrix so we have to bring it back now of course we've already seen four at this point now that we brought j back and so we need to go downward before we make our next collection so we say i plus equals one in line fifteen and ultimately we're going to repeat this logic in a very similar fashion we're going to repeat this logic four times so one two three four and now let's edit it starting with lines 16 through 21. let's take a look what that's going to be so now that we've gotten across that first row we want to now do the same thing column wise right now a way we're going to do that is by incrementing i so we say i while i is less than or equal to m as opposed to j is less than or equal to n okay so do the same exact thing res dot append and then matrix i j is visited and now instead of j plus equals one we have i plus equals one and eventually as you'll expect if you look in example two we'll go from eight to twelve and then i will exceed the bounds of our matrix so what we'll want to do here as opposed to j minus equals one we need to bring i back into the bounds and then we need to bring j to the left so j minus equals one okay so now we've gone from 12 to 11. so now we're on 11 at line 22. now in line 22 and line 22 what ends up happening is that we need to change our logic again except it'll look a little bit different also say while j is greater than or equal to zero because now we have to traverse left in that bottom row res dot append matrix i j same exact thing but this time instead of j plus equals one j minus equals one and eventually we'll have eleven ten nine and that exits the bounds of the matrix so we have to bring it back in so j plus equals one and then i minus equals one because in line 27 right and then in example two if we take a look why we want i minus equals ones well we get we'll get to nine again when we bring j back into the bounds of the matrix we want to move up and we'll have to move up to 5. now the final while loop that brings us upward on the left side of the spiral that we're working on is going to be edited as well is going to look a lot like the one that we just the one we just looked at that's i is well i is greater than or equal to zero and matrix is not uh matrix i j is not v so not visited res data pen matrix i j is v and now instead of j plus equals one we'll say i will say i minus equals one because we're going upward we don't need to increment this anymore because remember on the next iteration of this while loop we'll say um i j equals k so k plus equals one and then finally we return res we run accepted submit outstanding
Spiral Matrix
spiral-matrix
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,3,6,9,8,7,4,5\] **Example 2:** **Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\] **Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\] **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m, n <= 10` * `-100 <= matrix[i][j] <= 100`
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row. Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
Array,Matrix,Simulation
Medium
59,921
328
hey everyone in this video we are going to solve the odd event linked list question on lead code so we are given a head of a singly linked list so we need to return all the nodes with odd indices first followed by the notes with even indices so one thing to remember here we are not talking about the value inside the node we are talking about the indices so this one is odd this one is even odd even or this one so this is the question let's see how we get to it so let's say we are given this linked list and we need to put the nodes with odd indices first and then the nodes with even indices so let's first write what are the odd one and what are the even one so this one is odd this one is even this one is odd even okay so uh what we'll do we'll uh use a variable let's call it is odd initially it will be true but we'll keep toggling it when we move forward and uh since we are gonna need two separate lists for one odd and for one even we'll use two heads so first will be let's call it quad head next one will be even head and initially they both will point to a list node 0. so when we'll start so first for the first time is odd is true that means first we need to add this one to the odd list so we'll add one here then we'll move forward and then we'll change this two is odd to false now is odd is false that means we need to add this one to even one even head so now we'll add 2 even head then we'll again move forward and we'll change back is or to true now is what is true so we need to add this particular node 3 after 1 inside the odd head list so after one three will be added then again we'll toggle is Dot from True to false and we'll move forward so this time is what is false this means this one has to go in the even list so four will came after 2 here then again we'll toggle is odd from pause to true and we'll move forward at five so is odd is true so 5 will be added here and at the end after the even head will insert a null here and after the odd head will point the even head dot next and will return forward head dot next as a result so this is the drawing explanation let's see how we can do it in code so as discussed let's just first declare our variables so let's call this first one or list it will be equal to new list node 0 next we'll call it as even list it will also point to list node 0 it will be node next we'll create our two pointers so first one odd head equal to or list then let even head equal to even list oh sorry even list yeah then we need to create our is our variable so is odd initially it will be true then after that we'll run a while loop inside this will check if is odd is true or not so if is odd is present that means we need to add it to the odd list so odd list dot next will be equal to head and we'll move one step forward so our list equal to Or List dot next else if this condition is not true is odd is false that means we need to add it to the even list dot next equal to head and even list equal to even list dot next so we check both of these condition now we need to toggle the azort variable so azort will be equal to not episode and we'll keep moving our head pointer one step forward now outside the while loop will Point null to even list shortening so even dot email list even less dot next equal to null and odd list dot next will be equal to even list dot next and at the end we'll return our odd head pointer so hot head dot next so if you run this okay my bad this one will be even head dot next so let's run it again it's working let's submit it tool so that was it for this video thank you for watching
Odd Even Linked List
odd-even-linked-list
Given the `head` of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return _the reordered list_. The **first** node is considered **odd**, and the **second** node is **even**, and so on. Note that the relative order inside both the even and odd groups should remain as it was in the input. You must solve the problem in `O(1)` extra space complexity and `O(n)` time complexity. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[1,3,5,2,4\] **Example 2:** **Input:** head = \[2,1,3,5,6,4,7\] **Output:** \[2,3,6,7,1,5,4\] **Constraints:** * The number of nodes in the linked list is in the range `[0, 104]`. * `-106 <= Node.val <= 106`
null
Linked List
Medium
725
1,997
I'm back let's do Elite code first day where you have been in all the rooms okay so I did this question before I mean just now and it is quite tricky but it's a very nice neat DB question sorry for spoiling okay so let's go through uh there are any rooms you need to visit label with zero to n minus one each day is labeled starting from zero you would go in and visit one room a day okay you visit room zero the order you visit the rooms for the coming days is determined by the rules in a given zero index array next visit of length n assuming that untainted that on a day you visit room I if you have been in room I an odd number of times including the current visit on the next day you visit a room with a lower equal room number specified by next visit I where next visit I is between zero and I okay if you have been in the room I an even number of times including the current visit on the next day you'll visit room I plus one mod n return the label of the first day where you have been in all the rooms it can be shown that such a day exists since an answer the answer may be very large return at modulo 10 out of nine plus seven okay so let's go through an example because that's kind of difficult to get ahead around give these indexes it's one zero one two three so that's the index this is the next room to visit notice how that the next room to visit is always less than the index next visit I is always between zero and less than equal to I we want to figure out how many days it will take to reach all the room initially you start off at room zero and that tells us the next room to visit let's actually keep track of the number of days it takes to keep to reach a particular room minimum days to reach room for the first odd time so we've reached through zero on the first day and then what happens is this next room to visit tells us which room we actually visit next and that's actually the exact same room that we were in before okay so now that we're back in room zero well this time that we reach room zero is going to be the second time I reach uh the room takes two days is the mid number of days Min number of days to reach room for the first even time all right then if you keep track of these two somehow by some eventually you'll reach the last room which is say here whenever a number goes at this position because that's the first time we reach the last room and we know that we've reached all the we've visited all the rooms when we reached the last room because there's no way that we can actually progress to the Next Room unless we've visited the previous room twice why because all the room numbers or the next room to visits numbers are less than the index this means number of days to reach the room of index one is going to be 2 1 plus this value here which is three now okay how many times does it take to reach okay so what value goes in here what's hold to visit to room one again which is the same room that will take four days okay so all good so far when does it get tricky and this example is actually not that great let's change it so that telling us to visit room one this is always going to be 5 because we've had to visit room one two times to be able to progress to room two now what value goes in here is well we take a look at what room next to visit so this actually brings us back to room one from this starting position how many days does it take to get back to room two so that we visit it an even number of times so that we can progress to the next room if this said room zero then I would take it be taken back to the very first room and all I have to do is I know that it will take five number of days to get back to the same position so this would in this case this will be 10 because it'll be just 10 5 times 2 but um if this was one then let's just pretend that um the first initially takes 10 days to get back to the same position assuming that this value is zero but then since we started a little later in the rooms uh so this is one instead of zero subtract the number of days it takes to get to room one which is well if you think of it like prefix sums that will be let me subtract two days off from five so that's five minus two is three and then you add three to five so that this should be eight and then this one will just be a plus one which is nine so if I actually give this a test this should give the answer here should be eight all right because these are actually zero indexed so this is the ninth day but actually the eighth zero Roost indexed a day equals answer return eight yep yeah so that's basically how it goes it's like that this is the DP arrange that we need to create and that's the rule we have to follow so that's this let's um create the DP arrays okay one thing we have to watch out for is this is all very big numbers the constraints and there's up to 10 to the power five and so we want to work with long Longs because uh the answer could be very large and we should take it modulo 10 to the power of 9 plus 7. so let's do yeah um It's Time deaf long same mode is equal to one E9 plus seven each element we have a vector size two let's just initialize everything to zero go through each of the elements and we just followed the way we did it here first off we probably want to start here and have a base case uh we always know that first DP values here are one and two so we can say DP is zero of zero DP zero one is equal to two then here I could say DP no DPI at zero is going to be equal to I minus one at one plus one but uh that could potentially go overboard one E9 plus seven so let's take that modulus now DPI two is a little bit more tricky it's um what this value here was times two like we did here before I did five times two is ten and then we subtract the number of days it took to get to the next room we have to visit zero so let's just do times two and then we minus um well we can minus this value here two when we see a one is there an exterior of so next room to visit is one which is this when we subtract this value so actually let's just go and look here and we just do subtract three minus one that way you don't have to look at the boundaries and have an if condition so let's do instead subtract DP visit at I uh zero and then we subtract one yeah but we can actually expand this out and we could just expand the brackets out and just do this and modulus this so what do we return DP at the loss value which is next visit dot size minus one position to zero we have to subtract one problem with this is this value modulus could be zero so if two zero minus one and then modulus again that will give us something negative which is not what we want so we have to add mode foreign let's give that a go the modulus thing is a pain in the ass so yeah nice hopefully that makes sense um if that did give it a thumbs up and I'll see you in the next video
First Day Where You Have Been in All the Rooms
next-palindrome-using-same-digits
There are `n` rooms you need to visit, labeled from `0` to `n - 1`. Each day is labeled, starting from `0`. You will go in and visit one room a day. Initially on day `0`, you visit room `0`. The **order** you visit the rooms for the coming days is determined by the following **rules** and a given **0-indexed** array `nextVisit` of length `n`: * Assuming that on a day, you visit room `i`, * if you have been in room `i` an **odd** number of times (**including** the current visit), on the **next** day you will visit a room with a **lower or equal room number** specified by `nextVisit[i]` where `0 <= nextVisit[i] <= i`; * if you have been in room `i` an **even** number of times (**including** the current visit), on the **next** day you will visit room `(i + 1) mod n`. Return _the label of the **first** day where you have been in **all** the rooms_. It can be shown that such a day exists. Since the answer may be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** nextVisit = \[0,0\] **Output:** 2 **Explanation:** - On day 0, you visit room 0. The total times you have been in room 0 is 1, which is odd. On the next day you will visit room nextVisit\[0\] = 0 - On day 1, you visit room 0, The total times you have been in room 0 is 2, which is even. On the next day you will visit room (0 + 1) mod 2 = 1 - On day 2, you visit room 1. This is the first day where you have been in all the rooms. **Example 2:** **Input:** nextVisit = \[0,0,2\] **Output:** 6 **Explanation:** Your room visiting order for each day is: \[0,0,1,0,0,1,2,...\]. Day 6 is the first day where you have been in all the rooms. **Example 3:** **Input:** nextVisit = \[0,1,2,0\] **Output:** 6 **Explanation:** Your room visiting order for each day is: \[0,0,1,1,2,2,3,...\]. Day 6 is the first day where you have been in all the rooms. **Constraints:** * `n == nextVisit.length` * `2 <= n <= 105` * `0 <= nextVisit[i] <= i`
Is it possible to swap one character in the first half of the palindrome to make the next one? Are there different cases for when the length is odd and even?
Two Pointers,String
Hard
556,564
1,492
hey everybody this is larry this is one of uh one of the problems i sell for the bi-weekly contest 29 for the bi-weekly contest 29 for the bi-weekly contest 29 uh i'm gonna put the explanation in the beginning and then i'm gonna do the live coding of it afterwards let me know what you think about this format i'm still playing with it and here we q2 the k factor of n so this it could have been interesting but this is um because n is less than a thousand you only have to do a linear search to count all the factors and then return the first uh kl or the cave element with a bound check that if it doesn't have k elements then it's return negative one um so you can actually also do this in square root of n times by just go up to the square root of n uh to count all the factors so that is also another way but because n is equal to a thousand i didn't even have to think about it so this is o n times which is not roughly not linear per se it's just all of n times uh cool and this is just brute force for that reason you could go the square root of n and then um and then if you do if you check the square root of n then you get two factors right x and n over x and then you could put it in a way and either sort it or just keep track of it as it goes toward the middle uh and they're just an edge case about a square root but otherwise you could do an square root of n times uh relatively straightforward but yeah two the k factor of n so this one uh the first thing i looked at after seeing this is kind of look at the constraints of n and k well when i saw that uh n is the can n is a thousand then i was like okay well let's just do a proof for us i don't have to so there was the square root of n1 but it's a little bit trickier not that much trickier but a little bit trickier um and yeah and basically i just do a proof for us and just check all the factors put in a list and then return the k factor you don't even have to put in the list actually but i put it in a list and then you just kind of check it two
The kth Factor of n
time-needed-to-inform-all-employees
You are given two positive integers `n` and `k`. A factor of an integer `n` is defined as an integer `i` where `n % i == 0`. Consider a list of all factors of `n` sorted in **ascending order**, return _the_ `kth` _factor_ in this list or return `-1` if `n` has less than `k` factors. **Example 1:** **Input:** n = 12, k = 3 **Output:** 3 **Explanation:** Factors list is \[1, 2, 3, 4, 6, 12\], the 3rd factor is 3. **Example 2:** **Input:** n = 7, k = 2 **Output:** 7 **Explanation:** Factors list is \[1, 7\], the 2nd factor is 7. **Example 3:** **Input:** n = 4, k = 4 **Output:** -1 **Explanation:** Factors list is \[1, 2, 4\], there is only 3 factors. We should return -1. **Constraints:** * `1 <= k <= n <= 1000` **Follow up:** Could you solve this problem in less than O(n) complexity?
The company can be represented as a tree, headID is always the root. Store for each node the time needed to be informed of the news. Answer is the max time a leaf node needs to be informed.
Tree,Depth-First Search,Breadth-First Search
Medium
104,124
297
hello friends in this session we are going to discuss another lead code problem serialize and de-serialize problem serialize and de-serialize problem serialize and de-serialize binary tree this is one of the very common interview question asked in many companies what is serialization as per the problem statement or even in general serialization is the process of converting a data structure or object into sequence of bits so that it can be stored in a file or memory buffer or even transmitted across a network connection link to be reconstructed later in the same or another computer environment based on the definition given here and based on the method signature given here serialization means we need to convert a binary tree into a string format i mean serialize function here is taking binary tree root node as an input and returning back a string and then we should convert back the string into binary tree based on the d serialized function here as per the problem statement there is no restriction on how your serialization or deserialization algorithm should work it is up to you how you convert binding tree into a string and back to binary tree again let's discuss the approach there are two ways to address this problem we will take pre-order traversal problem we will take pre-order traversal problem we will take pre-order traversal based approach i mean we will use pre-order traversal to convert this pre-order traversal to convert this pre-order traversal to convert this binary tree into a string format first we will discuss serialization technique before going to the serialization technique we will take this binary tree for our explanation i wish you are aware of binary tree pre-order traversal pre-order traversal pre-order traversal in this we will visit root node first followed by left subtree followed by its right subtree we will start with root node once we are done with visiting root node we will visit its left sub tree this is its left subtree 2 is the root node for this left subtree visit root node first now we will visit its left subtree since 2 is a leaf node here it does not have any left child so we'll visit its right subtree again it is same it does not have any right shade because it is a leaf node now we will go back to its parent and traverse its right subtree this is its right subtree tree is the root node here visit this root node first and then followed by visiting its left sub tree this is its left subtree since 4 is a leaf node it does not have any children so let's go back to its parents right subtree since again 5 is a leaf node it does not have any children and also we are done with iterating all the nodes in this binary tree so this is called preorder traversal since we have to convert this string into binary tree again we need a delimiter to split the node values while constructing the binary tree the delimiter can be comma as shown here or it can be a space or any character you think of no restrictions on it we will use comma for now since we need to reconstruct the binary tree from this string how do we identify leaf nodes i mean node 2 does not have any children but node 3 has two children in some cases a node can have only one node either left node or right node how do we identify this case from the constructed string from here in order to address this we need to have a placeholder within the serialized string itself i mean the serialized string should hold null node references let's update a string here we will start with a root node its left subtree's root node is 2 since 2 is a leaf node here its child node references are null values we can use either null here or any other character here i will use n here the first en represents that node 2 does not have its left child its reference is null similarly the second n represents that node 2 does not have its right shell its reference is null hope you understood this notation it helps us to construct back the binary tree easily let's construct remaining string here we'll move to right subtree 3 is its parent node followed by its left subtree since 4 is a leaf node its left child reference is null also its right child reference also null let's move to this node right subtree which is 5 is again a leaf node it does not have any children we are done with generating this serialization string let's discuss how to construct binary tree back using this serialized string as a first step we will split the string using delimiter and push all characters into a queue in the same order given here and then remove character by character and construct binary tree in a recursive way the first character is one it must be a root node the second character must be its left subtree is a root node the second character is 2 the next character is again left subtree's root node this nodes left subtrees root node if you look at the character it is n which means this node does not have any left child the next character represents this node's right sub tree since this character is again and this node does not have any right shell here we are done with creating left subtree for this root node let's move to right subtree construction 3 is next node which is a root node of its right subtree here 4 is its left child since there are two n characters this node does not have any children and 5 is its right child since 5 is followed by 2 characters n it does not have any children here also we are done with constructing back this binary tree so this is the approach hope you understood let's write code now i have already copied method signatures from lead code as it is first declare few static variables like delimiter and node null references we will write code for serialized function first we will be implementing pre-order traversal using recursion here pre-order traversal using recursion here pre-order traversal using recursion here you can also try stack based iterative approach first declare a string builder to hold the string we will be writing a helper function which construct the string in the recursive approach we will pass string builder and root node references as input to this helper function finally we will return serialize string from string builder let's create helper function validate root node first if it is null then there is no node reference so append null character into the string builder otherwise append node value along with delimiter then make a recursive call on left subtree node similarly make a recursive call on right subtree node as well we are done with serialize function let's add code for d serialize function split the string using delimiter declare a queue and add all characters in the same order now we will create a helper function to construct the binary tree using recursion this helper function returns back the root node reference so return it back let's write helper function remove first character check if the character is null node reference or not return null if it is null node reference otherwise create a node reference using the character now make a recursive call to create left subtree similarly make a recursive call to create a right subtree i'll copy it and change the value here finally written the node reference bank we are done with coding let's test our code i have copied our code into lead code let's run i don't see any error let's submit it is success it has executed all the test cases so this is about serialized and d serialized binary trick hope you like the video thanks for watching please do like the video and do subscribe to the channel thank you
Serialize and Deserialize Binary Tree
serialize-and-deserialize-binary-tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. **Clarification:** The input/output format is the same as [how LeetCode serializes a binary tree](https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-). You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. **Example 1:** **Input:** root = \[1,2,3,null,null,4,5\] **Output:** \[1,2,3,null,null,4,5\] **Example 2:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 104]`. * `-1000 <= Node.val <= 1000`
null
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Tree
Hard
271,449,652,765
63
in this video we'll be going over the bottom up a very approach of unique paths two so in our previous 2d matrix approach we can see that in each of the iteration we're only relying on values from the current row and also the row below this means we can use a single array to represent our 2d matrix now let's go over the dot process so in the 2d matrix approach in each of the iteration we are only relying on values from the current row at r and the row below at r plus one this means we can use a single array to represent our 2d matrix then in each of the row iteration we will be replacing or updating the values from the previous row iteration now let's go over the pseudo code so i'm going to create an array paths to keep track of the number total number of unique paths then when it iterated this one stays the same we're going to iterate do the rows and then iterate through the columns and if the current cell contains a one that means the number of paths is going to zero so we're going to set path c to zero then we continue next iteration if rc is at the bottom right corner that means we have found one possible path so i'm going to place one at the current cell now we're going to create a variable current and set it to the current cell the current number of paths then we're going to reset our current number path to zero now if rc is not at the last row that means we can move downward that means we can increment the current number of paths by the number passing downward which is current so because paths r plus c is the same as path c now so we can increment pass c by current if c is not at the last column that means we can move rightward so i'm going to increment the number of rows uh the number of paths by moving rightward since this is the same row as our current cell we can just do path c plus one then we can return paths zero which is the total number of paths starting from the top left corner now let's go over to time space complexity the time complexity stays the same because of our nested for loop our space complexity changes because we're using a path array now so it's just going to be of n where n is the total number of columns now let's go over the code so we're going to create our array now our pass is converted to an array and we still iterate 0 if obstacle rc is equal to 1 the total number of paths is equal to zero then we continue the next iteration if rc is at the bottom right corner then the total number of paths at the current cell is go to one now we want to save our current number of paths before resetting it back to zero if r is not equal to n minus one that means we can still move downward so we can increment the current number of paths by the normal path moving downward and then if c is not at the last column then the bypass will be incremented by the number of paths moving rightward and then we can return path 0 which is the total number of unique paths starting from the top left corner let me know if any questions in the comment section below you
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
437
Hello Everyone in the on 17th October Subscribe Do Subscribe My Channel Subscribe Do Subscribe To Hai Digestive Process Liquid 437 Other Crops Ka Atal Gautam No Conflict Video Channel and subscribe the Channel subscribe our YouTube Channel and subscribe the according to the distic button Improve Vinod Algorithm To or even before starting with increase problem into smaller similar problems Subscribe Scan subscribe this Video plz subscribe Video Subscribe Will Reduce Per Fungi Subscribe The Fear of Vegetables Reel And What You Want You Will Do Again Subscribe Must Subscribe To Meanwhile Also Lets You ATM Sometime Plus 50 Se Zee TV Ko Namaal Xender Problem Phansi Guide To Identify The Account Of All Sach Possible Not Drawn In A Production And You Can Continue This Approach And To Account The Takhi Slip Lips Use Album Third Subscribe Must Subscribe And Subscribe Near Number That I Third Andar Laptop Three 500 to 1000 Responsibility Beach Tours In That Subscribe To Tomorrow Morning Darwin That Butter Tweet Torch Light Bill Gives All The Past Sweater Possible In The Country I'm Starting From The Giver Root And Wasm Equity Market Developed Subscribe Now Subscribe To Are Let's Talk About Helmet Force In Case Me Toothpaste Tube Channel Sedan Target Subscribe For Live Video Subscribe A Node To Cut To Code 500 Help And Midnight Parents More Than That Subscribe To Some Login The Developed Countries On That I Ho able to explain festival and subscribe button to upgrade device
Path Sum III
path-sum-iii
Given the `root` of a binary tree and an integer `targetSum`, return _the number of paths where the sum of the values along the path equals_ `targetSum`. The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes). **Example 1:** **Input:** root = \[10,5,-3,3,2,null,11,3,-2,null,1\], targetSum = 8 **Output:** 3 **Explanation:** The paths that sum to 8 are shown. **Example 2:** **Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22 **Output:** 3 **Constraints:** * The number of nodes in the tree is in the range `[0, 1000]`. * `-109 <= Node.val <= 109` * `-1000 <= targetSum <= 1000`
null
Tree,Depth-First Search,Binary Tree
Medium
112,113,666,687
490
hey what's up guys chung here again okay so today let's take a look at uh this list called problem number 490 the maze it's a good problem in my opinion okay so the problem says there's a ball in the maze with empty spaces and the walls and the ball can go through the empty spaces either up down left and right but it won't stop rolling until he hitting a wall and when the ball stops it could choose the next direction so i think here's and the maze is consists of a 2d array here basically where 0 means a path and 1 means uh what means like a wall so in this case and then with this maze it also gives besides the maze itself we also have like a start and end point so for example the example one here the starting point is this which is the zero four okay and the end point is uh 4 here yeah it's 4 here and the ball it won't stop sorry it won't stop until it hits a wall basically what it means that let's say for example starting from here the ball can go either go left and down right but the ball will not stop at this moment at this place it will stop at here so this is the first that where it can stop okay and then but and the ball can also stop from here so and that the ball can only change the direction when it stops which means from here you know it can change the directions by going back here right it can only go back and from here it can go down okay right now the ball is here so from here they're like how many options does the ball have it has two options either go left or go right okay and when the ball stops here at here right it can also have like another option go up and down okay and here it will it'll go uh go to the left until it reached the uh the end okay and then it can either go up go down or go right okay and then here at the end it will hit this one it will stop at the target and only then we will return true here okay and then there's another example here same thing the starting point is the same position but ending the destination is like instead of here it is it's a it's somewhere here but in this case even though you know as you can see even though the ball can pass through so even the bar may pass through this destination but it won't since it won't stop here okay because it won't stop it can only stop here and here so that's why we return a false here okay yeah basically that's the that's what this problem is asking you to do okay um i mean this problem it's a it's obviously a graph it's a traverse problem you can either use like dfs or bfs search to do this problem you know so i mean there are like two approaches you know for the basic dfs or bfs like every time let's say when we start from here we add all the uh with add all the uh the neighbors basically right we add all the neighbors to the uh to the queue okay and then we just keep processing it but in this case there's a difference i mean when we didn't basically you if you want to ser uh maintain like for each of the neighbors we want to add it not uh besides the uh the coordinates x and y we also need to add the uh the current directions right because let's say when we insist this node here right when we see when the bar is as at this node if the direction is it's going down right and then we don't have any other options but keep going down okay basically if on the same direction there's like the next one is not it's not a wall we have to go in that way right we have to keep going until we reach the uh a dead end basically and then yeah so we can do that but that will it's a bit more complicated and then for the graph we also need to have like a scene a set right as a scene set to uh so that we won't end up stuck in the infinite loop here so if we follow the first approach so when we have a scene here we have i and j right so ins besides y and j will we will be also needing to like have like direction i have a third value here because you know the same uh cell could be passed from different direction it could go from this direction or even from this direction okay right or from this direction that's why besides i and j we also need like a third uh third value to identify the unique statement state here yeah basically that's the first approach but um there is like a better approach so i'm gonna follow the second approach which is i think in my opinion it's a it's better so basically you know still we have a scene right so we have a scene set here and we'll be also we only will follow the standard uh bfs template we'll we will still be storing the i and j the two coordinates so and the way it works is like from the current starting point we uh we just uh let the ball rolling right uh keep rolling uh at each direction so and then we stop and we stop the rolling until it hits a wall so basically when the ball like uh start rolling to the left it will stop here okay and when the ball starts rolling to down it will stop here and every time when the ball stops we check if this position is our target right if it's target of course we simply return true if not we add this position to the scene uh stat here and then from here onwards will was i will keep uh rolling basically so basically from here because i the starting point is already has been added to the scene here right so when we uh so from the starting point we have two stops here the first one is here the second one is here and from here once it stops uh okay we'll start rolling again and at this moment since uh we can only start rolling back here okay and yeah this one will roll back to here but it but when it stops it sees okay so this one had this coordinate position has already been seen before so basically this branch will just simply stop but here right when we start going uh start uh rolling from this moment from this position we can either go down or go right same thing when we go right we see okay this position has already been seen before so we'll come here okay same thing when we come here we have we can either go right or go left okay and the ball will stop here okay so when the bus stop here uh it will either go up go down and so the next one will be here okay and from here uh we'll roll up to here right now it will roll down to here so and then this one will go here right and it'll roll to this position and this one will roll to here and from here onward it can either go up or go down okay now once when the ball reaches here it will also go left or right okay and here is nothing but when the ball reaches here okay we find our target then that's done okay so let's try to uh code these things up i mean so it they're comparing with the standard bfs uh or dfs you know bfs or dfs whatever uh the template the only difference is that uh we will keep rolling keep uh increasing the x and y until we reach the uh a wall and then we'll start from there that's the only difference okay so same thing for the dfs and bfs we're going to have like defined the four directions here right that's up down actually this is up okay down uh left okay and right okay and uh we'll define the boundaries first the boundaries of the maze okay oops and it's the length of the maze zero okay so and then we have we're gonna have like a queue or stack i'm gonna cut stack because it the sequence doesn't really matter right so i'm gonna do a stack here to store the uh the node we're going to we need to process and then we have a scene dot set okay right that's the scene set now i'm going to add this uh start zero okay right that's the uh the starting point start one to this queue okay or the stack and the same thing for the scene okay so now we just need to keep looping the stack okay and then in the end we return false right if we haven't find like if we didn't find like the target so uh we have current i right and current j equals to stack dot pop right so that basically that's our current one and so what we're doing we're like uh like i said we will we'll try to roll on four directions okay and for direction in directions okay uh nu i equals to current i okay new j equals to current j okay the reason i'm doing this is because i'm going to have a while loop here i'm going to keep rolling it until we hit like a wall basically while this well the new i is in the range okay and the new j is also in the range okay and the current one is it's still zero we keep rolling right that's the new i a new j we keep rolling while this well this can these conditions are matte right basically the new i d zero okay right the new j plus d one basically as long as the current ui and new j are vision are still valid we keep moving and follow this direction okay and then when this while loop is done okay and then the new i and new ji and out of the boundaries were are hitting a wall okay so that in order to find the this put the valid the stop point we have to backtrack by one we have to move back by one new i d0 okay right or well you can do this or you can do uh you can check this or you can check a new uh new i plus d0 it's not valid here right i mean then we you then while the while loop is finished you don't have to backtrack the position by one but either way it's fine i'm just doing this okay so this is more like i think it's easier for me to understand so to follow basically and we just go back one now the new i knew j is the is a position here right it's the stop position like i said we simply check if the new i is equal to the destination zero and new j is equal to the density nation one right so if that's the case we simply return true okay and otherwise right otherwise if the new i and new j is not in the scene okay if this stop stopping point has not been seen before right then we simply uh do a stack dot append okay we append this new i and new j we then will try to start from here okay and then of course we add these things right we add this new uh position to the scene before to the scene here okay and in the end we simply return false yeah i think that's pretty much it is let's try to run the code here okay so the test case passed submit ah oh sorry i think here and yeah success okay so it's past oh there's also like maze 2 and maze 3 yeah maybe out maybe i can do that later yeah but for this one yeah i mean it's uh it's a little bit of vibration uh comparing with the standard bfs uh template the only difference is the uh we not all the neighbors right basically not all the neighbor is a valid element to be added in into the queue it's only valid when we reach the a wall okay in this case it's this one and once we uh once we stop once we uh after hitting a wall we backtrack by one to find the pre to find the uh the position right and then we uh we start from that position basically we just essentially following what the problem is asking the bar is doing right the ball will go it won't stop rolling until hitting a walk i think that's what that's exactly what we are doing here we let the ball keep rolling until it hits a wall right and when it hits a wall we check if that position is our target or not right and then if not we'll just basically uh record we'll add that position into the scene so that we won't process that again right that position again and then we'll just go from there uh yeah cool i think that's it for this problem yeah it's a very interesting like uh a bfs search problem i believe you can also use dfs search yeah i think that it shouldn't make too much difference oh and the space and the time complexity right i think the uh so the space complex time complexity is m and then m times n so the worst case scenario you have to we have to traverse the entire uh 2d maze right and that's the time space is same space is also like a scene it's the same as the time because we might need to the worst case we will be storing all the elements into the scene here which is also m times n uh okay cool i think that's it for this problem yeah thank you so much for watching the videos guys and stay tuned i'll be seeing you guys soon yeah bye
The Maze
the-maze
There is a ball in a `maze` with empty spaces (represented as `0`) and walls (represented as `1`). The ball can go through the empty spaces by rolling **up, down, left or right**, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction. Given the `m x n` `maze`, the ball's `start` position and the `destination`, where `start = [startrow, startcol]` and `destination = [destinationrow, destinationcol]`, return `true` if the ball can stop at the destination, otherwise return `false`. You may assume that **the borders of the maze are all walls** (see examples). **Example 1:** **Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[4,4\] **Output:** true **Explanation:** One possible way is : left -> down -> left -> down -> right -> down -> right. **Example 2:** **Input:** maze = \[\[0,0,1,0,0\],\[0,0,0,0,0\],\[0,0,0,1,0\],\[1,1,0,1,1\],\[0,0,0,0,0\]\], start = \[0,4\], destination = \[3,2\] **Output:** false **Explanation:** There is no way for the ball to stop at the destination. Notice that you can pass through the destination but you cannot stop there. **Example 3:** **Input:** maze = \[\[0,0,0,0,0\],\[1,1,0,0,1\],\[0,0,0,0,0\],\[0,1,0,0,1\],\[0,1,0,0,0\]\], start = \[4,3\], destination = \[0,1\] **Output:** false **Constraints:** * `m == maze.length` * `n == maze[i].length` * `1 <= m, n <= 100` * `maze[i][j]` is `0` or `1`. * `start.length == 2` * `destination.length == 2` * `0 <= startrow, destinationrow <= m` * `0 <= startcol, destinationcol <= n` * Both the ball and the destination exist in an empty space, and they will not be in the same position initially. * The maze contains **at least 2 empty spaces**.
null
Depth-First Search,Breadth-First Search,Graph
Medium
499,505
524
hi everyone welcome to my channel let's solve the problem longest word in dictionary through deleting so given a string and a string dictionary find the longest string in the dictionary that can be formed by deleting some characters of the given string so if there are more than one possible result return the longest word with the smallest lexicographical order if there is no possible result return the empty string so this is our original string as given and we have to find out the word from this dictionary d which is subsequence with this string so that we can form that word by deleting one zero or more characters from this ah string s so if we see this character a l e word really we can form from this string as we have character a followed by l followed by e so this can be form and this can be answer but let's see next word apple a p l e can also be formed and now this bird is greater in length so we have to pick first we have to pick the biggest longest word so ah we will pick this now we will keep continue trying now monkey there is no m itself so we can't form this word from the subsequence of this string similarly p l e a we can form it is a last here but the length of this is less than the length of this apple which is 5 and it is 4 so we will have to return apple as the longest word so you can see here answer is the longer apple so now how can we solve this problem so one of the solution to solve this problem first of all we will sort our dictionary of words in the given like expected uh form of answer so based on the length first so we will sort this sort our dictionary first length based on the length and if two bird has the same length then we will sort based on lexico graphically once we sort this after that we will start picking ah and from the word so after sorting this string this will become first monkey then apple then pilli then l so this is the after sorting sorry for bad handwriting so now we will check is monkey is a subsequence of this no is apple is the subsequence of this yes so as soon as we find the first bird from the dictionary is a subsequence with our string as we will return this so this is the first approach and the first solution so let us see for the second example here as you can see all the word in dictionary is of length 1 and also sorted in increasing lexicographical order so which is what the problem is expecting so we just check if a is a subsequence yes a is a subsequence so we will return a itself so you can pause the video and try to code yourself first so here is the code snippet for the first solution so how we are sorting we are using a lambda ah divide lambda operations and where we are comparing first the length of two is string if it is equal then using ternary operator we are just using a dot compared to v so we are comparing the string a and b lexicographically ah increasing order while the length we are comparing in a lexic in the decreasing order so this will give us a sorted order and then we are checking whether word in the dictionary is a subsequence with the string s so we are calling a helper method is subsequence so what does this method is doing so this method is just starting like iterating ah j pointer for the word and i pointer for all the character in string s we will compare it whenever we see if the character at ith index on s is equals to the character on jth index of word we will increment j as well otherwise we will keep incrementing i and in the end we just return the if we found all the character of our current word into the string as in the order from left to right so this is a code for the checking if ah two string if whether the word is a subsequence with the s or not once this done this is the order now what will be the time complexity of this solution so let us see first string s is of length let us say n and the dictionary has m words so if dictionary has m word so sorting this will take m log n time by using collection.sort m log n time by using collection.sort m log n time by using collection.sort plus now we are comparing each word from the dictionary of m with the string and we are all checking whether it is subsequence or not so in worst case we will end of comparing m into n so this will be the time complexity of this solution so that's it can we try and solve with other approach so as you can see here we are doing sorting and then picking the first wherever we found instead of do doing sorting we just keep trying so let us take the same example here so we have let us see small example a b c d and here we have a b is a string and let us say v a is another string and then we have c and then here let us say d is also the string so we have four string ah into our dictionary and this is our original string as a b c d so now what we can do first we will create a result empty string that of length zero and now we will check one by one each word each string from the dictionary we will iterate again using the same for loop so we will see if bird is a sub like first word is a subsequence with this if it is so once if it is a subsequence then we will check if the length of our original result is the length of our word so the current word the let's say the word is word and if bird dot length the current word which is a subsequence with s if greater than the result word the so far the result we found if it is greater than which means we found a better longest word so we will update our result with this word and in case of the length is equal then in that case we will check if it is like word dot like this is com we will use if it is lexicographically current word is less than the our result then we will update so this is the approach and subsequence method we will reuse the same problem so you can pause the video and try it out code so let us implement the code so for the code i have written down this is a code for the old solution sorting one so here we just comment the sorting line and here we define our result string result from the empty string first and here we will check if the word dot length is greater than the length of our current result or like if the word dot length is equals to result dot length and ah result we will compare this word with result compared to result if this is smaller than 0 in that case we update our result with the current world that's it and in the end we return the result string whatever we get so let us try to compile this code now so code is getting compiled let's test one custom test case which we discuss as an example a b c d and now we have let us say first d then we have another word v a then we have another word a v and the last is let us say c so let us try it out so we are getting the expected answer now we can submit this code and it got accepted so what is the time complexity of this solution so as you can see again we have amber and the length of our string s so we are again processing and comparing each word whether it is a subsequence with s or not so the time complexity of this code is o of m into n that's it if you like this solution hit the like button and subscribe to my channel
Longest Word in Dictionary through Deleting
longest-word-in-dictionary-through-deleting
Given a string `s` and a string array `dictionary`, return _the longest string in the dictionary that can be formed by deleting some of the given string characters_. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string. **Example 1:** **Input:** s = "abpcplea ", dictionary = \[ "ale ", "apple ", "monkey ", "plea "\] **Output:** "apple " **Example 2:** **Input:** s = "abpcplea ", dictionary = \[ "a ", "b ", "c "\] **Output:** "a " **Constraints:** * `1 <= s.length <= 1000` * `1 <= dictionary.length <= 1000` * `1 <= dictionary[i].length <= 1000` * `s` and `dictionary[i]` consist of lowercase English letters.
null
Array,Two Pointers,String,Sorting
Medium
720
57
hey guys it's offline one here and today we're going to be solving instant interval in this problem we're given an array of non-overlapping intervals where array of non-overlapping intervals where array of non-overlapping intervals where each interval tells us a start point and an end point and they're telling us that it's sorted by ascending order already and we're also given a new interval that represents a start point and an end point and what they want us to do with this is insert it into the list so that it's still sorted in ascending order and so there's no overlapping intervals and if there is an overlapping interval we're supposed to merge them and in the end they wanted to return the new intervals list so here I've drawn this example down here and as you can see the intervals are 1 and 3 and 6 and 9 which I've drawn and we're given a new interval that they want us to merge that is two and five and as you can see the 2 is overlapping with this first interval so in the end they want us to make this one and three and two and five interval into one big interval that goes from one all the way to five like this and in the end we would return this new interval where we only have one and five and six and nine so here I've written out another example and before trying to solve this problem let's just think about the scenarios that can come up from our new interval being inserted into the list so that's pretty easy either one they overlap or two they don't overlap okay well that was pretty obvious but let's try and think about what this overlap really means here so for example let's just say we have this interval here and our new interval is like this and let's just say this is three and five and this is four and eight so how do we merge these well we know that the final outcome should be an interval that is from three to eight because this would include both of the intervals so when we find overlapping intervals we can say that the new interval is going to be equal to the minimum between the two start times so in the scenario three is less than four 4 so that would be our new start time and the end would be the max between five and eight because we need to include the greater number so the max between five and eight would be eight and this would be our new interval so when merging overlapping intervals we want to take the minimum of the two start times for the beginning point and the max of the two end times for the end point so now that we understand how to merge the intervals if they're overlapping let's try and solve this example so here I've drawn the intervals on this number line here and our new interval is above them so we can see where it's supposed to be inserted and this orange line here represents our new interval list which is going to have our new interval merged into it without any overlap to start we're going to have to compare every interval on our list to our new interval to see if there's any overlap so we're going to start with our first interval here one and two and we're going to compare that to four and eight to see if there's any overlap and the way we know this overlap is if the start of the new interval is less than the end of the interval we're currently looking at but as you can see here that is not the case these two are not overlapping thing so what we're going to do is just insert our current interval to our new interval list here so I've inserted the interval and I've also named this result just so it's a little clearer that this is the result array so now we're going to check our next interval which is three and five so let's see is the start of our new interval less than the end of our current interval yes and that means there's an overlap and when there's an overlap we want to merge the two intervals together so that there is no overlap so if you remember to merge the two intervals our start point is going to be the minimum between 3 and 4 and the maximum between 5 and 8. so with the minimum between three and four would be three so now our new interval is going to be 3 all the way to 8 because that is the max between five and eight and we don't want to insert this just yet because there could be more overlap with the other intervals and we can already see that's the case here so now let's look at our next interval which is going to be six and seven so let's see is the start of our new interval less than the end of the current interval yes so that means there's overlap and to take care of this overlap we're going to take them in between the new interval and the current interval and then just make that our new start and then take the max between seven and eight and make that our end time but as we can see here the new interval engulfs this current interval but we don't need to update anything here but because we technically merge these two intervals we still don't want to insert this new interval into our number line because there could still be more overlap in the future and then only then when all the overlap is resolved then we insert this so now we go to our next interval which is 8 and 10. and one thing I forgot to mention is that if the points are in the same point so let's say these Eights these are technically considered overlapping and same thing goes for this three here would be considered overlapping because they are at the same point so this interval here and this interval here are considered overlapping because they meet at the same point and I would just update our new interval to be the minimum between the two start times and the max between the two end times so as you can see the minimum is still going to be three but the max now is going to be 10. so our new interval is going to be updated to 3 10 and because we merge these two intervals we still don't want to insert this to our result array because there could be more overlap so now we look at our last interval here 12 16. so is there any overlap no as you can see here 3 and 10 is not in 1216 so we can finally insert our new interval into our number line and then now that we're done going through our intervals list we can insert this 1216 because we know there's no other intervals and now we're done this would be our final result array so now let's go over the timing space complexity our tie complexity is going to be o of n where n is the number of intervals we have because we have to iterate to all of them for space we're going to do the same thing o of n because we need to store our intervals and I'm pretty sure this can be done in constant space but it would be a more complicated solution that I don't think an interviewer would expect you to come up with so now let's get into the code to start I'm going to initialize an empty array and this is where we're going to store our new intervals list and then from here we just want to iterate through every interval so for Interval in intervals and now I have to do three checks so our first check is going to be if our new interval is less than our current interval the other scenario can be our new interval is greater than our current interval and if those two cases are true then I mean there's an overlap so for this first scenario here let's make up an example let's say our new interval is going to be 3 and 5. and our current interval is six and eight well if that's the case then that means the new interval is never going to have any overlap with any feature intervals so we could just append our new interval to our result and then just keep appending the rest of the intervals list so first we check if our new interval at the end is less than our current interval at the start then that means the current interval is greater than a new interval and if that's the case we said we would append the new interval and then we want to just append the rest of the list to this result array now and there's multiple ways to do this but I'm just going to say our new interval is not going to be equal to our current interval and then this scenario produce any errors because we're already guaranteed that the intervals list has no overlap so this would just keep iterating until the very end and then our result array would have every single interval and now we're done with that scenario so now we check if our new interval is greater than our current interval and to do that we have to check if our new interval at the start is greater than our current interval at the end and if this is true then that means the new interval is greater than the current interval so there's no overlap there so we can just add our current interval to our result list and this should be an else if statement and now at the end we're going to take care of this overlap and like I said our overlap is going to be pretty easy all you have to do is update our current interval at the start and at the end and for the start we're going to take the minimum between both intervals at the start so interval at 0 a new interval at zero so now our start is going to be the minimum between those two and the N is going to be the same but instead we're going to take the max between the interval at the end and new interval at the end so now our new interval is going to be our current interval and our new interval merged together so there's no overlap and like I said in the example we don't want to add new interval to our result array just yet because there could be more overlap in the future so once this for Loop is done we can just add our new interval because we're going to be short one interval and we can just return our result array and that should work and here I made a typo and now it should work so as you can see this code is pretty efficient and now we'll go through the code manually so I've drawn a new example here where our new interval is three and five and our intervals are mapped right here in the number line so now let's start so our result array is already initialized here in yellow so that's done and now we're going to iterate through every interval in our list so we're going to start with one and two so now we check is the new interval less than our current interval well let's see is the end of new interval less than the start of our current interval no because the end of our new interval is 5 and the start of our current interval is one so now we check this else if statement and we check if new interval is greater than our current interval so let's see is the start of our new interval 3 greater than the end of our current interval which is two well that's true so now we're just going to append our current interval to our result array so now we go to our next interval which is going to be 4 and 6 and we check is new interval less than our current interval no because new interval at the end is 5 and that is not less than the start of our current interval so now we check this next if statement is new interval greater than our current interval no because the start of our new interval is three and that is not greater than the end of this current interval so that must mean they're overlapping and that is true and the way we take care of an overlap is by updating our new interval at the start and end so the new start of our new interval is going to be the minimum between our current interval and our new interval starts so the minimum between three and four is three so that stays the same but now our endpoint is going to be updated to the max between the end of our current interval and the end of our new interval and as you can see 5 and 6 the max between these would be six and our new interval is going to be three and six and we don't add that to our result array because there could still be overlap for other intervals so now we check our last interval here seven and eight so let's see is our new interval less than our current interval well let's check new interval at the end is 6 and interval at zero is going to be seven so this condition is true so now we can append our new interval to our result array so now we can add our three and six and now we update new interval to be this last interval we just went through seven and eight so now we can just say new interval is seven and eight so now we're done going through every interval in our list here so this for Loop is done and now we just append our new interval which has been updated to seven and eight so our number line is going to include seven and eight and at the end we just return our result array which is this has the new interval merged together without any overlap so this is correct if this video helped me in any way please leave a like And subscribe thanks for watching and I'll see you in the next video
Insert Interval
insert-interval
You are given an array of non-overlapping intervals `intervals` where `intervals[i] = [starti, endi]` represent the start and the end of the `ith` interval and `intervals` is sorted in ascending order by `starti`. You are also given an interval `newInterval = [start, end]` that represents the start and end of another interval. Insert `newInterval` into `intervals` such that `intervals` is still sorted in ascending order by `starti` and `intervals` still does not have any overlapping intervals (merge overlapping intervals if necessary). Return `intervals` _after the insertion_. **Example 1:** **Input:** intervals = \[\[1,3\],\[6,9\]\], newInterval = \[2,5\] **Output:** \[\[1,5\],\[6,9\]\] **Example 2:** **Input:** intervals = \[\[1,2\],\[3,5\],\[6,7\],\[8,10\],\[12,16\]\], newInterval = \[4,8\] **Output:** \[\[1,2\],\[3,10\],\[12,16\]\] **Explanation:** Because the new interval \[4,8\] overlaps with \[3,5\],\[6,7\],\[8,10\]. **Constraints:** * `0 <= intervals.length <= 104` * `intervals[i].length == 2` * `0 <= starti <= endi <= 105` * `intervals` is sorted by `starti` in **ascending** order. * `newInterval.length == 2` * `0 <= start <= end <= 105`
null
Array
Medium
56,715
1,354
hey everybody this is larry this is day 24 of the june eco daily challenge hit the like button hit the subscribe button join me on discord let me know what you think about today's problem as soon as it loads um yeah i'm feeling a little bit off today so let me know uh we'll see how that goes because i was outside and it was pouring like pouring rain super soaked i need to get in the shower but i want to you know do this video for you at home before i do so and we'll see if that's a good decision anyway today's problem is construct target array with multiple sums you're giving away target of n integers from a starting array okay x is the sum of all elements in array choose our i and then we set the y of that i to x and then you do it however you like okay um okay so basically you can choose one number and then make it to sum right uh and then you have this like thing um and of course it doesn't really um like the order doesn't matter because you can always just change in some way how do i think about this so one okay then we have three right we have to choose three okay so three this three is forced and then the next we have five and then the question is do we want to change the five or one change to three to five or the one to five and then okay so that's one way to think about it right the star went away and then see if we could get to 935 the other way of course is just start with this target and see if we could get to one and what would the rules be on that one right well in this case we know that the biggest number in this array has to be because they're all positive there's no negative numbers anything so the biggest number in this array um will have to be the sum of all the other numbers right or the previous round what that what i mean by that is okay so then you have you know 9 3 and 5 for example and that means what does that mean right that means that nine is equal to the sum of the previous array so then what is the previous array oh this is weird what is this oh did that was this anyway right and then and that means that given that the other numbers are three and five then we know that previously the ways one three and five and then now we do the same thing which is that given this five what is the five is equal to the sum of previous array we know that the other numbers are one and three so that means that this number used to be a one and so forth so i think from that way in a greedy way we are able to solve this and also in a greedy way we are able to yeah i think that's pretty much it right in a greedy way we always get the max number and then see what that number used to be okay so i think we should be able to solve that now hopefully the explanation was okay i think i kind of was thinking for it with you at home so yeah um and the reason why i got to where hear could be is because with all positive numbers there's really no other way right like can nine be the can any other number be the sum of the previous array then just no because you have a nine so you know by like some kind of uh proof by contradiction thing um i think that's it okay so then now and of course now that i remember that this week is heap week um then you know this is and here again we want a max heap so let's get started again i'd like to do it this way you can do it at home however you like where i pre-write the push and the pops where i pre-write the push and the pops where i pre-write the push and the pops i don't have to think about it uh you can also probably abstract this into a class if you really like but uh yeah so then we have total is go to sum of target and here i guess technically we could have heaped but well like we could do a heap of x thing but it's fine this is slightly slower but that's fine as well for x in target um for x and target we just push x right and this is a max heap because we only get the max number out inside the array um there's one thing i want to do and that is just i guess n is equal to length of target um and n is both the number way but also the answer right because well not the answer but like that's the reverse target because this time all of these numbers are uh are one so then n ones is equal to n so that's basically the idea um okay alrighty then um yeah sorry i'm like i'm getting like stuffy nose just from the rain my hair is still a little bit wet i changed out my shirt but it's still uh i need to take a shower to kind of refresh myself but anyway but yeah so then now we go while total is greater than n right while total is greater than n we get the largest number so the largest is equal to uh pop and then now what does that mean right well we know the current total so then we know that without this total this is going to be total minus largest maybe right and then now the delta is just which one is it so the largest number is the previous sum so okay so maybe you can even uh yeah so then the largest is the previous sum minus the current sum is the delta right and then the delta is what we push back in uh as the thing um and then now after total is less than n and we do get there eventually or less than or equal to we just return whether total is equal to n i think that's pretty much it um maybe i miss i'm really i get the signs very easily wrong on some of these but i think this is mostly okay maybe not clearly uh so huh let me think about it so five eight five as you go to three five oh hmm total this is wrong maybe because so okay i think i was too fast on this one why do i think this is right i don't know i haven't but the new total is you go to the largest because that's literally me um i well what i think happened here is that i kind of need to add back in delta but this new total is just the largest right so uh yeah i just kind of forgot to add back in delta because we push it back right when we pop we push and so forth so that was just a silly thing apparently i got it wrong a few times hopefully today i don't get it well come on buddy or maybe even time limited who knows oh i do get time limited because if we have is there like zeros or something like this then yeah because what happens is that this row because what happens is that this is going to have 009 and then no why is this wrong actually hmm so 999 it's nine did i do this well let me think about just for a second uh clearly this is i accurately i was a little bit arrogant and kind of did it too quickly but okay so we have 999 total is 27. this is greater than three largest is a nine obviously so oh i guess this is only this algorithm is definitely correct if we assume the input is correct right so if this is true there's always terminate i think i lapsed a little bit in that when it is false there are then variants are no longer true i think i was focused on the true case where um in the true case yeah in the true case i was focused on the invariant that happens on the truth case um which is this thing um but on a first case i didn't really consider it enough so that was a silly mistake on my point um okay so what does that mean right so let's say twenty seven zero three largest of three total minus 9 and then this adds so del 2 is actually even bigger than total so okay um so basically what we should guarantee here is that okay if the largest i'm trying to think about it should be equal or greater than but okay let's think about this right if the largest number which is remember that here largest is also the previous sum right so if the largest is greater than so the largest number is less than okay after we subtract it but i mean i guess we could write it both ways so yeah so after we subtract it if total is greater than largest then we return false if this is equal we also return force but in that case delta is zero but and you push a zero but with zero there's no you know it's not possible right so that's basically why i think this is okay but i could be wrong hopefully this is right nope what did i get wrong on different third to last two i write true because this wow this is hard but that's also why you focus on it i suppose uh okay four oh no just this two this is two oh i set the same i said is that i mean i said the right things but then i implemented wrong because i wanted the reverse of my logic which was why didn't what that with their echo they're false but then i think i just mixed it up in my confusion um i think this is right maybe or at least more right so yeah let's give it some minute again hopefully this is a little bit better um well oh no is past larry going to be currently that would be sad all right maybe i need to slow down a little bit and see what's up um yeah huh oh huh i actually did not consider this case i didn't look at the that's my fault i did not look at the input enough because that's an obvious case um how do i do this i think you could do a mod type thing because what we want now is this but repeated subtraction right and repeated subtraction is going to be a mod so we should be okay here um but then now how do we total is not right anymore right um all right let's actually write rewrite these a little bit because i think i'm reusing total too much so okay so then okay so let's rewrite this so that we're a little bit clearer and understanding i'm also very sloppy today clearly uh i need to be a little bit better i bring it under the ring so yeah uh previous sum is equal to this right um and now current sum uh let's rewrite this as current sum um if yeah so delta is equal to um however say this missed the missing numbers you go to the current sum minus the previous sum right is that right yeah and then we actually want this to mod and then now what is the new sum is going to be missing so then okay so you have this uh missing and you just put it back in here but then now we want the current sum what is the new current sum right current sum is equal to the missing number plus the sum of all the other numbers right so just current sum minus wait uh so the current sum we want to subtract it by the delta well okay i think i've mixed some stuff here so okay so let's just say delta is equal to this thing right i think i'm confusing a bit myself a bit to be honest but okay so that's the delta um so for example okay let's actually put something more concrete so that means that for example if we have this thing i think that'll help me a little bit because i think i'm confusing myself a little bit too much not gonna lie so then now current sum is you go to 17 um previous sum is you go to two eight right um uh previous sum is equal to nine sorry and then the other numbers other sum is you go to this so that's equal to eight okay and then now we want well we want the current sum is equal to the other sum plus because that's just all the other numbers and then it's this one um nine is the number uh so previous sum is nine so then the missing number is equal to um the current sum or maybe the previous sum minus the other sum okay and then now the current sum will be equal to the other numbers plus the missing number um and in this case we want a mod here because we want to keep repeating um the subtraction and then i think we're okay uh let's give it a summary i just ran not a submit uh okay and then i forgot did i delete the end for some reason oh total uh i just say current sum let's go to this is that right because we'll see nope uh why is that not right now all right let's make this let's fix this for now just to all right let's see if the renaming fixes it for now uh the renaming does not work after i fixed it so okay sorry friends yikes right okay so the other sum is eight so the missing number is equal to one right so it becomes one three five all right so why is that okay i'm actually getting wrong in the first one so it's a little bit sad but uh and then current sum is equal to a plus one which is nine and then yeah that's good right and then now we go to the next and then now we have uh one three five the previous sum is equal to 5 the current sum is equal to what is it 9 which i think we do set correctly yeah um so that's still good other sum is you go to four missing as you go to nine minus four or yeah nine minus four so wait what our previous sum so five minus four so this is one right and then now current sum is updated to four plus one which is five right and then now we're one three one so why is it returning force then maybe i am doing weird let's see real quick maybe after some weird type loss uh doesn't even output that much so it just returned force here mostly huh i can't believe i have a regression but so the current sum yeah oh wait i think i changed my i think this is wrong um okay obviously the current song is going to be bigger than the previous song i think i changed my rare names and got confused okay so basically let's go back a little bit um basically if the missing number let's have it here instead if missing is or yeah if um if the previous sum is greater than or equal to the current sum then we return force i really am not feeling well today because we can remove this for just for a second though i think that's actually t i use due to uh so maybe that's just silly um so what do we want all right let me step back for a second the logic is right but i am just struggling today um okay so the missing so the previous sum um well the three for sum is also just equal to the current sum so this is always going to be true um just the way that we constructed it um what is the logic that i'm looking for basically if the new sum if current sum okay maybe i need this but i need it after i make the modification nope yikes what is going wrong with me uh now i'm just testing anything okay so let's actually step back for a second so again i'm testing it by a good case so let's actually look at it now but this we're testing it because uh well this will return true and it'll be good so the thing that i should test is having a force case and make and first identify that right so let's say we have one two then the previous sum is going to be two right yeah previous sum is two and if the previous sum is less than the other sum okay yeah previous sum is less than or you go to the other sum then we return first okay i think i confused myself with the name naming a little bit um this should tle but we just want to make sure that it uh you know because we have the 10 to the nine case in there okay let's actually remove it and then one again just to confirm that we uh we're good for now okay so we're good minus the tlu case so now let's put it back in and then now what we want is this mod okay that now makes it wrong but at least only on this one oh hmm the reason why this is wrong i have to think about this a little bit excuse me the reason why this is wrong is because um uh this becomes a missing number becomes zero and having a missing number of zero um this is just well there's no way to do it but how do i hmm all right let's just do something like okay and then this will allow us to kind of continue to step in one more way and it is i think this only happens when the other number is one because if the other number is two then what happens is that if this is zero then you would have something like two anyway so maybe if this is zero we just return well except for if when n is one so i don't know if that's true let's give a submit real quick uh and then see oh no oh i have to check this first oh sorry friends i'm really like sloppy today um also this is for so i mean this is an edge case that i didn't really consider because i think if there were more than two of these um this actually gets terminated early but if n is equal to one um that's a thing wow this is a hard problem okay but i did ultimately get it i did not beat larry from last year good job fast slamming but i did match the larry from two years ago i don't know how i feel about that today is very yikes uh i hope you enjoyed it um yeah let me take a look to see did i just so i got it right last time yeah i guess the logic is roughly the same but i was a little bit cleaner um yeah i had a condition here instead maybe this is cleaner this is actually i got confused by this loop because i think this loop does nothing it's just a wow true loop that gets broken by this or this which is why i don't know otherwise i guess it's the same idea i just forgot about that big case and i wow i spent half an hour fixing so i guess i spent half an hour fixing the big case last time and this time i only uh seen like 14 minutes though some of that was just explaining so maybe that was a little bit better maybe i am improving even though i'm more sloppy as well uh yeah and then i do some mod magic let's go with complexity really quick this one is a little bit trickier to analyze right the question is um what is the complexity right well each number so each number can this is very naive way maybe there's another way as well in the sense that maybe i don't know that this is the tightest bound but hear me right so let's say you have n numbers each number can be halved like every time uh because of the mod uh every time you run for this loop one number gets halved right and you have n numbers uh and each time you have it you have a log n thing right so that means that okay and this is array up around i don't know that this is a tied up about but okay but let's say you have n numbers um log n halving right each half and the idea here is that i do here and i don't know if this is quite right so i might have to think about a little bit more in detail for an analysis but the idea is that you know each have to cost log n times um the idea here is that each iteration of this loop um we have okay so in this case this analysis is gonna be o of n log or log n square but i think we could do a little bit tighter right because no maybe not maybe i'm wrong what i was going to say is that you can also look at the current sum right so current sum is going to be um you know n times the biggest number of it um and for you and as a result is that a tighter bound okay so you have n numbers um current sum halves every time so it is going to be log of current sum in the beginning but then what is current sum my current sum is just you go to n times the number of bits which is kind of you know like depending how you want to say it so then here because uh we have this amount of iteration we have log of n times bits iteration and then and each of these iteration costs log n time for the heap um that is the complexity as well right maybe is that right yeah i think maybe that's right um and of course it's n plus well that's just this part anyway um uh am i confused it's possible but that said that's not the most expensive point in that case because it is this part the construction of uh the heap and of course you could do like a linear time heap construction type thing i think so which i did not do but um and this is also linear obviously just going through it so yeah the way i did this is n log n and it seems like this would dominate so this is the dominating part um yeah that's pretty much what i have for this one let me know what you think this is a very long video so let me know what you think stay good stay healthy take your mental health i'll see you later and take care bye
Construct Target Array With Multiple Sums
find-players-with-zero-or-one-losses
You are given an array `target` of n integers. From a starting array `arr` consisting of `n` 1's, you may perform the following procedure : * let `x` be the sum of all elements currently in your array. * choose index `i`, such that `0 <= i < n` and set the value of `arr` at index `i` to `x`. * You may repeat this procedure as many times as needed. Return `true` _if it is possible to construct the_ `target` _array from_ `arr`_, otherwise, return_ `false`. **Example 1:** **Input:** target = \[9,3,5\] **Output:** true **Explanation:** Start with arr = \[1, 1, 1\] \[1, 1, 1\], sum = 3 choose index 1 \[1, 3, 1\], sum = 5 choose index 2 \[1, 3, 5\], sum = 9 choose index 0 \[9, 3, 5\] Done **Example 2:** **Input:** target = \[1,1,1,2\] **Output:** false **Explanation:** Impossible to create target array from \[1,1,1,1\]. **Example 3:** **Input:** target = \[8,5\] **Output:** true **Constraints:** * `n == target.length` * `1 <= n <= 5 * 104` * `1 <= target[i] <= 109`
Count the number of times a player loses while iterating through the matches.
Array,Hash Table,Sorting,Counting
Medium
236
1,652
let's solve the problem diffuse the bomb that's problem number 1652 it's a long problem here but I'll explain in simple words so you'll be given an array say something like this 1 2 3 4 5 which will be called as code and you'll be given a uh another integer K say for example k0 so what they're saying is if you get K Zer just return the same convert every number in the array to zero right so it would be something like this so I need to return this that's it right if I do this that's my answer okay what if K is equal to 2 right K is equal to any positive number okay in that case say case 2 in that case what they saying is for every number did the sum of the next K numbers so in this case the case to so I'll take a sum of next two numbers so for the first number I'll set it to five for second number I'll take a sum of three and four which will give me 7 for third number I'll take sum of four and five which will give me 9 for fourth number I'll take sum of five and the next number is there's no next number so I'll take it from the start so 5 + 1 gives me take it from the start so 5 + 1 gives me take it from the start so 5 + 1 gives me 6 for the next number which is five the next number there's no next number so I'll take it from the start so 1 and two that gives me three so this is the number I will write out what if in case the value of K is negative the -2 so the value of K is negative the -2 so the value of K is negative the -2 so the question says that if this is the case then you need to return the sum of previous two numbers so for the first number there's no previous number so I'll take it from the end so last two numbers 4 + 5 9 so I'll replace it with numbers 4 + 5 9 so I'll replace it with numbers 4 + 5 9 so I'll replace it with 9 for two I'll take the previous two sum of previous two numbers which is one and so there's no number before one so I'll take it from there so one and five that gives me six for three there are two numbers before it so the answer is three and for four there are two numbers so I'll add it up and write it five and for five there are two numbers so I'll add it up and write it seven so this is what I'll written so this is all the question is so how am I going to solve it if uh if I get k is the answer is simple I simply return uh add take zero and multiply it by the length of the input array named code what in case of positive two right positive two all I need to take care of is adding the next two numbers uh but what if I reach at four doesn't have next two numbers I have to take it from one from here one from the end so to solve this what I could do is I could attach take the K numbers from the beginning so in this case two numbers from the beginning copy it and add it at the end okay and go from 1 to 5 now so when I go from 1 to five I always have two numbers K numbers after it so for one I'll have two numbers after it for two I'll have two number after it for five also I'll have two numbers after it so I never end up in the problem of taking the number of this from the start I've already taken K numbers from the start and put it at the end copied it at the end but I will iterate only from 1 to Five I'll not consider the copied right same in this case uh if the number is negative ative right so if the number is negative what do I do in case of negative like for the first one it takes the last K numbers right so what I'll do is I'll take the last K numbers in fact k + one last K numbers in fact k + one last K numbers in fact k + one numbers and add it at the start right so now the problem and then I'll take uh go through just the first f numbers right so now the problem becomes the same as the ri four that is for this index first index zeroth index I can just take the sum of the next ke numbers okay and put it at zero index that is same as saying taking K numbers before one right similarly after uh when I am doing it for the second element I can take K numbers from after four so that will give me five and one which is same as saying K numbers before two which is the second element in our original are right so that's then the problem becomes the same for both right and that's how I'm going to solve it let's write the code for it if K is equal to 0 return 0 multiplied by length of code or I could set it as answer and return just the answer this is for the case first if K is negative uh that is K is less than zero what will I do I'll do two things I'll update code to be code k e minus1 Till the End plus code and second would be I will convert key to be positive because I'm converted into a positive Case by doing so I can solve it in the same manner when K was positive so I'll make K positive and if K is greater than zero which is K is already positive then code would be code Plus code first ke elements from the start I'll put it at the end right and after this I need to do go through for I in range 1 2 to what length now the length of the code has already changed so to be smarter I'll put it take length of code and store it on here this was my original code array I'll store the length of that code array in L and use it so even when the length of the code changes code array changes I still have the value original length with me so I'll just go to the original length from first till original length before that what I'll do is I'll take a sum and set the first index of it right so I'll take the sum of uh code from 1 to K elements k + 1 element right 1 to 1 + K element right so this will give to 1 + K element right so this will give to 1 + K element right so this will give me the uh some of the next key elements and I'll store that at zeroth index and then for the next all the next indexes I'll just subtract the first number and add one more number at the end so which will give me the sum of the next K numbers because all the numbers in between say the array is 1A 2 comma 3A 4 comma 5 and I'm looking for 1 so the sum for one when K is equal to 2 is 2 + 3 5 right so the sum 5 now if I want if I move to the second index okay at zeroth index the sum is fine if I move to Second index what I'll do is or I'll take a better example for the length of case three so for the zero index it will be 2 + 3 + 4 which gives index it will be 2 + 3 + 4 which gives index it will be 2 + 3 + 4 which gives me 9 right for second index which is the uh sorry for the first index uh which is at second place I need to take a some of these three numbers now if you notice all the three and four were already added in here along with three and four two was added which I need to remove so I'll remove the first element current element from the previous sum and add one more element afterwards right so that will give me 3 + 4 + 5 so 9 - 2 is give me 3 + 4 + 5 so 9 - 2 is give me 3 + 4 + 5 so 9 - 2 is 7 and then + 5 gives 7 and then + 5 gives 7 and then + 5 gives me 12 right which is exactly 3 + 4 + me 12 right which is exactly 3 + 4 + me 12 right which is exactly 3 + 4 + 5 so I can use this t right that's what I'm doing so answer at current index is equal to answer at previous index minus code at current at code at current index plus Cod at current index plus K or I said so if the current index is 1 and K is 3 so 1 + 3 gives me so 1 + 3 gives me so 1 + 3 gives me 4 so it will take second third and fourth that's correct so after this Loop it would have set for all the indexes in answer the sum of the next K values and so I return answer let's run and see there is slight error here so let's look at that I think the error is answer at index I -1 so not I - 0 i - at index I -1 so not I - 0 i - at index I -1 so not I - 0 i - one that was a silly mistake and it worked for all the cases now let's submit and see worked in 14 milliseconds better than 97 Sol per of solutions it's exactly same as the best solution also they also doing similar thing although they are calculating the sum each time so which could be bad time complexity wise our solution is better time complexity wise so that's how you solve the problem 16 by2 diffuse the B see you in the next video
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
1,857
hey what's up guys uh this is juan here so today uh lead code number 1857 largest color value in the directed graph so this one is a pretty cool graph problem okay so you're given like a directed graph you know of un colored nose and m edges okay and the nodes number are from zero to n minus one and then you're also given like a string right of colors which means that you know represents the color for each of the note right and so yeah that's the graph right so and our task is to find the largest color value of any valid path in the given graph so what does it mean it means that you know among all the valid path right we want to find uh the most frequent the most frequently uh color right in any of the paths so which means that you know if we have a like different path here you know it doesn't really matter how many paths we have right and we want to find a path right who has the most frequent frequently uh colored node and we want to return that frequency so which means you know in this example here you know we have uh we have like this path zero two three and four right and the frequency as you guys can see so we have a two three notes who has the same color which is uh which is a that's why the answer is three right uh and if there's i if there's a circle in this graph we simply return -1 circle in this graph we simply return -1 circle in this graph we simply return -1 that's why you know in example 2 here there's a circle here right that's why we return -1 we return -1 we return -1 all right so some regular constraints like 10 to the power of 5 and here the colors notice that the colors consist only the lower case english letters so which means that they're like only at most 26 colors all right so this is something we will be using later on okay so the problem is that uh first you know first thing first you know we want to find all the paths right and so actually there's a one implicit uh condition here which means that you know we want each path to be as long as possible right because you know so here it only says you know the path can be anything because you know let's say we start from this node here right i mean a path can be stopping at here right so it can be this and then this one right but you know actually the longer the path is i mean the higher the frequency will be right that's why i mean basically the longer the path is you mean the bigger the most frequently colored notes we can get you know that's why you know when we when considering the path you know we always try to consider the longest possible path from a starting point to an ending point which is the uh which is the end where when there's no other uh path so a few i mean a few things we have to be considered here i mean first is that you know in order to find the longest path possible right we want to find the starting point right because we don't want to start from the node right in the middle because that will not give us the longest path possible so that's you know so that's why we always want to starting from the node who doesn't have like a parent node right in this case we can use like the in degree right so which means that if we have like in degree here you know so we'll basically we'll start traversing this graph which the uh is the node has an indegree equals to zero okay right so that's the first thing and the second thing is that you know since we want to check all the colors you know because you know let's say we have different we have so for this node right we have two path we can get to this node basically this is the first one this is the second one and since we don't know which color could give us the biggest the most frequently uh most frequency that's why you know for each of the node we have to check all the colors right regarding this node i mean which means that you know if you want to define like the state for node right we have like what we're going to have like the node will be i'll be using the u right to represent each node and then the second one is going to be the color here so which means that you know the dp basically this dp u and c means that you know at this node and at the i mean ending with this note okay so ending with this node and with this kind of uh color what will be the most frequently basically what is the uh the notes count for this color ending at this low at this location so with this being said right i mean if we define a state like this you know we can use like topological sorting which means that we're going to start with all the uh the nodes starting with indegree because you know the reason we use that topological sorting is that you know we could have like a different uh starting point which means that you know this is not a tree structure this is like a forest right so which means that we could have like another node here right something like this right so in this case actually we will have like two starting point here that's why we're going to use like top logical sortings plus this integrate to help us to find the next available uh next available nodes that we can traverse and like i said you know whenever we reach like a node here you know we have to check all the possible colors right with this node because you know we don't know which color can give us the best answer okay actually note since uh you know this one actually is similar without like another dp problem which is the uh if you guys remember there's like another dp problems you know we have like a robot right and there's like a 2d grade here you know a robot can only move moving only moving down or moving to the right and they ask us i mean i think something like what is going to be that the biggest value right we can get right when the robot uh starting from here and ending to here right so for this problem as you guys can see so at each of the location here right at each of the locations here we only have like two options which is the ones above him and the ones on the left to it that's why you know for this one now when we define like the dp uh we only need to consider like the two scenarios right but for this one actually it's a it's going to be a little bit uh extension for this one because at each of the location here we could have like a multiple uh path leading to this location right it could be like three more basically more than two okay so that's why you know so this one is actually a little bit similar to the uh that 2d broad 2d board problem is that the way we are moving our state is by it's by using this kind of edges and plus this kind of topological sorting okay that's why you know when we have like this kind of a state here you know since we have we could have like different like a different path leading to this one we're gonna uh basically use all the possible paths right plus the other colors to update the states for this one and in the end we'll basically simply check uh we're gonna check you know this is on the dpu and c right so we want to check right ending uh ending with this co with this node right and did this color what will be the maximum uh value in here you know which means that you know we need to check all the nodes because since we don't know uh i mean which node will be the uh the last node here right that's why you know uh when we populate after populating this kind of a dp structure here we're going to check all the outer node and for each node we're going to check all the values all the colors all right um you know what i'll start coding then i'll explain a bit more so first let's define a few uh variables here first one is the n right and then we're gonna uh create the graph based on the address okay so for the graph i'm going to have like a list right of dictionary i'm sorry addiction of list and then i also gonna have like an in-degree in-degree in-degree okay default int but i haven't talked about how can we detect the circle right i mean basically if we use the topological sortings you know if the if in the end the note that we have been seen so uh so far you know it's less than the end then we know okay we have there's a circle right because since we're using a topological sorting you know ideally you know if there's no cir a circle we should have already uh processed all the nodes right if there's like a circle you know basically we'll be having some nodes that never uh been processed right that's what the circle will do for topological sorting and so let's uh populate the graph and degree here so we have a u and v in edges you know i'm kind of used to use u and v to represent the two side of each edge right so basically uv means we start from u and we end to at v that's why you know we have a graph of u right dot append v and then for the integrate right it can be v plus one okay so this is since it's the uh directed graph right and what else so okay and then the next thing is that we're gonna have like a q right so for q we're going to populate the starting node for topological sorting it's going to be a for u in the range of n right so for each node if the u is not in the in degree right it means that okay we that's the start we can that's the starting point of our topological sorting we're going to pan this one to the u right and then you know out i'll fit i'll try to write the topological sorting section first and then i'm we're going to add the dp on top of that right okay so while q right so we're gonna have a u gonna be the q dot pop okay oh and to we're also going to have like a visited note right so in this case uh all we need is the count we don't need to record it to visit the note details so each time we visit a note right we increase the visited uh count by one right then we have a four v in the graph of u right okay and then we're gonna in decrease the integral by for v by one right and then if the in degree is v is equal to zero right uh we can uh do the q dot append right of v right i mean we can also like uh delete this one from the integrate basically delete in degree of v this one is optional right okay and then that's basically the uh the topological sorting right it's like appealing the onions right layer by layer i mean so the reason we use topological sorting to traverse the graph you know it's because the topological sorting can also help us detect the uh what the circle you know instead of using topological sortings we can also use dfs you know dfs also works you know because yeah dfs also works it can also help us to find the uh to traverse the entire graph okay so that's basically the uh the topological sorting and on top of that right uh on top of traversing the uh the graph we want to make know like the longest right sorry the uh the most frequently uh node which th with this color so which means that you know like i said we're gonna define like uh a dp here so i'm going to define like a dp right here so at the beginning right we have 0 times 26 right 4 so in the range of n so this thing means that you know ending at node u right how many nodes basically path right path ending at node u how many nodes have color c okay so that's the definition of this dp here and yeah so as you guys can see if we have this kind of definition here you know at each of the photo here so what we need to do here is that we need to do this so for each of the colors so since we only have 26 colors that's why we can uh loop through all the colors here for each of the color you know since you know for each of the v here right we want to populate uh the color the state the dp state for v for all 26 colors that's why we need to have like an inner for loop here so basically the dp v of c right it's going to be the maximum so that's why since we have a edge from u to v right this is a u right and this is a v okay because we're going to have we might have a u1 and then we have a u2 they are pointing to v here that's why for each of the u so for each of the u we're going to use the uh the data for this parent u to update v we're going to do it for free for all the edges right that's pointing to v here that's why you know for this one we're going to have like dp of v sorry this not how many nodes uh the maximum right maximum nodes that have color c okay we're gonna have like dpu right dpu and c because you know since this one is for n for the color c right so that's why we're going to use it the u for color c because it doesn't make sense you know to use other colors because for that you know for other colors you know it will not add anything right to it will not help to increase this dp v and c okay cool so that's the uh so for the parent right for parent uh u and vc if we have that many uh nodes right have that you know we have to check basically if the current one the current color is the same as the uh if the v's color if this color is the same as c so to do that uh let me do this i'm going to have like colors you know color values uh to convert this string into its integer value that can help us simplify the code a little bit so for c in colors right so now i can use this one to do a v here so basically here i'm so this part is like straightforward right we need to use the same color from the parent note but this part it's basically it's saying that you know um if the color we're tracking is the same as the current uh the v's color and then of course we're going to add one to this dp v and c right because the color is the same as this c that's why i know we will at least have one color i have one note this is the with this c color right on this note and plus whatever colors we have from the previously parents path right so yeah i think that's almost done and let's check the circle basically if it's visited it's smaller than n right that means that there are some nodes that will never be able uh to be visited from this topological sorting which means there's a circle right that's why we return -1 otherwise right that's why we return -1 otherwise right that's why we return -1 otherwise we're going to return the maximum value right basically among everything is dp because like i said we don't know right uh we don't know the endings for the path basically the path can be ending at any node that's why we're going to check everything and in this dp that's why we're going to have like max of the max of x you know 4x in dp right this is how we check that the maximum value inside a 2d db sorry a 2d array in python right and yeah so i think that's it if i run the code oops oh i know what went wrong because um you know for topological sorting right this is a starting point right and as you guys can see we use a starting point to update uh we i mean we use u to update v right but we have a starting point right in the queue here and so when we add this starting point into the queue the dp here so notice here and everything was zero at the beginning right which means that you know the count for this u is also zero but this is wrong because you know this one has at least this one will have like one for this color at u right which means that you know the dp u and the color for this no for this node should be equal to one instead of zero that's why we're missing like uh one in the answer so which means that you know here when we uh populate this q here we should also populate the dp here which is going to be u of color values of u right equals to 1. yeah i think this should work yeah accept it if i submit cool there you go right so past um yeah so and type and time and space complexity um you mean nothing special right i mean you know this one's like uh constant 26 so we can just simply ignore it this one now for topological sorting you know the time and space complexity there they're both uh o v plus e right where v is the number of vertices and e is the number of edges yeah i mean that's it right so this one summarize right it's pretty uh i mean i would say it's a complicated one because we have to utilize a bunch of stuff you know first we have to detect like the uh the circle you know it doesn't really matter which method you use i mean so here i use topological sorting to detect the uh the circle and then the second one is that you know we have to come up with like a dp state uh to calculate the uh to calculate what the this most frequently occurring color of all the path right and to be able to populate this dp here you know we can either use a topological sorting to traverse the uh the graph or we can simply use like a dfs right to traverse it so either way works you know since the uh this one is like a it's a directed graph you know we don't need to worry about revisiting the uh same note right okay i think that's pretty much it is yeah so thank you for watching this video guys then stay tuned see you guys soon bye
Largest Color Value in a Directed Graph
largest-color-value-in-a-directed-graph
There is a **directed graph** of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. You are given a string `colors` where `colors[i]` is a lowercase English letter representing the **color** of the `ith` node in this graph (**0-indexed**). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a **directed edge** from node `aj` to node `bj`. A valid **path** in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The **color value** of the path is the number of nodes that are colored the **most frequently** occurring color along that path. Return _the **largest color value** of any valid path in the given graph, or_ `-1` _if the graph contains a cycle_. **Example 1:** **Input:** colors = "abaca ", edges = \[\[0,1\],\[0,2\],\[2,3\],\[3,4\]\] **Output:** 3 **Explanation:** The path 0 -> 2 -> 3 -> 4 contains 3 nodes that are colored ` "a " (red in the above image)`. **Example 2:** **Input:** colors = "a ", edges = \[\[0,0\]\] **Output:** -1 **Explanation:** There is a cycle from 0 to 0. **Constraints:** * `n == colors.length` * `m == edges.length` * `1 <= n <= 105` * `0 <= m <= 105` * `colors` consists of lowercase English letters. * `0 <= aj, bj < n`
null
null
Hard
null
988
hello peeps what's up we are here to solve another program from lead code this title is smallest string starting from belief given the root binary tree each node has a value 0 to 25 representing characters from a to z and we need to find out the smallest lexicographical string that can be formed during in the path from leaf to node leaf to the root of that tree okay so there we can have multiple paths if there are more than one leaf node in our tree and we need to find out the lexico lexicographically smaller string let's see in this example one here we can have four paths a b d a b e a c d and a c but we need to take we need to consider the reverse of these strings like the parts should start from belief and end at the root and at the boot so the four strings four parts which can be made in this tree are dba eba bca and eca and among those four strings lexico graphically smallest smaller string is dba so the output is db and let's see this example three there are only two possible paths from leaf to root and those are a b c and abc and among those abc is the smallest one so that output is abc so let's uh let me first explain what our approach or what my approach is yep to solve this problem i used depth first search yeah first of all i'm maintaining a global answer which let's call it answer itself and in which i'm storing the lexico graphically smaller string which i have found up till this point and i will initialize to some string which is greater than that because the z comes at the end of our string alphabets if we are considering only lowercase alphabets so what we would be doing we will start a traversal from the root and we will keep adding the characters which we find during our traversal and when we have reached to the leaf node then we will compare the string which has been made till this point to the global answer and if that string is lexicographically smaller than the global answer then we'll update our global answer otherwise we will not update it as our answer is smaller than the current path which i've just found let's try run that our code or our approach in this case so we will call our dfs on the root which is a here so we will be using will be maintaining a running string which is the path so we're storing the path over dfs at this point our string is just a and then we move to b to our string becomes a b then we go to abd here it becomes abd and as we need to consider path from d uh leaf to root what we'll doing we will just reverse it the reverse would be dba then we will compare this dba to our global answer that is that and we found we see that it is lesser it is lexico lexicographically smaller than z so we'll just update our answer to dba and then we move to b as we are doing dfs and we will remove b from our running answer we'll just have a b at this point we go to e now our running string is a b we take the reverse which is e b a but it is not lexico lexical graph is smaller than db so we will not update it now we will move to a and then we go to c now our string is ac then d now we have acd reverses tca but again we see it is not like civil gravity is smaller than our global answer we do not update it we go up to see we go back to c again then to e and a c e you take the reverse which is aca and still it is not electrically smaller than the answer dbh will not update it so our final answer here is dba this is the smallest lexicography substring which can be made in the path from leaf to root answer is dba okay so we are using that for search and we all we are able to do all the processing in one dfs traversal so the time complexity would be of n where n is the number of nodes in our binary tree let's see the code now this is the global answer which we are maintaining and initially we have initialized to it a z plus one which is basically a character opening curly braces it has a higher sky value than z which is 123 and then we call our main soul function on the root of our binary tree initially we have the running answer as null because we have not added any characters to it but this is the main function this is the running answer what we're doing first of all we're checking if it's a leaf or not if it's a leaf now we need to compare our the string form to the global answer first we will add the character present at the leaf we will just reverse it and see if the path formed the current path formed is obviously is not empty and it's uh it is lexicographically lesser than the global answer which we are maintaining that is result then we'll just update result to running and the end we are reversing our string the running answer and returning as we are using uh pass by value i think even we do not need to reverse it the second time we'll see if it gives us any errors and if it is not the leaf then we should proceed our we should proceed with our dfs call we do not need to match our string because we would be only matching the running path the final path formed with the global answer when we are at the leave so if we have passed the if string it means it is not a leaf it is unknown leaf node this point we will uh append the character present at that node and see if it has a left child call function on its left child and if it has a right child we call it on the right child so we are sure it will traverse or to all the leaves present on the subtree of the left child of root and similarly here it we're sure it will traverse to the leaf nodes of all the leaf nodes of subtree present at the right of this root so yeah let's see as i've commented this line let's see if it's still working or not yeah it works let's see everything if time changes if i uncomment it oh it becomes even faster whatever that and one more thing which means which needs to be observed which suppose we have empaths from root to leave so basically if we have m loops so we would become having m comparisons that is with the global answers because every time we are at the leap we are comparing it with the globalizations and times so that's all for this video i hope you learned something from it and if you like our videos please like and subscribe and yeah see you in the next video take care sayonara
Smallest String Starting From Leaf
flip-equivalent-binary-trees
You are given the `root` of a binary tree where each node has a value in the range `[0, 25]` representing the letters `'a'` to `'z'`. Return _the **lexicographically smallest** string that starts at a leaf of this tree and ends at the root_. As a reminder, any shorter prefix of a string is **lexicographically smaller**. * For example, `"ab "` is lexicographically smaller than `"aba "`. A leaf of a node is a node that has no children. **Example 1:** **Input:** root = \[0,1,2,3,4,3,4\] **Output:** "dba " **Example 2:** **Input:** root = \[25,1,3,1,3,0,2\] **Output:** "adz " **Example 3:** **Input:** root = \[2,2,1,null,1,0,null,0\] **Output:** "abc " **Constraints:** * The number of nodes in the tree is in the range `[1, 8500]`. * `0 <= Node.val <= 25`
null
Tree,Depth-First Search,Binary Tree
Medium
null
123
hi guys hope you're doing great our today's question is best time to buy and sell stock three so the question says say you have an array for which the aia tournament is the price of the given stock one day i design an algorithm to find the maximum profit you will complete at most two transactions you may not engage in multiple transactions at the same time that is human cells stop before you buy again so this is pretty standard that is we cannot hold more than one stock at any point in time with us and the added constraint here is that we can complete at most two transactions which means that we can also do just one transaction right that's also a possibility so for example here the output is 6 because we buy on the day 4 and sell on day 6 so that's the profit and then we buy on the 7 and sell on day 8 so we're basically finding two combinations here right one is the first buy and the first cell which gives us the maximum profit and relative to that the second buy and the second cell which gives us the maximum profit and similarly here so here this is 1 and 5 is it's an increasing sequence and we just make a single transaction because we get the maximum profit by doing that right so and since this is decreasing so we there is no way we can make any profit so that becomes a zero okay so now talking about how to approach this problem so as I was saying that we need to focus on four values right one is the first buy okay so yeah so one is the first buy okay and the first sell play so we need to make sure that we maximize the profit beyond from this transaction so now it could be possible that one might just travels through the whole array once and find the min and the max and that would be the first buy and the first sell sure so if it's a case like 1 2 3 4 5 here then the there's only one transaction that needs to be made then that thing will work right but if we want to make two transactions of the array itself that two transactions really more profit in that case we will end up catching the minimum and the maximum value and since in between those two values we can make no more transactions because at any point in time we can hold just one stock right so we would be devoid of the other opportunity of making more profit that is by doing a second mine and a second set so that helps us understand that these values are interdependent okay so and the final answer right so it's really important to understand that for example I am buying a stock right so the first buy means the amount of money that is left with me after I purchased this stock so we want that to be maximum so what I mean by that is let's say for example if there is a stock of price 1 ok and there is a stock of price step and we have 100 rupees with us ok so one and 10 these are the two stock prices and we have got 100 bucks with us so if we buy it at 1 right so we have to pay 1 - to buy that right so we have to pay 1 - to buy that right so we have to pay 1 - to buy that particular stock and what will be left with is 99 correct and if we buy the one at 10 we'll have to pay them so what we'll be left with is 90 right so in order to ensure that we buy at a lesser price right we need to maximize the amount of money that is left with us after buying ok so that is why we want to maximize the first why maximize the second sell sorry first sell right and similarly the second buy and the second cell and then at the end after completing these whole transactions whatever is left with us is our profit right so I hope this makes sense and that is the reason that we cannot compute them separately we need to compute them in one go and at every day we need to find out that if at this day I take this as my first by then what will be the impact so I just pick the whatever first buy I have computed till now or the first buy from this point ok similarly first sell second buy and second sell so I just understand the effect of that particular price on that day on all these four values and then we have a final second cell which is the maximum so we just try to implement this and see okay so if price is dot length is equal to zero then you can just return zero okay and fine so we'll just need four values we'll just tape first buy okay and we'll just assign them some very small values we'll just say that it's min value okay and we'll also assign the second my integer dot I mean you because we want this to be initialized in the first phone and our first second first cell is equal to zero and the second cell is about so it goes to zero okay now we'll just start from I equals to zero I less then prices dot length and I plus okay and for first by will say that away first by equals two math dot marks off first by okay whatever we have done in the past and whatever value is the maximum value we have been able to get for the first by in the past either that or since this is going to be the first of this whole streak right then just the negation of prices of right because we are saying that we don't have any money at this point in time all we are doing is we just pain that's the first transaction so since we are buying we are paying and we just do a negative of prices of Phi okay first cell so after doing the first five we will come out of the first cell right so either the pre computed value if that's more or if we are selling the stock we purchased at this price the first by then we can say that so this is going to be our price on which we will sell it right and what we have is first by right so after buying whatever money we are left with we will if we sell it at this price we will add that price value to that money and what we are left with is first by right so after by we are left with some money right then if you are selling this so we add this price because we have got some money after selling it to the first by okay then with second by we have to do something similar so either second by or now here we don't have to start with this because this is not a first transaction so what is the amount of money that we have right now is the first cell right so first four cell and since we are buying we have to pay right and then second cell equals two similarly either this same value or we just the recent amount of money that we have is the second by so that plus the price is a 500k so this way we will be able to in a relative manner compute all these values and then at the end we just have to return the second said because that is the ultimate profit that we will be able to make so let's say that words oh that's weird so the time complexity for the solution is o of n because we just traversing the prices every once and the space complexity is off one because we're just using four variables so I hope you guys find this video helpful if you do please like share and subscribe keep coding tickets
Best Time to Buy and Sell Stock III
best-time-to-buy-and-sell-stock-iii
You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete **at most two transactions**. **Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). **Example 1:** **Input:** prices = \[3,3,5,0,0,3,1,4\] **Output:** 6 **Explanation:** Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3. **Example 2:** **Input:** prices = \[1,2,3,4,5\] **Output:** 4 **Explanation:** Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again. **Example 3:** **Input:** prices = \[7,6,4,3,1\] **Output:** 0 **Explanation:** In this case, no transaction is done, i.e. max profit = 0. **Constraints:** * `1 <= prices.length <= 105` * `0 <= prices[i] <= 105`
null
Array,Dynamic Programming
Hard
121,122,188,689
763
hello everyone welcome to question coder so in this video we will see the question that is partition labels so it is a medium level question and the problem statement is a string as of lowercase english letters is given so we want to partition the string into as many parts as possible so that each letter appears in at most one part that means that we are given this string of length any length like uh it will be in between one two five hundred and we are only given the lowercase english letters that is from a to z and we have to partition the string in such a way that a particular character occurs in only that partition it does not occur out of that partition so for example in this string you can see the each letter appears in at most one partition and return we have to return the list of integers represent representing the size of these parts so of this string we have made three parts you can see maximum parts that we can make are three because you can see e occurs in this only this part only after that you can see the these are the other parts and it does not occur in these and b also occurs only this part not in that other parts so we have to make the like maximum parts that we can make of a particular string and all the each character should occur only in one part at most it should not occur it should not be like if a is here and a is also here then we have to increase our size of this window or this partition and can like merge these partitions also if a occurs here so here it is that this partition is so that each letter awares in at most one part and a partition uh you can see here they given another example also here they have merged these partitions so actually this is also logically correct but we are we have to find the maximum possible partitions that we can make so this is a wrong answer for this particular question because we have to find the maximum partitions at you can see at d we can make the another partition starting from d because a does not occur after d and uh from the all the characters in between this a to a it does not occur after uh this a so that's why we have to make maximum partitions possible so let's see how we can solve this so actually if uh this is the same example that we are given in the lead code so let's see so this is our string so if you see the first reference of a is here so we have to find actually the maximum occurrence so maximum occurrence of a is at this point so you can see a occurs at this point if you check b occurs in between this range uh it is inclusive in between this range and here also be a cousin between this range and c also occurs between this window or this range actually you can see so this is luckily we have got the like first uh character indeed got our first partition so now if you see for d we have to actually make the partitions or the windows if you see d so now d occurs at this point and the ending or the last time the d occurs is at this point but if you see e is not in between this range it is actually after occurring after d so we will have to extend our window for that particular uh character the maximum that we can extend so it will be at this point so now if you see f lies between this range and e also lies between this and g also lies between this range so now we can uh like this how we will make the partitions for this you can see uh h lies here and as a second or the last occurrence for patches here but this is not the full window if we see i lies here so we will update or extend our window till here then we uh encounter a j so j occurs at this point so we will again like extend our window and we will get we like getting this point this whole three partitions so now what we have to return is we will simply uh like we will use the indices to find the length of the particular uh string because we don't have to print it so we will simply use the indices so if for example if it is e so it is s so we can simply do e minus s plus one for uh like making it one based indexing instead of zero so we can simply do plus one so let's see how this algorithm works i hope this uh you got it clear how we can like think of this approach as a windows approach or you can say and then we have to extend the windows so let's see so actually for this approach what's happening so actually for this approach we will create a counter you can say from a to z which will contain the last occurrence of this last uh the index of last occurrence of the particular character so you can see in this given string a occurs last at eighth index you can see a occurs at last uh last at this index you can see eight so this is how we will make this array and for the like for example e occurs last at this index not this actually it is wrong sorry i will change it so you can see e occurs at this point so maximum will be 15 so let's uh check it again a is last at eight and b occurs last at fifth index so actually this is at fifth index so you can see fifth index and then if you see c occurs last at seven d occurs last at fourteen and e occurs last at fifteen f occurs last at uh this 11 and g occurs last at 13 uh if this h occurs last at 16 oh okay no 19 so actually i've made lot of mistakes so it is 19 so now you will be also able to understand how we have made this array so it will be actually from a to z but i've only written this for a two from a to l because we our string o d contains from a twelve so i have like due to the space i've made it like that so for i curse lasted 22 and jacques last at 23 and k at 20 and l at 21. so i will show you in the code how we can make this array actually but now let's see the intuition of the algorithm how we will use it so if you see we will have to after making this after that we will get this array we will have to initialize two variables that is start and then actually start uh at the starting start and then we'll be at same position that is zero and i will uh we have a pointer or you can say traversal or for use that we will use for our traversal so if you see i so now start and enter 0 and will be about the ending point of the index and we will extend it whenever we want to because uh for this example as we saw the occurs at this point so starting will be over here and our end will be at this point because of the last occurrence of d is at 14 but if we encounter e so and will be extended to the last index of e that is 40 15 it is greater than the d so let's see so how we can do that so i will not show you fully but like i will show you the intuition actually so if you see here i is at this point and our end will be the maximum of this uh the uh you can see of the electron is at zero and will be maximum of the particular occurrence of this like index of this uh a so the last index at a occurs is at a so end will be set to this point that is this a so now our end is at here and start is at here and i will move to another next point so it will become coming here that is one then i will see uh that will check and will be like updated i will write it here also so actually n will be max of the previous end and the current value that we are getting from this value that is count and the character that we are checking so this will be the character so now we are at b character and the value that uh b value of the b is this from this array is 5 so if you see five is smaller this then this eight so he will stay to its previous value that is a and then we will again come to a and a is previous value is eight so it will be not that accelerated then we come to b and nothing happens then c since c's value is 7 which is smaller than the previous value of e that is 8. so we will simply not extend this window and similarly we will keep like i will reach to this point that is 8 when we will see when i and e becomes equal that means we have traversed the full like window and we have not found any character which occurs after this uh like uh this window so we will we have made our fun partition actually if you see so now what we have to do is to find the length of this is we can simply write you can see i or you can write they are at same index and then we can simply do i minus s and for making it one based indexing we can simply do plus one so if you see the value of i here is eight so eight minus uh you can see this is s so s is actually zero so zero plus one to make it a zero and a one based indexing so we can record the value nine you can see our first length of the first uh string was uh the partition was nine so we have got the correct answer so now what we have to do is we will set this start actually to the i plus one index because now our one uh like partition has ended so we need to update of a start so it will become i plus one which is nine so start will come here now let me erase the these values actually so now our i will be starting from this point so what we will do now we will check the ending point of d is 14 so we will set our e to the ending point of d where it occurs so now when i comes at this point that is e so we will check the ending last and instance of e which is at 15 and 15 is greater than the previous value of e which is 14 so now we will extend this window and e will come here instead of this so he will come here that is at e sorry for the writing i actually i am using the mouse so it is not easy to write so now if you see now uh like we will traverse to this i will come here f and f is the last instance of f is 11 so it is not greater than e that is 15 so then e is actually 15 only then g 13 is not greater than e then this d actually it is also in between this range so now again i will come till this point and e will stay as it is because we have no other character which occurs after this partition this actually this window so now if you see i n er equal so we what we have to do is simply find the length so now our i will be you can see i is over 15 so 15 let me write it 15 minus this start is 9 plus 1 so what we'll get it is not string answer what's happening so yeah so let me show you so uh 9 15 will be six so plus one will be seven so now we have got the second partition size which is seven that is two so now similarly for this also we will again run our loop uh loop will keep running and we will find the maximum point at which occurs uh this letter occurs so let me show you that also quickly so let's see so these were our partitions that we formed uh actually and these were our partitions so now our i will be here and starting will be also here and ending will be set to the value of this uh h that is from this point this array that is 19. so and will be coming here now i comes here that is at l so uh that is i so this is i not n so if you see let me check it or so yeah this is i actually not l this is i so if you see this is i so if we check the last point so it is 22. so 22 is greater than the previous value of uh e 19. so we'll extend it to this point so now it has extended all the way to this where this point now if you check i will come to j now if we check the value of j from this array it is 23 which is greater than the previous value of e so that means we have to extend our window so now our window will be extended so similarly it will traverse to the remaining elements and then we will be left with this partition so now we will simply find this uh value and that is 23 so 23 that is i minus 23 plus minus is uh starting value and plus 1 so which will be 8 this is how we can simply find our like partitions and the size of the partition and print it so let's see the code also i hope you understood this uh solution actually here we are using only one reversal so it is trying to mix it will of n and the space will be also of n so let's see the solution so i will code it so first of all what we have to do is we have to prepare account array so what we get a vector we can say so actually we will do ink and count or actually i will name it as last index so last index and it is of size 26 and we will initialize it with minus one then we will like to start passing through this string that is for i is equal to zero i less than this s dot size and i plus then we'll simply uh get the value of the last index actually so s and i and we have to actually subtract the value of my sky value of minus a so let me tell you that at this point if you see the sky value of uh for example x k f value of c is 99 so how we can map it to this array at the index three so for that we have to minus or subtract the value of a the sky value of a which is 97 so it will become three so it will come two you can see so now one uh zero one two so it will be mapped to this two index so we have to that's why we have to subtract the minus uh the sky value of a so now we can simply plus the node plus actually i that is the index at which it has occurred so now what we have to do is now we will get our last index array now we have to make our result vector so that's what we have made now will simply again traverses stream and i lessen s dot size and actually i plus and now we have to also initialize our variables that is start and end start will be zero and end will be also zero so now for every uh like this point we'll check and will be our maximum of the previous value that is previous and which is uh zero now and the current uh the value that we are getting that is last uh sorry last index of s of i minus here to map this minus a and then and will be updated to the maximum value as i told you it will be updated with the maximum occurrence of this value that is 15 so if end is at this point 12 so it will be uh like this point actually 14 so it will be updated to this value that is 15 so it will come with that so now uh what we have to do is if we check for the condition when the partition ends it will be when i is equal to is going to end then we will simply just add the result actually and place back so why i use and place back is because it is faster than the pushback function actually so now we have to make i minus s plus 1 we can simply insert that so i as i told you i hope you remember that uh that we did here the calculation so now what we have to do is also update the start to i plus one because we have to uh make the start also to the starting uh the point to the starting of the next partition so that's what we are doing so now we have to simply return the result all right i hope this works actually let's see i hope i haven't made any mistakes so society so actually yeah it should be comma here so you can see it has let's make it so yeah it got accepted you can see it ran in like four milliseconds and it was faster than ninety seven point six percent of solution and it took less memory than eighty seven point eight zero percent of solution so i hope you like this video and i will uh share this code in the description so you can refer it from there i hope you understood how we can solve this question and all the intuition might hit so guys do like this video and subscribe this channel and share this video thank you for watching guys
Partition Labels
special-binary-string
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these parts_. **Example 1:** **Input:** s = "ababcbacadefegdehijhklij " **Output:** \[9,7,8\] **Explanation:** The partition is "ababcbaca ", "defegde ", "hijhklij ". This is a partition so that each letter appears in at most one part. A partition like "ababcbacadefegde ", "hijhklij " is incorrect, because it splits s into less parts. **Example 2:** **Input:** s = "eccbbbbdec " **Output:** \[10\] **Constraints:** * `1 <= s.length <= 500` * `s` consists of lowercase English letters.
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coordinate reached. If F is the answer function, and S has mountain decomposition M1,M2,M3,...,Mk, then the answer is: reverse_sorted(F(M1), F(M2), ..., F(Mk)). However, you'll also need to deal with the case that S is a mountain, such as 11011000 -> 11100100.
String,Recursion
Hard
678
110
okay this see the um easy question and the topic Tre defic b anyway uh so we have the uh we are given a binary tree and we must determine if see high balance binary tree so a high balance binary tree is a tree with the depth of two sub trees of every node never differs by uh more than one which mean we can see the not number nine the dep is technically one and we can see the not number seven is the dep one to okay going to do this one to draw I mean why not okay um so for the another example we can see not number four we have 1 2 3 the dep definitely three and the dep here E1 and 3 minus one is to is not sell balance and the way we Sol the problem here we can see that we're going to calculate the of this one and we minus this one we have high here number one and we minus High number two really easy that's the reason why it's called easy equation okay I think I can clear this one and do the coding okay so first of all what you going to do is just con code lady height okay let me check make sure video recording okay calculate the high on the left okay this one same as above okay um the way we uh calculator High we just you def guys I really love deficit okay defy deficit defic set here we going to do here we put the self in inside class and we get a root okay uh B case if not good all I going to you if not good return zero the reason we return zero we well if it's here and it's none is technically there's no level here the high is zero we don't have like the negative high right so uh so what we going to do here we you the le High we're going to spare it down okay equal defus Theus root Left Right High okay the root. right uh return what we what are we going to return here return Max guys Max left height and we return right here and the reason we return Max like I'm going to draw again I guess return marks because we have this here one two three and one two three uh what if we have another a not here right we have to calculate here one two three 4 and we need to like get the max here that's reason why and also we need to Plus plus one as well the reason we plus one because if this is the base ke there no NOS but we go here we going to plus one here that's see the reason why we going to have a plus one here okay I think that's on uh we can do the uh function con here but first let we uh let do here so there uh Ro okay let just run it make sure everything you're running I see okay let's see we need this one I don't know why we need this one in here but just make the compiler happy okay another is so we have here no attrib lab the reason is that we need a b if root e none okay root if not grou return true because if nothing that is sell balance it's the no thing right okay uh run again just to make sure we on the right track okay look good so the thing here what we going to do we going to calculate the high on the left High left height left High equal deficit uh deficit on the lab right and right high def we go right here okay we have two of them return the left High minus right High uh we going to get absolutes of this one the reason we get absolutes because we don't care I don't care about the uh the side right okay R than uh if let two we going to return true right okay see it's accepted but I think but I know that we going to have an is if we submitted it because let's see if you guys know like what see wrong here we go uh okay the uh it's saying do like this should supect like return form but like we should true dra the tree draw the tree here one two here uh one two we have three here we have no one here we have none here we have three here we have four we have noon uh we have noon here right let me drink again one two three noon 3 4 noon and four is here okay because we can this see noon right one two three four no okay that's good Okay the reason the comp saying that we have an issue for this one let's check okay one the left high is three right and the right High one two three minut three is zero right and this balance but it's not the reason if you look at inside here uh we have the sub tree here with this is known right we can just crosses and definitely is not B inside here and the uh let me clear it here you and the description saying that every not need to never differ by more than one the reason is that we need to check the every Sub sub tree as well if we check the overall right after that we have to check the smaller one here as well so what we going to do we're going to do just some simple step here okay let me wrap it here the bracket okay and E I'm so lazy e balance we going to have to check the root on the left to be a balance tree and we have to do the same thing for the right this is the tricky part of the question and if we submitted it what we going to expect uh okay see I think we need to call this one inside this class okay submit that really confident and you can see we are accepted and that's it for the question if you guys any have any question concern let me know in the comment section thank you very much
Balanced Binary Tree
balanced-binary-tree
Given a binary tree, determine if it is **height-balanced**. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** true **Example 2:** **Input:** root = \[1,2,2,3,3,null,null,4,4\] **Output:** false **Example 3:** **Input:** root = \[\] **Output:** true **Constraints:** * The number of nodes in the tree is in the range `[0, 5000]`. * `-104 <= Node.val <= 104`
null
Tree,Depth-First Search,Binary Tree
Easy
104
223
So gas main us review agarwal welcome tu ko tricks channel made for you made by so let's not start today sleep good problem name of good problem for today is rectangle area medium level problem trust me which is very simple problem don't worry If there is no such thing, then first of all let us see what is given in this question and what is this question trying to say about itself, then in this question there is no coordinate access given, above which there are two rectangle plots. How are both the rectangles plotted? Given are the coordinates of the bottom left corner of both the rectangles. Now let's assume that if this is rectangle A, then the coordinates of the bottom left corner of this rectangle will be ax1 A1 and the coordinates of the top right corner will be ax2. A/2 corner will be ax2. A/2 corner will be ax2. A/2 Similarly, if we consider this rectangle as Rectangle B, then its bottom left corner will be coordinated as bx1 B and the other top right corner will be coordinated as bx2 B/2 Okay, so now your I came to know B/2 Okay, so now your I came to know B/2 Okay, so now your I came to know that how these two rectangles are plotted, what I have to do is to cover the area of ​​this rectangle, I have to calculate the area of ​​my coordinator cover the area of ​​this rectangle, I have to calculate the area of ​​my coordinator cover the area of ​​this rectangle, I have to calculate the area of ​​my coordinator access, I have to return it to the area. How much area of ​​your coordinate axis is area of ​​your coordinate axis is area of ​​your coordinate axis is covered in these two rectangles? I hope you have understood the question well. If you have understood the question well, then now let's see how we will solve it. So solve this. What we have to do is simple, first we will calculate how much area is this rectangle covering, then we will calculate how much area is this rectangle covering, okay so both of these It's done, but this area is being added to this rectangle and this area is also being added to this rectangle, so this area is added twice, so we will subtract this area once. From this and then we will get our total area, then we will return our total area, then you have to read yourself, you have to calculate the area of ​​the rectangle, you have to plus it, you have to do the area of ​​the rectangle and then you have to subtract it. Okay, now what is the area of ​​a rectangle, Okay, now what is the area of ​​a rectangle, Okay, now what is the area of ​​a rectangle, meaning. If you calculate this thing and its height, then how will you calculate the length? Now, for the length, which one do you need, then one of these coordinates is needed for the Now, if we subtract these two, our length will be equal to this, so this coordinate is given to us, minus three van, the coordinates of the bottom left corner were closed, so if our XXL is minus three, then we have got it. If we are standing here and if we are standing here, then subtract our -3 by -3, then the height, if we talk about our bottom left corner, then the point on the A-axis inside it is point on the A-axis inside it is point on the A-axis inside it is this. If we get the A axis, then this exercise is zero and similar. If we look at the top one, then the one on the top right corner is given. So, is there any difference in the A axis of the top right corner, is there any difference in it, then we have given these two. You can calculate with four by doing mines, then how much will be your length in bread 24 Sapna has got the area of ​​the rectangle 24, then we will calculate, okay for that also, first of all you will need this length, this one from here to here If the length of the till is correct then Apna is one if it is made of the bottom left corner then what is the X If you do this then it will be 9. Okay, your length is 9, the length of your line is, these characters will be calculated, now Punjab - 1 and if you do your plus one, it will be 3, so your given is three, so 9 * 3, how much your given is three, so 9 * 3, how much your given is three, so 9 * 3, how much is18 9 * 3 27 Sorry gas, 9 * 3 27 Sorry gas, 9 * 3 27 Sorry gas, how much rectangle is given to us 27 Now if we add these two areas, how much will we get Let's calculate the common area, first of all we will get our answer automatically When we open it ] Okay, because the minus is three and this is zero, then what will be the maximum of these two? If it was like this, zero, that is, it would start from here, then which would be our common area, our common meaning would be the coordinates that would come here and the maximum of the coordinates that would come here. What are the coordinates? Mins is five and what are the coordinates here - 3. So this time if we get the maximum of both of them what are the coordinates here - 3. So this time if we get the maximum of both of them what are the coordinates here - 3. So this time if we get the maximum of both of them then -3 will come. Okay, so then -3 will come. Okay, so then -3 will come. Okay, so this one on the left will become the coordinates of the If it is not there, then how much will be Apna's maximum will be this one. Calculate. Apna's maximum will be zero with them. Okay, so Apna's left axis becomes zero. Similarly, if Apna's right axis comes out then what will be Apna's right axis will be this one's. And the minimum of this one is correct [ is correct [ is correct So we got it 3 - 0 3 - 0 How much is it And we will calculate the maximum of this one How much is the maximum of this one Zero is your bottom rate is zero. Similarly, if bottom, your bottom rate is zero. Similarly, if you want to calculate your top grade, then it will be the minimum of this one, what is the minimum of this one, do 2 - 0 What will you do Then if we calculate this coordinate of ours, then what will be the coordinates of this one, the meaning of this one is the maximum of ax1 and bx1, then this will get the length of ours, if we get the length of ours, then we will put the breath inside this, then the bread will become ours, first of all If you calculate this one, then what will happen to you for this, you will have to minimize yourself, A/2 and B/2 will become minimize yourself, A/2 and B/2 will become minimize yourself, A/2 and B/2 will become minimum, this one will be the top one's coordinates Why did you do this, so anything from the bread Less than zero A is less than zero In which case will less than zero come? Less than zero will come in this case That these two rectangles are not intersecting either If our rectangles are such that they never intersect So if we take the minimum of this one and the minimum of this one, then obviously minus tu will come, meaning this will come smaller than zero because these two will intersect at some point. If it is not there, then the combined area between these two will never come, otherwise it is less than zero, meaning it is not intersecting its own, it is not intersecting, then it is not intersecting any common area, otherwise it is common. We will not mine the area, so we have taken both of them as zero. If you become zero in zero then our answer will be these two which are never intersecting and if there is any actual answer then we will return ours, then this is our simple. If you have any problem then yes, this is absolutely accepted answer. If you like the video then like the video, subscribe the channel and if you have any doubt then please mention it in the comment box. We are always present to solve your doubt. Thank you so much. Mach
Rectangle Area
rectangle-area
Given the coordinates of two **rectilinear** rectangles in a 2D plane, return _the total area covered by the two rectangles_. The first rectangle is defined by its **bottom-left** corner `(ax1, ay1)` and its **top-right** corner `(ax2, ay2)`. The second rectangle is defined by its **bottom-left** corner `(bx1, by1)` and its **top-right** corner `(bx2, by2)`. **Example 1:** **Input:** ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2 **Output:** 45 **Example 2:** **Input:** ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2 **Output:** 16 **Constraints:** * `-104 <= ax1 <= ax2 <= 104` * `-104 <= ay1 <= ay2 <= 104` * `-104 <= bx1 <= bx2 <= 104` * `-104 <= by1 <= by2 <= 104`
null
Math,Geometry
Medium
866
739
foreign hello everyone and welcome back to another video So today we're going to be sewing the leaf code question 739 daily temperatures cool so we're going to be given an area of integers called temperatures and they represent the daily temperatures okay so what we need to do is we return an array called answer where answer I is the number of days you have to wait after the ith day to get a warmer temperature so what does that mean so very simply let's say at Day Zero I have a temperature of 73. essentially the question is asking us how many more days do I have to wait after day Zero for getting a temperature greater than 73. so in this case I have to wait one day right as it says here and that is 74 right so the next day has a temperature of 74 which obviously is greater than 73. cool so let's look at another example so let's say I'm at 75 so that's day number zero one two so day number 2 and over here I need to see how many more days until I have a temperature greater than 75 so that's one day that's two days that's three days and finally that's four days right so 76 is the only day that is greater than 75 so it takes us four days to have a temperature above 75 okay so let's end one last condition so if there's no future day for which this is possible keep the answer zero okay so let's actually see how so in this case we'll look at 76 sorry so 76 um there's no day after that day with a temperature greater than 76 same for 73 right since it's the last day so both of those just have a zero cool okay so what I want to do or what I usually do with these type of questions before I can solve them is I kind of look at some basic conditions that we have right so what is one very simple condition okay so let's say I have it in ascending order cool so one two three that's some example so what is the result going to look like well at Day Zero it takes us one day to get a higher temperature than one over the same over here and same over here right so if it's in ascending order the answer is just going to be all once right we just need to wait one day so this is going to be one simple solution right what we could do is we iterate through each of the values and then we just iterate through all the remaining values to see until we get a number greater than the value itself so we're at one we look at all the numbers after that index and see if whatever the first number is which is greater than one now in this case it is always going to be the first number right so in that case that is the time complexity of this Brute Force solution is just going to be Big O of n now obviously it is approved for a solution it is not always going to work so let's look at the opposite condition where we have descending number so three two and one now what is the result going to look like for this so it's actually just going to be all zeros and the reason for that is because there is no date that's going to come after a certain day with a higher temperature so I'm at the day at day 0 with temperature three and since it is in descending order there's going to be no day after it which has a temperature that is greater than three right so it's just going to be all zeros so in this case our Brute Force solution is going to be N squared because we have to check all the numbers all the N numbers after the number itself so this is going to be a time complexity of Big O of N squared so this is why the brute first solution is bad okay so now let's actually look at another condition um and let's look at this okay so I'm not going to give you the final answer but I'll kind of build up to it okay so let's say I have three two one and I have a number 10 Okay so obviously in this case just by looking at it the answer is it's going to be the number of days I am away from 10 because everything until year is in descending order right so that's the basic idea so let's look at our setup for this so I'm going to have result array and this is going to be all um or let's just leave it all blank for now okay so that is how it's going to look for now and now I'm actually going to keep track of one more kind of area okay now I'm not going to tell you what data structure it is we'll kind of build up onto it but for now let's just say it's some sort of area okay and I'll just call it to check okay so what is this going to uh contain so this is going to contain all the numbers that I want to check right so essentially so first I have the number three and now do I know the answer for three so do I know what the next answer at the index 0 is going to be well I don't so since I don't I'm going to keep track of it into check okay so I'm gonna have the number three and I'm going to have its index which is going to be the index 0. now why do I need to keep track of index so very simply uh the reason I'm keeping track of the index is because that way I can find the distance right so let's say I'm comparing index 0 to the index 10. and the distance is going to be 10 minus 0 which is 10. so what that means is it takes 10 days to get a hotter temperature so that's why I'm keeping track of the index cool so I have the value and I have the index so now let's move on to the next number two so before just adding the number two to our list over here what I'm essentially going to do is I'm going to check if the number two is greater than any of the values in our list okay and if it is well that means we found an answer right so over here I compare two to the number three well it's not greater so in that case I'm just going to add it so that means I don't have a answer yet so 2 and its index is one okay so let's move on so now I'm at the number of one okay so it's 1 greater than three it's not is one greater than two again it's not right so 1 at the index two cool but now things kind of change so I have the number 10 okay so now I have this number 10. so is 10 greater than three it is so now that means I have a answer right so I finally found a number that is greater than the number three and I need to find how many days it took to get there so 10 is at the index 3 and 3 is at the index 0. so what I do for finding the number of days is I just find the difference between the indices so three minus 0 is the number three now where do I put this result so I put the result at the index zero okay that's it so this has a value of three so now I'm done with this so I don't need to check it anymore so I'm going to pop it out I'm going to remove it okay so now same thing 10 is greater than 2 as well okay so what I'm going to do what am I going to do over here so same thing find the distance so the distance here is 2 so I remove this as well and finally over here again 10 is greater than 1 find the distance is one and that's it so now this is going to be a full duration but we have one small thing in this thing we did not put a value for this so well one simple thing we can do is the loss value this is always going to be zero but now this is not the best solution so just quick detour what we do you know actually is we can just set all the results to have a value of zero in the beginning and if they have to be changed they're going to be changed that's it like how we change them right now okay so just look at the condition three two one okay so now in my two checklist I'm first going to have the number three then I'm going to have the number two and then I'm going to have the number one and I'm not I don't actually make any changes because there is no number that comes after that is greater so in this case the result stays untouched all zeros okay so that is one kind of thing right so all the results are going to be uh with a value zero so now we actually come up with a small thing which is how exactly do we come up so this two check array how do we add and remove values right so what we did is we had so I'm not writing the index just for you know making it simple so I have the numbers three two and one right and then what I did is I removed the numbers from left to right so this is one very important thing to notice that all the numbers are going to be in decrease in order no matter what now why is that so I just want to think about a scenario right so let's say I have the number three then I have the number two and then I have a number one now if I get the number 100 that means that so far that all the numbers before it right which are less than it have already now have the number 100 which is greater than it so they're going to have some sort of answer right so three is good to have some answer this is going to have some answer and so is this so now let's just say we have more temperatures so let's say now I have the temperature 100. now let's say I have the temperature 101. now if I have this temperature that means that for the day where I had the temperature 100 I already have an answer so this is also not going to exist okay so this kind of continues so now let's say I have 102 then I have a hundred and three right so in this case as well if I have 102 that means 101 has an answer right if I have a 103 102 as an answer okay so no matter what this two check array is always going to be in descending order but so this is where it kind of becomes important so this is a stat or is this a queue right so what we did is we popped out at the zero index so this is where it gets kind of important and I think I could best show you that using an example okay so let's say very similar to the previous one but I have something like this uh let's say a 101 uh three four sorry let's do 101 uh and then I have five and then I have three and then I have ten and then I have a 9 and then 200 okay so here's where you get slightly interesting okay so I'll just quickly do the setup to result so how many zeros am I going to have one two three four five six cool so one two three four five six so this is how I initialize it and now I'm gonna have my two check area Okay so this is very good it's important so now I have a number of hundred and one okay 101 at the index zero cool so now I go to the number five well five is obviously not greater than 101 so I'm gonna add it five at the index one so now I have the number three so three at the index two again three is not greater than anything now I have the number 10. so this is where it gets interesting so if I get the number 10 so 10 is going to be less than this number over here okay so let's say if I was comparing them I'd have to compare through all the values over here okay so I have to compare 10 with 1.1 right and obviously 10 is with 1.1 right and obviously 10 is with 1.1 right and obviously 10 is smaller so this stays as it is but 10 is greater than 5 and it is greater than 3. so the values over here do get updated so essentially what I'm trying to say is we're going to go from right to left we're going to move in this direction and essentially why is that important so first I compare 10 to the number 3 okay so now in this case so 0 1 2 3 so 10 is at the index 3 and 10 is greater than three so this has an answer okay so let's update it quickly so at the index 2 we're going to have a answer of one and now this is going to get removed we're going to pop it out so now we have the number five okay so at the number five what do we have so uh 10 is greater than 5 correct so what is this is three minus 1 2 so we update our result this becomes two now we pop this out so now we have the number of hundred and one so 10 is less than 101 so now we can actually stop the entire iteration so let's just for the sake of it let's say we had numbers greater than 101 prior to it so let's say over here we had 999 and before that we had a thousand all those numbers would be to the left of it and it would not matter we don't even need to check it right like I showed you earlier this is in decreasing order so it does not matter so essentially we're going to move from right to left and this is going to make our two check list a stack and more specifically we call this a monotonic stack and why is it monotonic well monotonic means it is in One Direction it is either all decreasing or all increasing in this case it is a monotonic decrease in stack because the values decrease okay and kind of like I showed it earlier right because if in between you have any number that goes up right if it increases then in that case all the numbers that were greater than it or sorry less than it are going to go away that's it okay so now let's continue this for example right so I updated screw values now I'm at the number nine so I append the number nine because nine is non greater than 101. to 9 at index four now I'm at the number 200 okay so is that index five and I do the same thing so 200 is greater than 9 so I continue so over here what do I end up with so 200 is greater than 9 so what's the distance is one five minus four one zero one two three four so over here we update the value one and now we remove this so now at 101 through 101 is less than 200 so this gets updated as well so this becomes 5. that's it okay so this is essentially how it's going to work right so just for the sake of it let's say over here I had the number 300. so let's add the extra value to the result and over here 300 comma zero would be what we have right and over here the 300 is going to stay as it is it's going to be untouched right and after this we append 200 comma 5 and both of these are not going to end up being changing they're going to stay as it is okay well this is going to become six now but yeah so that's basically the idea right so it's always going to be decreasing order that is why it's called a monotonic decreasing so yeah you can you kind of use this idea for different questions as well so anyways let's just look at what the code of this looks like oh let me just reset it okay so let's see so essentially what we're going to do over here is I'll just show you step by step so the first thing is we're going to make our results array okay so in our results array like I said it's just going to be all zeros to start off with so what is the length effects into the same length as temperatures over here okay so now we need to also have our two check values essentially this is like I said so now what I'm going to do is I'm going to iterate through this so for index comma temperature in so I'm just going to enumerate if you don't know what that numerator does essentially gives you the index and the corresponding value okay so what do I do so first I need to check all the values one by one and I need to pop them out and update the values if this current temperature is greater than whatever is inside of two check okay and now remember I'm gonna pop out the values from right to left okay so let's do that so let's first um we're going to have condition so first we're going to check if two check is not empty and if that's the case we're going to go to tune check we're going to get its topmost value or like I said the rightmost value if that helps and we're going to get the zeroth index of that now the reason for that is because we're storing the temperature comma index okay so we get the temperature and we're going to make sure that the current temp temperature is at two check now if that is the case we pop that value out okay so to check dot pot okay pop it out you're gonna get it's uh or let's just call this so let's call this stack um temperature and this is going to be a stack uh index okay so we have these values now and we're going to update it in our result so in the result we go to the stack index and we give it the distance essentially and the distance is going to be from the current index to whatever the stack index is that's it so we've updated our result that way okay and now one more thing we have to do is we need to add the current element to our stack and the way we're going to do that is we're going to give the temperature comma and after this we're just going to return our result and that should be it so if you submit this our solution should get accepted so yeah thanks a lot for watching guys and do let me know if you have any questions foreign
Daily Temperatures
daily-temperatures
Given an array of integers `temperatures` represents the daily temperatures, return _an array_ `answer` _such that_ `answer[i]` _is the number of days you have to wait after the_ `ith` _day to get a warmer temperature_. If there is no future day for which this is possible, keep `answer[i] == 0` instead. **Example 1:** **Input:** temperatures = \[73,74,75,71,69,72,76,73\] **Output:** \[1,1,4,2,1,1,0,0\] **Example 2:** **Input:** temperatures = \[30,40,50,60\] **Output:** \[1,1,1,0\] **Example 3:** **Input:** temperatures = \[30,60,90\] **Output:** \[1,1,0\] **Constraints:** * `1 <= temperatures.length <= 105` * `30 <= temperatures[i] <= 100`
If the temperature is say, 70 today, then in the future a warmer temperature must be either 71, 72, 73, ..., 99, or 100. We could remember when all of them occur next.
Array,Stack,Monotonic Stack
Medium
496,937
141
hey guys in this video i'll be going through how to solve leak code question 141 called linked list cycle so in this question we're going to be given the head of a linked list and our task is to determine if there is a cycle in the list um so in this example this would be an example where there is a cycle because this last node points back to another node in the list so this will always cycle through here and then we're going to be given one kind of constraint to the question where we're asked to solve with constant memory so the approach to take with this question is going to be to use two iterators to essentially like loop through the list i've drawn an example here so we're going to have one iterator um that's a red and it's going to be like our slow iterator so it'll only move one space at a time and then we'll have the blue one be a fast iterator and that's going to actually move two spaces at a time and then using this these two will be able to see if there's a cycle and i'll show you how um so say to start the red one moves one and the blue one moves too um that'll be the first move every time obviously and then we can tell if there's a cycle in here by if the blue one ever catches up to the red one or if the blue one is ever equal to the red one so if we just continue with this example blue would move two red would move one again blue would move two get back to there red would move one blue would move two but we wouldn't compare yet and red would move again blue would move two again and get back to the starting node and then red would move one and they would be equal and we could tell right here that there's a cycle so why does this work so the blue will always start out ahead of the red and so if there's a cycle we can think of this as like the blue is chasing the red until it catches it and because the blue is only moving two at a time we can see that it'll always catch the red it'll never like pass it without um hitting it so imagine like if the red is only a head by one space the red would move one and then the blue would move two and then they would hit each other and we would say that there's a cycle or if the red is ahead by two spaces then the red would move by one blue would move by two and then we can see it's only behind by one now and we just proved that these will intersect on the next move um so if there is that cycle blue will always catch the red um on exactly the same node and then if there's not the cycle we'll be able to tell that by the fact that the fast node will eventually hit a null pointer okay so to actually start coding this we're gonna have our two iterators and i'll just call them fast and slow and they're both going to start at the head of our list node so then we'll do a while loop and we're going to do while fast is not equal to null pointer because um fast will be the first one to encounter a null pointer if it's there so we're gonna do slow is equal to slow next which moves the slow pointer one as we did in the example and then fast is going to be equal to fast next so this one is moving two every time um and then since we're moving this two every time we'll also have to check that the fast um next pointer is not null because if this was null then this would give us a run time error where we're trying to access next like this next on a null pointer and then if this condition is met obviously there's a null pointer at the end of our list and so the condition is going to be false because there's no cycle um so we can check if this is if these are equal to each other then we want to return true because there is that cycle and then if we make it out of our while loop meaning we encountered a null pointer then we want to return false and we can run this code and it works so starting with the space complexity for our analysis of this um we did meet the specification that it's constant space because we're only storing these two pointers right here so we can just say constant space and then for time complexity this is going to loop through up to i guess two n um times because it could take like we saw in the example two times around the list before the nodes intersect so it would be 2n but with time complexity or complexities in general we always just remove the constants to reduce to o of n time all right i hope that this was helpful for you guys and thank you for watching
Linked List Cycle
linked-list-cycle
Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. Return `true` _if there is a cycle in the linked list_. Otherwise, return `false`. **Example 1:** **Input:** head = \[3,2,0,-4\], pos = 1 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). **Example 2:** **Input:** head = \[1,2\], pos = 0 **Output:** true **Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node. **Example 3:** **Input:** head = \[1\], pos = -1 **Output:** false **Explanation:** There is no cycle in the linked list. **Constraints:** * The number of the nodes in the list is in the range `[0, 104]`. * `-105 <= Node.val <= 105` * `pos` is `-1` or a **valid index** in the linked-list. **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory?
null
Hash Table,Linked List,Two Pointers
Easy
142,202
153
hey there everyone welcome back to lead coding i am your host faraz and we are solving the questions from binary search i uploaded an assignment for binary search and there were five questions in the assignment it was the first assignment of binary search and this is the third question of that assignment if you haven't tried this by yourself please make sure that you first give it a try and if you're not able to solve or if you think that solution is not optimized enough you can continue watching this video all right so let us first read the problem statement so we are given a sorted array and that sorted array is rotated so basically this is the sorted array 0 1 2 3 4 5 6 7 and if it is rotated 4 times in one rotation the last element will come to the front so in the second rotation the last element that is six will come to the front so this is rotated four times that is why the array looks like this zero one two then four five six seven okay so basically a rotation is let's say uh if we have this one two three four and if we do one rotation it means that this element should come to first position so after one rotation it will look something like this four one two three okay and if i try to rotate it one more time then again the same thing will happen the last element will come to the front so it will be three four one two okay so what will happen uh after the four rotations we will get the same array back that is one two three four all right so once we are clear with this so we take an example of the rotated array here's the rotated array four five six seven zero one two so we can see something we can see that the first part is sorted so it is in increasing order and the second part is also sorted it is in increasing order so it could be considered as two sorted increasing order areas right okay so now in this we have to find the minimum element right return the minimum element of this array we have to return basically this the first element of the second part okay this is the second part second rotated area this is the first rotated array and we have to return the minimum element of the second part okay so um it might be possible that we have rotated it seven number of times in this example and we will get back the same array so in these type of cases what i will do is i will just compare the first and the last element okay so if nums of zero if it is um is smaller than num start back it means the array is not rotated or it might be possible that it is rotated many number of times and we get back the same array so in this case the first element will be smaller than the last element okay in all the other cases the first element will be larger than the last element so in this case i will simply return the first element that is the answer number of 0 is the answer okay let me just plot a graph for this as well so it is always good to practice binary search questions using graphs here i have this graph this is the graph for the first part it is an increasing order and this is the smallest element of the first part that is 4 this is the smallest element and the second part will start something like this from even below and the last element is 2 so this will be 2 and this is 0 so we have to find this element right this is the smallest element you have to find this one so this is the total graph of this array 4 5 6 7 then it is 0 1 2 like this now in this we can simply notice that the last element that is 2 it is always smaller than the first element that is 4 in case if it is rotated otherwise this condition will come when numbers of 0 is smaller than nums dot back the last element in this case the array is not rotated and hence we will return the first element if nums.size is if nums.size is if nums.size is um equal to one then in this case i can simply return numbers of zero um can the size of numbers be zero as well no it cannot be zero so okay all right so now let us move on to the binary search part so we are taking as usual two pointers the start pointer pointing to zero and the end pointer point the last element that is num store size -1 num store size -1 num store size -1 and i will run a while loop while s is smaller than equal to n okay then i will find the middle element mid is equal to s plus start n minus star divided by 2 why this we can even take it as s plus n divided by 2 but sometimes that gives us the integer overflow error so to avoid that you can always write it like this mathematically both are same so now i have the middle element okay so let me just plot the graph again this is the graph right this is the graph and this is the graph so this is the first part this is the second part both these parts are sorted and this element is the smallest one this one marked with the green this is the smallest element we have to find this okay now first of all we find the middle element and the middle element could be in the first region or it could be in the second region as well if it is in the first region then the value at this middle element that is array of m or nums of m this value will be greater than the starting uh value of the array that is nums of 0 or area of 0 okay area of 0. so this value array of m will be greater than a of 0 then we will know that we are in the first part what about the second part so array of m in the second part if m is in the second part then this value array of m will be smaller than the first value of the array that error of zero so in that case we will know that we are in the second part so first of all let us figure out that in which part we are we know that we are going to find our answer in the second part but first of all let us figure out in which part we are standing in which part of m is lying okay so if nums of m is greater than or equal to nums of zero in this case we are lying in the first part why uh did i take the equal to sign because it might be possible that uh our mid is also zero okay i might be zero so that's why we are taking this so in this case what do we need to go to the second part because we are sure that we will find our answer in the second part actually the answer is the first element of the second part so we need to go to the right side and how do we go to the right side in the binary search we go it using the s pointer so s is equal to m plus one simple otherwise we are sure that we are in the second part okay we are sure that m is in the second part so maybe m is somewhere here or maybe m is this element as well okay maybe m is the answer so in that case what i will do is answer is equal to minimum of answer comma um nums of m and n is equal to mid minus 1 finally i will written the answer after the while loop let me make an answer here and answer initializing it with the int max value so that i can minimize it and is equal to m minus 1 and let us try to run this and let us see if there are any compilation errors it is giving us correct answer for this test case let me just submit this now okay it got accepted so the logic is simple as usual in the binary search the first thing that we do is to find out the middle element okay so let me just clean this so this is the graph okay this is the first element this is the last element the first thing that we do in binary search is to find out the middle element okay so the middle element it might lie somewhere here or it might lie in the second region as well if it is in the first region uh we do not care about it we simply move on to the right side why because we know that the answer lie in the second region this is the answer we need to find out the smallest element of the second region this is the first region so we don't care about it we just simply move to the right side so we do s is equal to m plus 1 and how do we know that we are in the first region so we compare the first element of the array that is uh nums of 0 and this is nums of m we compare these two elements so if nums of m is greater than numbers of zero we are in the first region what about the second region so if m is in the second region then nums of m is smaller than the first element okay this we know uh because the array is rotated so if numbers of m is smaller than the first element of the array numbers of zero then that case we lie in the second region so what to do when we are in the second region so in that case it might be possible that we are at the right location so maybe we are standing here or maybe we are standing somewhere here so in that case i will try to find the minimum answer so answer is equal to minimum faster common numbers of mid it might be possible that we are at the right location so that is why we are trying to minimize the answer and maybe we are at this location here so we will try to move to the left side so to move to the left side we use n is equal to m minus 1. this is as simple as that okay this was a really simple problem from binary search there is another version of this problem that is search in a rotated array okay that problem is exactly on the similar lines you have to search an element target element uh in a sorted array in that question also you first try to figure out that in which region do you like the first region of the second region and then accordingly you source those elements all right so this is it for the problem if you understand the solution make sure to hit that like button and leave your comments also do subscribe to the channel and press the bell icon if you don't want to miss out any notifications for the future videos thank you
Find Minimum in Rotated Sorted Array
find-minimum-in-rotated-sorted-array
Suppose an array of length `n` sorted in ascending order is **rotated** between `1` and `n` times. For example, the array `nums = [0,1,2,4,5,6,7]` might become: * `[4,5,6,7,0,1,2]` if it was rotated `4` times. * `[0,1,2,4,5,6,7]` if it was rotated `7` times. Notice that **rotating** an array `[a[0], a[1], a[2], ..., a[n-1]]` 1 time results in the array `[a[n-1], a[0], a[1], a[2], ..., a[n-2]]`. Given the sorted rotated array `nums` of **unique** elements, return _the minimum element of this array_. You must write an algorithm that runs in `O(log n) time.` **Example 1:** **Input:** nums = \[3,4,5,1,2\] **Output:** 1 **Explanation:** The original array was \[1,2,3,4,5\] rotated 3 times. **Example 2:** **Input:** nums = \[4,5,6,7,0,1,2\] **Output:** 0 **Explanation:** The original array was \[0,1,2,4,5,6,7\] and it was rotated 4 times. **Example 3:** **Input:** nums = \[11,13,15,17\] **Output:** 11 **Explanation:** The original array was \[11,13,15,17\] and it was rotated 4 times. **Constraints:** * `n == nums.length` * `1 <= n <= 5000` * `-5000 <= nums[i] <= 5000` * All the integers of `nums` are **unique**. * `nums` is sorted and rotated between `1` and `n` times.
Array was originally in ascending order. Now that the array is rotated, there would be a point in the array where there is a small deflection from the increasing sequence. eg. The array would be something like [4, 5, 6, 7, 0, 1, 2]. You can divide the search space into two and see which direction to go. Can you think of an algorithm which has O(logN) search complexity? All the elements to the left of inflection point > first element of the array. All the elements to the right of inflection point < first element of the array.
Array,Binary Search
Medium
33,154
576
hello hi guys good morning welcome back to the new video in this problem out of boundary pairs now if you have done this problem and if you think it's a easy problem then for sure you have not done this problem because there is we go on from very scratch like region memorization bottom up and all that stuff you will go from Super basic but if you think it's actually medium no I think okay maybe you think that but actually it's a medium hard considering you go on to the optimization level as well memorization will actually be easy because we have seen many problems like that but it's a 3D memo like improvised bottom up which actually is the trickiest question or trickiest portion in bottom of D cool and yeah just a quick thing um no matter what if you are in college if you're working like if you're working and your life is already done if you in college please enjoy as much as possible in those four years or 5 years whatsoever in college after that it will be insanely tough with that let's start with the problem sa um boundary like out of boundary points is it says that you are given a m cross n grid with balls now it's just one ball not two um the ball is initially at the position start row comma start column so just a quick glance that I will be given M comma n m is the number of rows n is the number of columns it's a matrix and I will be start row and start column okay it is a 0 comma 0 from where in what point of the Matrix I'm starting off it's a 0a 0 great now it also says one variable as maximum number of moves that how many maximum number of moves I can actually do so uh what it mean and what he wants from that maximum moves he want that okay I can allowed I'm allowed to move the ball to one of the four adjacent cells which means if I am let's say if this is a matrix I am at this cell in one move I can either move to up right left or down this is a four possible options for me to move my ball and uh and also I can move out of the grid also cool now you can apply at most maximum of moves to the wall which means maximum moves is the limit which means I can apply these number of moves to my ball and we have given these integers which I have already showed you we have to return the number of paths to move the ball out of the grid boundary we have to return the number of paths to move the ball again I want the number of paths My ultimate aim is to move the ball out of the grid boundary for that I want to find the number of paths and for sure it can be very large so give me mod7 let's see the example statement what he wants okay moves are two we saw it's a 2 cross two grid and starting from 0 so I start off from this set in one move I in see in one move I can go up left right or down as I go up or left I will go out of my grid and that's what he wanted so there are two ways okay when I was starting from here itself there are two ways to actually go out of my grid so I'll increase my answer by two okay my answer is because number of paths will actually increase by two okay now in the next move for sure it will if it is going if it has gone out it can never come back as it's not okay I'll go out and then come back and then F go out no we'll just only go out okay that's it ball is gone out of the Matrix now for the possibilities when the ball is inside the Matrix okay ball could be gone on the right side or it had gone on the down okay if it gone on the right side again it is the okay in the one move it has gone right now in the second move he can go up right left or down but Aran left was already visited I want paths which means let's say let's imagine your ball again I'm just show I'm just tracing One path for my ball so my ball can go this so you saw my ball is tracing a path itself so it is a path which means you can see if I go left I can also come right also don't confuse it with the BFS okay if I have visited a cell I will not visit that again it's a path which means if I go like this okay now see you were actually here your number of paths your number of moves were actually okay two like okay right now I can do one move and then I can do another move so as you went here that which means okay you were starting here then you right and then you came left then you could have come down also so right left down it's one path and okay from this ball down it's one path so there are two paths for it so okay even if I have gone through that I still can visit back so I can also go backwards then down and then for sure right and up now right and up is just another two moves for sure sorry another uh two paths for me to go out okay I'll add two in my answer and the other possibility we saw that if what if it had gone down again I will have two outs so I will have okay it can go out two outs now your number of moves are exhausted because you have okay one move was done coming here another move you have done okay either going out or down which means in the next move in the next for him after he has completed his second move he would be either out or on these cells that's it now again after it is your question is done so you saw that you were able to achieve six out paths which means the path which into moves at Mass to moves the number of paths from which I can actually reach out so it's six now let's see with the super Again by this example itself you could have actually figured out that what's what can happen so in as simple as that um if we plot it so we saw that we had we were at one point and we had two options like all we have four options we can go right down left or up and as I go out I know okay that is one path for me one valid path for me as I go out again in early cases you were see okay as I go out it's not a valid but for the question here right here as I go out it's valid path okay great now what if my moves are exhausted okay as soon as my moves are exhausted I'll simply say okay that is completely done which means in the example as you saw earlier if your moves are exhausted which means if your remaining moves become zero which will become zero after this operation so you can easily say y you have to return a zero itself because there are no valid moves remaining so for short there will be no paths also for that move and ultimately um what all options we have four options we if I am standing at I and J this is I comma J I can move to I + 1A J I can move to i - 1 comma J I can + 1A J I can move to i - 1 comma J I can + 1A J I can move to i - 1 comma J I can move to I comma J + 1 and I can move to I comma J + 1 and I can move to I comma J + 1 and I can move to i - i j minus one these are the four i - i j minus one these are the four i - i j minus one these are the four options which I have I simply try all these four options so my code looks as simple as that if I reach out which means my I is M my J is n i less than Z J is less than Z which means I'm out of my gr then I simply return a one because that's a one valid path and for sure as you saw if my remaining moves although Maxum moves is the moves which you have remaining if this becomes zero simply a zero and for sure you can try recursively for all the possible cases okay you can try that you can try to go to i-1a j i + 1 comma j i can try to go to i-1a j i + 1 comma j i can try to go to i-1a j i + 1 comma j i comma J +1 and I comma Jus one these are comma J +1 and I comma Jus one these are comma J +1 and I comma Jus one these are four option which you can try now if you see off that's okay for one ball at a location I have four options now to figure out although from here itself you can figure the time complexity out but for just a general case without even writing the code if you want to figure out the complexity It's about okay if for a one ball you have four options and it will keep on going it will if it will keep on having four options for the entire tree of what depth of the depth number of moves because I was doing okay this I have four options for one move now as soon as the ball reaches at these points again for all these balls which are this and this I will again have four options because of four like four directions right four is the directions and this was okay one move now next move again so at every move I have four options so four Power number of maximum number of moves is the complexity is the for time complexity for us and for sure the depth entire tree depth is maximum number of moves which will for sure not work 4 50 um it will never work so you are screwed up no you are not if we see and look back for sure it's a recursion maybe we can memorize but we have to prove that it can be memorized so what we could do is okay if we was if we were at this cell let's imagine we are we were at cell 0 number of moves remaining are five okay now as soon as again it can go out I can increase my answer by one but if it stays in okay one option is it came down which means this cell one option is it came right which means this cell again he is now at cell 1 Comm 0 now the possibility the number of moves remaining for him is four now if he is at this cell again he is at 0a 1 number of moves remaining are four again when he can go up so answer will increase by one he can go left answer will increase by one but still he has all these three options again open to him so again for three options again I could not write all three up because of space but if I just show you two options so okay it is up it is right it is down so okay um I can say up one I wrote here right one I wrote here down one you can just imagine there will be one more one which is down one same way for this it can be right down and left same way I could not write all three but yeah I'll just show you that for right for this left one okay um I want to have at this c yeah so I will be having that okay uh left one this is one down one which is this is one and right one will also be there now if I just again come back and ask you now it is a new problem saying you are starting from 0 comma 0 and number of moves maximum number of moves remaining for you is three same 1A 1 Maxim moves remaining for you is three same 1 Maxim moves remaining for you is three and same 0 Maxim so you see this is the two same sub problem for which you are calling the recursion again so for both of them the entire recur recursive tree will keep on iterating again and again so rather you can just memorize that now memorizing is simply nothing but you know that you have i j and all and your this remaining number of moves so you need to have these three states because these are States on which your entire tree is actually built right from this number of mes remaining from this coordinate number ofes remaining so your coordinate i j and number of moves remaining is actually the states of your DP so I'll simply do the same exact same thing which I showed above it's just I'll now memorize that so I have initialized globally my 3D DP I know because one state is M other state is n other state is my max number of moves that is my state of my DP I initialized my entire DP with a value of minus1 now I can simply go and solve a simple recursive function solve from this specific start index again um this here it was the start and if you remember in the basic code earlier we had these like we had the start okay I'll start from I comma J although the variable in the question is something else but you actually using I and J so it's much more easier so yeah you'll start off from I comma J do you pass okay I have start from I comma J and my number of moves remaining are maximum number of moves now um simple reion the exact same base condition if you reaches if you reach out of the grid which means if I is M J is n i is z J is z simply return a one because that's a one possible path if your remaining moves become zero simply return a zero this is a simple memorized step that okay DP of i j and remaining moves if it is not equal minus one then simply return that DP State value which you have stored this is exact same again make sure to do a modular because the problem was saying for the modular also so I just simply did a module also at every step that is a basic operation but exact same thing I + 1A J i-1 comma J IA J +1 I comma J + 1A J i-1 comma J IA J +1 I comma J + 1A J i-1 comma J IA J +1 I comma J minus1 with the moves remaining moves are decreased because one move I have done above and simply store that in your DP and that's how by simple converting obv Bally simply adding these two conditions this and this return condition you have simply memorized that and simply return the answer now you know your DB State have simple i j and remaining moves so complexity will also be m n and remaining number of moves which is the maximum number of moves and space Also is same now okay that up till so far although I'll say up till so far it's a medium problem because it's a very standard DP problem but now I'll ask you can you improvise that earlier so far improvisation in DP we had seen only in a 2d DP where you had just I and J and it was very easy to visualize also but now I am saying can you improvise that now it's a 3D DP you know that you have to convert that 3D DP to a bottom of DP and that's actually going to be tricky but again we will see that firstly converting that to bottom up and then we will see that how we can improvise that so now to convert the same thing to bottom up we will actually have to trace back the same example again you might see in many videos we see that it's very easy to con from top down to bottom up yeah it is true but in some problems you cannot directly convert your top down to bottom up so you have to figure out again you because see right now you will just see that you are accessing all these so you are trying to have remaining moves from remaining moves minus one you are actually trying to grab that value so we will try to do the same thing we will try to find the answer for remaining moves plus one from remaining moves that's as simple as that because here it was moves minus one so I simply said okay remaining moves plus one and remaining moves I'll try to do the same thing again whenever you are converting to bottom up make sure that you take the reference of top down parallell right okay cool but your base case will change because you know that you cannot go out in actually a grid because it's a bottom up so it's a matrix you cannot go out it's not a recursive case that it will try to go out and then you can also handle that but yeah you will have to handle that if I'm inside like before going out itself I know okay now I now at this point I could have gone out so before going that which means if I am at the borders if I at the borders then I know in the next move in if I know okay I'm at these borders at these location so I know for sure in the current move I have a possibility to go out so I'll use that knowledge which I have that okay if I'm at the border I can go out rather than actually going out of my Matrix and placing if conditions I will actually say if I am at the border I know that I could have gone out so if I am at the border I could have gone out like this and like this these are the possibilities for me to go out I'll just handle these possibilities at the border itself now let's see that how we can do it so again uh firstly if I am starting from again we'll just Trace back and see but we know that our rough structure will look something like this only right if we have a rem like remaining move we will have be accessing remaining move minus one but I as I mentioned I will be doing a remaining move plus one here because it's a one indexed right uh because I have made my DP one indexed uh to actually make my you'll understand but yeah it's remaining move plus one and it's remaining move right okay cool no worries let's come back now we just Trace back a little bit that if I'm standing here firstly I will initialize something I have to initialize my DP as you saw in a base case you usually initialize your DP with something initial values of DP usually you show the zero values by default but something itself needs to be initialized we don't know what that going to be and also I know that I have to I know I'm currently at I comma j i comma J and the remaining number of moves are five for me but you saw you are building bottom up so I'll say okay I'm currently at the first move which I can perform that is okay because I'm building bottom up so I'll go okay from move one then move two then move three and so on and so forth now if I am oh firstly I starting from 0 comma 0 I am actually at the borders how I know I at the border to Simply know if you are at the border or not that your I is it a zero your I is it a again M minus one your J is it a zero your J is it a m n minus one if any of this case is there which means you are at the border now for the same case okay you will see okay my I is actually a zero so which means I am at I will have one of the outs which means I can go out in one directions and I saw my J is also zero which means I can go out in other direction also okay I know that from this base from this cell I can go out in two directions but right now you just saw that I'm just saying I can go out in just two directions that's it for this cell only because it's a first move which I'm having again that can be confusing because we going to see a 3D DP bottom up approach which actually is tricky so please be with me again it's not a medium considering you actually go on to bottom up and people don't go it's actually tricky to make you understand and to understand also now but as we go on to next state which is the move two what will happen we will have to again in move two I need to know that in how many ways I can REO okay if I'm reaching to this specific point if I'm reaching this specific point I know I remember that okay from move one I can go out that is obvious but I can also go to move I can also go to some other cells which is this cell so I have to make sure in how many ways I can come here now it is obviously that okay in move to in just one number of way you can come here and that is from above now Aran why is that even needed why you want to know the count of number of ways to come to this location it is because that if you remember that you can come here either via up or bya right how if you are in the again in the move in the number of in the second move you were at this sorry in after the first move which means at the second move you were about to do the second move you were at this location now when you were about to do the second move you were at this location right if you can see the tree that is like this now you know that after the second move which means in the third move he can go here which means to come at this specific cell as I showed you repeating problem I have two ways now how that two is useful is right now how that two is useful is what if now this two represents that to reach here in the third move I have two ways now if you remember I wanted to know ultimate M MX is to find the count of path I'm saying what if this specific value let's say DP of I comma J right if this would have been a two as we have shown here now what this two would have said again I'm just saying hypothetically let's say if this would have been a two hypothetically it would say that to reach here in third move I have two ways that can be any two ways and that I am kind of adding up from my parents which is from the second move he will propagate the value and say that from me I can give one move to my child so this will give one possibility to his child which is this specific value this parent will give one possib one possibility to his child which is this specific value so he will give one saying okay one move you can take from me he will give one move you can take from me so he has got two moves now I am saying that I can reach at this specific cell in two ways now what will be the answer which he will contribute if it is just okay if as you remember he contributed only one and one so I incremented my answer okay number of paths were actually two but now if I know I can reach here in two ways so one of the ones will give two and other way other path will give me other two ways so in total my answer will be nothing but two the like number of face which is two into the actual path which is two so I can easily say that for I know number of ways so number of phase to actually reach at this point at this last Point let me change the color to reach at this last point is two so to go left I will have two paths because the number of ways to reach here are two to go right I will have two parts because number of each ways to reach here were two so this will help me to give the count of actual parts now coming on back again if you have not understood this please plot this and I'll repeat once again for the folks who have actually got this can you can skip this part but I'll repeat once again very concisely how actually it happens so initially in the very beginning I will populate my base value which means the base case saying DP of 0 comma first move is a one why it by why I said that is 0a 0 is a starting point and for after like it is a first move which I will I'm about to do now number of ways to reach here is just one this is what this DP State represents that starting point is this 0 it is the first move which is I'm about to do and number of ways to reach here is just one because I'm it's a starting point so I will be standing here only now what will happen is that I will ask him that what is your cell my cell is I comma J let's say in the code I will say it as X comma y right now my cell is X comma y I say check okay if x is a zero X is a n minus one sorry X is a n minus one y is a zero Y is a n minus one if x is zero which means he can contribute by going left outside if xal to m minus1 in down it is in up it is in down he can contribute by going on the left side in the left side um left down and same goes for right he can also go right because it's just one corner right you saw one can have at Max two like at Max two values left right and all that stuff so um just going out I'm saying now uh and same goes for him for up like for this zero I can go up he I can go down and same goes for this that for this zero um he can actually like for this specific zero he can go up and down so just representing that I can go out for every of these possibilities right for every of these possibilities I can go out as I showed you up left down right up so this is I'm just representing that I can go in these directions coming on back I will say that in my first move I know number of ways to reach here is one so outside or above I can go in one way only outside I can go in one way only but I need to also give my child that in how many ways my child could be reaching so I will say Okay firstly I got the answer which I wanted to have then I will say for my other child which means for my four possible Childs again for my four possible Childs here I have only two because of right and down so I'll say okay you could in the next move you could be reaching one way and I'll also say to him he can also reach one way so this value which means DP of 1 comma 0 in the second move will actually be storing one saying that 1 comma 0 in second move I can be I could reach in one way possible here also DP of 0a 1 2 will say it's a one way possible and again before propagating the values to the child I will have to compute the answer for me as a current path which means I in how much I can contribute to the path number of possible paths so I will just say okay I my I is actually nothing but zero sorry my J is nothing but zero which means I am at this specific left border which means I can only go out left like this so for sure if I can go only out so I can contribute my answer with nothing but again that is nothing but I'm contributing my answer with these number of ways which is DP of 1A 0 comma 2 again I added one only in the answer but this is nothing but number of ways to reach here because number of ways to reach here that number of ways I can also go out and the same way I'll add my answer this one is nothing but this specific value itself the this specific value itself will be get will get more clear when you will see that when he has added in the answer he will again give his child that okay you can reach here in me ways plus one way okay I have just one way to reach okay for sure you can reach here okay in these many ways you can reach here in one way and one way now he can say that I can reach here in my third move I can reach here again when I say third move I am saying I'm about to do a third move I can reach here in two ways now if I just represent that as a edge value which means let's say it would have been at Edge like super Edge so as maybe it might have been contributed the answer so it say okay I can reach here in two ways so for sure I can go I because again I have options to say that I can go left I can go right so I'll say that two ways I can reach at this point so for sure two ways will be outside also and two ways will be down also like outside right like outside left and outside down also two ways will be there because my value was two so in my path answer I'll be saying answer plus path now path will be nothing but DP of IG and again like move will also be a like value but answer will be nothing but contributing to GP of I but for all of them like I'll just say check if I equal to Z I = to m-1 J = to 0 J = if I equal to Z I = to m-1 J = to 0 J = if I equal to Z I = to m-1 J = to 0 J = to m-1 because you saw depending upon to m-1 because you saw depending upon to m-1 because you saw depending upon what point it is Al you can also add if conditions many of the if conditions but as I showed you I can have all these possibilities to go out so I have to handle all those possibilities now let's see the code again if you have not understood that I'll say uh can you please go back and draw it by yourself uh a bit more example because again it's a 3D DP bottom up which can be tricky for you cool now the code is as simple that as we explained that first we initialize our DP will remain exactly same it's just that by default value should not be a zero now AR in why is this maximum Value Plus two because you remembered um I was saying that for my uh for my DP of again um this I have taken it as X comma y rather than I comma J because if you remembered my I comma J was my variable itself so I was thinking okay let's take X comma y itself so although I could have modified this to the original start in start point start x coordinate start y coordinate and then used would have used I comma J but I was very lazy for this so I just took as X comma y now coming on back um we'll simply do okay I'll go on to all my moves starting from move one up till the move last move maximum number of moves because you know I was doing okay first move second move third move like this and then for every move I will have to go into the entire Matrix now before propagating the value to my child I will have to first contribute I will have to first find the answer which I can contribute in my path base case as I mentioned this is a start index and the first move I will say I will contribute one now before even starting off which means cont which means propagating the value to my child's child I know every node will have four Childs I will say that can you please contribute the answer which I can give so these are the four cases which I showed you that corner cases like the okay how the answer can only be contributed if you are at the borders of the Matrix so this is the borders of the Matrix right and for sure in at one point of time you can either go to at Max two of these conditions because of the coordinate how the coordinates works it's either X or Y now uh as we mentioned that if we are at the borders we can simply say that whatsoever is the number of ways I can reach here that many number of ways I can also go out so I can simply add these values again that's not a if else that's a if conditions because you remembered I can also go out when my X let's say this was The Matrix so you saw that my I is a zero and my J is also a zero which will contribute going outside contribute so I is z J is z both contributing outside going outside cool now when I have contributed the answer which I could have considering I could have reached here these many number of ways I have to propagate the answer to my child also and I simply will say to my child that bro listen that if I like this is my child which is the which is which will have the next move so I will say to my child bro listen that one thing you can reach again my child let's say I am at this state this specific State now I am this state now my child is this my child is let's say he's pink baby pink now I will tell him that bro can you please find the answer for you and again I'm finding his answer which means his next state which means the next move for him because he will be he will actually be um utilized in the next move so his answer his my child answer will be calculated from top left bottom right this will be my child answer so what I did was again there are two ways to implemented one is that okay you keep contributing the current value which means your parent answer to all the Childs or you see okay let's imagine this as a child which is the pink child and get in the answer from all the possible parents so all the possible parents you get the answer and then when you have got the answer for this specific child this will be used next time as a parent so uh here I'm just using this specific way again this specific way also work that for a parent keep on contributing to all of its child and same way let's say for him as a parent he will contribute this to his child same way it will happen both are actually same it's just a implementation way different now um coming on back that I just say that for my child get all the possible parent values again you will see that it's a move + one and I'm doing a move + one and I'm doing a move + one and I'm doing a move which means this is the current value this is my child which is the upcoming child is nothing but who is coming next and move Plus One will be coming next because you saw I'm going on the move so move Plus One will be coming next which is my child for sure so I will just add all the possible values and again you can only add when you have a valid index that's how a matrix work again you can also put a border Matrix like usually how we if you want if you don't want to deal with these edge cases what we do is we just put in a like border Matrix okay I'll put a 0 but yeah if you don't want it then simply skip it but what will happen with this is I am asking X - 1 y I'm asking x this is I am asking X - 1 y I'm asking x this is I am asking X - 1 y I'm asking x +1 y I'm asking X Y -1 I'm asking X +1 y I'm asking X Y -1 I'm asking X +1 y I'm asking X Y -1 I'm asking X comma y + 1 and ultimately this is my comma y + 1 and ultimately this is my comma y + 1 and ultimately this is my parent and this is my child and that's how I can simply add the number of phase to reach to my child because this number of phas to reach to my child will again let's say to reach to my this specific child number of ways were three so now to actually contribute to my answer which means the path which goes outside here you'll see I can only go out Only One Direction so rather than only in One Direction that I know but I will add a three as just specific this direction and maybe if it was possible to go let's say if this would have been the child and next time he would have come in and let's say for him the value would have been three that in three ways I can come at this point so I would have added three here and three here as the number of phas so my DP value is contributed as the path count you'll see my DP value is contributed as a path count I'm adding answer I'm not doing answer plus one I'm doing answer plus my DP Valu which means number of ways to reach at that point and from that point I can go out okay I can go out and again at Max I can go out in at most two directions and that's how again simply get the answer this will be the cool as simple as that again people will not teach this hands down they will not because it's a very tricky problem but again that's a risky State that's a risk key part which you do that you should not touch these kind of things which is 3D DP bottom optimization people might not and again if you're confused because it there's a high chance if you're confused it's your first 3dp optimization problem or 3D bottom up problem then I'll highly say please go back and watch the video again now simply you can see you can very visually see the improvisation that for just move plus one I'm only using my move as we have seen previously also that okay for DP of x XA y x y + 1 y + 1 that okay for DP of x XA y x y + 1 y + 1 that okay for DP of x XA y x y + 1 y + 1 I'm only using DP of X comma y if that happens you know okay I can actually replace this with two vectors so now I can replace this entire thing with two 2D vectors so I can just say that this DP let's name it as a next DP and this DP is nothing but the DP itself because you saw it's a move plus one which is the child DP or the next DP which is up coming DP so I'll name this as a next DP and this is a DP itself so rather than having a 3D DP I will have two 2D DPS saying one DP will be nothing but the DP itself and other DP will be the next DP you can also name it as a child DP next DP or you can also name it as a child DP with this simply I'll just replace the entire thing I it will not be there and yeah that's it that's the only difference which I will do and thus I'll yeah one difference is I'll also remove this and I only have DP I will also have a next DP being initialized that's the only change I have to do to actually improvise that so you'll see I initialized my DP and next DP and I changed all of these variables I mentioned it became next DP and all these became my DP and I removed the move variable because I know the next DP is the next DP and this is the DP itself with this you saw the time will still remain same but the space is now reduced and that's how you can actually out it I hope that you goodbye take care bye-bye hope that you goodbye take care bye-bye hope that you goodbye take care bye-bye and please make sure that this is again a not a medium problem considering you go on to the improvised bottom of DP approach bye-bye
Out of Boundary Paths
out-of-boundary-paths
There is an `m x n` grid with a ball. The ball is initially at the position `[startRow, startColumn]`. You are allowed to move the ball to one of the four adjacent cells in the grid (possibly out of the grid crossing the grid boundary). You can apply **at most** `maxMove` moves to the ball. Given the five integers `m`, `n`, `maxMove`, `startRow`, `startColumn`, return the number of paths to move the ball out of the grid boundary. Since the answer can be very large, return it **modulo** `109 + 7`. **Example 1:** **Input:** m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 **Output:** 6 **Example 2:** **Input:** m = 1, n = 3, maxMove = 3, startRow = 0, startColumn = 1 **Output:** 12 **Constraints:** * `1 <= m, n <= 50` * `0 <= maxMove <= 50` * `0 <= startRow < m` * `0 <= startColumn < n`
Is traversing every path feasible? There are many possible paths for a small matrix. Try to optimize it. Can we use some space to store the number of paths and update them after every move? One obvious thing: the ball will go out of the boundary only by crossing it. Also, there is only one possible way the ball can go out of the boundary from the boundary cell except for corner cells. From the corner cell, the ball can go out in two different ways. Can you use this thing to solve the problem?
Dynamic Programming
Medium
688,2239
744
hey everyone today we are going to solve the little question find the smallest retargeters and Target so you are given an array of characters letters that is sorted in non-decreasing order and the sorted in non-decreasing order and the sorted in non-decreasing order and the character Target there are at least two different characters in letters return the smallest character in data that is lexical graphically greater than Target if such a character does not exist return the first character in let us so let's see the example so you are given cfj and the target is a output 3 C so because in Python we can compare alphabet and a is our smallest and D is our biggest so in this case uh so we can find a character that is electrical graphically greater than Target so that means C so the discographically greater than means I think a next bigger character I believe so in this case that's why I have to put e c okay so let's jump into the course directly so because uh so we can compare alphabet and letters is sorted in non-decreasing letters is sorted in non-decreasing letters is sorted in non-decreasing order so that means we can use a binary surgery and in the end so left position is a regular return value so okay let's begin so left equals zero and the right equal ranks of uh Red Letters minus one so we initialize two pointers and uh start looping wire left is less than or equal right in the case um mean so calculate the minimum and not to minimum middle pointer so left plus right divided 2. and if letters middle is less than or equal Target in the case I'll move left equal middle plus one else right equal middle minus one and then after that if left position equal length of letters that means um so there's no um like a letter that is uh like uh the discographically algorithm Target so that means we should return first later so let us in the zero and else to put else return letters and the left yeah that's it so let me submit it looks good and the time complexity of this solution should be order of log n where N is a number of elements in the letters list so this is a because this solution probably used by the research to find the next greatest letter so that's why and the space complexity of this solution should be order of one so we use a like a um just a simple variables um left and the right and we don't use extra data structure so that's why space complexity is o1 yeah so that's all I have for you today if you like it please subscribe the channel hit the like button what if your comment I'll see you in the next question
Find Smallest Letter Greater Than Target
network-delay-time
You are given an array of characters `letters` that is sorted in **non-decreasing order**, and a character `target`. There are **at least two different** characters in `letters`. Return _the smallest character in_ `letters` _that is lexicographically greater than_ `target`. If such a character does not exist, return the first character in `letters`. **Example 1:** **Input:** letters = \[ "c ", "f ", "j "\], target = "a " **Output:** "c " **Explanation:** The smallest character that is lexicographically greater than 'a' in letters is 'c'. **Example 2:** **Input:** letters = \[ "c ", "f ", "j "\], target = "c " **Output:** "f " **Explanation:** The smallest character that is lexicographically greater than 'c' in letters is 'f'. **Example 3:** **Input:** letters = \[ "x ", "x ", "y ", "y "\], target = "z " **Output:** "x " **Explanation:** There are no characters in letters that is lexicographically greater than 'z' so we return letters\[0\]. **Constraints:** * `2 <= letters.length <= 104` * `letters[i]` is a lowercase English letter. * `letters` is sorted in **non-decreasing** order. * `letters` contains at least two different characters. * `target` is a lowercase English letter.
We visit each node at some time, and if that time is better than the fastest time we've reached this node, we travel along outgoing edges in sorted order. Alternatively, we could use Dijkstra's algorithm.
Depth-First Search,Breadth-First Search,Graph,Heap (Priority Queue),Shortest Path
Medium
2151,2171
1,673
Hello Pintu Bhaiya Lakhan Question Images Of Shinchen Biwi Three A Question Find The Most Competitive Subsequent Play Store's Dual Air Lines And Positivity Subscribe To Scientist This Sub Sequence Pimples Optimization Element From His Form Is Also Giving Subscription 1234 Work And On Thursday Subscribe to that ball par trend and honey we need to find the morning and to give in the saddest id 2nd test day three to the number in competitive is to-do list number two to two hua tha aadhe luti are saudi are to whatsapp ka Number formation of where to come 820 assistant form like are you respectively 60 command2 command1 512 the five respectively letter this thing maximum set affairs which can be created when did not equal two seater select distic absolutely minimum one which can be used for letter this is the number To Cash Withdrawal Subscribe Welcome To The Volume Minimum Subscribe Now To The Number That In This Scenario Game On Custom After Came1 I Don't Have Any Individual Minimum One Which Were Looking For A Lage The Amazing That I Admin Se Left Door Vishal Bhawan Her Parents For 20 Minutes We Will Bake It In The Oven 200 What Do You Mean By The Way Want To See The First Indexes Religious Book Dengue's Number 99 999 9999 Was Made Then Pick Number After One Only Don't Have any significant foreign tour next minute number specific you right word is the loot take 200 foreign etc will come this meaning of yourself to shut up saved its just what do you looking for a gas to take medicine at smallest number specific sequence in btc 1003 people settings Co institute for this like 2004 to me to do you know how to opposite side is look at distinctive who did this triangle from ok your for all differences can the minimum number in the years evolved and from powder number five govind different from back to two To to now we length k and tried to compare to years and vishwaveer which is the full form of ki log nazar coaches but problems with label also not ki i need to can create first number formations the enter into complaints of values ​​for the completed And looking at his own values ​​for the completed And looking at his own values ​​for the completed And looking at his own highest to recovery to printing hot water commission shampoo during lyxy more options and black office to computer player operations if you questions ok cancer oo right toe left hand free mode to turn right side number to duties If you know that person help android five most effective way to decide on tree torch light five nikla meaning of looking at edifice of ooo length to bahraich ok after five gotra -2 weight reduce victims will -2 weight reduce victims will -2 weight reduce victims will come into practice for indie time 300 grayton 2012 Number After Two IDBI Happened In November 1969 In Success Metal Is A Danger Commandant Ayurveda Part On Nimar Abu Dhabi Understood What They Want To Achieve And Trying To Achieve This Interactive Water Into Giving And Sharing Next Element Subscribe 10.52 Subscribe to the channel loot do and what is the meaning of computer world setting this solution withdraw its first of all we are in this star plus no water drop oil mast of account it is great andhero phone dual mind which where is my last Tried When Last Not The Great To The Number To Back To Values ​​Were To Log In Values ​​Were To Log In Values ​​Were To Log In That Inverter Market Index Is Zee Account Of Current Tax Act A Tax Better Than That A State Have Sted The Risen Examine This Position And Destroy Them In The I Can Not Good Enough Power value-2 Because I Don't Have Any Thing After Good Enough Power value-2 Because I Don't Have Any Thing After Good Enough Power value-2 Because I Don't Have Any Thing After 125 Play List Justified subscribe and subscribe the Channel and tap on ki agar value number par hai aap kisi flat no want you to return is a ki agar mango 2010 Amazon Artificial Mastech Product Value S is a Tax Code Value S.A. a Tax Code Value S.A. a Tax Code Value S.A. Hua Tha A Stanging Desh Versus Facts With Examples Which You Can Stand Roadways Juice One Hai Ribbon Hai 110 Tu Hai Na Ki Vikas Bhawan Ke Master 212 Written His To Ka One President Twitter Sweet Dreams Will Create Hurdles Entry Are Vishnu Size Of A Ko Bhi Return Value Hai The Internet And Murder Quote Will Do You Understand Why Didn't Seem To Take Into Account MP3 Simple To 9 Tags Page 10 Start Ho Rahi Hai Who Is The First Pock The First Power Say Add Pimple To F-18 Not Withstanding counter - Pimple To F-18 Not Withstanding counter - Pimple To F-18 Not Withstanding counter - 102 that you that a you can not want to get near this [ __ ] famous six and aspiration do more [ __ ] famous six and aspiration do more [ __ ] famous six and aspiration do more vitamin E 220 hands inside William morning re-look 220 hands inside William morning re-look 220 hands inside William morning re-look into account were sugarcane correct admin top of the value of the Like Moment And Left Ko Lootna Dhund Tags Page Like In Tax Credit Balance Measure Last Well With Festival Is A Whatsapp Message To Cash School With U Rock Band E-Books Text Chaupaiyaan City Rock Band E-Books Text Chaupaiyaan City Rock Band E-Books Text Chaupaiyaan City Of Baroda And Requested To Initiate VR Looping Shruti Ko Everyone specific 2018a my device rumor i hope you liked this relation and gave a solution and pondicherry boyfriend a history yadav interesting hard and schedule with request again revolt sexual to 100 slaughter in subscribe to question a
Find the Most Competitive Subsequence
find-the-most-competitive-subsequence
Given an integer array `nums` and a positive integer `k`, return _the most **competitive** subsequence of_ `nums` _of size_ `k`. An array's subsequence is a resulting sequence obtained by erasing some (possibly zero) elements from the array. We define that a subsequence `a` is more **competitive** than a subsequence `b` (of the same length) if in the first position where `a` and `b` differ, subsequence `a` has a number **less** than the corresponding number in `b`. For example, `[1,3,4]` is more competitive than `[1,3,5]` because the first position they differ is at the final number, and `4` is less than `5`. **Example 1:** **Input:** nums = \[3,5,2,6\], k = 2 **Output:** \[2,6\] **Explanation:** Among the set of every possible subsequence: {\[3,5\], \[3,2\], \[3,6\], \[5,2\], \[5,6\], \[2,6\]}, \[2,6\] is the most competitive. **Example 2:** **Input:** nums = \[2,4,3,3,5,4,9,6\], k = 4 **Output:** \[2,3,3,4\] **Constraints:** * `1 <= nums.length <= 105` * `0 <= nums[i] <= 109` * `1 <= k <= nums.length`
null
null
Medium
null
127
hey yo what's up guys babybear4812 coming at you one more time leak code 127 word louder this time and um i'm laughing for two reasons one is like i struggle with this problem i think medium is deceptive here i think this should be a hard uh the other thing is that it is actually my second time recording this video i forgot to press record the first time so if you're here to learn how to get better at leak code you come to the right place if you're here to learn how to make good youtube videos uh get the hell out of here so now that's out of the way uh let's start by noticing that amazon goes trigger happy on this question facebook google lyft uh you guys can read you see it there um like i said this one's a toffee and i know there's a word ladder too i'll get to that one as well but um i think this one's tough if you haven't tried it already as always give it a shot come back after you know the drill but uh otherwise let's dive in and see how we can tackle this thing because it's a beast since we're given two words a beginning word and an n word and a dictionary's word list we need to find the length of the shortest transformation sequence from begin word to n word such that only one letter can be changed at a time and the second condition is that each transformed word must exist in the word list okay we're given a bunch of notes here uh saying we need to return zero if there is no such transformations that's kind of how it sounds like error checking to me um all words have the same length cool it's convenient uh all words contain only lowercase alphabetic character is fine uh we may assume no duplicates in the word list and beginning n word are not empty and are not the same cool so no funny business now to give you a specific example imagine we had hit and cog as the um as our words and we need to find out how to get from hit to cog by changing at most one letter at a time uh with the kind of condition that one letter change needs to result in a word that is in our word list in their example the shortest way there is to go from hit to hot so the eye becomes an o and notice that hot is in here hot becomes dot okay so h becomes d dot becomes dog is in here dog becomes cog is in here we're done this is one of the shortest transformations i'm sure there are others i know there are others but this is one of them we do not need to actually return the steps themselves we only need to return the length of these of what these steps would be so a lot to digest there but i think we can break it down into a couple of components one thing to fundamentally notice is this is we're trying to get from one word to another okay i'm gonna move over to the whiteboard we need to go from one word to another in the shortest possible path immediately i think that should start to scream that this is a graph problem and right off the bat if you don't recognize that i think that this will it'll be very difficult to proceed i think there might be a way to do with the prefix tree or like a tree or tri-spelt with an eye let me tree or tri-spelt with an eye let me tree or tri-spelt with an eye let me know down below if you have a nice elegant solution for that because i couldn't come up with one but um you know if you don't recognize it's a graph problem you may be maybe a bit hard-pressed bit hard-pressed bit hard-pressed um the other thing that is nice to note is that uh we can kind of conveniently represent this as a graph and maybe i'd like to go ahead and do that here just to show you guys what i'm talking about here so i'll start arbitrarily just from the word hot it's the first one i have in my list here and hot can go from looking at this list it can either become dot or it can become blot in both cases it's only the first letter that has changed uh dot here looking at this list it can become either a lot or dogs so it can become lot it can also become dog so again i'm showing a graph just to visualize this a bit dog can either become a log or cog i'll put a log down here and i'll put cog here and so doc can kind of go there and uh finally or not finally but lot we know can go to dot and it can go to log can go to lot or dog or cog and cog can go to dog or log and again i'm jumping through this a bit like i've looked at these before if you pause the video and just look at the words you'll see what i'm getting at how i put this out this is one possible graph it is one part of a um of an isomorphism graphs where you uh for your graph theory fans out there and what we'll notice is that this is actually an undirected graph so no matter where we go uh we can kind of traverse either way and as well it is an unweighted graph there's a reason that i say this if we have an unweighted graph and we are looking for the shortest possible way to get from point a to point b we can just use breadth first search and that guarantees the shortest path so that's nice that means that you know right off the bat we can say okay so i'm looking to get to the end in the shortest possible way it's unweighted it's undirected and namely because it's unweighted we can just use breath for a search and that's awesome that's going to save us a lot of trouble this was weighted if you're in a situation where you have a weighted graph and you need to find the quickest way from point a to point b then you'd use something like dijkstra's algorithm uh in order to actually calculate that because it is a bit trickier but in this case point one that we want to notice is like okay we wanna somehow uh use let's to see utilize but too fancy use bfs all right so that'll be good that'll give us part of the way for sure now the weird part about this question i think what makes it harder is this business of like you can only change one letter at a time all right so how do we go about doing that well when i did this problem at butcher i tried to do it a bunch and i was timing out a lot and one thing that i realized is this is a computationally heavy problem meaning that there's gonna be no way to get this down to like a linear time or anything close to that so it will be i think like m squared times n or something along those lines uh it'll be up there in terms of time complexity so you know we're not going to try to be heroes although i think what we will come up with is the most efficient way to do it whenever you have something that's computationally heavy rather let me take a step back and walk you through my thought process um the reason it will be computationally heavy is because if i'm at hot i will have to check okay let's see i'm at i'm not hot here what happens if i drop the h i only look at ot and then i need to look at every other word that's got that only ends in ot i'm going to do this here then when i get then i'm going to do the same thing with the o then i'm going to do the same thing with the t and i'm going to do this for every word no matter where i stop i'm going to keep repeating that same calculation over and over again and that's a lot of work okay that's a lot of complexity a lot of space a lot of time one way that we're going to go about doing this and i think this part is very i'm not sure that it's very unintuitive but i don't think it's obvious is that we can do some pre-processing to is that we can do some pre-processing to is that we can do some pre-processing to speed this up so the one of the big tricks here i'd argue is to recognize that there is some pre-processing that can be done pre-processing that can be done pre-processing that can be done and i'm going to tell you exactly what i mean by pre-processing mean by pre-processing mean by pre-processing this calculation that i just described if we can do that once up front and create some sort of dictionary so an instant access structure to actually figuring out if i'm not hot where can i potentially jump that'll save us some headache down the line and it's essentially one of the keys to solving this problem let's think about this what i'm going to do is i'm going to represent all the possible variations of hot using wild cards and when i say variations that will mean uh only removing one letter and replacing it with any other possibility so what i'll do is i'll say you know imagine we had this dictionary and i'll say that i can have this can be one of my words it can be uh this is a pathetic attempt an asterisk uh ot and from there we're gonna have a list of words that we can go to i'm also gonna have h asterisk t and i'll yield me another list and finally i'll move this down a bit um h o asterisks and from here what i'm going to do for each one of these prefixes i'm not in prefixes but i'll call them wild card words i'm going to look through my list and find out what word fits this combination okay and when i say fits this combination means there's only one letter off so these two match and the star can be anything and these two match and the answers can be anything and you know what i'm getting at well if i look through this list the words hot so the word itself as well as the words dot and lock which i just drew right here all will go in here this means that when i'm sitting at oops wow i was thought so i think what's happening is my computer is really pumping as i've told you guys before this is a 2013 macbook pro like i don't know how much horsepower on this thing so that's why it's a bit slow and the writing is all awful um from here there's no other words that fit this kind of template so this will only be the word box and also again only the word hot wow that's brutal and there we go all right the reason this is going to help us is as follows and by the way i've only done this for one word we're going to do this for all six of these words so they were in this case 18 entries in this dictionary what this is going to allow us to do is when we step on this node hot when we go through a breath first search we will recognize that okay this word has three possible wild cards for each of these wild cards let's look up where we can go right can we go to hot can we go to dot or we can go to hot we can go to dot we can go to lot if we haven't visited them already right that's going to be a condition that'll kind of help us break out earlier if we need to but that's essentially what the logic is going to be here if i can pre-process going to be here if i can pre-process going to be here if i can pre-process the possible paths from the place that i'm standing here and then that's i'm going to be building my cue the part that takes us a layer deeper here that may be a bit less intuitive is it's not just about saying okay i'm not hot where can i go next if i'm at hot i can either go to a certain amount of places if i'm at star ot or if i'm at h start key or if i'm at h o star and of course as the words get longer they're going to be more and more of these combinations and so uh without doing this pre-processing uh without doing this pre-processing uh without doing this pre-processing we'd end up in a lot of repeated calculations that would be very messy and that would likely time this out so i this is the you know the second part to the problem here and i'm i know i said this is the top prominent is i still do believe it's a bit misleading in my opinion you know to it's honest that seems misleading to say this can be done if you just understand there are two major chunks happening this problem but that's the truth of it if we can understand how to pre-process if we can understand how to pre-process if we can understand how to pre-process make this you know dictionary and then do a standard breadth first search uh that's actually going to be enough to make this problem work and again it's one of those weird ones where i see a lot of people struggle with it i still think it should be ranked hard apparently a lot of people in the discussions agree but when we really break it down there isn't all too much going on per se that said i think we're in a good spot now where we can pause i was gonna say pause the video we don't have to pause the video we can keep recording the video but pause it on the whiteboard explanation and jump over to the code and see what that would look like so a couple points here uh first thing we're going to want to do i'm going to move this over so i'm not my big head isn't covering the code uh i'm going to do some error checking as per usual i'm going to do our pre-processing i'm going to do our pre-processing i'm going to do our pre-processing we're going to do this together then we're going to do the bfs and within this breadth first search remember i said that if you're doing the bfs you will get to the shortest point by default if you ever hit it at that point we just return our value so if we never get if we never return anything in this bfs we haven't found what we're looking for kind of like youtube and then we return zero so that's where we're going to have that at the end and i didn't get into the menu of why that works but if you and i would urge you know if you're curious to do a google search that will give you a much more explicit and thorough explanation than the 30 second sound that i'm about to give you but basically if you imagine when we're doing a breath first search imagine like a you drop a little pebble in a pond and it kind of ripples okay so you'll get this one maybe a little ripple right here and then it'll and then that ripple little it'll grow into something oh i'm sorry that'll grow into something into the bigger ripple which will cover these two over here and then the bigger ripple which you know visual cover log and dog and then eventually what's going to happen is since we're going out kind of one layer at a time the shortest possible layer with the almost a diameter if you will that'll hit this node is going to be by default like the or not like but the shortest path to actually getting there that's just a quick visualization to make a bit of sense out of that anyways i digress in the air checking i'm just going to make sure that we've actually been given all these okay that's one thing so if not begin word or not and word or not wordless or here's the sneaky one so when they try to pull on you and you see it in the example here they might give you an n word that's not in the list so or n word not in word list then we're gonna return zero because it's not possible uh really simple error checking okay nothing to write home about there now we're actually gonna do the pre-processing here and what i'll do is pre-processing here and what i'll do is pre-processing here and what i'll do is i'm going to say i'll call processed words uh equals i'm going to call a function here just to modulize our code a bit i'm going to write it out separately so i'll call self. preprocess the word list please let's go ahead and write that out super quickly not too quickly but quickly enough uh where we're going to define pre-process and we are going to use pre-process and we are going to use pre-process and we are going to use put in self and the word list itself so we're going to want some dictionary i'm going to call it d for sure i'm going to want to return this dictionary when i'm all done with it and what i'm about to do oh sorry but you knows this happens a lot when i record it no it's wrong it's like a mental thing um what we're going to want to do is sorry what we're about to do there is a way to do with default dict i believe uh so for those of you who are familiar with it go nuts um i like to keep these videos for the most right down to first principles just so the uh the code is really accessible and understandable no matter who's viewing it what i'm going to want to do is for every word in the word list before it and word list i'm going to want to at every step of the way create this wild card so i want to drop one character systematically at a time so i'm going to say for c in range the length of the word i'm going to want to create a wild card and i'll say that wild card is equal to the word that goes up to this character c up to but not including and then we're going to replace that with some sort of asterisks and then i want the next character onwards so i'm going to a word of c plus 1 all the way until the end so if i want to draw up a character c i'm going to go up to that character but not include it instead of that character i will add an asterisk and then from there i will add the next character onwards and that's going to create my wild card entry i'm not going to say if the wild card is not in oh i don't need the word is if wildcard not in d then we're going to want to say d of wild card is equal to some empty array because what we're going to do if it is in there or even if it wasn't and out will be we're going to say the wildcard dot append the word so if i'm dropping one letter then i'm going to want to append the word onto that wild card kind of like how we did here with uh with hot all right see hot was in there and then every time i come across another word when i'm creating wild cards if it's only that one letter off and the wild cards match up if you will we're going to append that full word into the into that dictionary entry right over here and that's it this is actually all that our preprocessing is and that will create this structure exactly for in this case all six of our words uh three letters a piece so our 18 entries so we have that pre-processing done pre-processing done pre-processing done that's arguably half the battle maybe even the harder half because the breadth for search for the most part is just a standard bfs with maybe a couple of small tweaks but uh nothing to write home about here within the actual bfs we are we're going to want to do a couple of things first thing we want is to actually create a cube i'm going to use the built-in deck library here i to use the built-in deck library here i to use the built-in deck library here i know maybe that's contrary to what i was saying earlier up here about not using the built-in libraries but i not using the built-in libraries but i not using the built-in libraries but i feel like you'll be overkill for this video to build like the nodes in the doubly linked list and make all that from scratch because that's not the purpose of what i'm trying to do here so i'm going to be using the built-in deck using the built-in deck using the built-in deck and spell it right and uh we will and by the way that is pronounced deck it's not i thought it was dq the uh the documentation says it's the deck so yeah uh i'm in the queue i'm actually going to want to append our first sword so i'm going to say begin board now there's one other thing that i will want to append for the following reason as we're going through this bfs if we find the word that we want to find we want to have somehow kept track of the length of the amount of steps that we've taken in order to get there the easiest way to do that is just to put this in some sort of tuple um or an array i like to put an array you can use the tuple if you like and start by you know start by certain word one because we are on our first transformation of this word in the question the way they described it and how they went through the examples uh this would actually count as uh as legitimately being the first transformation onto the word itself i would argue logically i would put a zero here i think that would make more sense we haven't done anything with it yet but following the instructions and in the examples that's um that's how the math is going to check out so it is what it is like as you can see here when we went from hit to cog we had one two three four five so this word itself counts that's what i'm starting from the one here i'm then going to jump into the standard the bfs stuff which is while not wild uh while q so while we have any sort of items in the queue let's make some stuff happen i'm gonna i'm interested in finding the current word that i'm working with that's gonna be cur and what i'm gonna do for that is i'm gonna pop out uh from the left side of this cue i'm gonna pop that first item in so if you can picture the cue on the leftmost side that's kind of the head of it that's what i want to take off right otherwise i would say pop if i wanted something from the end what this will pop out will actually be an array in this first iteration through this loop it will be this array here so what i'll do is i'll actually just destructure this immediately and say and grab both the current and the level that we are at again the level will be needed because we may be returning it if we find the n word that we're interested in now a couple things we need to say the following we've got to say um for this word that we are on so for example we're on hot right here actually you know what i think there we go we're on hot right now for hot i need to check all the possible paths that i can take to jump out of this node the possible paths that i can take exist within this pre-processed array that we within this pre-processed array that we within this pre-processed array that we created however what that does mean is that i'm going to need to check every wild card here okay so once again i'm going to be borrowing this code and saying for c in the range of the length of kerr in this case i'm going to want to create a wild card and now wild card they'll be the same as the ones above and what we'll be doing is we're just going to be checking if this wild card is in here then we can potentially make some movements so uh if uh wildcard in uh process words then we're going to want to you know do cool stuff so the reason i'm checking this here again is because maybe not um actually so maybe i'm overkilling it here let's see uh if i'm honest with you this if statement might be overkill but i want to make sure that i'm not going to get a key type error if for whatever reason this uh the wild card isn't within the processed words if the wild card is in the processed words then what we want to say is the following we want to say uh for word in processed words at that wild card we got just in the space there let me move this over a bit more we want to look at every word in this cube so for example uh we've got you know all these words here that we want to look at so i'm going to loop through each one of them there's one thing i missed here that i'm going to add in a moment but i want to see the following i want to say if that word is actually equal to our n word then when we're done then we're just going to return the level that we are at plus one the reason we're having the plus one is because again if we start it at a level one that was our initial word we then made a change we're taking we're making a transformation we're taking one step further i haven't taken that account yet into my level so that's so i'm going to return the level plus one otherwise if we haven't visited this note already and the one thing that i forgot to add in here was some sort of scene or visited sense maybe i'll call this visit and make it a satchel so we have that instant look up so what i'm going to say is if the word is not in visited then we say the following we're actually going to add it to visit it because okay we've been there and then what we're going to want to do is add it to the cube so we're going to say q dot append and again we're going to put the word in itself and we're going to want to include its respective level this word is one transformation up from the level we were currently at and that's why again we're adding the plus one here kind of like we did over here maybe i'll leave that i was gonna i'll format the spacing so it's all unique and that should be because if i hadn't missed anything that should actually give us everything if we if it was visited we don't do this otherwise if we go through this entire array we've never returned anything we will return a zero because that path was not possible i'm going to press run here and make sure i didn't make any typos and as always i did i made one on line 29 and i called it word instead of calling it cur this should have been cur okay this should have incurred and then the rest of these are all word that should be good and i'm just going to submit and make sure that i didn't miss out on anything else cool and you see the results there uh super good speed and memory usage not so great i'm not sure we could fix that but regardless just to recap uh and i'm gonna make sure there we go you can see all the code and the screen fits perfectly uh i don't think it's an easy question i don't even think it's immediate question but i think it's doable fundamentally you need to begin by understanding that this is a graph problem without that it's going to be really difficult to proceed when you realize that it's a graph problem there you can you notice that it's an unweighted graph and that means that if they're asking for the shortest distance which they are we can use breadth first search on top of that if you can notice the kind of this wild card pattern and realize that we need to check all these combinations and there's a way to speed that up slightly by doing a lot of the calculations and on a pre-process like ahead of time and on a pre-process like ahead of time and on a pre-process like ahead of time um in and ahead of time way and be mindful of that's going to be the second part to understanding how to get this thing done and that was again this method that we wrote up here this function i hope this video helped i know this question has caused a lot of confusion i've seen some videos of it up already um i struggle to understand a lot of those videos not all of them but for the most part so i was hoping to make something that would be a bit more digestible and a bit more understandable to get you over the finish line with this one i hope it helped as always like comment share subscribe i'm not going to tell you what to do anymore i probably will but i don't like to but you know if you could share that would be awesome uh yeah i think here i think your uncle needs to see this one i think that's what the word on the street is so don't forget to show him and uh yeah any questions about this let me know down below anything else you want me to do also let me know below and i will see you guys next time peace
Word Ladder
word-ladder
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 _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._ **Example 1:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\] **Output:** 5 **Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long. **Example 2:** **Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\] **Output:** 0 **Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence. **Constraints:** * `1 <= beginWord.length <= 10` * `endWord.length == beginWord.length` * `1 <= wordList.length <= 5000` * `wordList[i].length == beginWord.length` * `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters. * `beginWord != endWord` * All the words in `wordList` are **unique**.
null
Hash Table,String,Breadth-First Search
Hard
126,433
237
Hello friends today I'm going to solve liquid problem number 237 delete note in a linked list so what's a link list let's see first um so in a linked list we actually have multiple notes and each nose are connected with each other in one way or other so if there is only one direction in which the nodes are connected then it's a singly linked list if there is a direction from the other side as well then it's a doubly linked list and we also have like um circular linked list where the last node is connected to the first one so here in this question we actually are given simply linked list and we want to delete a node and in the question we are not given the head of the link list so we are only given the note that we need to delete and then we need to connect the next of the previous node with the last so in order to perform deletion in a linked list the conventional method is we are given the head of the link list so this is a linked list with four elements and one two three and a four suppose this is a linked list with four elements and we need to delete this node so in order to delete this node we need to connect the previous of the node to the next of this node so this is the node n and this one this node is the previous of this node and this is the next of this of the node itself so how do we go are about solving in the case when we are given the head we know we keep the uh keep the track of the previous node and the current node so in that way we can actually connect the previous node with the next of the next node but here in this case we are not given the head of the node at all we are only given the node that we need to delete so how can we actually solve that so let me draw a new note linked list again so this is our new linked list a singly linked list so we are only connected in One Direction and in the question we are also given that the node is not the last the tail lot so all the values of the linked list are unique and it is guaranteed that the given node is not the last node in the linked list which means that it will never be this node that we must delete it is either one of these three notes that we have to delete so given that we should delete this node we are asked to delete this node then uh let me add some values to the node so this is 2 this is three and this is four now we do not know the head so we do not know the previous node but what we know is the node that we need to tell it and again we also know uh the next of the node given node right because we have we are connected with a linked list so we will obviously know the next Doctor note so what we are going to do is actually store the value of the next node in a variable so suppose a we store the value of the next node which is equals to 3 and then we delete this node so we are actually deleting this node here and then we are not deleting this one so let me just erase this thing and so we are given a note to delete but we are not deleting this one we are deleting the next node but before that we store the value of the next node in a variable and then we change the value of the node to the next node three so in this wave what we get is our new note our new linked list is one three and four so this is what we wanted we needed wanted to delete the node two and we still did that but in an in a different way now let me code it so it's very simple actually um so we first need to store the value of next note so note that next gives the next node and then dot val gives the value of the next node now we are going to delete the next node so how am I going to do is I'm going to connect the next uh the next of this node to note that next and then I'm going to change the value from the current node to next note and that's all so the time complexities or one and the space complexities of one as well
Delete Node in a Linked List
delete-node-in-a-linked-list
There is a singly-linked list `head` and we want to delete a node `node` in it. You are given the node to be deleted `node`. You will **not be given access** to the first node of `head`. All the values of the linked list are **unique**, and it is guaranteed that the given node `node` is not the last node in the linked list. Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: * The value of the given node should not exist in the linked list. * The number of nodes in the linked list should decrease by one. * All the values before `node` should be in the same order. * All the values after `node` should be in the same order. **Custom testing:** * For the input, you should provide the entire linked list `head` and the node to be given `node`. `node` should not be the last node of the list and should be an actual node in the list. * We will build the linked list and pass the node to your function. * The output will be the entire list after calling your function. **Example 1:** **Input:** head = \[4,5,1,9\], node = 5 **Output:** \[4,1,9\] **Explanation:** You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. **Example 2:** **Input:** head = \[4,5,1,9\], node = 1 **Output:** \[4,5,9\] **Explanation:** You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. **Constraints:** * The number of the nodes in the given list is in the range `[2, 1000]`. * `-1000 <= Node.val <= 1000` * The value of each node in the list is **unique**. * The `node` to be deleted is **in the list** and is **not a tail** node.
null
Linked List
Easy
203
1,727
so in this question we have to find the largest area of submatrix uh and here uh we can only in reorder The Columns so if you can see in this question uh we are given with a matrix and after reordering the columns so we after like placing this uh this column 111 uh in the middle we are getting an area of four so let's see how to solve this problem and this one is a kind of trick one but let's see how we can do this so here we are given with a matrix which is Again The Matrix taken from the example itself now what we are doing is we are basically calculating the sums of the row so first of all I'll take this First Column so I'll be taking let's say this column okay so after taking this column uh what I'll do is like I'll be basically summing it so for example this is zero after I'll go down uh I'll go over here which is one this is one right and then after going here uh what I'll do is like uh like 0 + 1 will be one itself which is like 0 + 1 will be one itself which is like 0 + 1 will be one itself which is what I'm placing over here and uh 1 + 1 will be 2 so I'm here and uh 1 + 1 will be 2 so I'm here and uh 1 + 1 will be 2 so I'm putting it over here similarly I'll be traversing through the next column so sum is zero sum is one and again since I find this another sum as uh like another element as zero I'll be putting it at zero itself because I have to find the continuous one sequence so that is why it is zero itself so if you can see it is zero over here let's see here so one so for one I have placed one and then 1 + 1 is + 1 is + 1 is 2 and then this is three right so we have calculated the cumulative sum uh some Matrix so we can replace the same Matrix with this Matrix so we do not need to use any additional space so this is what we have done as of now so since we have calculated the cumulative sum so this will look something like uh something like this so something like this in a sense the maximum of the zeroth column is to maximum of the First Column is one and the maximum of the third column is three we have this as a now so this looks something like a histogram so what we if we sort this histogram and make something like this which is like 1 2 and three and then what we can do is like run a loop from 0 to n and we'll find the maximum area this can occupy so let's say something like this which is basically let me change the color here so suppose I have sorted this thing the maximum thing and I'm getting something like this so at the one like zeroth column what I'll take is like the value of this particular uh what say particular length into the number it can cross so basically it will be something like one cross this three right so it will the area will be three now if you go to two the area will be 2 into 2 which is be 4 and if we just look at this the area will be 3 cross 1 so 3 the maximum will be 2 right so we 2 into 2 which will be four so we'll uh return four we'll see the code how this works so for this what we'll do is like we'll sort each row so after sorting each row so let's after sorting each this will be the vector like Matrix which will be getting like 0 1 and then 1 one2 and then 0 2 and 3 Let's see the code how we have implemented this which is here let me try to zoom it for you so that it will be easy to understand uh let me know if it is visible nicely so what we have done as of now is uh this n is the uh size of the array like not array n is the size of uh The Matrix the row of the Matrix and M is the uh length of the column of the Matrix and we have initialized answer as our answer as a variable to store our answer of the maximum uh area yeah so this will rest the maximum area which will be returning so if you see in this Loop what we are doing is like basically we are uh we are just arranging this finding the maximum the cumulative sum finding the cumulative sum is uh this thing this Matrix is what we are calculating so if you see over here what is we are doing is like if the Matrix of I comma J is one then only we are adding with the previous one so we'll be running this loop from uh I so for uh so this Loop is for every column so uh this first Loop is for every column so for every column we are traversing through each and every element of the row and we are if checking if the element is one then we'll be adding with this with the previous one so let's run this Loop over here and uh find uh this array which we have calculated so when we run this Loop uh in this Matrix what we are getting is like this will be zero right so as of now we are at zero J equals to Z so since J is zero we are at zero column and then our I is one so we are at I row I is row is this is the first row one row right so if this element is one yes this is one then what we are doing is like we are updating this with the previous + one so previous this with the previous + one so previous this with the previous + one so previous is 0 + 1 is 1 so we are getting this one is 0 + 1 is 1 so we are getting this one is 0 + 1 is 1 so we are getting this one again will it uh it down and if this is one yes this is one then we are summing previous which will be this one + one which will be two we are ending + one which will be two we are ending + one which will be two we are ending over here now we'll go to the next column which is this column and if and we'll not be looking at the first row like the zero throw we will directly go to first row according to the loop which will be like 1 comma 1 now so at 1 comma 1 we have one so we'll be adding 0 + 1 we have one so we'll be adding 0 + 1 we have one so we'll be adding 0 + 1 which will be 1 this is what we'll get now since this is not one this is zero we don't do anything we won't do anything and we'll this and we'll move to the next column now let's see uh we'll go at u 2 comma 1 and at 2 comma 1 we'll be adding the previous value from this part which will be Matrix of uh 2 - 1 will be 1 comma 1 so Matrix of uh 2 - 1 will be 1 comma 1 so Matrix of uh 2 - 1 will be 1 comma 1 so sorry two yeah two I is uh as of now one yeah so 0 comma 1 so this is our uh 0a 1 this plus this will be two similarly uh 2 + 1 will be three so this similarly uh 2 + 1 will be three so this similarly uh 2 + 1 will be three so this Loop is basically adding Loop is this Loop is basically adding our Matrix so we are creating a cumulative some Matrix and after that what we are doing is like for every row we are sorting The Matrix so begin and end so for every Ro will sort the Matrix so after sorting we'll get something like this which will be 0 1 for this row and for the same row what we are checking is like okay what is the answer if so let's let us suppose that if my Matrix was only of one row and not of two row so suppose my Matrix is just this row that's it this is this row and let's hide the these rows these two rows we hide it so among this what will be the sum so one will be the sum and let's suppose now uh let me show the code again yeah so we'll be sorting this and we'll be checking for each element what will be the maximum which we can get so the maximum which we can get is like the The Matrix value itself into M minus J is basically uh will understand this m minus J when we'll come to the last Loop so let's see the last column directly so this is the last column after sorting right so last column after sorting 0 2 3 so 0 2 3 means this means that we are looking at now the entire Matrix because even all these are in consideration now and suppose we are at uh this zero value suppose we are at over here so what we'll do is like we'll multiply 0 into three this three till here so we'll get zero no issues now we'll move at this place now we have the value two so 2 is basically our Matrix of I comma J value so I comma J is 2 so 2 into M minus m is 3 - 1 is 2 so 2 into 2 4 so minus m is 3 - 1 is 2 so 2 into 2 4 so minus m is 3 - 1 is 2 so 2 into 2 4 so we are getting 4 so we'll update our uh answer with four as of now because this is the maximum then again we'll Loop in and uh we'll get the value three so now we'll do like 3 into M minus J so J is 2 so 3 - 3 into 3 - 2 which will be 1 so 3 - 3 into 3 - 2 which will be 1 so 3 - 3 into 3 - 2 which will be 1 sorry which will be 3 into 1 will be 3 so the maximum what we are getting is four and this is how we'll update our answer I hope uh you have understood this code uh this was a little bit complex but I hope I have explained it well thank you so much for watching the video
Largest Submatrix With Rearrangements
cat-and-mouse-ii
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order. Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._ **Example 1:** **Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\] **Output:** 4 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 4. **Example 2:** **Input:** matrix = \[\[1,0,1,0,1\]\] **Output:** 3 **Explanation:** You can rearrange the columns as shown above. The largest submatrix of 1s, in bold, has an area of 3. **Example 3:** **Input:** matrix = \[\[1,1,0\],\[1,0,1\]\] **Output:** 2 **Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2. **Constraints:** * `m == matrix.length` * `n == matrix[i].length` * `1 <= m * n <= 105` * `matrix[i][j]` is either `0` or `1`.
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
Hard
805,949
139
hey and welcome back to the channel today I will show you how to solve word break interview question from lead code this question has been mostly asked by Facebook but it also has been asked by various other companies like so we will use JavaScript via BFS Solution by leveraging an area as a queue also there will be another video about dynamic programming solution as well in the near future before we continue make sure to like subscribe to the channel and comment below and give me a feedback it's highly encouraged and appreciated now without further Ado let's Dive In foreign word dictionary return true if s can be segmented into space separated sequence of one or more dictionary word note that the same word in the dictionary may be reused multiple times in a segmentation let's see some examples here are the examples for first example we have lead code as in pedestring and lead and code as a words inside of a word dictionary what we need to make sure is that basically to see if we can break our string using the given words so in this case seems like we can because if we use both lead and code we can create the given lead code string with one spacing bit and there will be nothing left from given string second example basically is the same this example's response to notify us that we can use words from dictionary multiple times as you can see the result is true and there are two app pulse used in this case last example result is false because if we use words from dictionary we only will be able to succeed to create some part of the given string not all let me show you so we have cats and dark here as a giveness drink one possibility is to use in cats plus dogs but there will be n and S left it out second possibility is using cat plus sand but in this case there will be odds left it out last month we'll be using cats plus and but again there will be Alex lifted up so this example exactly clarifies what the problem asks for we want to segment the given string in a readable format V the spaces only using given words and at the end nothing remains let's think about how we are going to solve this problem so the Brute Force solution could be something like checking for each value from dictionary and maybe if we found something that matches with some part of our string we will remove that part and at the end if there is nothing left from given a string that would mean we can break this board using dictionary and if not we can so as of our first attempt we will check for cats then we have a match here so we will remove it let's try it one more time for dog next board in a row check first we find something we remove it now as you can see there are three letters left in this case that does not match with any other word in the dictionary let's move on to another word combination this time we won't use the previous word just for trying something new let's check for cat without s we have a match for it remove it another new word sand we have another match then remove it now we left with Ox which there are no match for it in the dictionary moving on to the last combination check let's try cats bit and the last word that we haven't used before and see what happens so cats match remove second one and match remove again another leftover from imp string so literally we can't break this word with given dictionary of work we basically can code that but first usually we don't want to mutate or change our input values in algorithms and second for that solution we need to do a lot of iteration and search over both string and dictionary which does not sound efficient enough so there has to be a better way let's explore let's imagine our second example that we might return true for it I need true case to show you the process so what we are going to do is a search idea originated based on the input string not the words in the dictionary we need to search every possible range of words from our input string and if there is a matte market and continue looking for another potential word from dictionary in this case let's think about a range of word indicated by two variables start and end they cannot both be at the same index so end pointer has to be at least to the next index from starting point for each range of letters that start an end pointer will give us as we Traverse over or input string we are going to check our dictionary to see if it is there and if we can't find any match from dictionary for our current range we have nothing to do except expanding on Range one by one and search again if we happen to finally find the match from a dictionary like the Apple in this case okay that sounds good we will save that index for next iteration where we will update our starting pointer to start from that point to be fun but that's for next iteration and we haven't finished our current one so let's continue and as you can see there is no possible match until the end of this iteration but for next iteration we already know where to start we saved it right here in our storage that means if we ever find a word we will ignore that part of string in the next iteration and jump forward as long as that word we found and start from there do the process again and again until we finish the iteration of our string so as you can see we shifted out first item from our storage and started from there this time index file and as we continue in our lookup we will find nothing until this index here index 8 of or string we have another match from dictionary pen so we will push its index into our storage and again continue looking for more like before until the end of this iteration there will not be any match from word dictionary but since already we have found the match the board pen for the next iteration we know where to start again yes you are right index 8 the last number that we push into our storage array so we will shift it and start looking from that index as you can see if we do a quick iteration like so we will face with another word of Apple so one last iteration will give us another match as soon as our end variable reaches into the last character in the war end of or string but before we updating or storage I want you to think about two things first we found our last map second we are literally at the end of our string or end variable is at the last character and even if we update our store it and pick up end index as next starting point there is literally no place to go this is the point that we know that we successfully broke down this war and there is no need to update our storage at this step we can't just return true from here now there are two things before jumping into the code first as you might have noticed I've used different colors for first Apple pen and second Apple that was only because I wanted to show you how this Bread's first search worked of course BFS is so obvious and clear in the tree shape data structure but the only way that I could explain it was like making your thought process to accept how we Traverse all possible combination for each starting point that we found there will be more videos on Channel about these methods of traversing and I'll do my best to explain it as simple as possible so make sure to subscribe to the channel for those videos too second I want you to focus on this storage that we had and how it actually worked in our case we needed a special mechanism over array for handling or situation which has been called the cube for now just note that by special mechanism I mean we always only pushed items to the end and shifted items from start of the array by that mechanism we can have small and quick version of Q in our hand in JavaScript this is basically how Q Works in a nutshell but keep in mind that the real Q data structure has other methods as well now let's jump into the code so here we are in lead code first we need to create our queue so we will do an empty array like conspu equal to and pure right then we need to iterate over our Q because our entire algorithm relies on this queue since we are supposed to push whatever possible breaking point or indices into it so we will do while as long as q that length is a true c number we will do some stuff here at this step first we need a way to trigger our main while loop because all of our logic will be placed inside of it so we have it by using Q's links on the other hand we will start from index 0 to iterate over three because we need to start from beginning of it we need to push index 0 into our queue by default and that is why we actually glue this while loop into length of our queue so we will do 0 here next inside of this while loop we are going to take the first starting point for our Q which is 0 at the beginning so we will do const start is equal to Mu dot shift first item this will give us the zero at the as a starting point then we will do another loop for input string but this Loop is only responsible for or end pointer because we already got our first pointer from Q right here so we will do for let and equal to Star Plus One and less than equal to s dot length and N plus remember that I told you end and start pointers could not be overlap and end pointer has to be at least next to the start pointer that plus one will do the job here okay moving on now inside of this for Loop since we have both start and end points we can slice the part of the word that we want so we can do pause or s dot slice starting point to the end point that's the word that we need now we need to check if this sliced word exists inside of our word dictionary we need another search so we will use array.include if or so we will use array.include if or so we will use array.include if or dictionary that include the word if that is the case we need to do two things first we need to check if our end pointer is at the same index as our strength length because if so then we know that we finished our creation and can't break this string using our dictionary so we can return true in this case second if that is not the case we will push or end pointers index into our queue because next iterations has to be aware of it that is the point they need to start so we will do if and equal to s that length we will return true here and if it's not the case we will push the end index into our Queue at the end if we finish both loops and could not find anything we can save return well indicating that there are some leftover characters that could not match with any words from dictionary now if I run this will pass all of the test case like all of the smoke tests before submitting but there are two things before the real submission first is the way that we look up for Words inside of our dictionary using array.include array that include using array.include array that include using array.include array that include loot in JavaScript has oauth end time complexity but we can improve that lookup to all one constant time complexity by using a set so we will create a set of word dictionary so we will do our dictionary is going to be new set of or real dictionary and then check from or set in order to see if it has the possible match for or work and if I run this again everything is passing second thing will happen when we submit so if I submit seems like there's a super weird test case that causes our algorithm to through a Time exceed error let's wait for this guy here this test case so let me explain in text that what is happening in this case here we have our longest ring like that here is our dictionary of words basically starting from 1A to 10 A's at the same time or string to show you the process and here's our cue so what is happening in this case is a bit Overkill but my guess is that the lead coders put this test case here just to teach us something really minor about caching and memorization so in this test case what is happening is if we start from index 0 and index 1 is our end pointer we will get an immediate match so we will put or end index into q and move on to search more another match and another match until we reach into the index 10 of this long string now we will continue to search more and basically check for what we have more than 150 60 possibilities here but we have nothing that matches with any word from dictionary so in the next situation that we do over queue we will pull out first element by shifting whatever we had in our queue we get our new starting point in X1 now starting from index 1 ending in two we have a match so pushing two again into our Q moving on another match until index 11 we do still push those indices to the queue and this is the important part then finishing up those 150 60 checks without any match moving on to shift 2 from or q and doing the same cycle again which will add this amount of indices into queue again same thing happens for index 3 4 and others but you get the idea we are literally flooding or queue in this special case now imagine how much work we need to do in order to make our Q clear and empty while each number that we shift out from our queue and we do the cycle we literally add 10 more items in it we definitely want to prevent this Behavior right we don't want to check again for the same items that we already did so the key here is to have a visited array or preferably a visitor set again because of all of one constant and look up that sets brings to us and check for starting points before we enter to our for Loop actually that was the reason we had time limit exceeded error for that test case back in the lead code so let's implement this caching now what we need to do is create a visited set like const with the tab equal to new set which at the end of each Loop we will push our starting point to it like this is our for loop at the end of each for Loop we will do visit at start like that but the actual rule in order to prevent flooding or queue is to check for starting index up front so we will do if visited that has start but with the exclamation mark indicating that if it doesn't has that let's do all of this logic inside and before running I want to mention that I've already added that a special test case in our smoke test so let's see what will happen if I run this code and as you can see it passes this special test case too and we can submit at this step and we have a good space usage in here now let's jump into the time and space complexity analysis for time complexity we will have of n in power of 3 because we had a while loop for Q then we had a for Loop over each string then we were using arida slice method which has all of end time complexity by its own so all were nested then or total time complexity Becomes of an impoverup tree for space complexity it will be of n where n is the length of Q and at the worst case Q can take up to the length of the given string for indices with that I can say that was it for this video also there will be another video soon about dynamic programming solution for this problem so make sure to subscribe to the channel in order to not miss that one I'll I also will put the link for string playlist in the video description where we go through solving string problems from lead code so thanks for watching and please like comment and subscribe to the channel and finally hope you enjoyed this video and stay tuned for the next one
Word Break
word-break
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words. **Note** that the same word in the dictionary may be reused multiple times in the segmentation. **Example 1:** **Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\] **Output:** true **Explanation:** Return true because "leetcode " can be segmented as "leet code ". **Example 2:** **Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\] **Output:** true **Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ". Note that you are allowed to reuse a dictionary word. **Example 3:** **Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\] **Output:** false **Constraints:** * `1 <= s.length <= 300` * `1 <= wordDict.length <= 1000` * `1 <= wordDict[i].length <= 20` * `s` and `wordDict[i]` consist of only lowercase English letters. * All the strings of `wordDict` are **unique**.
null
Hash Table,String,Dynamic Programming,Trie,Memoization
Medium
140
111
A firewall welcome to bank OTP just like guddu beat change the name of the volume minimum death of binary tree select so friends problem solve problems and given a banner tree - minimum death and the given a banner tree - minimum death and the given a banner tree - minimum death and the number of notes of this type of do the nearest loot ke Notification Not with No Children Members Pandey Tree and Where to Find Hotspot of English Class 10 Drops of Honey Spot with Sauce Ninth Child Officer Country-Foreign Hotspot Signature Can Be Country-Foreign Hotspot Signature Can Be Country-Foreign Hotspot Signature Can Be Travelers Using Others Face Death Cigarette subscribe The Channel and subscribe the Dr. Sunil How to find the right child in the app to find the fatherless child and where to find the minimum between the volume minimum death and various effects using back subscribe our Channel and subscribe the Channel bottom left There is a subscribe button on the side and even to these years questions are coming very much then half the time complexity of over fun but in real life all these updates Paschim Sach Krishna will be Muktipath so let's you search to solve this problem super singer field a professional Can be written notes in length 119 length 120 why set an alarm when research velvet the notes in difficulty level in seekers and travels through documents that set thank you ride through the elementary so why not return not travels for the why that sir travels She is so cute under-22 that sir travels She is so cute under-22 that sir travels She is so cute under-22 that nine any two first travels for each level inductive right and this level industry light shades childhood days left or right any two travels and all the child in the travel guide superstar to see is your element ordinary till you agree that Particular time light members give me the element and the particular time writer of elements of knowing God has been element which is youth open the settings open a message send love only going and two judgment thoughts in the tribal super style for the element from the why love you Don't Char Settle Give Me The First Element Desktop Muslim Interactive And Orders Will Remove The Elements From The Why Not 10 Elements Of Is The Fighter But They Can Be Cut This Point To That We Can Check Share Subscribe To Are Butter Vihar Pandit Improvement Balance Rights To 20 of first level 851 increment balance kia developer that and were also a pond child line too notifications for that but they also need two brothers pile operate soils of millions the very first time that forced reap equal to for that which oil go taluk atal pandey On this a false some verification DFI will come pave the way to do it state no do join us in this sign * and the china see the in this sign * and the china see the in this sign * and the china see the why check year after year absolutely no the nod32 please Do not the to subscribe idly return in the length date of the free shoulder time congress chief and where is the number of notes industry in verse case scenario select submit this and see the question on the latest of spineless updater code loot and according to accept The Second Person Poster This feature is available only on 10 videos Please like button and to subscribe our Channel and Hit The Bell Icon Per Oil Notifications From This Thank You
Minimum Depth of Binary Tree
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. **Note:** A leaf is a node with no children. **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** 2 **Example 2:** **Input:** root = \[2,null,3,null,4,null,5,null,6\] **Output:** 5 **Constraints:** * The number of nodes in the tree is in the range `[0, 105]`. * `-1000 <= Node.val <= 1000`
null
Tree,Depth-First Search,Breadth-First Search,Binary Tree
Easy
102,104
56
A Heavy 1872 Will Be Discussing District Problems From 28th March Overlapping Sub Intervals Subh Problem States Having Been A Collection Of Intervals Neetu Mann Chaugi Overlapping Intervals Application Use In The Form Of Free Water Into Coma Sex Begum Attendant Team Ko 180 Vacancy Date 15312 Weak Overlapping 100 Years Boy Jumped Morning One President Will Appear To Be Venomous Snakes And Comment 10 Tej 10158 Clear Tense Future Updates Intervention 1.5 Clear Tense Future Updates Intervention 1.5 Clear Tense Future Updates Intervention 1.5 500th Food And Clothes For Watching Sorry This Sum No 1.2515 12th Interview Tips 1.2515 12th Interview Tips 1.2515 12th Interview Tips Interview Giving That All The Interventions For Kids Mod On Not Because Know When The Problem Tools Mention If Interview Shifted To Not Building Code Intervention Sot An Adarsh ​​Inter Very First Intervention Sot An Adarsh ​​Inter Very First Intervention Sot An Adarsh ​​Inter Very First Question Options Given Interview NodiJS Yo Solving Skills But Also Suggests You Own Way And Skills Like Are You Considering All News Are You Asking Him Not Something That's Enough Interview K Winter Short Notes Azim D Interview Shesh Interview Not Sorted Three Forces Interview With Proof and Suppoch Celebrates His Approach Airtel Ne Interviewer Tags Sauth All The Giver Intervals Yaar* Saunf Website All The Giver Intervals Yaar* Saunf Website All The Giver Intervals Yaar* Saunf Website Sporting Wicket Something Like This Is Vansh Water Blurry Hydrate For everything even in temple should start from one to minister land dispute which of this in adh 9th what e was going to have to take one mode switch and stored in march past former forest minister antu respectively red chilli and give one officer in your Desktop should against oven ko ma sex scandal egg candidate and anything that you check out pintu kumar six for this person ko mental already lies in the previous tree 0982 waist six chapter 8 108 contest se zokkomon isko light videsh shekhawat amol intervals vaccine surplus normalized porn watching With the government and sorry for one day you know its order to avoid come 80 299 exist others not be considered as a not inside ko mutton shekhar pradeep rich person 2018 joint drafting committee chowk you all the thing interview time being in force for every interview Right to the right interviewer ne candidate ne interviewer don't forget to subscribe and also subscribe quarter enemy ko mere medium aanch ved par on The Video then subscribe to the Page if you liked Na Reminder Musa 128 Celebrate Earn Tuesday Actually Downers Scholar Ko Mashisan Dorment 10 Celebs Bid To Replace 181 Next Point To Sisters 2829 Love With Others On 11-11-11 Subscribe To Others On 11-11-11 Subscribe To Others On 11-11-11 Subscribe To Ped Namo-2 Next Ped Kunwar se jara Ped Namo-2 Next Ped Kunwar se jara Ped Namo-2 Next Ped Kunwar se jara check de 600 800 tedders to aap aasat u can actually rafi kam 10 back singh ko masse or festival pressure ne over what is related to take care love you all the best result this thank you for watching gand chali aai Will Get Result One Know I Get Something Mirch 1000 Swift Update And Put Into A Bigg Boss 10 From The Inventor Of World Records They Have Already Started Giving Lift To Approach Of Law Of Attraction After Written Test And Interview Subscribe Returning From Us You Can Give Me Faizabadi declared its and championship spoon intervals which will be ultimate and at will return to take care of this is not given in the world after taking place in the state and we difficult * * * * * * * * state and we difficult * * * * * * * * state and we difficult * * * * * * * * * this entry to maximum of The Writer of the Match Shoulder Lia Story and Not for Simply Watching Pradeep Result of Considerable * * * * * * * * * * Pradeep Result of Considerable * * * * * * * * * * Pradeep Result of Considerable * * * * * * * * * * subscribe and subscribe the Video then subscribe to the Page Roop aur Hasla Voluntary Tak Menu Service to Festival Garlic now this Tricks Time Fog Simply Damage To Right Maximum Justin Not Why subscribe to the Page if you liked The Video then subscribe to The Amazing Subscribe
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
48
so guys so this is Josh from Brazil right now so moving along with the matrix related problems last one was solved as a transpose E and matrix which we did it with the easiest way possible we still using a little bit of space this problem is a little bit more complex but you can also use that transpose technique so I do recommend you going to my channel and checking that up that one out if you like that but let's move ahead and this one as long as a little tricky so let's go through it so this one is called real take image so it's basically rotating in gray so you I'm gonna do is that you have an array here a matrix here you want a row data right here so y'all know rotate 90 degrees right base so for example let's say dad you have this here what do you want to do sorry about my video yeah what do they do is that you wanna do this that's basically one so you know rotated clockwise so you have to update the image in place which means that you cannot modify you need to modify the matrix that you get as an input and you do not need to return anything just a quick note on this like when exercise usually ask you to write it in place it's still allowed to use or temporary variables here they're the only things not allowed is that you're gonna create a whole new data structure just to just as a result of your exercise but in this case we're not gonna do none so the easiest way to think about this problem they're far more complex ways to deal with this the easily given for this problem is we're actually gonna suppose the matrix pain lights and them since work because what we're doing when the transpose is that we're getting the first row and we're making that into our first column and we're getting a second row and you get naked eye with your second column so a transpose is gonna rotate an image 90 degrees clockwise and transpose is actually almost doing jobs so sorry so what do you do after is that after you get the transposing you we can go over dere the matrix call row by row and just reverse it and that can be done quite easily by two so let's try this so and then couple of things that we I think we can do here is that we can get the Greens the matrix and square matrix variable to make it easy we're gonna transpose this by looping all the rows columns and basically making each in place and we don't need to return anything so this just can be nothing that's pretty much it let's go it's called a size and here we're getting the length of our matrix is gonna go for pi inch size and for J in range I choose size the reason we do this is that since we're doing it in place we do not need to visit the same cell same block more than once because then things have got messed up so that's why on the second for loop here we start wherever this guy he was so we wherever we've been we just forget about it and here what we do is that matrix J I and matrix I J are equal to the opposite of that so this and this is your desk just like this so if we create our array now our matrix I can come in very well it isn't a race so he for print does now you can see that we got a transposed matrix right but it's not what we want so but you can see that one two three now I have wanted for the first column you have tooken four we have four five six you have four five six and seven column and he has seven eight nine you have seven eight nine on the third column so or don't need to bring this right so then what I'm going to do is that we're going to go for I in range sighs because we just like we're just going to go through our rows and then we're going to call the matrix i yeah this should do it yeah so and this guy it doesn't really impact our complexity because it just goes to a row so this is because this guy's are adequate quadratic versions for polygons so the time complexity does Oh and in this is the batter we can get it is for this type of exercise as far as I know your figures with you know just like release in four spaces one because we're still using the same array we're not using not here we're calling this guy creating the size which doesn't matter this is for just for the sake of cleaning Kinkos so he can reference this guy here so I don't have to keep repeating this thing over and over again this is also easy to read and if we submit this hopefully you will get except that it did you can see here that I did a couple of other ones I took some other approaches here this one is quite good I guess I mean it's fast enough it a percent it's not horrible uses less and six percent of item online submissions so I guess it's okay so that's it for this exercise this can be a tricky one but if you know the basics of it can actually you can go through it a lot very easy and if you dig into the solutions here and or even when internet I gonna find a dozen different solutions for this exercise a lot more complex ones there's on and that's it hope you guys enjoyed this and see you next time let's stop this
Rotate Image
rotate-image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. **Example 1:** **Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\] **Example 2:** **Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\] **Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\] **Constraints:** * `n == matrix.length == matrix[i].length` * `1 <= n <= 20` * `-1000 <= matrix[i][j] <= 1000`
null
Array,Math,Matrix
Medium
2015
701
Hello guys welcome to my video directly guava problem vijay call insert into binary search tree subscribe now to receive new updates reviews and property value 12-12-12-12-12-12-12 all the best all the example of all the great wealth and property example person to Interest BST Web Lines At Least Sundar Roop Note 90 Let Me POCO F1 And Fashion Good Night Ok Bye To Tech 93005 20300 President Will Be The Side Of The First Time Voters Of This Great Content On Web Banner-01 A Question pet's impedance problem ok no problem content delivered want to insert month in place for the same technique suicide note friends benefit to decide weather to be left to right to have decided morning simple condition is ok friend one to check is the louisville to be late This model for example this great content 16 to write in this time to 5900 knowledge 3232 subscribe to press the switch of noida and load this channel by 9:00 am my channel lotus ayurveda 9:00 am my channel lotus ayurveda 9:00 am my channel lotus ayurveda india in 600 and you want to for binary search tree Vid Nod Let's Move To The Falling Fast So They Have Cost Condition Fruit Subscribe to this channel if you liked The Video then subscribe to the Page Dimple Yadav If You Pimple Value Than When Is That Case How To Suck Left Side Subhash Torch Pimentel Must Follow But You Have Some Will Have To Decide Based On Moral Values ​​Maurya And Decide Based On Moral Values ​​Maurya And Decide Based On Moral Values ​​Maurya And Roots Value Is Model Ok Send Notification Only Love If Then Notice Greater Andar Bhoot Wali Definitely For Rent In This Chapter Was Thirsty And Druts Values 1032 Example 3230 Middle Order Should Support Also Get Also Will Call This Function Again Insight Into BSP And Will Power Subscribe School Annual Function quintal Tanot Hai Suni This Follow What Happened First Point Notes Left OK Drops Right Option Destroyed During The New Route With Insisted You no deal also guava friend will see iron on slider code here and half inch right just give life is the giver is a root so let's mix dance with me 4a this area that lakshmi the currency of soon this area past drive loan so galaxy Gear Driver for Cold Bay Alert System Example Let Straight Vighn Is Length Players Want to Insert Values ​​of Players Want to Insert Values ​​of Players Want to Insert Values ​​of Love in the Best ISKCON 11th Five Year Roots and Currently Roots Not Under Root All Products Children Victims Not Looking at This Condition Will Not Be Satisfied and Roots Loop Condition Improves the condition of what do we call the function of this is the phone number were coming to destroyed when is the root in new call with values ​​through thugini according to root in new call with values ​​through thugini according to root in new call with values ​​through thugini according to this function fruit is this point and when you still Remains levels will check the same condition now in this test Lou Vincent in this condition school which country is called this condition third condition improves because of the value of lemon is lesson 20 current water not at all left side of the function morning school left side of the Function 9 near me the function call ok vidmate function and fight against them where is the function of that in the left part of the current fruit in the morning hard work function call attend a meeting of function ko lage is this time what is the root drug taste well in the morning but Function Call to the Left Previous Verses Lucia Twenty-20 Cricket Se It Verses Lucia Twenty-20 Cricket Se It Verses Lucia Twenty-20 Cricket Se It Enters into the Spider Condition First Conditions for Secondary School Third Condition Improves Ball Sun Gives May's Function Contours Left Parties' Syllabus Loot Left Parties' Syllabus Loot Left Parties' Syllabus Loot Will Harmoniously Make a Function Held Difficult Close Loop 8 Ep 90 Calling Lootpaat Again They Are Making A Third Function Quite Interesting Powder Function Qualities Which Will Help In The Stock Hogi Lekin Main Function Ko Lage Na Welcome To Dysfunction Call The Roots Nalon Ke Pehle Kam Hair Portal Par Play Services Welcome To Taste Between The Sun Roots Channel Tweet Celebs Condition ₹50 000 Tension Al-Sudais Condition Porn ₹50 000 Tension Al-Sudais Condition Porn ₹50 000 Tension Al-Sudais Condition Porn Site Will Create New Route And Will Return Back Particular Celebration First Nourish The Screen To Connect With This Part Of The Court Will Create A New Load Well Placid One Point Will Create New Route OK sweet create nude and returns on returning to know what is pair creating new note and returning and middle goa tourist function from all over the world its function ride from this point of the year award function and avoid to return back to the Must Subscribe Hotspot Of The Roots Left Will Welcome Equal To What Ever This Is The Function Return What Is The Function Returning Dysfunction Has Written In The New Note 11th Divine Love You Place On The Left Side Of Twelve Pocket Sudesh Kaul Will Get Excited And Left Side of 12th is Pluto's ascendant spray Venus Yantra this line has also exaggerated Mukesh once lines execute what people will return route past route and vitamin the function call with node s12 definitely suav in return back to life in colleges pain return back to dysfunction ok report fold is function which word is function 0 1 0 's pimples 's pimples 's pimples paste function yesterday morning veeravikram the new roots left disinterest quarter this is gone returns to this will return explosive device election dis-integrate will get addicted to the dis-integrate will get addicted to the dis-integrate will get addicted to the Laptop 70% Earlier Laptop 17Years Having Only Laptop 70% Earlier Laptop 17Years Having Only Laptop 70% Earlier Laptop 17Years Having Only 1230 Navya Winter You Not Love And Faith In There Part Plus Return Back To Dysfunction Co Election Laptop 17th Come 10 And Definition Of These Service Centers Pacific Tree Sunna One President Fruit What Is Written In Tire Root With Its Children At Strengthen Part This Point Is Interpreting Return Back To The Function Of Ten Election Departed Soul Executive Were Coming Back To The Main Function Fruit Juice Add Na Witch Life According To Call From You Soon That From Distant Second Line Rate Surendra Roots Tank Verification Levels Dresses Condition Was All Births and Condition Year-2008 Peace of Cold Have Been Called OK But Year-2008 Peace of Cold Have Been Called OK But Year-2008 Peace of Cold Have Been Called OK But Function Call a Call and Battles Returns Its Written and Right Part of the Route Will Become the Center Part of the Train OK Deposit in This Getting Beaten Up Election Minutes Letter disposal Seth ji this itself and Sudesh to officer frustrated will not even checked third condition for donations for sacrifice will go to this line and where returning to rule what is powder also written 19 gourmet hua bread call this intense function right from one department coincident Functions Were Turning in Between Tires Center Route in the Morning Returning Back to Sentence Route Distance in This Function College Staff and Students End Join This Page
Insert into a Binary Search Tree
insert-into-a-binary-search-tree
You are given the `root` node of a binary search tree (BST) and a `value` to insert into the tree. Return _the root node of the BST after the insertion_. It is **guaranteed** that the new value does not exist in the original BST. **Notice** that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return **any of them**. **Example 1:** **Input:** root = \[4,2,7,1,3\], val = 5 **Output:** \[4,2,7,1,3,5\] **Explanation:** Another accepted tree is: **Example 2:** **Input:** root = \[40,20,60,10,30,50,70\], val = 25 **Output:** \[40,20,60,10,30,50,70,null,null,25\] **Example 3:** **Input:** root = \[4,2,7,1,3,null,null,null,null,null,null\], val = 5 **Output:** \[4,2,7,1,3,5\] **Constraints:** * The number of nodes in the tree will be in the range `[0, 104]`. * `-108 <= Node.val <= 108` * All the values `Node.val` are **unique**. * `-108 <= val <= 108` * It's **guaranteed** that `val` does not exist in the original BST.
null
null
Medium
null
605
hello everyone welcome or welcome back to my channel so today we are going to discuss another problem but before going forward if you have not liked the video please like it subscribe to my channel so that you get notified whenever i post a new video so without any further ado let's get started so the problem is can place flowers it's very easy problem you have a long flower bed in which some of the plots are planted and some are not however flowers cannot be planted in edges and plots given an integer array flower bed containing zeros and ones where zero means empty and one means not empty and an integer n return if n new flowers can be planted in the flower bed without violating the non-adjacent flower rule violating the non-adjacent flower rule violating the non-adjacent flower rule what does the problem means let's see in this test case so this is an array given to us and it has 0 or 1 so 0 means that this plot is empty this is empty and one means that here there is a flower so we need to plant n flowers so but there is one condition that the flowers cannot be placed adjacent like if here it is one we cannot place a flower here because then there will be adjacent flowers that we cannot do so if we have to plant one flower so we can place it over here in place of this in this plot which is empty so then there will be no edges in two class so this is true so let's see like what we are doing is we need to place this flower in an empty plot we have to play place this in empty plot means wherever there is zero so where we can place it so either we can place here or we can place here now we cannot place here because previously it has one right and two flowers cannot be adjacent so if we place one here then two flowers will be adjacent so that is not a possible so we cannot place flower here also because then if flower is here then they will be again adjacent which is not possible which should not be done so ideally we can place this one flower over here so this flower will not be adjacent to any other flaw so in this case we can place these n flowers here so this is true now if let's say we have this another test case 1 0 same test case but this time n is given to us is two that means we have to plant two flowers so either we can plant here or here so we two flowers we have to plant so that is not possible right we can only place one flower then only it will not break the rule but if we have to uh place two flowers then one flower either we have to place here or we have to place here so in either case it will break the rule of the no adjacent rule right so that's why output for this will be false we cannot place two flowers in this flower bed we cannot place two flowers so i hope you understood what the problem is now let's see how we'll approach it so if this is the test case given one zero one and total flowers is say one so see um we if first point which we can notice is that we can only place flowers we can place flowers in empty bed wherever it is empty plot so empty plot is at zero so what all we have to consider these places where zero is there right this is one thing second thing is that for example we can place here if we are thinking to place a flower here then here and here it should be zero right that there should be empty plots and then only we can place flower here otherwise if here it is one then we cannot place flower here because then they'll be adjacent or if flower is here then we cannot place flower here because then they will be adjacent even if here it is zero even if here it is empty we cannot place we can do like this that if here it is one here it is 0 and here we can place but that 2 depends upon the whatever previously it has so if you can understand from these examples if we have to place here at this particular position in the middle of these two if you have to place here then it depends upon whatever it is present here and whatever it is present here so just pause the video and think that what should be the condition so that we can place a flower here two conditions which should be there see first if let's say this is i your i position first thing should be that this flower bed of i this value over here should be 0 means it should be an empty plot this is first condition second condition should be that whatever is previous here whatever the previous element that is flower bed i minus 1 this should be 0 and the next that is this index that is flower bed i plus 1 right this should also be 0 if this is 0 and this is 0 then only we can place a flower here right i hope you understood what i'm trying to say so this is the approach which we'll be using here so these two are the conditions now uh let's see how we will do it so we have one zero one and n is one let's say we will start from here and we at every step we will take two variables previous and next which will tell us whatever the previous element is and whatever next is right so over here it is one so obviously we cannot place a flower here so we will go forward here now here it is zero so that so we can place a flower right now let's say we have uh we have two here uh well let's see one only so see we have zero here now we will check what is previous to it previous is one and next is zero so can we place a flower here no because in order to place a flower both previous and next should be zero then only we can place a flower here in the middle so we cannot place here so we'll go forward also we will place we will have a total variable which will tell us how many flowers we have planted yet so now we will check for this we will find what is the previous of this previous is zero and next is also zero so now both previous and x is zero hence we can plot we can plant a flower here so we will increase our total by one and we will make this as one so this since we have planted a flower here this will become one don't forget to change it to 0 to 1 right otherwise it will affect the further iteration now what we will so now this will become one now we'll go further so we will iterate further and this will be zero so this is zero so we will see the previous is one and next is also one hence we cannot place a flower here we go forward and one is here so we do not take it obviously we cannot place a flower here so if you see at last our total how many flowers we have planted is equal to the number of flowers we have to plant so these are equal hence we will return true if otherwise over here n was 2 then obviously we cannot plant it we can only plant in this case we can only plant one flower so n is not equal to total so we will return false so in this case we cannot plant all the two flowers here in this flower bed i hope you understood the approach and the dry run let's see the code java code will be in the description so see it's very easy we have taken a total variable this will tell us how many flowers we can plant and we are running a loop until the flower bed size is not uh that is we did not reach the end of the flower bed or our total is less than n means we uh still have to plant flowers so if the flowerbed value is zero then only we can plant so we will find out the next if we are at the last index then we will take next as zero otherwise we'll take the next index then we'll find the previous if we are at the starting index that is like let's say over here then the previous will be taken as zero otherwise we'll take flowerbed i minus one as previous so if both are zero then only we can plant the flower at that index and we will do total plus right we will uh since we have planted a flash so we will increase total variable by one and at last if total is equal to n then only we will return true this will check if both of them are equal to each other then only this will return true
Can Place Flowers
can-place-flowers
You have a long flowerbed in which some of the plots are planted, and some are not. However, flowers cannot be planted in **adjacent** plots. Given an integer array `flowerbed` containing `0`'s and `1`'s, where `0` means empty and `1` means not empty, and an integer `n`, return `true` _if_ `n` _new flowers can be planted in the_ `flowerbed` _without violating the no-adjacent-flowers rule and_ `false` _otherwise_. **Example 1:** **Input:** flowerbed = \[1,0,0,0,1\], n = 1 **Output:** true **Example 2:** **Input:** flowerbed = \[1,0,0,0,1\], n = 2 **Output:** false **Constraints:** * `1 <= flowerbed.length <= 2 * 104` * `flowerbed[i]` is `0` or `1`. * There are no two adjacent flowers in `flowerbed`. * `0 <= n <= flowerbed.length`
null
Array,Greedy
Easy
495,735
1,732
Hi guys, Namaskar, let us do 90 day AC prep. This is the question. Lead code 1732. Find the highest altitude. 18th question is this from lead code 75. See what the question was. So, I am telling you that you are standing at zero altitude and I am telling you this. Have you gained or lost your attitude? Tell me what was the highest point. It seems like a very easy question to me. So I said that in the beginning you are at zero and then at -5 we have been given the data -5 -5 we have been given the data -5 -5 we have been given the data -5 1507 -5 1 5 0. -7 highest altitude 1507 -5 1 5 0. -7 highest altitude 1507 -5 1 5 0. -7 highest altitude what did you hit ok look we are standing on row and this is told we were on row -5 so we went and this is told we were on row -5 so we went and this is told we were on row -5 so we went down -5 reached forest now we reached -4 down -5 reached forest now we reached -4 f 5 so reached forest If 0 remained at one then -7 then reached at -6 then tell me at -7 then reached at -6 then tell me at -7 then reached at -6 then tell me at which location you went to the highest. If you went to the highest here then keep adding and the maximum value that will come is the answer. This is a very easy question so do like question. If it was not there, what did I do? I kept adding altitude, kept altitude zero and kept adding and kept comparing max, returned the maximum attitude that came, it was a very easy question, meaning this was actually really not worth doing it, a very easy question. Tha never the less no problem all kinds we are doing lead code 75 so whatever questions will come in that we will do so that was there we did that also no issues all right let's meet in the next question thank you so much by
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
1,190
Ajay Ko Hello friends good in this set bank wedding today we are going to do this is question on reverse substring between legs what is to do a spray that they will get a pin at school time it has parentheses inside it and some English lower case letters According to this constant and it would have been ABCD that now it would have been something like this, on this you had to do value your innermost but due to this, there is juice inside it, now there is a screen, now lever it, if the people from outside were the same then there is a substring on the inside. This answer is reverse lead, it comes tight, your answer would be this BTC 4G, after sharing this trick for this group, and you have to tell this, okay, I am so, the first thing is the balance, that is, opening. For threatened and watering there was crack on it then some more how let's see how to do gram reverse I have done some real work and here let's see the first one so this is again on this very and the subscribe inside this We have to reverse it, this time let's use this Jhali CEA is fine and this was a request to myself and the accused is that teacher, look at this, there are two legs, one is here and the other guy is here, so let's see for both of them. First I have to work for the innermost one, such a question has been said, so here I reversed the most that vol-4, here I reversed the most that vol-4, here I reversed the most that vol-4, then the remaining springs that have gone become some sperm, YouTube and video arrow came and this entries again an introduction inside it Then we will reverse the skin. Okay, so this transformer will go to this space and this is also the answer. Okay, let's look at the free band and send multiple entries on the last test case. Okay, so in this, but what to do? Let's first solve the innermost one, this is the whole train that NHI PTA Peeth now in these temples Karma I reverse that is that this next one here most current is this one is reverse airplane mode PP this story meaning It is spring, it has survived again, so this guy is the innermost currency, all the rest have also handed over that we do your fast, speed plane mode, E A I N, it has become reverse and the castor that is outside can also be outside, so the string. You don't have to do anything with this, it will come like this, so the resulting result was pop coding and this is what was to be done, okay, so you call this and let's meet and it is on video. If you have done the previous two questions, then This question will be very easy for you, how to do it in SI, so what was the inner most parateers, what else was said in it that any other leg which is not dependent on it, we had to call it first right and before that On two questions, now the minimum ad to make was on the website and it was off parent, we had done the same thing on both these questions recently, two penalty spinners are the most, it does not have big trees, we had called before that, okay, so these two questions I asked for reference to the logic which was used there, let's use it here also and see if it works or not, otherwise let's see before this test. Okay, so Prince William had made the extract last year. And out of this, you had made all the elements scientific, when it is done on a daily basis, then we worked till the opening, it is the same, we use the same hybrid SIM, the first one tied the opening racket, I did justice on this track, the second one was NIA. Bring has come again opening racket apne pc opening racket see this so now it is crossing gate ok so now if you see this trick outside only, earlier this guy was solved and there was no Odia on its replacement because we have to replace it Right, here also we will do the same thing, here when the crossing was about to be removed, this time I will pop the work content till the opening racket that it is ok, now we do not focus on how to reverse but look at the logic here. But time is like this so now we keep the field that I will remove this much content from here and will reverse it also on request this body will be done ok I have removed this much content from here and on its replacement I have appointed that team. Now I am ready to put this so now my sequence is in actual that the sequence must have been such that I have removed the previous content and have put his replacement Roddick. Now Jain looked ahead, I have another closing racket so if you see above Now look, if I have solved so many then the next dry fruits should be the one from here to here, right and this is coming on my track also, this is basically the logic of the previous question, so we used it. I was like, what do I have to do here, I have to remove the opening racket and reverse it, right, so many rinks, if I reverse it, this will become on you deoders, I will put this guy in its place, I will go to hand free mode, are you okay then? If you look here also, I have done all these people's work and Yusuf has come here, okay, now let's see what's next, I have done this, I have done that, I have done reports, now I have done one report here, so many people, so many. Friends, if these parents come inside this, then I will have to use all this screen here and keep it here that replacement works, if I reside about this then p.m. reside about this then p.m. How much reverse swing is made in plain mode? Okay, so on its replacement, let's put this guy in the back mode of 1080. Now I have done the next exercise. This is basically my complete. So, so many guys should have come. To do the complete work of and this also means that we had seen the logic earlier, so on 2 questions, we modified the same logic a little bit like in quarter sub here also or basically the work was to reverse it and so we used the reverse logic. But the reverse function from Xtra is at Jamia that this algorithm is already extreme but still we do not know how we will reverse it then we will do it with Prince Kodio so let's see the reverse function of Sab Singh so let's see that we Will force that my guy was sitting in his SP lead that so many guys I have increased till and so I should reverse all these brothers by doing so many guns and there should be A B C D A and if I pop the actor So look at their sequence, what will happen, then before that, D will come out, from here, first one and a half, this is good of CIA, okay, so basically the sequence of letters that I wanted is coming there when I pop it, but still what did I have to do with all these brothers. I had to replace it and put that I will have to send these prisoners to this camp and I will get them back on this cut, okay, let's see them once again, so when I leave from here, these two will now be seen in the court. But I can put right one of the deep created characters and put DCBA there in such a way that I don't know because there are so many people here, I can't do agro. Okay, so I will have to use some dynamic size here also, what data structure? Now let's assume that there is a data structure here, so I have given the first one, that is, the one that is locked is the worst one, what do I have to do at the end, I have to remove this one, first of all, I also have to mortgage it to the first one, from this data structure. Okay, let's write once that Pura-Pura came first after Dr. Ya, C came in this data structure still and Ya-Ya structure still and Ya-Ya structure still and Ya-Ya came first on this data structure and I have to remove it first, so this is The order is matching the queue, right, so by implementing the one here, this reverse one can be matched. Let's try using the queue once here, okay, so if I assume that the wells here. It is made because basically what I did was that after removing all these brothers, why would I first go here that like Rakshabandhan, only the dues would come here and then when the opening racket came, I had stopped the work. So I stopped the work, now there is same here, why do I remove the element D first, it will come out here, it will come out to be three, I have increased the tax, it will come out, I have put it to Tushar and one will come out at that time. But I have put the extra rooting that I wanted, the reverse one, I have tracked it well and why by using both then let's do another test with WhatsApp to report the same algorithm and see if it is ok then press this. Let's do this thing first opening bracket love you I my bracket hair is healthy diamond its / singer people back again so what am I going to do its / singer people back again so what am I going to do its / singer people back again so what am I going to do till I made these two I give that this is a lightning strike and why this first I removed it, added it here, still popped it, added it here, popped it, called here, did less but added it here, when you got bed, I stopped my work but so many There is a replacement character on the bande, a replacement spring is going to come, so ask in the next day, if I call all the guys, then first of all there is Kaya A Piya A Ka Ya and then LIC Ka Ya, so this time EEA which was supposed to be in my sequence section. BOAML had to be worn as replacement only after reversing so many of them. Right now what I have on this track is my bracket speed that some sequences are being run by BDO L so it seems to be working then let's increase the algorithm further that after Come and again hey grow cigarette So if I'm gonna make 1 you Love you but what do I have to pause until the opening credits come I have to put the sum of pipes first You're gonna be here Is that the drink That's it and at the end Now I saw that there is a pin drop here, so my work has been stopped, okay, now on his replacement, he got another one from here, removed the voice mail, removed it and pushed it to the pin here and you are okay. If I have my sequence is done, I have given wings to next9. It was the old one, so the mail was tight on gas, so my work is done here, now the next day I had to do it, all the friends who have done this trick will call me a prince. The right to make a return is still there, this can be done by the Chief Secretary, so if I want to do any work then I will basically request using Kyun, hey don't reverse me now brother, I need ILO for this order. We are fine, what can I do about this, if I know their size, tell me their size is 12345 and 60, this time I can do this work easily on the table, one character, I have come here to fold the arrangements of a friend. Now when I take out this guy by mistake, this is the access, I should come on the last tight and then I took out one, then it should come after that, I took out after that when I help and came, okay So on this sequence that from this sequence I should get the therapy, everything should be prince venture, now it is useful to make some tricks, so that is basically the specification of the language, if we want to share the rice, then we can create a new ring and this character. If I say so, then press it on his place, it will make the processing, okay, he does the whole album once, what do we have to do in porn, ice cream, I get my belt, on opening day, I simply push it that If we get alphabets, those who often rob, then they also have the same work in the first two. The work is done in the letter, on the one with closing date. What do we have to do on a tight project ? ? ? You are clear about your gender and alphabet. Using back is at stake long ago. To all those guys in the SE Corp who stomp until we get an opening credit and then after completing that we pop the opening racket after we get the opening date and then removing the why Let's make it tight on the track, so write all these algorithms, do it once on these faces, okay, now let's make Ajay shine like this, let's make the character torch light, for the wave, we will see that when the current string is a rolling bed. Then we have to do the complete work of remove, we have to do the work of reverse, right here on the second, when the opening racket is there, our profit is there or the ABCD characters are sleeping, then simply we will do that on the track, so that now it is completely cooled. Let's take what were our steps on this, make a who, there is a network of characters and why is it increasing after removing everyone from the pack, then till the track dot, I do not have my basket, till then goodbye you are fine, it is about tax. Removed your breast and you have taken out all the guys and put it on it. You don't guys, till the time of pregnancy, put it on this book, I am my album, this is complete, now we have to do the work of making them, just look at the fist. Take the answer, how to make it, save whatever content on my extract, that much time is required to make castor oil, write and character replay, start filling them from the last, then this work is done, keep the iPod and the elastic, if it is fake, then I have written that text. I had cropped both of them one by one, indexed them and then they lag behind again after it is completely completed that I have to make it electric and tight, that will become the trick, so let's burn it and see that it is coming right, its cost. For a good reason, the teacher is doing this logic, but still one part of it can be improved by doing the reverse part, like a, I am yours, currently, what are we doing, when I am a I got the string so I gave it to him and put the racket on the track. He teaches ABCD tuition, so I want to reverse so many brothers. Right, for the purpose of doing this reverse, why would I make a separate one and put all these brothers in this. Between this and again in hair removal, on their replacement, why did I remove all these brothers and asked the people here that if they have a length belt on it, then I removed it and showed these rings for the screen. For this, I have worked twice, first by doing that from here and putting it on this and then if you remove it from here and do it on this, then for the balance, two help order of Agri also but why is there a striker, then the road will grow to do this work. For this, there will be some internal workings in Plus also, they will do some internal work so that if we look at it for macro, then this much work will be done for one tube well and in Plus there will be some less for their dynamic grand, now that I would have got a batter to reverse it completely. If I add all these processes, you are ready, there is something before, there is something after, and this string is lying here, now it is on the original border, AB bleed, that if I had to reverse the address, then this point. You keep this point, how do you reverse it, keep moving it forward and put it back, if there was a balance penis here, then I would have to hydrate egg white and because it is there, then both the input read and write operations here are very much. If we look at the exact time complexity, then we will get improvement from this one. We have spread order here too. It is okay, but in exact time complexity, it will be more beneficial to do this work on the address, then reversal on the address. To solve this question, please make a video on Twitter patel10 You can use this idea and install it, see you in the next video. Thanks for watching a video.
Reverse Substrings Between Each Pair of Parentheses
smallest-common-region
You are given a string `s` that consists of lower case English letters and brackets. Reverse the strings in each pair of matching parentheses, starting from the innermost one. Your result should **not** contain any brackets. **Example 1:** **Input:** s = "(abcd) " **Output:** "dcba " **Example 2:** **Input:** s = "(u(love)i) " **Output:** "iloveu " **Explanation:** The substring "love " is reversed first, then the whole string is reversed. **Example 3:** **Input:** s = "(ed(et(oc))el) " **Output:** "leetcode " **Explanation:** First, we reverse the substring "oc ", then "etco ", and finally, the whole string. **Constraints:** * `1 <= s.length <= 2000` * `s` only contains lower case English characters and parentheses. * It is guaranteed that all parentheses are balanced.
Try to model the problem as a graph problem. The given graph is a tree. The problem is reduced to finding the lowest common ancestor of two nodes in a tree.
Array,Hash Table,String,Tree,Depth-First Search,Breadth-First Search
Medium
235,236
355
today we're gonna be working on lead code question number 355 on design twitter i design a simplified version of twitter where users can post tweets follow and follow another user and is able to see the 10 most recent tweets in the user's news feed implement the twitter class twitter function is going to initialize the twitter object post tweet is going to be the user and its tweet id and then the list of integer get feed to uh get news feed is gonna give you the user id and we're gonna be returning 10 most recent tweet ids in the user's news feed each item in the news feed must be posted by user who the user followed and by the user themselves so we're gonna keep the record of both of those kind of tweets okay tweets must be ordered from most recent to least reason okay most recent to the least reason so we're also going to be using the priority queue for that okay follow is going to be a user id and the followee id so first the user id and then who the id of the person who the user is following unfollow is again the user id and the follow e id okay for this one but we're gonna have like a global i think with the global scope is a time stamp so for that we'll say private uh static and timestamp which is equal to zero okay and then we're gonna have our map which is basically an integer which is gonna let the id associated to the user so for that we're gonna say private uh a map with an integer and an object of type user it's gonna call user map i'm gonna call it user map okay we will be initializing it own so there are two other things which we're going to use again one is going to be the user and the other one is going to be called the tweet so that we can actually uh like basically uh do the timestamp and so we want that object to private class tweet okay it's gonna have an id it's gonna have a time and it's gonna have like a tweet which is gonna basically point to the new tweet so for that well you just say public uh tweet next so this tweet is gonna be like a linked list which is where it's gonna be pointing to some other tweet okay and then we're gonna initialize that now with the constructor uh tweet is gonna be getting an id so we're gonna say that this dot id is equal to this incoming id time is just whatever the timestamp is uh increment that and that's going to become equal to time and the next is going to be equal to initially going to be equal to null our other object our other class is gonna be the user one we're gonna say class user okay for this one we're gonna again have the user id and id we're gonna have a set where we're gonna be telling that uh who which other users this user is going to be following so public asset of an integer followed okay and then we're gonna have a head tweet so a tweet uh like which is gonna be the first tweet so every single time when a new tweet is being tweeted by this user or another person who is following so this is gonna get updated uh tweet underscore ahead uh we're gonna do a few things with it we're gonna have a function called uh like we're gonna initialize it with the constructor uh it will be getting an id just like the tweet we're gonna assign this id equals to the incoming id we're gonna say that the for load is gonna be initialized to a new hash set and the follow is gonna have this idea for those kind of function we're gonna be defining soon so basically it will just tell you that uh first like it should follow itself that is gonna be because when the user is created he's gonna start following himself right away tweet head is gonna be equal to null and depict it's also gonna have follow so public avoid follow and id okay where we're gonna be adding that i did in the followed for load set okay it's also gonna have unfollow a user can should be able to unfollow it's gonna take that id and remove it from that set so followed dot remove that id okay what else and it should be he should be able to post so public void post and the id and when he is posting it basically we are interested in updating the tweet head so we're gonna say we're gonna because he posted we're gonna create a new tweet where the new tweet we're gonna give it an id and then the t dot next is gonna be equal to uh our tweet head and we're gonna update our tweet head to this new tweet okay nice so we are basically done with this one now we're gonna initially when the twitter comes and we're gonna be making use of this user map so we're just saying user map is gonna be equal to new hash sent now sorry hashmap and we can say it takes an integer and a user okay uh the first thing is the post tweet right when you are posting a tweet uh what exactly are we doing in the post wait so basically we say we check the map and say that if the user exists right if the user exists uh what should we do if the user exists we should just post it right so if user map dot contains key user id right so if it does not have it so basically if we don't have that uh if we have that user right so we're gonna we're not gonna be entering this one if we have that user so if we have that user all we're going to be doing is the user map dot put uh take that id actually first get it user id right and then post it with that new id tweet id let's see if the user does not exist then we're gonna be creating the user u is equal to a new user with the user id and we also need to put that same user in the map user dot put this user id and this new user right so that should do for the post tweet so one thing is the we need to do the now we're going to be working on the get news feed right so for this one because we need a list of integer back so let's just define that list of integer is going to be equal to result is equal to new realness actually just do with the linked list both should work okay uh okay the first thing is he's asking about the user feed right so the user should exist right so let's just make uh do that sanity check that what if the user does not even exist so if the contains key is not true for this user id we know we're going to be returning a result nothing is gonna be in the result okay now we need to get the users which are being followed by this user right so for that user map dot get if i do the user id so i have the user now so once i have the user i can actually check uh the set of users it's he is following so followed so uh i can do that so that's gonna give me a set of what users user right okay actually those it's gonna give me an integer it's going to give me an integer uh of you we're going to call them users so follow now if you check at the follow uh for followed it's going to give you a set and the set is basically a set of integers okay so we have the user's name all right and then we're gonna be using the priority queue based on the timing when they put the um and it's gonna be like uh you know descending in a it's gonna be in an order where the most recent one is going to be has the priority so periodic queue which takes a tweet uh we're going to call it our queue uh it is equal to a new periodic eq okay off tweet okay and we are gonna define it's gonna have the user start size that's how big that is gonna be and other than the size we're also gonna say that how if it is getting a and b what it should do is like it should look it should return b based on b time minus a dot time so once we have it okay so okay now we're gonna get the user from this list of users okay and every for every single one we're gonna say that the tweet t is basically equal to uh we're gonna get the header and then move the header to the next one and then get the new tweet and that's how we're going to fill it up so we're filling it up filling up our priority queue right so for that we'll say user map dot get user hit this is gonna give us a user and then we're gonna do is that tweet head so it's gonna give us the tweet on the head itself if it is not equal to null right if t is not equal to null we can put it into the queue q dot add that t okay now we what we're going to be doing is we're going to say our n is equal to 0 right and we have two things while we have our queue is not empty and we also wanna make sure that we don't wanna return more than 10 values is less than 10. well these two things because that's in the problem statement uh we're going to say that the tweet t is equal to q dot poll and then the result dot add that t dot id and then we're gonna increment our pointer and then if the t dot next is not equal to null we know that we can uh q dot add that t dot next because we want to fill it again right yes and in the end once we come out of this while loop we can just return the result and that should be enough for the get news feed now the last two things that the follow and unfollow follow is basically saying that if the user map dot contains key follow our id so basically we are checking that if that follower id basically does not exist right so we're going to create it for him right but if it does we want to see that if the follow e id exists or not again if it does not exist we're going to create it if both of them exist all we need to do is to say that get that user map dot get uh follow r id dot follow e id okay that looks good now we just need to create the new users if they don't exist use it map down put follower id with that user say very similar things over here user u is equal to new user of follow eid user map.put user map.put user map.put now follow eid with you okay last thing is the unfollow one again if any of them does not exist we can just return no there is no need to do anything else so if the user map says that i don't have contains key for follower id okay i don't have it or i don't have contains key for follow e id we can just return no need to do anything else otherwise if both of them do exist we want to say that give me that user okay we're gonna get that user which is the id done unfollow and follow e id so there is an advantage we are actually making use of using these classes of the class because the this unfollow is already defined in the user okay we do not cannot find the symbol for clearity map integer time which one should we keep going on time step user map should be user map follow id should be follower id this is looking good and it did pass all the test cases
Design Twitter
design-twitter
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed. Implement the `Twitter` class: * `Twitter()` Initializes your twitter object. * `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`. * `List getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**. * `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`. * `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`. **Example 1:** **Input** \[ "Twitter ", "postTweet ", "getNewsFeed ", "follow ", "postTweet ", "getNewsFeed ", "unfollow ", "getNewsFeed "\] \[\[\], \[1, 5\], \[1\], \[1, 2\], \[2, 6\], \[1\], \[1, 2\], \[1\]\] **Output** \[null, null, \[5\], null, null, \[6, 5\], null, \[5\]\] **Explanation** Twitter twitter = new Twitter(); twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5). twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\]. return \[5\] twitter.follow(1, 2); // User 1 follows user 2. twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6). twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> \[6, 5\]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5. twitter.unfollow(1, 2); // User 1 unfollows user 2. twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\], since user 1 is no longer following user 2. **Constraints:** * `1 <= userId, followerId, followeeId <= 500` * `0 <= tweetId <= 104` * All the tweets have **unique** IDs. * At most `3 * 104` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.
null
Hash Table,Linked List,Design,Heap (Priority Queue)
Medium
1640
70
in this video we'll go over lead code question number 70 climbing stairs here's the question you are climbing a staircase that has n steps you can either climb one step or two steps at a time how many distinct ways can you climb to the top we'll also assume that n is at least one so for example if the staircase has three steps then the first way to climb the stairs would be to take one step and one step so that's one way to climb the stairs another way would be to take one step then take two steps so that's the second way and the last way would be to take two steps first then one step and that's it there's a total of three distinct ways to climb the stairs so first let's look at the recursive solution and once we understand that then we can improve it using dynamic programming so let's look closely at the very first decision you can make again you can take either one step or two steps and those are your only choices let's say you choose to take one step well after you take that step the next question would be how many ways can you climb the remaining stairs your other option would be to take two steps so similarly after you take those two steps the next question would be how many ways can you climb the remaining stairs those are your only two choices so we can now write the recursive definition which is the total number of ways to climb n stairs is the number of ways you can climb n minus one stairs plus the number of ways you can climb n minus 2 stairs we also need to define the base cases if a staircase only contains one One Step then there is only one way to climb it which is to take one step if a staircase contains two steps then there are two ways to climb it you could take one step then another step or you could just take two steps at once now that we have the base cases our recursive definition will work so here's what the code looks like in Python where the function name is going to be climb this part here takes care of the base cases so if n equals 1 then we return 1 and if n equals 2 then we return two if n is greater than two now we hit the recursive case so we'll call climb and pass n minus1 which is the number of ways you can climb nus 1 steps plus the number of ways you can climb n minus two steps and we return that result let's visualize how the recursive tree looks so let's say n equals 5 so we'll call climb and pass in five since five is not one or two we'll make two recursive calls we'll pass four to the first recursive call since that's n minus1 and pass 3 to the second recursive call since that's nus 2 we still haven't hit the base case on either of these functions so we'll recurse again climb with n = 4 will call recurse again climb with n = 4 will call recurse again climb with n = 4 will call climb 3 and climb 2 on the other side climb 3 will call climb 2 and climb 1 now we have reached some of the base cases when n equal 2 there are only two ways to climb the stairs and when n equals 1 there is only one way the only recursive calls left to do is over here and now we finally hit the base cases for everything we can now find the answers by just adding up all the base case values so the final answer is that there are eight ways to climb five stairs so this is the fully recursive solution and it works but now let's take a closer look at this tree notice that we are calling climb with three twice here we are also calling climb with two three times and climb with one two times the point here is we're calling the same function with the same arguments over and over again and this leads us to going down the exact same recursive branches multiple times you can see that in this far left Branch with each recursive call n gets reduced by 1 until we reach Nal 2 so this tree will have n minus one levels and since each non-leaf minus one levels and since each non-leaf minus one levels and since each non-leaf node has two branches this algorithm ends up running in O of 2 to the nth power time so it's very inefficient how can we improve this and avoid making the same function calls over and over again that's where dynamic programming comes in instead of making redundant function calls we're going to save our previous results and reuse them now there's two ways to do this a top down or a bottom up approach I'll be focusing on the bottom up approach in this video since this approach allows you to eliminate the recursion entirely so let's say there are five steps again but this time we'll create an array that goes from index 0 to index 5 the value of each element is going to represent the number of ways you can climb a staircase where the number of stairs is equal to the index of that element so for example the value at index 3 should be the number of ways to climb a staircase with three steps the idea is to start at the beginning and reuse previous values to build up all the way to index 5 so to start we'll need at least two values so let's fill index zero and index one with one since there's only one way to climb one stair now I guess you could argue that there's actually zero ways to climb a staircase with zero stairs but for this implementation we'll have to start with one and you'll see why in a second so we'll start filling in values at index 2 and the question is how many ways can you climb a staircase with two steps as we know the recursive definition is it's the number of ways we can climb One Step plus the number of ways we can climb zero steps and as you can see we already have those values 1 + can see we already have those values 1 + can see we already have those values 1 + 1 = 2 so there's going to be two ways to 1 = 2 so there's going to be two ways to 1 = 2 so there's going to be two ways to climb a staircase with two steps next let's find the number of ways for three steps and that's going to be the number of ways to climb two steps plus the number of ways to climb one step and again we have those values which are two and one so there's a total of three ways to climb three steps and we continue these same steps the value of each element is the sum of the previous two elements so instead of making the same recursive calls over and over again we calculate each result only once and reuse them to build this array from the bottom up we're now finally at index 5 so we're going to add the number of ways to climb four stairs with the number of ways to climb three stairs which is 5 + 3 which equal 8 so now we which is 5 + 3 which equal 8 so now we which is 5 + 3 which equal 8 so now we know that there are eight total ways the big difference using this method is that we only had to Traverse an array of length n + 1 once so the dynamic length n + 1 once so the dynamic length n + 1 once so the dynamic programming method reduces the runtime to O of end time I'll also point out a fun fact here if you look closely at the sequence of numbers you'll see that this is actually the Fibonacci sequence each number is the sum of the pr previous two numbers before it so what this question is really asking you to do is to find the nth Fibonacci number there's also one more optimization we can make right now this algorithm also runs in O of n space because of the array that we have to make but we actually don't need this entire array to fill in any given element of this array we only need to know the previous two elements before it that's it so now let's look at the code and I'll show you the bottom up dynamic programming approach that runs in O of end time and uses constant an space I'm going to bring over this array diagram from the previous section but I want to emphasize that this array does not exist anywhere in memory I'm only leaving it here so that we can make the connection from the previous section so first let's assume n equals 5 again the base case is if n equal 1 in which case we'll just return one this is not true so let's move on then we'll create a variable called one before and set it equal to one in the array diagram this variable corresponds to this El element here so it's the element one before the total number of ways that we're about to calculate similarly the next variable will be called two before and also be initialized to one so that corresponds to this element in the diagram here it's two elements before the total that we're about to calculate the last variable to declare is called total and for now we'll initialize it to a dummy value of zero then we'll start the loop to build up our answer we already took care of the case where n equals 1 so we'll start at two and since the python range function excludes the ending Index this will end that index 5 we don't directly use the I variable in this Loop so I'll keep track of it here so first let's calculate the total which is going to be 1 before plus 2 before which equals 2 as you can see we're doing the same thing as what we discussed before where we are adding the two previous values together then we need to update one before and two before in the diagram this means shifting them to the right so we'll set 2 before equal to 1 before and set 1 before equal to total and now you can see that they have been shifted now we're ready to loop again and calculate the new total equal 2 + 1 which is the new total equal 2 + 1 which is the new total equal 2 + 1 which is 3 and again let's update the two trailing values two before will become two and one before becomes three and then we do the same thing notice that since now we aren't using an array anymore no matter how large n is we only need to use these three variables to build up our answer so we're using constant space now we're at the last iteration total is 5 + 3 which is8 two iteration total is 5 + 3 which is8 two iteration total is 5 + 3 which is8 two before is updated to be five and 1 before becomes eight but at this point we're already done so all that's left to do is return total which is eight and we're done
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
498
hey guys I hope you're doing well this is Jay sir who is not good at algorithms I'm making these videos to prepare my interview in eczema in this video I'm going to take the cap for 9 8 diagonal Travis we're given matrix of n by n elements we turn audience of the matrix in diagonal order as shown in the below image 1 2 3 4 5 6 7 8 9 we need to return 1 2 4 7 5 3 6 8 9 well let's analyze what's the characteristic of this problem so we are going to return this array into another format like a in a diagonal way right so what's the common what's what are these three numbers in common which is in effort in the same diagonal Wow if we take like take a look at the index we know that 4 3 being the X should be 1 0 2 is 1 2 1 so their sum will be it's the same for diagonal right this sum is 0 1 2 3 4 so this is the how to say this is the key of each diagonal right what for the direction if it is the first one it's to the right if next one is to left right if you look at to the yet look at in a horizontal view right left right so we could also determine a direction just by the key the oddness of the key right so we could actually create each create all the array for each diagonal and we loop through original tricks like one because he's too right we push on that we like this no we I'll shift right if it is this is odd this is even this is odd if we travel this way then we push right and then finally we will collect all the diagonal array and it will generates the output what right cool let's try to do that by good luck well how many are there for like this for this one you see that there should be M this is the end so n plus n minus 1 right so new array M plus matrix I say cost Rosi close matrix done in column C close matrix that if metric is empty it might be empty right yeah matrix turn and if rows returned empty because we were using dot 0 and then so this might be empty new array rows plus cost plus 1 a minus 1 right and now we could loop through all the numbers in a ordinary way ordinary order he would be I plus J right and if ki if it is are then we on shift Oh the first one is uh even right this is a zero so is even so if it is even then we all shift it should be diagnosed key shift the shift Rose I know matrix I okay a Salaam equals cash Tina for the other cases we are shift we will push them right this is even and then we push yeah finally and then we collect the result right just to return diagnosed reduce result they are empty return result resolved to a push the data are running code we forgot to initialize this is my bad man okay cool Sammy yay we're accepted and let's try to analyze that time and space complexity for time we had actually Travis all the elements and then Travis through them again right so it's to time to round and so it's generally M space we use this array to holds all the elements but it's actually this is a result and yeah we use an extra base diagnose it's also um and yeah so that's all for this problem hub helps see you next time bye
Diagonal Traverse
diagonal-traverse
Given an `m x n` matrix `mat`, return _an array of all the elements of the array in a diagonal order_. **Example 1:** **Input:** mat = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\] **Output:** \[1,2,4,7,5,3,6,8,9\] **Example 2:** **Input:** mat = \[\[1,2\],\[3,4\]\] **Output:** \[1,2,3,4\] **Constraints:** * `m == mat.length` * `n == mat[i].length` * `1 <= m, n <= 104` * `1 <= m * n <= 104` * `-105 <= mat[i][j] <= 105`
null
Array,Matrix,Simulation
Medium
2197
201
okay so what's up guys this is a here and let us continue with the next question of a bit manipulation playlist so the next question is about the bitwise and of range numbers the question is a medium category so let us read the question is very self-explanatory as well so we have been self-explanatory as well so we have been self-explanatory as well so we have been given two integers left and right that present represent the range inclusive of left to inclusive of right return the bit wise and of all the numbers in this range so for left equals to 5 right equals the output is for so let us first understand the input and output and then we can think of all the possible approaches right great so we have what we have here so how for left equal to right the output is four let us write the binary representation of five so it is nothing but uh 1 right and then we have six which is nothing but 1 0 then 7 is nothing but 1 so we need to return 5 and 6 and 7 right so if we do five and six what would be given 1 0 I'm add and then you will get 0 and one then I need to do the and with seven s is nothing but 1 one if I do and operator 0 and one and you can see four is your answer right so whatever we did that is the method one that is the brute for whatever the question is saying you just do that and that would become your Brute Force approach so that and that is why it is very easy to guess as well so method one and again will again Take You O of n time capity as o of one that we will calculate the and for the given range now this and it takes o of one but since we are traversing in the range it would be o of n right now what is Method two try to pause this video try to think of the approach that how can we do this in log n right so let me write some particular bunch of numbers so I will write 1 then six is nothing but 1 0 s is nothing but one and can You observe something here can you observe something here so if this is five then definitely next number is your even number and even number cannot end with a set bit why because if you have a set bit and the end then definitely this will give you a weightage of 2^0 right 2 will give you a weightage of 2^0 right 2 will give you a weightage of 2^0 right 2 power 0 is nothing but one so adding one to any number will give you an odd number if you add one to an even number which will give you an odd number right so to get an even number definitely there should no one present at the last and that is why and maybe you can understand that is one of the reasons that is why the reason you can see that there will be an unset bit if you have a even number so similarly for eight if you see for8 it would be 1 0 right so what we need to observe here is we need to find the constant part if at such place the bids stop flipping then definitely to its left hand side every bit will remain same right so that means we need to start from the right hand side and we need to cover that when your range F that is we find the constant part so what I'm saying is that for five and 7even what are the values 1 0 and 1 for 7 it is 1 right so when I'm at this position I will see what I will see H so I will check that my left and right while my left is not equals to right because I want the flip to discontinue at that position right so what we can see five and seven is not equal as of now so I will reduce one bit and I will just say count Plus+ so count and I will just say count Plus+ so count and I will just say count Plus+ so count was initially zero it become one so again what I will do I will right shift the numbers that is left equals to Left Right shift one so left uh right shift one or you can also say left is equals to left by two and similarly you can say right is equals to right by two so again 5 by two will give you 5 by2 will give you what 2 and 7 by two will give you three again left and right is not equal right so again I will do a count Plus+ 2 so again 2x two is 1 do a count Plus+ 2 so again 2x two is 1 do a count Plus+ 2 so again 2x two is 1 3x 2 is 1 so now you have a constant part right so at this place you will not do a count Plus+ and this is your do a count Plus+ and this is your do a count Plus+ and this is your weightage this is your final answer you'll just say whatever your left and right is so left here is one so I have traveled two times from my right bit from the right mode B to the left side right so what is the weightage here is so to get the weightage I will just say one left shift two right so this is nothing but 1 into 2 Star two which is which will give you four so I think this part of screen is not visible let me just scroll it through so 1 into two star 1 into 2^ two will give you as four star 1 into 2^ two will give you as four star 1 into 2^ two will give you as four and four is your answer right so what is the logic here you just need to check that once your left and right is equal right and definitely all the bits before it would be same right and you can take the weightage whatever or what the you can take the weightage for the times you have traversed from the rightmost bit to the left bit until you have left and right as equal correct so for the first glance if you're solving this question for the first time maybe it would be a bit uh difficult to digest the logic but then again spend some time with this question try to run in some more cases and you will eventually get it right yeah so let us switch back to the code now so that's the code in Java we have so while left not equals to right we are uh right shifting it or you can say right shifting or dividing by two of both the numbers and we are doing countless and the last we just have to say either you do left shift C or right left shift C right that remains samees great so what is the time complexity o of login would be the time complexity and O of one would be your space complexity the same code will run in C++ complexity the same code will run in C++ complexity the same code will run in C++ as well so let me just hit the Run button for you great so that's been done right so uh you can get all the source code available in my DSA repository you can start and folk my DS repository to get help with the source code maybe and yes this consist of many standard questions we have covered in past that is from gfgp and everywhere so yes uh what else so yeah if you have understood the solution and the problem and solution as well so please like share and subscribe till then keep learning keep bye-bye and take then keep learning keep bye-bye and take then keep learning keep bye-bye and take care let us meet again in the tomorrow's video
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
2,000
Welcome back tu video and in this video we will see this easy level problem whose name is reverse prefix of word so friends directly we see the example and understand it then friends we will be given a word and a character will be given like right here. If di is given then we will look at di first, that means we will move left and right and wherever there is current first, we will stop there and then from here we will take this word from starting till here, we will reverse it, then if you write reverse. So what will happen is that first the C will come, the C, B and A, so what have you done in this part, you have reversed it and then this part is next to it, you have appended it to this, so this is our output, one word will be given and one character will be given and the character will be We will find the index where if the index is -1A, that means where if the index is -1A, that means where if the index is -1A, that means any characters which will be returned will be fine and from there we will reverse and then do the remaining caps and return them, so now let's implement it directly. So in the word string, the word is A and in care K, I am giving us the character from where I want to reverse, so first of all we find the index, what is the index of which character, so the word dot index of, so this is the function, friends, which is OK, so if our word was A B C D I F D then we would index it as 01234 56 and the support would be -1, so first of all we would check the would be -1, so first of all we would check the would be -1, so first of all we would check the story ID X. If - 1 is not there then IF I story ID X. If - 1 is not there then IF I story ID X. If - 1 is not there then IF I DS index which is if it is -1 then DS index which is if it is -1 then DS index which is if it is -1 then return the word from here because we do not need to reverse anything. Friends, if it is not so then only then we will go below this line and go down then first of all what How to do this: When we are given, we have to How to do this: When we are given, we have to How to do this: When we are given, we have to extract this word from here, so for this we will substring it, so there is a function sub string, so we have to write the word dot sub string and from zero we will take idli x + 1 because if If index 3 comes + 1 because if If index 3 comes + 1 because if If index 3 comes then what is it that it will not include di so to include di I have to take IDEX + 1 right and take IDEX + 1 right and take IDEX + 1 right and pass it to stringbuilder is new string builder so that we can reverse and this new stringbuilder is a. Now on this what we did yesterday, you can do reverse function in different steps also but I have combined it in one step so that number of lines have to be written less so basically I repeat again from here we This word, after extracting one word, made it an object of StringBuilder. Okay, now in StringBuilder we have the function Belt in Reverse which does the reverse and then what have we done with it, we kept it in StringBuilder and named it. SP is ok, so I hope till now we have understood, now we will have to do second check that now the remaining words will have to be appended and in this, but some things will have to be kept in mind, it is assumed that this word does not exist, only this much, then some other word. No, okay, then what can we do here we will put okay, that means whatever you are talking about, the index of which is 4, should be smaller than its length, like its length is seven, now four is small, so it means and We have characters, we will institute this step only when we have more characters, so speed and now we have written till di, what we need, what will we write for ff, we will again do the substring function on it and write substring and here. What will we write now, we will start here and add it, then our I think is reduced, we just return it, then run it and see if it is good, this is our solution, accept this video, see you in the next video.
Reverse Prefix of Word
minimum-speed-to-arrive-on-time
Given a **0-indexed** string `word` and a character `ch`, **reverse** the segment of `word` that starts at index `0` and ends at the index of the **first occurrence** of `ch` (**inclusive**). If the character `ch` does not exist in `word`, do nothing. * For example, if `word = "abcdefd "` and `ch = "d "`, then you should **reverse** the segment that starts at `0` and ends at `3` (**inclusive**). The resulting string will be `"dcbaefd "`. Return _the resulting string_. **Example 1:** **Input:** word = "abcdefd ", ch = "d " **Output:** "dcbaefd " **Explanation:** The first occurrence of "d " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd ". **Example 2:** **Input:** word = "xyxzxe ", ch = "z " **Output:** "zxyxxe " **Explanation:** The first and only occurrence of "z " is at index 3. Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe ". **Example 3:** **Input:** word = "abcd ", ch = "z " **Output:** "abcd " **Explanation:** "z " does not exist in word. You should not do any reverse operation, the resulting string is "abcd ". **Constraints:** * `1 <= word.length <= 250` * `word` consists of lowercase English letters. * `ch` is a lowercase English letter.
Given the speed the trains are traveling at, can you find the total time it takes for you to arrive? Is there a cutoff where any speeds larger will always allow you to arrive on time?
Array,Binary Search
Medium
1335,2013,2294