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 |
---|---|---|---|---|---|---|---|---|
76 | it has been asked by Facebook Tik Tok Amazon lyt Google yendex Snapchat nagaro Adobe Airbnb LinkedIn Microsoft Apple Spotify Uber we can have let's quickly see what the problem says the problem is simply short and simple saying that we have two strings s and D of length M and N okay respectively uh just one thing in the future code you will see that I represent my string n with length M and string t with the length M there's just a small change here so just remember that and return the minimum Windows substring of s return the again substring is a part of a string window is nothing but same saying okay it's a substring of s such that every character in t including duplicates which means if in T I have duplicate characters let's say a b c a is coming duplicate a is coming twice so in the window of s which I will take my a should also come in twice so okay and including the duplicates is included in the window and again in that window portion which I have I can have a B I can have other characters also d c it's just that in the window all the characters of D should come in that window of s that's the only condition and all such Windows okay all such possible windows I have to minimize the length of that window and return that specific window which means return that minimum length window having all characters of T in that specific window now just says that there will not be any two windows having same so basically cases which are generated the answer is always unique which means there cannot be two windows where the window length is minimum but you have two different strings that's not required that's not uh given and also if it was given that it would have specifically mentioned that you can return any window but yeah uh for example for in this case you will see that this is one of the window in which you have corrector a corrector B Cor C and this is my condition which means all the correctors again duplicates also it should be inside my back window so right now the length is six but I have to minimize my length so I will try to find some other window so some other window is this specific window again I have a b a and c a b c order doesn't matter I just only want to have all these characters inside it now this length is four so okay I can minimize my length this is the minimum length and just return that specific minimum length window that is B A and C is the answer now uh first very basic boot Force approach which comes in our mind is AR and I have to try on for all the possible substrings and in that okay which means we will try on as you can see a substring is okay you will try on for this string then this which means you are trying on for all the possible substrings now number of substrings in a string of length n again remember I said that my string s is of length n and string T is of length M just a small change uh so for sure to just figure out all the possible substrings I will have o of like n Square substrings so o of n Square will for short com in picture now when I have figured out a specific substring now I will have to check if all the characters of p is actually lying inside my that substring or not so one very naive way for this specific check to just check okay all the characters of my t is lying inside my that window that string which I have formed because I know I have n square substrings but yeah one to just have a check okay that specific substring that specific one subring is actually good for me or not and it will be good only when the characters of T is lying all characters of T is lying inside that substring so very na check will be I'll just go on and check okay if that character of T is inside my window or Not That C of is inside my window or not and all that stuff so for sure I will have to iterate on my entire for every of my sub strings so that will be o of n sare into M but you have so far thought of I why have to you go on to every character again and again for T just make sure that you keep track of all the characters of T in a hash map because you know that you have only English alphabets so you will have only 26 characters so now for that specific window just make sure the just make sure that okay you have just 26 characters frequency so just make sure that all these characters which are here for t for T should lie inside that specific substring so I can just simply rather than iterating again and again on the entire string T I can keep track of the count of frequency of the characters of T and then use those characters so I will reduce that to just over 26 time rather thaning on all the characters again and again for the entire and I just for one subring I just have to iterate on the 26 CEST to know what's the Frequency inside my T and would not have to go on the entire T again and again so that can reduce our time a bit but still it is still high it is still o of n squ so right now we have see okay from o of n square into M then o of n square is the complexity which we have seen so far but um why you were finding all the substrings but if you remember that okay you just have to find a substring with the minimum length so if you have found a substring then why can't you expand or drink that substring why you have to go and try to find the subing again and again now again the main two hints in this problem is that you have to go and find a window you have to minimize or maximize that specific window length window and subing both are same window length which means if I have found a specific length then it's good no I will just try to minimize this length that's it so that is where our sliding window comes in picture when you know okay you have a window then you have to just maximize and minimize that window again in sliding window also there are two approaches that the window will either keep on shifting again the window will always keep on shifting but the window will either will only and only expand and that's it window will only expand but they can be Cas Okay window will extend and then expand like as in string expand shing string so there are two variations in which only the shrinking will take place like the size will never ever decrease like much Beyond it or never increase much Beyond it and okay in other case it can be increasing decreasing increasing anyway we'll see uh what and how something can be useful but right now we just know one thing okay if we have again if you don't know that how window and all that work no worries hold on we'll just see everything so let's see if we have seen again R what does this window mean all that stuff I'm new to it no worries uh even if you're you are new and you want to practice just go and watch this arraying playlist in this we have two pointers window very deep questions very deep now let's say you have a window in you will just have to make sure you have to expand that window or Shrink the window again there's a simple rule that if your window is not good for sure try for a bigger window if your window let's say if you want to S outside let's say if you have a home and if you want to take outside if your window is small your main purpose is sneaking outside if your window is small then you will try to expand that window so that you can sneak outside right your main purpose is sneaking outside you expand the window what if the window has become large but okay that's taking a lot of space but you want to minimize the window length so you'll try to shrink it that you will try to shrink it only up to the point that still you can peek outside that's it so I'll do the same thing right now I can not peek outside when I like when I say peek outside I mean okay I have a and b now A and B C is still missing so I should expand my window size so I just simply expand my window size but AR it will keep on expanding no as soon as it will go up till c now I have got all the correctors okay so when I've got all the correctors this is one of my good possible window now when you have got a good possible window just try to shrink the window and see if it is still good or not so I'll just shrink the window now oh as soon as I shrink it became bad now if something becomes bad oh so okay again try expanding it in the future try expanding and so on and so forth so this is the entire concept of sliding window now just remember two points for sliding window that again that's a standard ad hog template for you to always Implement sliding window like this it will be very busy else you will be like me okay just worried okay where the point is going all that stuff just remember these two points that you will have your I and J is moving always ahead at every step my J will move j will move at every step that's it no matter what my J will move at every step J will never stop which is the endp pointer and when I have got a correct window size then which means it matches the condition again the window size logic if the window is correct or not it will depend from question to question right but depending upon if the window is right now correct this I to J window is right now correct then just try shrinking the window and see that if you can minimize the length or not so if the current window it matches with the condition whatever condition can be in this case the condition is to T then you just try keep shrinking your window now shrinking again shrinking only happens J Will for short move as I told you earlier also J will for sure move and it will move at every step but I move when I have a correct window and I want just okay minimize the length now uh we will see that how it will actually happen now the condition okay for J to move at every step it is as simple as that you will have a simple Pointer while J is less than n and simply J will keep on moving at every step no matter what so this is a simple template for J but what about the condition so for the condition it is simple that right now you are at I andj you have this specific window this is was this was your team now I said that if the current window satisfies the condition now the condition is condition to T so the condition right now is that the I toj window size all the characters of T should be inside that window size should be inside that window now to implement this specific logic to implement this condition only we have three possible options again in the beginning we saw two variations of Brute Force itself now for the optimal which means for the sliding window again we have three possible options one is a very naive way that okay you have a window I2 J and you want to know if all the characters again we had seen so far is that we will just keep a track of all the characters of T in a hash map of size 26 which will keep try of all the characters of T so that I don't have to on T again and again I just only itate on my window right now so one naive way to check if all the 26 characters frequencies is corresponding to that window of from I to J is one n way simply trade from I to J and check if all the characters frequencies of T is lying inside my i2j window size so it will take a o of n time because I to J is kind of a string s of length n and space will be o one because of no extra space you are using You're simply trading and the hashmap which you had already made of T you can simply decrease its frequency and find if it becomes zero for all the characters of T then I am good now you can see it taking o of end time and that is for every window now window as in okay J was keep on moving so I know one thing for sure J will keep on moving J will for sure keep on moving so o of n will for sure come in picture and then I will also move so o of 2 into n will be my pointer movements and for every pointer movement I am saying I will take o of n time so it's still L of n Square that's bad now the next smart way is that you have to just know again you have known that the frequency of all the characters int right now you just have to make sure if all these characters are lying inside your I to J that's it so which means ultimately you're also concerned about what are the frequency of characters in the window I toj so when I ask you in the smallest possible time you have to know the frequency of characters basically you have to know the summation in a range of characters of the frequency of characters like frequency okay is it's nothing but the summation of how many times it is occurring if you want to know that simply use a prefix sum so what I will do is I will use the prefix sum to know that I to J what is the frequency of all the characters now if you had not known how we do a prefix sum for these characters so let's say if I have a b c d and e let's say a b c a A and B so I will just keep track of the prefix sum will say a equal to 1 here it will say AAL to 1 b equal to 1 AAL 1 b = will say AAL to 1 b equal to 1 AAL 1 b = will say AAL to 1 b equal to 1 AAL 1 b = 1 Cal 1 a = 2 b = 1 c = 1 a = 2 b = b = 1 Cal 1 a = 2 b = 1 c = 1 a = 2 b = b = 1 Cal 1 a = 2 b = 1 c = 1 a = 2 b = b = 2 Cal 1 now if I ask you what is this specific range frequency so you can just subtract this from this so you will get a = 1 b = 1 from this so you will get a = 1 b = 1 from this so you will get a = 1 b = 1 and Cal to 1 this is a frequency in this range so you sol saw that you just keep track of the 26 characters and length was n so now you know that the time required will be a o of one operation to know a window to know all the characters in that window and when you have got all the Cs in that window then you just have 26 size on which you have to iterate so time will be o of 26 after you have made this which means the precomputation which you will do will take o of n 26 time this is a pre competition which you will do or you can say of end time that's it uh after this pre competition is done then you can simply go and find any window frequency any window cus frequencies and for sure you can see the space required will be n is for this entire length and 26 is for 26 is in the worst possible case so that seems okay that for sure work again this approach will for sure work in this problem because it's a easy the time required is less but we can still optimize the space I don't think we require the space how we know that again now to optimize this space it's actually a bit tricky part how that other ways rather than making the entire new making that because see right now this space is required because I am keeping track of the frequency of s which means all the characters in a range for S I'm trying to find now I'm saying my only concern was if my T if my character like frequency of characters of T is inside my S or not that's it so rather than making s why can't I simply use my T itself which means I can simply decrease or increase the frequency of characters and T so as to manage my window size so what I thought of okay I can simply use the map basically the map of 2 which I made for t i can simply use that map or the frequency of 26 characters of my te which I have made and I simply use that itself to know if my window is right now correct or not and this is actually a tricky thing to optimize the space in this particular problem but many people just directly jump onto it without even knowing that the most intuitive approach is using the perix sum to know the frequency or basically to know the count again in a context if I would have been there I would have used this specific approach but it's more intuitive but still we can optimize the space and we'll only use the T frequency which we have made and thus we will again do it in o one time same was here itself but here you will see again you will see that here the time will be exactly over one like it will not be over 26 like for every step and space will be just as you can see the T the temp so the t uh map which you have made the map for T frequency map which you have made that space is the only space required no space of 26 required and that's how you can simply solve it now this is actually a tricky part now let's see that how we will solve it via actually using the map of T So as we saw that for a specific string T we will simply make the map of him it is T map so I have written my t- map it is not temp it is a written my t- map it is not temp it is a written my t- map it is not temp it is a t- map so this is a t- map which I have t- map so this is a t- map which I have t- map so this is a t- map which I have made now A B C I just keep track of the frequency of those characters as I wanted from the very beginning I will for sure have taken that but now I'm saying I only use this I'll only use this T map to actually trade on and find the window if it is correct or not so for sure in a specific window how you move on okay you have your IJ in the very beginning make sure remember two steps J will always keep on moving I will only move when you have got the correct window now the correct window is all the characters of T should be in that window now uh I seems nice ni um so one thing is for sure to know if I have got all the characters in the window how will I make sure because okay if you are saying that I will use this specific map so for sure as I will as I'm standing on this specific character so I said okay I'll use this character when I say I use the character so what modifications I should do in my existing map because I have I know right now that all the modifications I have to do this existing map only so I'll do all the modifications here itself so one operation I can think of very like naively is I am at a this was my existing map I have to somehow make sure that I have taken my a this is the existing map so I simply reduce the frequency of a one 1 a taken then I'll simply move on but as you have seen that 1 a is taken oh 1 a is taken now how will you make sure if all the characters of T are taken so one thing you can also make sure is keep track of the initial count of characters in your t as soon as you take any character which was inside your T then you can decrease its frequency or decrease its count okay right now the remaining characters which I have not taken in my window are two this represents that and because as you can see a is taken so a is right now in my window remaining characters which are not taken in my window right now are two and this will help us make sure is if I have if in the current window if I have taken all the elements of t or not because as soon as my count becomes zero I have taken all the elements of character I have taken all the characters of T in my window I to J and then I can simply start shrinking my window okay let's see as you can see my J moved forward again simply decrease again the operation is still same but simply decrease the frequency but R and B is not even there no worries at all D is not there simply decrease the frequency d isus one so if I decrease the frequency so shall I decrease the count also n why not because you know that you because you know your D is not even there now AR that is okay D is not even there but how will I figure out if my D was here or not because you just told that okay as soon as you encounter your nums of J simply go in the map and decrease the frequency okay you decrease the frequency but then you also said that okay nums of a when the frequency was decreased but then you also decrease the count how will you make sure that some decreasing which you doing right now is from your like from your T string or not as simple as that how I'll tell you because if you have these T if you have the characters of T by default all of them were actually positive which means more than zero their count by default would have been more than zero so if some count is more than zero which means it was from my string T if it is less than zero or if it is zero or less than zero because T you can see was Zero T's frequency sorry D's frequency was zero so it was not even there in my map so I can just make sure when I'm about or when I'm about to decrease something when I'm about to decrease a frequency if the frequency is positive which means it is for sure from my string T if it is zero H simply decrease it because it is not from my string T so that's how I simply decrease the frequency of D now it became minus one but my count never decreased okay cool no worries move ahead now I am at o again decrease the frequency of O count will still remain same because it is not inside my string T now again increase the frequency again move the I sorry move the J because see you will keep on moving J at every step as you saw J will keep on moving at every step no matter what now uh B oh B I try to decrease the frequency but before decreasing frequency I can see it its frequency is positive which means it was inside my string T so I'll just decrease the count now my count will become a one I'll simply decrease the frequency of b will actually decrease and will become a zero and does I'll simply keep on going so right now you have seen that the standard template was while your J is less than n simply keep on increasing your J but I saw that as I'm currently at the GTH index I will firstly check if my t map of that s of j s ofj was B your this character was a b the T map gives me the frequency of that character at the J index if that is positive which means it is lying inside my string T if it is please simply decrease the count as you can see simply decrease the count now when you have decrease the count no matter what you have done this or not simply for that s ofj in the T map decrease the frequency so as you can see the this will happen no matter what for B for a for d for o for everything it will happen but this thing will only happen when my frequency is more than zero represents that it is inside my string T and what makes this question hard rather than other sliding window problem is this specific optimization of only and only using your this specific T map okay and simply this for a step one operation which means simply keep on moving your J forward always now with the stand template we have seen so far okay simply go on moving your T moving your J okay J will move e was not there simply e frequency again minus one now J again moved so C Okay C is there frequency was one so simply firstly decrease the count becomes a zero decrease the frequency of c frequency will become a zero and then J should move ahead but ah now do you see one thing it's simple that your count has become a zero H that is the case which means you know that this specific window has all the characters of your team this window has all the characters of your team now if that is a case voila great man great um just one thing that firstly put your answer right now my answer is this window of size six again right now my answer was Infinity I have to minimize my window length so I put the answer as six but if your answer would have six just simply minimize the answer okay Infinity by default now it became a six now uh as we saw if the window a condition matches then try to shrink the window so what I will do is I'll now when I like when I say Shing I'll just simply keep on moving my eye now when I say I'll keep on moving my eye I'll simply say that whatsoever eye you have let's say eye you have is here now simply move your eye ahead but as you're moving your eye you have to make sure one thing uh where is this gone as you move your you have to make sure one thing that if I is going so which means I this character should come back to life so a is coming back to life now I simply increase the frequency of K A because it is coming back to life a is coming back to life so as I was moving onto character I was decreasing frequency so if something is coming back I'll increase the frequency now the same thing comes in picture if I if you increase the frequency if it becomes positive which means it is for sure because of it was a line inside your string T and thus if something if the after bringing back to life which means after increasing the frequency of that character a if it becomes positive it was because of it was in this inside my string T and thus please increase the count also now the count becomes one which means now your window is not correct now window is not correct so simply again now keep on moving forward so now we have seen that as soon as we Tred to shrink again we know that we know the condition has matched so first I have to minimize my length so I just make sure I'm just minimizing my answer I just I'm just minimizing my answer now when that specific thing is done my minimization of answer and stuff is done so one thing is for sure that I will now increase try to increase my eye now when I say I will increase my eye I just simply keep on doing it while my window is valid and how is the valid condition window valid is only when the count is zero while my window is valid if my current window length if it is less than my minimum length current window length it is less than my minimum length then simply update the minimum length with the new minimum length and also if you make sure that RM y have taken minimum start because in the answer if you go back if I just show you in the answer you have to return um where is the gone in the answer you have just in the answer yeah in the answer you have to return a b n c which means a string to find the string you need to have the index of the string and the length of the string for to access the actual string which is the substring from the main string you have to know the index and the actual length so one thing we have seen so far is that we will actually make sure that we need both minimum start and the minimum length but if you had been following so far you must have seen a small catch Aran one thing while like you said that if you are at pointer J you will firstly check the pointer J and like as you mentioned before only you will decrease the frequency from s of J and then you will increase the pointer so and you said your J will always increase so your J would have already been increased and this was your I by default in the beginning so for sure your window length will be J minus I only and Not Jus I + 1 so one thing is your Not Jus I + 1 so one thing is your Not Jus I + 1 so one thing is your window length currently is J minus I because your J has moved one step ahead already so that's your window length is J minus I and the same way here window L is J minus I because your J will for sure move ahead one step but as soon as it has moved now it will give a chance to I bro now you will try moving okay the implementation as in the actual implementation will which means the utilization of the specific J movement will be seen in the next step next V Loop but it just says okay my J has moved next step and then again as you can see also your J moves but as soon as the next while loop comes in picture its impact will be seen it's impact will be seen but right now the J has been moved also if you want what you can do is put the condition here itself and move your J in the very end of the code that is one way to do it then you can actually use the same logic of J Min I +1 just make sure that of J Min I +1 just make sure that of J Min I +1 just make sure that pointer think that where you are placing your J I usually make sure thatth where is this gone I usually make sure that if I'm placing my piece of code of checking that window correct logic I usually if I place here then either my J is in the end or I place it after this specific condition if you placing after it which means your J has already moved ahead but the good practice is you can place it here also that's completely simple that's completely easy that's completely okay now as you can see um I'll simply move on my specific because of the window which I have moved on shring my I actually minimize my window length and the same way goes that as you have shring the window which means the S of I tmap frequency will increase if the frequency increase becomes actually more than zero which means it is positive so simply increase the count also and also increase the ey pointer but this V Loop will only keep on going until unless your count is zero as soon as your count becomes more than zero sorry bro um you have got the incorrect window length thus you can simply keep on going forward now if you remember uh you will simply keep moving your J now as soon as your you moved your J okay your o frequency will decrease o frequency will become minus two then simply again the count is still a one uh your you will increase your J again the d will come in picture D frequency will increase to minus 2 like decrease again uh then e will come in picture minus 2 then again B will come in picture okay it will become a one sorry it will become a minus one because B is coming picture no if something is coming in picture it was a zero if something's coming in picture simply do a minus one as simple as that again the count will not decrease because the B by default frequency was not positive then okay I'll simply keep on going on my a was actually a one now I will actually decrease it my actually frequency will decrease it oh if it decreased which means for sure my count should also become zero now bro count becomes a zero if count become a zero then this is my specific window right so I'll just say my window will be Jus I + 1 by default again I'll show you Jus I + 1 by default again I'll show you Jus I + 1 by default again I'll show you both the codes how this Vari like VAR like Vari but if you increase your J right now then you will you can see that the window length is J minus I but yeah if you don't increase the window length right now like J right now so you can say okay in the next Val loop I increase my J now your window length is Jus I + 1 my J now your window length is Jus I + 1 my J now your window length is Jus I + 1 and thus you can simply say that 1 2 3 4 5 6 7 8 9 10 but my by default length was six so it will not be minimized so length will still remain same but now I have opportunity to shrink my window so I'll just simply increase so D frequency will increase become a minus one o frequency will increase become a minus one again move on I keep on moving ey B frequency will increase it will become a zero H again it has not become positive so you can never increase your count okay again um move your i e now it's a e uh decrease the frequency increase the frequency become a one minus one again I C you have got a c ah simply you have got a C increase the frequency now it has become positive simply increase the account also because this is the new window which is valid after this as soon as you will move after as soon as you will move you are done so here right now I have got a window length which is actually valid so 1 2 3 4 5 6 which is already same length so rather I should try minimizing the window length because it was a valid it's a valid window right it's a valid window so I just try to minimize the window length which means I'll go here as soon as I go here which means you saw that I tried to decrease the frequency of C it has become like frequency sorry it has I moved I has moved so for sure my frequency of C will increase count will also increase now kind my count has no longer remain zero so this is no longer a valid window length now if something is no longer valid window L simply keep on increasing your J okay n frequency will become minus one uh n frequency will become minus one now again move on J C frequency will become a zero count will become a zero this is a valid window length now okay I was here so uh increase the frequency of O it will become a zero then D it will become a zero then uh e it will become a zero then B it will become a one it has it now again it has become a one which means now okay now it is actually valid again still it is so far it is valid I'll first try to minimize my length which is j- I + 1 so minimize my length which is j- I + 1 so minimize my length which is j- I + 1 so now my length will become a four again length will become a four now okay when I have minimized my length only then I will update as you have remembered first I'll try to minimize my length only then I will update my temp frequency and stuff so after I have checked off for my length minimize the length only then update it which means it will become a one now count will become a one so now it is no longer valid now simply keep on moving your J forward okay J forward and thus you can simply get the answer cool now uh it's exactly simple as that the code here um I will just show you a quick modification in the code that rather than um again like first I'll show you exact implementation of everything which you have seen so far is as you saw that first we'll keep track of the T map is T is the strin T and the frequency of that is the T map for us now I will have few variables I and J counter is the count which I have taken if you ever remembered by default the counter was the string length right I have those many number of characters for my string uh T minimum start and minimum length is for the final string final most optimal smallest window length I need to have a start for it and the length for it to actually find the substring for it and thus my n is nothing but I have to iterate on my J up till the nend so the simple Loop will while my J is less than n and I'll simply as I explained above also I'll simply try if my frequency of j s of J is more than zero which means this character this s of J is inside my T string T So decrease the frequency decrease the count and also um decrease it everything this everything you will understand by the snippet of code which I have shown you above this entire block I have showed you one at one place this entire block I have showed you at one place which means this is minimizing this is getting a minimum length and then as you move on your eye please revert back all the operations which you have done now the only thing which I was saying is that right now it is J minus I because your J has already moved one step but I also do like that if I put I if I put my J in the Super End which means right now your J will be at that specific Place only then what you can do is your current length will be j- I + 1 is your current length will be j- I + 1 is your current length will be j- I + 1 and the same way it will be J - I + 1 and the same way it will be J - I + 1 and the same way it will be J - I + 1 and that's the only change which you have to do and th if you try to submit it will still work because it was exactly same now coming on back uh this was the portion where you move your J at every step as going to see J at every step because you have already moved your J so it's the reason I have put a j minus I but if you just put your J afterwards which means your J will move only in the end then you can just simply have a check minimize your length and then update move shrink your eye as you have shrinked your eye ultimately in the final answer you will have minimum start and minimum length as the same okay it is a starting length of the window having a minimum size and that is a minimum length for that window this will give me a subst strring if the minimum length is infinity so there is no substring simply an empty string and that's how you can simply Solve IT of n plus M time is to Simply make this specific hash map and N time is to iterate on this entire string of length n okay it's actually a 2 into n because your I and J pointer will move one step I can also in wor case move one step so it is a 2 into n plus M and for sure space is just over 26 this is the most optimal solution which you can have see goodbye take care bye-bye again I specifically went on to bye-bye again I specifically went on to bye-bye again I specifically went on to these all five approaches to actually specify that what all you can tell in an interview cool byebye take care | Minimum Window Substring | minimum-window-substring | Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time? | Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer. | Hash Table,String,Sliding Window | Hard | 30,209,239,567,632,727 |
1,844 | all right let's talk about replace all digits with characters so the idea is that you shift how many times after c so for example fight five times after a you get f and then there's a constraint it's guaranteed let your shift never exist z so the maximum for a is 25 a plus 25 is 26 right but for this is simple a right a plus one is b and then c and d e and f right basically you are taking the previous character plus one but the number could be different like two three four right you just have to worry about your tongue your constraint because for this character you don't have number and then you end up just by itself then we need a stream builder to build okay let's just start looping now i can just do it like this make it easier and no matter what right i have to append a pen see okay so i have to check the character if the character is less than equal to 9 or n sorry n c square equal to 0 which is which should be one right okay one you can say zero but zero doesn't work the minimum number is one right should be one and we have to make sure i mean choosing case the previous character is quite a good view right so index if i'm here i have to make sure this is this index is valid so let's just say new character neutral is equal to uh stock chart at i minus one but since this is the taking the previous character plus the number right and then the number will be c right it's the choice c right c minus zero right we don't want the zero technically so for the ascii value you subtract the subtract 48 and then this since this is char right we just have to cast a chart that will be your answer and you need to append a pin neutral so when we append b right we don't want to append a again because c equal to a right so we continue right so id is pretty much it so i just have to return string for the string builder and check if i have arrow cool all right let's talk about what happened so there's a case for zero right and then we have to worry about zero now checking again cool okay let's talk about timing space for the space is all the fun why because you are storing every single character into the string and for time it's all of them right you're looping every single character inside the screen and a little bit so time and space are all the fun | Replace All Digits with Characters | maximum-number-of-balls-in-a-box | You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices.
There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`.
* For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`.
For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`.
Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`.
**Example 1:**
**Input:** s = "a1c1e1 "
**Output:** "abcdef "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('c',1) = 'd'
- s\[5\] -> shift('e',1) = 'f'
**Example 2:**
**Input:** s = "a1b2c3d4e "
**Output:** "abbdcfdhe "
**Explanation:** The digits are replaced as follows:
- s\[1\] -> shift('a',1) = 'b'
- s\[3\] -> shift('b',2) = 'd'
- s\[5\] -> shift('c',3) = 'f'
- s\[7\] -> shift('d',4) = 'h'
**Constraints:**
* `1 <= s.length <= 100`
* `s` consists only of lowercase English letters and digits.
* `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`. | Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number | Hash Table,Math,Counting | Easy | null |
1,470 | hi guys let's talk about a google interview question today the question is lead code 147 or shuffle the array uh it goes something like this given that a number consisting of two n elements in the form x 1 x 2 x 3 until x n y 1 y 2 y 3 so on until y n you have to return the array in the form x 1 y 1 x 2 y 2 x 3 y 3 and so on until x and y n okay so it's a lead code easy problem but it becomes pretty hard to solve if someone asks you to solve it in one space and o in time complexity like it's easy to solve in on space but one space is pretty hard and in a google interview you will be expected to solve it in o in space basically shuffle this array in place so let's look at the input constraints are like n is less than equal to 500 and length of basically n is the half of the size of the array because length of array is 2n and num psi is greater than equal to one less than equal to thousand okay so basically uh all the numbers in the array are positive a pretty important constraint which will help you develop a solution of open space okay and here's our test case as well like nums is two five one three four seven n is three which is half of the size of array and output is two three five four one seven anyways like uh you can solve it in o in space by creating a new array and just copying the elements in the order specified in that new array very easy but let's see how to do it in one space so like i have taken example here original is one two three four five six shuffled array will be one four two five three six okay and here i am denoting the mapping as well of the numbers from their old position to the current position uh basically sorry from the current position to the new position basically the position in the original error and the position the shuffled array okay like blue color is denoting all the numbers uh in the first half of the array and red color is denoting all the numbers in the second half of their basically all the numbers whose index current index is greater than n and blue color current index less than n okay so this mapping actually helps you to visualize and uh like the position of the array in the original and position of the numbers in the original and shuffled array and it also helps you determine a formula to come up with a formula for the uh for the new positions of the elements okay and let's see what that formula is so i have here in violet color i have written the indices of the like the current indices of the elements in the original array and any n as i said is the half of the size of array so the new positions in the shuffled array will be something like this like if current position is less than a new position will be twice of current position else new position equals twice of current position minus n plus one okay and you can also see this formula is correct like uh for two the current position is one its new position will be uh twice of current position which is two and you can see here in the blue color two is here which is at index two and similarly for five like its current position is four is obviously greater than n which is 3 okay so its new position will be twice of 4 minus 3 that is 1 so 2 into 1 plus 1 that is 3 and you can see here in the red color that 5's new position is 3 and this formula also holds for the elements at the first and last position i mean their position remains same in the original and shuffled array like for one uh its new position will be twice of zero which is zero only and for six its new position will be twice of five minus three which is two into two 4 plus 1 5 okay uh now what would be our algorithm so algorithm would be something like this that uh what we will try to do is go in cycles in for each index like what we will do let's take an example for the number two which is at index one i determine the new position of two using this formula it comes out to be two only okay i will replace the number at the index two with the number at position index one basically this two so what i would do instead of placing two here i would place minus two here okay and why i'm placing minus two is because i want to mark that i have actually visited this element and like since i cannot use an extra array for marking that i have visited that particular element i will mark the visited as by keeping that number as a negative number okay and since i already told you in the constraints we are given that all the numbers are positive so that negative will not basically uh but you can say basically destroy our array okay so what i would like i have replaced two with this and then i would similarly determine the position new position for the number which was at index 2 and replaced that number with this particular number at index 2 and i will keep on doing that until i come to a position which was already visited okay in case you did not understand this uh let's actually try to simulate this scenario okay so here i am like my current number is two current position is one uh which is here i determine the new position which is n is as i told you three new position will be twice of uh twice of one which is two and the new number that is the number at new position is three okay so what i would do i would replace this number so here i am i replace the number at index two with minus two okay and i then i swap current and current number and current position with new number and new position so my current number has now become three current position has become two i determine the new position for this which is twice of two which is four and at index four the number is five which is our new number so again i will swap uh basically what i would do is that i would replace the number at index 4 with -3 4 with -3 4 with -3 so that's what i have done here i replaced this with minus 3 now and swapped new number and current number and new position current number is 5 current position is 4 so new position will now become 3 because like 4 is greater than 3 we'll use this formula so it comes out to be 3 the number at index 3 is 4 which is our new number so now what i would do is i would replace the number at index 3 with minus 5 so that's what i did i replace this number with minus 5 and swap new number current number new position current position now our current number is 4 current position is 3 we determine the new position again 3 is not less than n so we did use this formula to determine new position which comes out to be 1 and number at current sorry new position is 2 so now i would replace the number at index 1 with -4 so as you can see here index 1 with -4 so as you can see here index 1 with -4 so as you can see here that's what i did here i've denoted these negative numbers with violet color and as now our current number becomes two current position becomes one i determine the new position which comes out to be two okay so i would replace the number at index 2 with minus 2 so i did that okay and after doing that what would happen is our current number will now become minus 2 and current position is 2 so now since current number has become minus 2 it means that we have already visited this we do not need to you know go further in our cycle here we can stop this our cycle here and we will keep on doing that for each position like this i have only done for one like if you remember here we started with the number at position one but we will do this for each we will repeat do this cyclic thing for each position like for two three four and five okay so this way you can clearly see that we have basically not used any extra space and this will also make sure that we you know transform our original error into the shuffled array now the thing is like what is its time complexity so the time complexity is order n and let me tell you why is that so that is because this visited thing like we are replacing every number with the negative of that number so that makes sure that every index will be visited at most twice okay once uh like it would be visited once when we encounter basically when we are replacing that number that particular index and then there might be a scenario that we might come back to that index again in our cycle but at that moment we'll break out because you know uh we are using this negative as a visited flag so this thing make sure that all the indices are visited at most twice only so we will at most do like two end traversals and sorry to win iterations so uh and let me show you one more thing like this we have done only for the index one then we go to index two so at index two we see that the number is already negative so we do not do anything here current number is already negative we go to index three again current number is already negative minus five we go to an index four current number already negative minus three then at five like uh last this is the last number so last number will remain at its own position and we finally break out of this loop so you can clearly see that this visited flag took care of not repeating our iterations and you can also see that this uh like after doing this what we will do is that we iterate over the array once more we will replace all the numbers with negative numbers with positive value of that particular number and uh finally we will get our original shuffled array basically our expected shuffled array which is one four two five three six and if you remember this was the answer as well one four two five three six so let's look at the code for it uh so here is the code which i had written like this is the api we had to implement and i what i am going to do is that for each index i will try to you know do that cyclic process so that's why i'm iterating here from i equal to 0 to length of the array and initialize current number as num psi current position is i and we only basically do you know iterations in this while loop until this current number is positive until this current number is greater than zero and we figure out the new position based on current position and this is that particular formula and then what we do is that we would replace the number at new position with the negative of the current number and we will then swap the current number and current position with the new number and new position okay and we'll keep on doing that and eventually when uh after this for loop we iterate over the array again and if we see that num size less than zero we replace it with the positive value of that uh number and eventually we return the num array so time complexity o n space complexity oven we have solved a google hard interview question good to move to second round thank you guys for watching please do not forget to like subscribe and comment on this video i'll see you all next time | Shuffle the Array | tweet-counts-per-frequency | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null | Hash Table,Binary Search,Design,Sorting,Ordered Set | Medium | null |
489 | hey everyone and welcome to another Elite code problem so today we're going to be doing problem number 489 robot room cleaner and it's a backtracking problem it's a hard one it's probably one of the hardest backtracking problems I've done um even if you know like backtracking there's a lot of annoying parts of this problem for sure so I would encourage you if you are learning backtracking it is on the backtracking explore part I would encourage you to try this one for sure um just to test your you know understanding of backtracking and the hard thing about this problem is I'll just tell you is so you have this robot in a grid and you don't know you're not given access to the grid the only thing you're given access to is a couple functions for the robot so you're given a move function that will return true if the robot can make a valid move and then you can turn the robot left and right and it starts off facing up and so yeah the annoying thing is like you don't see the grid you don't really know where the robot is and it's hard to visualize if what your algorithm is doing is correct also the other annoying thing about this backtracking um is like let's say you're in some cell draw a grid here so let's just draw a simple grid three by three grid with no obstacles and let's say here's our robot so Circle it's going to be facing up so The Annoying Thing is how to figure out well how do I actually backtrack like let's say I call move and the robot moves up here it's still so whenever you move you're still facing the same direction but how do I actually backtrack like what's my backtracking algorithm like if I return it's still going to be in the wrong grid so what so how do I even do this and so what you're going to want to do is you can visualize I mean when you go somewhere your end State needs to be your robot needs to turn around right so it needs to face this way and then you need to call move and then you can handle backtrack in one of two ways so you can either move back and then return and then like turn it around in the function right before you return or you could handle it in the actual backtrack function so let's say you just call backtrack right you call backtrack with some you know you move and then you call backtrack then what you can actually do is once the function before returns like let's say this function you can call backtrack the robot's over here and then it's looking the way you want it to let's say for the ending state maybe you want it to look like this I don't know there's a bunch of ways to do it then what you would have to do is well what would you have to do to make this state turn into this state right and this is our original state and to fully complete our backtracking so in this case we'd have to turn left or right twice so we'll just say turn left twice so we can just call that function then we have to go move and then we can turn left again twice so hopefully that makes sense when you have this robot you turn it around so a 180 degree rotation would be left or right twice then you'd call move then it would go here and then you'd turn around again and then that would give you the original state of the robot before it entered this so this is how you would get out now the other annoying thing for so for most backtracking problems well it actually depends but let's say you do have some backtracking algorithm and let's say you're backtracking algorithm just so let's say you try the cell in front of you and then if it doesn't work you just keep turning right and you keep turning right well let's see what would happen so we can't go here so we're gonna turn right okay and we're remember when we go into a cell we Face the same direction that we came in we can't go here we turn right it's going down okay we can go here okay we can't go down here so we turn right okay can't go down here so we turn right here then go here okay well now we can't go here we go here so how do you how do we even know and then we end up here how do we even know we ended like we don't have a grid remember and in this case it worked out but in other cases uh you can try out some other examples but some other examples when you do this when you just keep turning right here so in this case you did end up where you started but in a lot of cases you'll just run into like a loop and how do you even know and then you just hit maximum recursion depth right because you keep looping but you don't even know that you cleaned every room and you can't check that you cleaned every room you don't know how big the grid is you're not giving access to any of that information all you can do is move the robot and so how would we solve that problem and to solve that problem this is also kind of really annoying actually what we're going to do is we're gonna have a visited set and you may ask well how do you have a visited set if you don't even have an index of like where you're starting and so what we actually need to do that makes this problem difficult is you have a visited set and then you need to figure out what index what at least what relative index you're at and so let me show you what that looks like so let's say we let's call this index 0 right so we just say inertial index is zero so we put zero in here and now by the way when we Traverse we're gonna only Traverse if our if the place we're traversing isn't in our visited set because we don't need to visit the same room twice also for this backtracking that makes it different from some other ones like a Sudoku is even if you like once you're on a path and you go to a bunch of rooms when you backtrack to where you started you never have to go back to any of those rooms again because we of we've already cleaned them and we've already went as far as we could from any of those rooms so once we have visited set and we add items we're never going to remove them in a normal backtracking you normally do remove and you kind of check for a Final Solution type of thing you know like for end Queens you would go down all the rows and you have to see is there a final solution and you can you keep removing Queens from the set but in this case once you were in a room once you never have to clean it again because as soon as you go into room we can just hit clean and then it's clean so let's say we're here so what we're actually going to use is we're going to use um to actually use this for a lot of DFS so we're actually going to have an array like this of directions and we're gonna so normally when I have this array of rays for different directions I have like one zero one negative one zero and so on but here the mistake we need to not make is we need to make sure that so we're going to be turning right a lot and now we need to figure out what are the values that you need to go up and then if you turn right we're gonna try to make sure that the value to the right of the current one we're at is the right thing so to go up actually it would be this we are going up a row now if we're going up and we turn right now what is okay now what is this is column plus one and so this is another tricky thing is you have to make sure you arrange these in the right order and for this problem so this is going to be 0 1 okay now down if we go right so down is one zero and then so yeah if you do a normal like stuff they use for other functions you're going to get an error so now we were down now we need to go right or sorry left right so down if we turn right from down it's a left and left is actually 0 minus one and so this is what it's going to look like and all we're going to do when we turn right is we're just going to say let's just go to the next Direction let's go to the next Direction and when we reach the last one we can simply just go back to the first one so let's see what kind of that looks like so we're at zero now we know we're going up so if we're going up that means our row is minus one right so then that would be negative one is zero and so this index I might cut out for a second so this index is going to be negative one zero now we tried to go up we can't we go right so then what is right going to be well right it's going to be negative 1 and so on so you're gonna have these relative indices instead of absolute indices so even though you don't know how big the grid is you have to know which way you're facing and where you started and from there you can figure out what relative index you're at and so we're going to keep adding to our visited set until we can't go anymore and then we are going to like I said when we're facing some Direction so it's going to look like this is what a backtracking would look like for just one particular square right so if we have a square let's say we came from here so we came from here we're in the Square let's say we can't go anywhere so we try to go here can't we turn right try to go here can't and because we can't because it's visited then we turn right again and then we try to go here and we can't and then we turn right I'm gonna double check the code but our ending State wants to be like this so in our after we tried everywhere we want to be here yeah so actually first we don't turn right so we turn right four times total so we try here we can't try here can't and then we turn right one last time until we turn right four times total and if we turn right we make 360 degree and then once we're actually going down here then we simply to go back like I said we turn right twice so then we turn around and we go this way we hit move so then we're back in this cell and then we simply turn right two more times either and you can do this either in either method as long as you do it because even once you're back in the original method you can actually hit move and if it's like an invalid location as soon as you've act as um as long as you've cleaned all the cells it doesn't really matter like if you try to move and you recurse back to the original method it'll be fine okay so let's take a look at the code and we'll explain that so I actually didn't want to code this up on the Fly because there are definitely I would there's yeah there's not a lot of code but there's a ton of Errors you can make here okay and so like I said they said these are the directions so this is representative of up then we have right and we have down then we have left oops and we have a visited set and then we have this backtrack function so first thing we do when we get into a room is we clean the room right so as soon as it doesn't hurt us to clean the room so we might as well do that then we add that room to our visited set and then here's our Loop where we try every single Direction and so to get a new Direction our initial direction is going to be up which is going to be this thing right here and so to get a new direction we're just going to have an i and a range four and then we are going to do Direction plus I mod 4. and what that does is it starts with zero right so the original direction would be this then it'll add this then a lot of this but let's say our Direction our original direction is three maybe so we're on this one then if we add one and mod it by four it'll actually loop back to the beginning of the list so let's make sure we're not out of bounds and then we just loop back to the beginning of the list then recalculate a new row and a new column based on the direction we're at and the current row and column we're in and then remember so this is also another thing you can screw up when you do this check to make sure that your row and column isn't in your visited set and this robot move make sure that you check that the row and column isn't in the visited set before you do this robot move because if you do the robot move now you're going to be in another square and then you're not gonna like this stuff isn't gonna line up so you have to make sure it's a valid place to go before you even try to go there otherwise yeah like even if you can't go there it'll be fine but if you can go there and it is in your business that's going to screw your code okay so now we backtrack to the new uh Direction and new row column then remember when we backtrack this is when we're recursed out so in my code I made it do this 180 right after you leave the back trap Loop you can do this in a bunch of different ways and then we turn right so we turn right four times as I said so really what's going to happen is this is going to be when we return from a square right so let's say we were in this top square we went down right then we returned from a square well the way my code works is when we're returned we're actually going to return facing the other way and so when we return we just need to 180 around to be in the original state we were in before we backtracked and so that's what that does so turn right we check remember we check the next place we can go to and then this is simply what we do before we backtrack out so when we and like I said I could have done I'm pretty sure if I wrote this code uh in here this would have worked too I don't want to test it actually I can do it I can try to test it so let's just see let's say we backtrack out and we literally do it right here instead what happens it might work maybe there's some other thing that I need to think of but okay so it actually does work so that's another way you can backtrack out is so now what I did instead of my original thing is I have something like this and so let's say I'm here and now I would be actually see here so I moved I turned around twice and then I move yeah okay so I believe that the final state is like this of the cell that I backtrack to so what I need to do is I need to turn it around right then I need to move back and then I need to turn it around again and that would make it the same state here so like I said you can put this code in multiple different places but basically yeah you have to make sure you handle this and turn right to Nursery you know you want to turn right as many times as you turn left so the gears on the robot you know don't get rusty you don't want to keep turning right only okay so anyway so yeah so you go back and then this is the initial function call and I just made it pass with one zero because and so what I would encourage you to do by the way if you're getting a lot of Errors is maybe um one thing that helped me is this grid is really big so you can just make a custom grid and you can even try something like this you know where you have a custom grid and this is the custom grid I used where every cell doesn't have anything and then I just made all of these ones one meaning it doesn't have a uh it doesn't have brick so it needs to be cleaned and then I made my starting location this and then I would try to draw out the states of the robot on my grid and then also print like the visited set and where it was in and make sure it matched because that's how you catch a lot of your areas that's what saved me a lot of time for sure um so and then you can also do that by if you don't know in this new lead code version what you can actually do is you can go to test case you can add a test case and so you can say like if you know what it looks like so something like this you can add that in copy that so this would be a three by three array if you wanted to and then you could say yeah like start at you know one and maybe print my visited Saturn row column or whatever it is when you have errors because like if you think about it there's no really way to test for this what makes it really annoying and difficult is there's no really way to test your code like when you have a bug it'll just say all the rooms weren't cleaned and you don't really know where the robot was or where it went because you have no access to the grid so it's a real pain to try to debug it unless you actually draw at the grid yourself and try to follow like is the robot facing the right way is it going in the right order by checking where the visited set is and where the column is and so on and so I do think this is a great problem for backtracking it definitely does get annoying with you have to do a lot of israelization and figure out what things have to look like with limited information so okay so let's do the time in space complexity and actually the time and space complexity for this prom are pretty good compared to a normal backtracking algorithm normally they're very inefficient and so here because we're never actually removing from the visited set we're not visiting a cell more than twice so we are only visiting cells that are ones and not uh so let's say zero is a brick we're only visiting cells that are one so it'd be something like count ones mine or just be count ones right so if we have whatever many empty cells we only visit them one time we do have to technically go back actually but I think that is not going to add complexity so that's fine okay and as far as the space so what did we do for space so we do have a we do have um this visited set right and so this visited set is going to have every single so this is kind of the same thing it's going to have every single room we visited but we can only visit rooms with cat ones so that's just going to be big of count ones and yeah like I said if we clean a room and we backtrack uh I think that should be constant time to backtrack back or yeah it's actually going to be no it's actually gonna be like Big O of so we do actually have to visit a room and we backtrack back so let's say we go something like this is our path and we have to backtrack back how much does that cost like our maximum call stack does get to like the number of rooms we visited but we're basically just visiting a room and then coming back so it's going to be like Big O of 2N instead of n it's not going to add any more and then once we did visited these rooms and come back we can never go into any of these rooms that we visited ever again because we're never getting Rhythm and they've visited um in the visited set that's what would make things more expensive and that's why most backtracking operations are more expensive because you have to fill in let's say nine different you know problems and then you can have repeated work where you're here you can't once you've visited a room you're done okay so that's all for this problem and if you like the solution app please like And subscribe to the video it helps grow this Channel and I'll be posting more in the future so I'll see you in the next one | Robot Room Cleaner | kth-smallest-instructions | You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot.
The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API `Robot`.
You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is `90` degrees.
When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell.
Design an algorithm to clean the entire room using the following APIs:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is obstacle and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling turnLeft/turnRight.
// Each turn will be 90 degrees.
void turnLeft();
void turnRight();
// Clean the current cell.
void clean();
}
**Note** that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall.
**Custom testing:**
The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded ". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position.
**Example 1:**
**Input:** room = \[\[1,1,1,1,1,0,1,1\],\[1,1,1,1,1,0,1,1\],\[1,0,1,1,1,1,1,1\],\[0,0,0,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\]\], row = 1, col = 3
**Output:** Robot cleaned all rooms.
**Explanation:** All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.
**Example 2:**
**Input:** room = \[\[1\]\], row = 0, col = 0
**Output:** Robot cleaned all rooms.
**Constraints:**
* `m == room.length`
* `n == room[i].length`
* `1 <= m <= 100`
* `1 <= n <= 200`
* `room[i][j]` is either `0` or `1`.
* `0 <= row < m`
* `0 <= col < n`
* `room[row][col] == 1`
* All the empty cells can be visited from the starting position. | There are nCr(row + column, row) possible instructions to reach (row, column). Try building the instructions one step at a time. How many instructions start with "H", and how does this compare with k? | Array,Math,Dynamic Programming,Combinatorics | Hard | null |
62 | cool 62 unique paths will bite it's located on the top left corner over m-by-n great the robot can only move m-by-n great the robot can only move m-by-n great the robot can only move either down or right at any point in time well by trying to reach the bottom right corner and the grid how many possible unique paths are there ok it's a little so actually I mean this is actually a very straight forward I want to say dynamic pole and well and it's not straight for in a sense that is you know you've come up with it's just very standard in the sense that it's a very possible textbook type album yeah like yeah my only concern and that's I'm missing something it's kind of like what happens if the number gets too big because easily with a man and it's a hundred that's not missing something yeah and that's I'm missing something like you could definitely over for long or and a lot very quickly and actually there's a halving the thing to notice here is that it's actually I mean once again this is a straightforward issue unquote dynamic programming problem which stems from I mean it's very textbook me in a sense once you kind of get it down but the other fun thing about this poem is that it's actually related to how you calculate binomials in a sense that just where I wish I could draw but you know binomial type things and I could we'll try to attempt some ASCII or so bear with me for a second but let's say you have a tough thing oh yeah so the binomial is X and so you have like the top layer and then you have to was a car like 1 plus X 2 man I don't remember my mathematical formulations to be honest but uh but yeah but on the next level it's huh it's 1 plus X and then I know the next level is 1 plus 2x plus x squared oops and so forth I mean you know their expansion for that kind of worries for me love it and you get this so that's kind of like I mean you could keep on drawing this is where is like you learn it in greats not one of the great schools or maybe high school I don't remember anymore and that's just like you know and actually tip yeah that's why I messed up so one in time and then just and then this obviously this corresponds to 1 plus X 2 is 0 this is 1 plus X to the first and then this is 1 plus X to the second and so forth right so then that's the kind of the pattern here and it turns out that this thing also is a way to kind of like it's I think they're called something like generating functions attire there's like a decade of math ago hey back to a follow him strike him trip em but yeah but that's the general thing here and that actually and you could and kind of a standard way to explain it is that and you could I forget what that parameters core I just finger was PI Gnomeo bread scouts tryingo that's what I'm thinking of way and this is a Pascal triangle thing where you know you could think about it as 1 and then 1 2 1 go say the same pattern you Center what I did before and where this node is just the sum of the two entries and you know in the world before and so forth way dot so this is Pascal's triangle which relates to this other thing that I guess I should have started with the Pascal triangle by just blank underneath but anyway so the fun thing about this is that this is if you kind of tilt the board a little bit or like you look at it in a diagonal way now you could see your entries are actually like 1 on the first world 1 in the first column and then 2 3 and so forth and then you told your head a little bit you could get like the diagnosis so this maps to these in the diagonals right I don't even know how George is on ASCII or despair but like diagonal for the first row and or first diagonal and so forth so those are your things right and also it the fun thing is that this is also the number of unique paths because you could look at you should know to be like okay how many ways do I get here well just one way to get to this cell and there's one way to get to this cell so there's two ways to get here and then how do I get to here well there's two ways to get to this cell and there's one way to get to this cell so that did doing ways to get to this cell and so forth and anyway so there's all these math things so anyway there's a very long explanation hopefully it's kind of interesting to you but it's a long way of saying that's how you would solve this problem in the same way and if we left a binomial and Pascal's triangle and all these other fun stuff but one more thing that I will leave you with this problem then is actually another kind of interesting thing is if we sum up the rows of in Pascal's triangle which is also diagonals so this is actually if you sum it up is two to the zero and if you sum this up is two to the one and you could see that easy and then here is two to the two and two to the third and so forth right and you could kind of make this proof the other way very quickly because for each entry in the previous world you're gonna for you to of those paths there'll be two paths outweigh so you always double the paths every time where so I said so on each row the sum is 2 to the K or whatever so that's kind of one interesting thing about it and that also goes back to there's another way to prove this but another way to kind of visualize it with binomials because we're binomial is another way to think about it's like this entry is also the number of ways to choose one given three elements choose one element way this is given three elements true zero do we animal choose to do a true story right and something so like so that's yeah so it's 3 to 0 3 choose 1 3 and then you see somewhere that should be 2 to the K because that's literally the number of possibilities you can have because that's just you know like the in our counting type thing way anyway so that's a very long-winded way of saying that's a very long-winded way of saying that's a very long-winded way of saying but the reason why I kind of brought this up and not just to flex or show off or whatever is that it's something that I think about when I see this form because when m and n will be at most 100 what that means is that so like you know just let's say this is 100 I mean I skip ahead a little bit so I gave this entry here so yeah I am and I forget I guess we should check with you and then like in the corner here is M plus n right and the thing here is that as we talked about before so this is a most going to be M Jews oh sorry M this is M plus and you know what is that well I guess I've always MPUs well that diagonal is ampersand and choose what know the sum of that one is oh I don't remember man I'm mixing myself up it's been a while but the point is that this is dominated by like the sum of that diagonal you will oh yeah oh wait no cuz okay I'm thinking of this tag so I was doing the math with this place where has to be between m and n there's some eggs but if you're doing like diagonal then M plus N is under on this diagonal which is yeah so it's M plus and choose notice M times n times choose M percent I don't know but the point is that this has a bound of like something like 2 to the M plus N and that was what concerned me when I saw that M plus n will be 100 because you got a really big number is my point so and looking up and down my other daughter about it is to see if they have any kind of strange to be like oh hey but it's ok because you know it's between a hundred oh sorry with the answers like the answer will fit in long or 64 bit or 32 bit and debate the other one too it is usually something that they would tell you but anyway so given that or set this is that's why this dynamic programming problem is a way straight for it dynamic program in this sense and then it's just about coating it up so I'm wearing do not yeah okay and there's a easy optimization that I'll talk about but I'm not gonna do yet I did last time so maybe I should do it mmm I've been trying to do it more okay I'll just do the obvious thing first center corner to do the one and then yes it doesn't actually I just found checking and now we just have to return no maybe it's off by one out sometimes I walk by one on these things good oh yeah oops would I get deep oh yeah let's try a real number for kicks oops we're in Python I think I don't have to kill but it's just in other languages a little weird that they don't specify especially in JavaScript for example see there's a very long number and I guess they don't have an expected result because it crashes on it that's why you need to specify your things watch I Mississippi case ok cool yeah so again this is very straightforward but that's how I kind of think about this problem and it these things are kind of fun to kind of think about because it comes up in random places as well oh yeah the other thing that I would say a very common thing is to refactor this is that well this is a dynamic program well obviously of M times n and with all of em times and space as well but the thing is you actually reduced this 200 of min of M or n by noticing that if you look at this away you actually you know which is this array here you essentially pretty much right so now 2 will always look at you know one and this one and so forth and some domed we will go get the 2 and the 1 and sum them and so forth and then now like we go all the way down and then now for some of 4 and 5 say well the thing is at the for you notice that you only add 2/3 the for you notice that you only add 2/3 the for you notice that you only add 2/3 under one way so actually in this entire well let me add some data tots in this entire world you only care about the results from the previous world right so this will only calculate itself in this flow so actually if you kind of take advantage of that you could actually just get rid of all these stuff well not get written I mean maybe get rid of it but you could you don't have to think you don't need that memory to stay around and that's you need to look up stuff for whatever reason in the future but yeah so you notice that then actually you only need to keep track of the last two rows or the current world and the previous well so you can actually do that in linear space as well because yeah it's like you know when this is done then you just keep track of the new one and so forth way anyway so that's good how you solve this was I would say for a dynamic programming problem this is way fun um this is a way one of they were more fundamental ones I should definitely get to get familiar with and I heard that Google was still asked a lot time before grandpa I actually went into Google for a long time but uh but that's what I've heard but you know the way interviews I feel like people have not been asking dynamic programming well so yeah maybe it's a but yeah we've want to go Google I guess you should study timing programming oh yeah that's why I have for this one | Unique Paths | unique-paths | There is a robot on an `m x n` grid. The robot is 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.
Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_.
The test cases are generated so that the answer will be less than or equal to `2 * 109`.
**Example 1:**
**Input:** m = 3, n = 7
**Output:** 28
**Example 2:**
**Input:** m = 3, n = 2
**Output:** 3
**Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
**Constraints:**
* `1 <= m, n <= 100` | null | Math,Dynamic Programming,Combinatorics | Medium | 63,64,174,2192 |
1,732 | welcome to code map today we are going to discuss daily record challenge find the highest altitude now let's discuss the question there is a biker going on a road trip the road trip consists of n plus one points at different altitudes the biker status strip at point zero with Attitude equal to zero you are given an integer array gain of length n uh where gain I is the net gain in the altitude between point I Plus 1. where I is between 0 and M you have to return the highest altitude of a point let's understand it with a given example test case in this example this case we have given again array which is minus five one five zero minus seven another question it is given that the biker is starting with zero again so at the beginning gain is zero now when the backer will be at the point zero so it's its gain will be 0 minus 5 which is -5 which is minus 5 and here also we can say it is -5 say it is -5 say it is -5 now when the biker will be at point one this gain is 1 so it's so its current gain will be minus 5 plus 1. which is equal to minus 4. and here we can see that it is minus 4. now current we have current gain ah current gain current again as minus 4. now when the marker is when the vehicle will reach 0.2 when the vehicle will reach 0.2 when the vehicle will reach 0.2 0.2 which is 5. 0.2 which is 5. 0.2 which is 5. so current again will become minus 4 plus 5 which is equal to 1 and we can see that here it is 1. now when the biker will move at the point three the gain is 0 so 1 plus 0 equal to 1 so the current gain will be 1 and here we can see that it is one and when the biker will be at the point 4 his gain is -7 so the current gain 4 his gain is -7 so the current gain 4 his gain is -7 so the current gain will be 1 minus 7 which is equal to -6 -6 -6 and we can see that it is minus 6. now let's this is the code uh here I have taken a variable risk which will show the highest among all the altitudes and I have taken a current gain which will restore the current gain and I have run a loop to iterate through the gain array and I have calculated the current gain at every iteration and I have maximized the current again and my result is in the resultant address variable and I have returned that now let's submit this code now we can see that our code has successfully passed all the test cases thank you for watching | 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,716 | hello everyone today we are going to calculate money in lit code bank which is a problem which is a Del quing of today so uh basically what is happening is that you have a certain number of day which is the number of input n and then from that input you are supposed to compute the total amount that has been saved in the bank given that uh the bank is the money is safe given a process that can be described as follow every day you are going to put like $1 day you are going to put like $1 day you are going to put like $1 plus what you put yesterday so if today I put $1 tomorrow I'm going to put two I put $1 tomorrow I'm going to put two I put $1 tomorrow I'm going to put two and after tomorrow I'm going to put three and so on but there's a little trade at the end of the week I'm going to restart that means after 7 I'm not going to put eight but I'm going to put $1 more than what I put in the first the $1 more than what I put in the first the $1 more than what I put in the first the last first week so this is the first week I put $1 here so at the end of this week I put $1 here so at the end of this week I put $1 here so at the end of this week I'm going to put two instead of one so I'm not starting back with one I'm starting back with two so um this is how the thing is actually arranged now the goal is to find out how many uh what is the total amount we are going to have at the end of the process that means at the end of the and days so for you to understand better of what we are doing let's say you have four weeks the first week you are going to put 1 2 3 4 5 6 7 the second week you're going to start back at two that is 1 + 1 and then you are going to have is 1 + 1 and then you are going to have is 1 + 1 and then you are going to have the Siri 2 3 until 8 and so on and at the end of the day you are going to have the total amount of the money you need to keep so um giv this process how are we going to solve it so my Approach of solving this will be as follow I first so my Approach of solving this will be a follow I will go through two approaches the first one will be based on the exact description of what has been said here so I'm going to have a Conta which is going to move from one till 7 and once we are at 7 we are just going to restart our cter but not with zero but with the previous day plus one so that is what I'm going to implement here so uh for me to implement that the first thing I need to do is to have like a result here my result is actually zero I'm going to return the result here and then I need to have a follow up here so I have the number of week uh the number of week starting at zero and I have the days which is starting at one right and then I will say the end of the process is actually the day where the number of day will be equal to n and since I'm going to restart the number of day after each week I need to compute the total number of day a little bit different here so I need to say week * 7 plus d so this is a number of D so * 7 plus d so this is a number of D so * 7 plus d so this is a number of D so while this is actually less or equal to N I will say a day ++ because I'm N I will say a day ++ because I'm N I will say a day ++ because I'm incrementing my number of days and then what I'm going to do here is I'm going to say result plus equal to day plus week so what I'm saying is that after each operation I need to add the number of the value of the number of day to the total sum that means at this step I'm going to say okay my total s will take the prev value that was 0 + 1 at take the prev value that was 0 + 1 at take the prev value that was 0 + 1 at this step it will take the pr Value Plus two and so on but guess what actually I'm doing what I'm doing here is actually the same thing that I'm doing here just that for each of those value I'm adding + one + one + one why value I'm adding + one + one + one why value I'm adding + one + one + one why because we are on the week two so what you can do is that you can see keep adding the number of day but just adding the number of week so you can directly handle the fact that we have different value for different weeks so that's what I'm doing here now the question is how do I take care of the number of day how do I change the value to make sure that it is actually accurate with the process you're going to say okay if D is actually equal to eight that mean is the beginning of a new week you're going to say okay day we take one and week Plus+ so whenever we are Hing the Plus+ so whenever we are Hing the Plus+ so whenever we are Hing the end of or whenever we are starting a new we are saying okay we are going to restart the number of day so we are still going to have 1 2 3 6 7 but we are going to increment the number of week so that is why we are titing the number of day and the number of week here so let us run this and see what it gives everything is green let to submit so uh we have everything green uh so another approach of solving this will be uh based on artic formula we are going to L the fact that the saving process is been performed using a progression and using that we are going to compute the value that has been saved using mathematical formula so what will it look like you're going to use this which is saying that if we want to compute the sum of element following an arithmetical formula we can directly use the first element plus the last element time the number of element divided by two and we are going to have the sum of the element so this is what we are going to use to kind of Leverage The the fact of using arithmetical formula to have this solution so what will it look like this is our things the first thing here is to find out what is the Ser right and then you can see that during full weeks we have uh like static element like this we have 1 2 3 2 7 now the next week we have again the same value 1 2 3 till 7 till 8 this time but we are going to we can transform this into the 1 2 3 until 7 plus 1 one year and for the third week we can transform it into the same year plus 2 two year which will always give you like the 28 for the first week plus Z for the second week 2 with 28 + 7 and 28 + 14 so this week 2 with 28 + 7 and 28 + 14 so this week 2 with 28 + 7 and 28 + 14 so this can be computed with number of week time 28 which is the static value and here we have a Ser which is actually 074 which can be see as a Ser of 7 * 074 which can be see as a Ser of 7 * 074 which can be see as a Ser of 7 * 012 so this is a series now that you able to figure out this so how do we compute this so let me just grab you my solution so uh you have to compute the number of week we need to have the total number of week and then we need to have the remaining days we are going to use it for this one all right so um now to compute the amount save in Full full days we are going to have total full week which is actually the 28 time number of week that is what we said because we have 28 and then now we are going to compute the remaining year by using the formula we just see here that means the first element plus the last element time the number of element ided by two so in this scenario our first element is actually zero our last element is actually the number of we minus one and the number of element is actually equal to the number of we so that's what we are going to use here we have our first element which is zero we have our last element which is actually number of we minus one we have our number of element which is actually number of we that we going to divide by two so this is the formula Computing uh this ser and don't forget that we put seven in Factor here so we just need to reuse this seven here time 7even so this is actually the formula that will have us to compute the total number of week The Total Money Sav during full weeks now we also have a total remaining how do we compete the total remaining so the total remaining here we can see that is actually for this specific case will be 4 + 5 + 7 this specific case will be 4 + 5 + 7 this specific case will be 4 + 5 + 7 which is still kind of 1 + 2 + 3 because which is still kind of 1 + 2 + 3 because which is still kind of 1 + 2 + 3 because that is actually the starting pattern of saving but depending on the week we are going to have a certain amount that has been added so if you have three weeks that means the four week each value are going to be like the normal saving plus the number of week here we are on week four the number of full weeks I mean here we are on week four we had three full weeks that means here this one is going to have the normal one plus three because we had three full weeks and the same year so this is actually the Ser year and for you to have the total value you can just reuse this the first element is one plus the number of week the last element is actually uh the number of full weeks plus the uh the number of week and then the and then uh yeah that's the first element that's the last element so how can you solve this you're going to say the first element is one plus the number of week the last element is uh the remaining days I mean the remaining days is here number of remaining days actually the remaining days plus the number of week and then the number of element is actually the remaining day so we have the first element number of one plus number of week last element number of plus remaining there and the number of element is remaining there divid by two this is the formula so this will actually give you the value of this and now that you have this you just need to return the total full plus the total remaining which is actually this so let us run this and see what it gives so it's working really strange that the I will say um the big of one solution is per performing less better than the big of end solution so yeah this a woring thing so um I hope it was interesting for you going through this I hope you were able to learn something so don't forget to like share and subscribe see you on the next video ciao | Calculate Money in Leetcode Bank | maximum-non-negative-product-in-a-matrix | Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**.
He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**.
Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._
**Example 1:**
**Input:** n = 4
**Output:** 10
**Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
**Example 2:**
**Input:** n = 10
**Output:** 37
**Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2.
**Example 3:**
**Input:** n = 20
**Output:** 96
**Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96.
**Constraints:**
* `1 <= n <= 1000` | Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point. | Array,Dynamic Programming,Matrix | Medium | null |
201 | Hello and welcome tool again this is Shaur Awasti and today we will talk about a medium level problem of lead code which is bit wise and of number range so basically what is in it, in this we are given left and right and what is we have to tell that in What will be the end of all, like suppose five and six and sane, what will be the answer of all three, okay, so we cannot do it by putting a normal for loop because that TL will give us okay, so if we want to see a little optimized code, then we have to do this. We can do this with the help of bit manipulation, so if we move towards enter, if we look carefully, one thing that we can see is that brother 2 and f if there is a range and we have If our range is from two to sorry, two and seven, we have written all the elements from two to seven in binary representation. After that, if we look carefully, a pattern follows when we write the binary representations and suppose if we are adjacent. If we keep looking at the elements, if we follow the continuous elements, then a pattern follows i.e. zero then a pattern follows i.e. zero then a pattern follows i.e. zero index P means the one which is the highest, LSB is the least significant bit. If we look at it follows the pattern of one, i.e. alternate one to alternate, significant bit. If we look at it follows the pattern of one, i.e. alternate one to alternate, zero i.e. zero then one then zero i.e. zero then one then zero i.e. zero then one then Zero then one then zero then and so on is fine. Similarly if we look at the second one here then it follows and 00 and then again 00. By doing like this the meaning of saying is that every element is following a pattern meaning. Every number, every bit follows a pattern, depending on which position it is in, so one approach we can think of is that there will be elements between all the ranges here. Will not depend Answer: It all the ranges here. Will not depend Answer: It all the ranges here. Will not depend Answer: It depends only on the first and last number, why did I say this because the first is the smallest, so its MSB i.e. the most significant bit, there are i.e. the most significant bit, there are i.e. the most significant bit, there are chances that it will be at the lowest position, i.e. chances that it will be at the lowest position, i.e. chances that it will be at the lowest position, i.e. look at it is found right here and The most significant bit of our largest element has possibilities that it can be at the last position. You have to set the bit ahead of it, that is, you cannot find the bit set further ahead of this, anywhere above because this is your maximum i.e. largest element and this is i.e. largest element and this is i.e. largest element and this is your minimum. So we Now we have understood that it depends only on the first and last number. Why did I say this because it follows a pattern and if we end each other then everything will be canceled out? Brother, if we look at this then rows and rows will be canceled out, right? 0 will be canceled out. If we look at it like this, it becomes one, then again row is zero, then there is one, then this row will cancel out zero. If even one zero falls in the middle, which is bound to happen, because it follows a pattern of alternation. If he is doing okay, then that zero will become zero, so the maximum dependency, we have taken the example of our dependency from 2, where is it coming from our two i.e. 1 2 where is it coming from our two i.e. 1 2 where is it coming from our two i.e. 1 2 3 4 Let's assume like this, okay 5, 6 and 7. Let's take it in 8 88 bits, this is how I took it, for seven I took 1 2 3 4 and here there will be one more four then three, okay oh sorry, it will be like this okay, this is the representation of seven, so this is our Now if we look at this thing carefully, we can find out on the basis of these two, why did I say this because the most significant bit will be at the lowest position and the one at the most. It is significant that the largest element will be the highest i.e. no middle highest i.e. no middle highest i.e. no middle element will be found in which father one is found ahead or father one is found here ahead i.e. no sorry, no middle element will be i.e. no sorry, no middle element will be i.e. no sorry, no middle element will be found in which the most significant bit is found before it. That means here also zero is present and no other smaller number will come in between it and in this case no bigger number will come in between i.e. it number will come in between i.e. it number will come in between i.e. it cannot go beyond this. Okay, so if we look here then In this, we will keep reducing the elements one by one from the right side, that is, we will keep shifting it to the right, we will keep shifting the left one to the right, that is, the right sen will also be shifted to the right one by one, until we have both left and right equal. As we go, we shifted this element disappeared, this element shifted, okay again this element or element shifted, now we have the remaining left and right i.e. 00, both of them are equal, so we right i.e. 00, both of them are equal, so we right i.e. 00, both of them are equal, so we In the while loop we will write while left is not equal to right, what will we do till then we will keep shifting left to right, ok one by one and also keep shifting right to right one by one until we become similar as soon as our It will be similar and we will come out of the loop, okay and one we will put a counter and as many times as we are shifting, we will take a counter so that we can come back to our position, okay ultimately when both are equal. When both are equal, meaning whether you lift left or right, now the two that are left here, when the right shift is completed and the two that are left at the end, will be equal, then either all the zeros will be zero or all the ones will be one and Either all the forests will be one, take one example and understand the case of one, okay take one more example let's suppose here 1 0 1 and this 1 10 If we see in this then right shift this The one element has disappeared, this row has come here This element has disappeared here, this row has come Okay, this is our left, this is our right, again it is not equal The row zero has disappeared, this row has come here from here again Look again, still not equal Left Right again it disappeared and one more zero came in the right sides means three zeros are totaled. Again not equal. Gaped again one more zero got inserted. Okay so now four zeros have come from here and the next four We have shifted the elements, so now ours becomes left and right, this becomes left, this becomes right, so if we look here, now we have equal brother, left is equal to right, okay, there are four set bits in this, it is at the same position. There are four sets of bits in it, so everything is equal here, so now that it is equal, in this case, if we look carefully, when it is equal, then the elements that are left on our right side, that is, on the left side, which we have not shifted yet. Right, all those are equal, either all va's or all ji's are ok, so what to do in this case when these two come, in this case we can take any one, take left or right, take it at the end, this is what our answer is left. But to bring it back to its position, i.e. the number of times we have taken the count here, the i.e. the number of times we have taken the count here, the i.e. the number of times we have taken the count here, the number of times we are shifting, that is the number of times we are taking the count, after that we will count minus the number of times and the same number of times we have shifted right. With that much time we will shift left or left let us suppose that we picked up the left and from there we shifted it left with that much time i.e. that much time i.e. that much time i.e. all the elements which were there returned to their positions and 0 00 came here 0 00 When we come here, now what was the value of left, four times 0, four times one, then four times 0, four times one, back, how many counters did we have, brother, here one doti cha four, we shifted right, so four times we did this. We will shift left four times. Whatever will come. Okay, so ultimately this will be our answer. Okay, so this thing is clear. Once we will code this thing and see, it will be a little better clear to us. Okay. So first of all, we create a counter in this, okay, after that we write the while loop, while left is not equal to right inside, what will we do, okay inside, till the time our left is not equal to right, then in the left we right shift. Once again we will update the value of right. Right shift is ok. Now this thing is cleared. Then we will keep incrementing our count. After that finally we will answer when left or wide loop will exit only when left. Or right, both will be equal to each other, left and right, then after that keep your left in return or keep right, to bring it back to its position, we will hit left shift again, how many number of times count the number of times, we will return it and see. Does the answer come? OK, here I have missed the semi colon. OK, all three items are passed. Once submitted, it is fine. Thank you so much for watching this video. If you liked the video, then like the video and subscribe to the channel. See you in your next video till then bye | 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 |
1,961 | um hello so today we are going to do this problem called check if string is a prefix of array so the problem says we get a string s and then array um of string words and we want to determine whether s is a prefix of strings of orders okay so we get s and then we get an array that is a string of words okay so this is array and this is string s and then i'm going to determine whether s is a prefix of words so s three tricks or four something like this okay what does that mean um so a string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k you know larger than the length okay so it seems like what this would mean is that we will get like a something like words that contains um some values like w1 something like this and we can say that s is prefix of words if s is a concatenation of let's say the first case strings in words so words right the first basically we concatenate the first k words and then example here we get a sequel to this and what is equal to that and we want to figure that out so um so what this would mean here is that we get um so if we say so s can be a here is actually it's just like was zero plus word one uh plus words yeah that's pretty much it's okay is equal to the first two words yeah i think we should the problem is whether it's concatenating the first thing you can just check right so here it can be made only by the three last ones but not containing the first one so i think we can just keep checking right and until we reach the end so that would mean something along the line of for cns uh in words right actually we can even do but i think we can just return if s is in join you can just join actually not in it starts with so python string starts with uh yeah i don't think that would work because if a portion of it is in one um one of the array values and not in the not the entire value then we'd have a problem so we can do this so we'd have to say for say w in words let's say this is c this is kind of um okay how can we name this so yeah let's call it c it's just a concatenation right so here we do c plus w and then if s equal to c then return true otherwise it's returned it's a very simple solution here okay so it seems like that one works um what if i try one that kind of has just this right and this should not work it should be false okay so that should work i think okay cool so that works um what if we try something can we do it in a better way um yeah i think we can so we can do actually just uh yeah i know i was thinking of doing maybe joining words like this but that won't really be that i think to do we can't use any here uh because we want to check the accumulation maybe we can use scan i think um because cam gives us the last result okay let's see python uh scan okay i want this functional uh the functional one okay let's call it let's look for reduce um okay so definitely do the juice right so if i do if i take the list of words here that we have so that will be words equal to this and then if we try to do the juice here so for reduce we'll do some need to do something like reduce and then pass a lambda for the function which would be x and y and then what we want is to concatenate them and then we need to press words okay so this groups everything together the problem is i want to somehow be able to compare this but if s is this it should still return false sounds like i need all the concatenation so i need this and i need to check equal so i need all the concatenation up until that point um so how can this so we kind of need to reduce with intermediary results accumulate maybe so accumulate ah okay so i think this is potentially what we want okay so import from error tools you put accumulate okay and then what we need to do is call it and so the ira irritable is words and then the function that we want is this just a plus okay if we turn it into a list just to see the content it's exactly what we want right and then here we can check if any so here any is takes a miracle right so it can take actually this so any uh i need to first define s so s is let's say this right and so what i need at this point is to any um equal to s for w in this variable uh okay seems like there is a okay this so it says true because yes it does i think this should be this should work so something like this okay so that seems like it works let's try to submit but i think so that works cool i think though we can make this i think there is a plus um in python uh python reference plus operator uh okay so i'm not sorry about that so python pass plus function yeah somehow remember but can it be just passed like this so maybe it's what accumulates even does by default yes so um actually accumulate does concatenation by default both strings because if i do this and just show it as a list then i get the same thing so it's even better with just accumulates like this and we'll check if we find any and actually we just need to check if s is in this we don't even need to do any so this is a lot simpler submit and that works so an even simpler solution is just as my weight yeah i think this is good enough cool | Check If String Is a Prefix of Array | maximum-ice-cream-bars | Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`.
A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`.
Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\]
**Output:** true
**Explanation:**
s can be made by concatenating "i ", "love ", and "leetcode " together.
**Example 2:**
**Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\]
**Output:** false
**Explanation:**
It is impossible to make s using a prefix of arr.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 20`
* `1 <= s.length <= 1000`
* `words[i]` and `s` consist of only lowercase English letters. | It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first. | Array,Greedy,Sorting | Medium | null |
1,650 | hey this is josh from leak dev where we try to explain programming questions as simple and concise as we can today we'll be talking about the lowest common ancestor of a binary tree according to leed code this question has been asked quite frequently by facebook amazon microsoft and just from my own personal experience i was actually asked this question multiple times in screening interviews and actual on-site interviews on-site interviews on-site interviews so being able to know how to work with trees will be a good thing to have in your tool set given a binary tree we want to find the lowest common ancestor of the two given nodes in the tree so what that basically means is for example if we were given p equals five which is right here q equals one which is right here we return three because three is the first common ancestor of five and one in example two we're given five which is right here and four which is right here the first common ancestor of them all is five itself because according to the definition of the lca a node can be a descendant of itself so we return five for example too and then finally in example three we have a tree we don't have a picture of it but we can imagine a tree of one two which probably just like this three and one right here and then we would just return the answer one 1 would be the root node and once again a node can be a descendant of itself one thing to note is that there are several constraints to this problem specifically the important ones to know is that all node values are unique the p-value that we're given are unique the p-value that we're given are unique the p-value that we're given is not the same as our q value and that p and q are guaranteed to exist in tree to solve this problem and all tree problems in general we'll use a recursive solution where we will traverse through the whole tray and find our lowest common ancestor taking a step back and looking at this problem at the high level intuitively it's pretty simple we want to do is we'll recurse our tree we start from one we go through this love child see if it's one of the notes that we're looking for and if it's not we go down look at its left child we find three and we know that it's one of the nodes that we're looking for so return some value back up say true to our two and then we recurse the right tree and see that it is also one of the value that we're looking for q and so we return something back up so maybe another true in this example and then once we're back at 2 and we finish recursing both its left child and its right child we can see both its childs and see that we have found our answer and so we return ideally the problem we want the specific node but in this example let's say we return true and then we go back to one we recurse it's right child and c5 5 isn't what we're looking for so we look at the left node which is null so we return say false and we also look at its right child which also is null so we also return false so because we haven't found the notes we're looking for in five we return back false and then once we go back up to our starting node at one we looked at the left node and we see that we did find our ancestor so we returned some value back up and that would be how we would solve this algorithm of course we can't just return true or false because this problem wants us to return the node that is our least common ancestor so we want to somehow return to in the previous example we bubbled up a true or false value to indicate whether or not we found the nodes and then we bubbled it back up to the top unfortunately that won't work because in this specific problem we want to return the exact node itself that would give us the answer however we can modify our algorithm a bit for example instead of returning a true or false value what if we return the node itself for example once we find the three node we return that node back up and once we find the for node we return that node back up too and then once we're at the least common ancestor and we identify that there are the it is the least common ancestor we can just return that node back up and eventually return that as an answer to be able to accomplish this algorithm i have a six step plan above now first let's clean this up like all three problems we usually iterate through the tree using recursion and we need to do recursion we need to define our base case and our recursive case so what is our base case we have two base cases the first base case is when we reach a null node that means we haven't found anything when that happens we just return null back up the second base case is what happens if we find one of the descendant nodes like three or four when that happens we return that node back up and finally we have a recursive case where we have an identified answer and we want to just continue iterating there's two parts to this first we want to just continuously explore the left and the right subtree of the node that we are currently on and then eventually we will hit those base cases that we talked about and we will return a node back up so three and four now at two while we're processing the left and right subtree if both of them are true we can just propagate the node two back up otherwise if one of them is actually a value and not a null we can just return that one otherwise return null so example in five we would return null because both of its subtree child is null and then we return no back up here and then finally at 1 we'll see that we have 2 and null so we just return 2 which would give us our answer there is one specific case in this algorithm that i didn't address that it handles perfectly though and that's what happens if we have a node that is a descendant of itself so for example if our value p equals two and q equals 4. how this play out in our algorithm because we would actually never process 4. so first let me clean this page up and then we'll do a quick run through right so what happened here is we go to 1 and then we go to two and then two would be one of our base case and then we just return it up however you might just wonder well didn't we just ignore four how do we know if two is actually the ancestor and the reason for that is because of one of the constraints in our problems specifically that p and q must exist at this point if we found one of our nodes and we turn that up that node already is guaranteed to be the common ancestor if we don't find any other nodes in the other sub tree of its parents so in this instance we would return two back up and then everything will play out the same we go to one would then go to its right subtree which end would return null and then finally back at one we compare two and null and then return two because it's the only non-no value two because it's the only non-no value two because it's the only non-no value and we would have our least common ancestor and that's roughly the idea of how this algorithm works let's get to the coding section in recursion problem i like to find define a private helper function because usually you need to pass in different nodes in this instance it's all the same but i'll create one anyways so to reiterate q and p is the nodes that we're looking for and node is the current node that we are at remember for all recursion problems we need to define our base case and our recursive case our base case is either if we hit a null node which means we haven't found anything or if we found one of the nodes and then when that happens we just return the current node that we're at otherwise in our recursive case when we are iterating through our node we have to go all the way to the left child and see if there's a common node and the right child to see if that's a common node and if both left and right is a common node that means our current node is the ancestor otherwise we just return the node back up and that's all for this algorithm very straightforward to code but not so easy to think about and actually implement however just like what we always do let's walk through our problem so first we start with our helper function and we pass in basically everything we were given so current value node is one is not null nor is it any of the descendants that we're looking for so we enter a recursive case to do that we just explore our node.left and we just explore our node.left and we just explore our node.left and we just pass in p and q that brings us to node two also does not hit the base case so we enter our recursive case we check our left node which once again is now three actually is our base case so we just returned three back up back at two our left is now three but we're not done recursing yet the next thing we need to do is we need to recurse through our right node so we go to four and we find that four is one of our base cases it's actually equal to q so we turn four back up so we're back at two and our left node is 3 and our red node is 4. now we are at line 21. if both the left and the right node is not null that means we found the common ancestor and we can just return our node we return two back up to our one node so we exit our left recursive case so in this instance let me just erase everything we are at two for our left node now we still need to explore our right node so we go down there and we enter our recursive case here 5 is not null nor is it any of our descendants so enter a recursive case and just to reiterate where we are i'll use blue to say this is the left and right value of our word node and i'll use green to say this is the left and right value of our five node so r5 and we enter a recursive case we go to left subtree which is null which is our base case and then we turn null back up so that says null and then we do the same with our right subtree which is also null and because both of our nodes are null we don't enter our if statement and so we go to our else case in this code we said that if left is not equal and null we return left otherwise we turn right in this instance because they're both null it doesn't really matter and we just return no back up so null goes back up here and we're back up here and now in our one node we have our calculated node write subtree value which is null and then we follow the same exact logic because both of them are not equal to something we don't return the current node we're at so instead we check if the left node or the is null and then we want to check if one of our nodes is not null and then return that in this instance our left is not null in fact it's actually our ancestor so we want to return that node back up and so we just return two which one will give us the answer to this question now let's submit our code pop this back up and there you go this is how you solve the least common ancestor problem the code itself once we look at it isn't horrible to write but once again this the thought process and reasoning involved to get to it takes a quite a bit of a leap key to these tree prom is that we always want to explore all the nodes go to our base case or usually the bottom of our tree and then bubble our answers back up to the root node now if you consider this video helpful please consider hitting like button and maybe even hitting the sub button to get notified whenever we make daily updates otherwise i'll see you in the next video and have a great day | Lowest Common Ancestor of a Binary Tree III | find-root-of-n-ary-tree | Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_.
Each node will have a reference to its parent node. The definition for `Node` is below:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). "
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` exist in the tree. | Node with indegree 0 is the root | Hash Table,Bit Manipulation,Tree,Depth-First Search | Medium | 1655 |
103 | hello everyone welcome to coding decoded my name isja I'm working at sd5 at Adobe and after a very long time I have come on to creating a new video because uh all the questions in the month of February seems like an easy question and most of them were already solved by me already and for those who were not I believe that you guys are capable enough to solve those questions because the land up an easy category and today since it was a medium question that I haven't solved in the past so I thought let's create a video and it will give me an opportunity to interact with you so welcome guys welcome to day 19th of January lead Cod Challenge uh it's ex wait now it's 19th yeah day 19th of February sorry February lead Cod Challenge and the problem that we have in today is binary tree zigzag level order reversal the question says you need to perform the zigzag level order reversal of a binary tree and what does it mean it means that whenever you are moving from one level onto another uh the direction in which the BFS reveral has to be performed will change for example here you will be moving from left to right here you will be moving from right to left here you will be moving from left to right and the answer correspond that first is left to right then it's right to left then it's left to right so without further Ado let's quickly move on to the presentation and let's quickly get hold of the algorithm lead code 103 binary tree zigzag level on the traversal this question is a medium level question on lead code but the subscribers of coding decoded would feel that this is an easy question and for those who are new to coding decoded this video is primarily for them also in case if you have any doubt understanding this problem upart if you want to ask anything from me in general with respect to job opportunities internships placement please feel free to drop a message on the telegram group of coding decoded we have 2,000 developers working decoded we have 2,000 developers working decoded we have 2,000 developers working from all top notches in this group and we openly discuss problems that we face in day-to-day activity what's new in day-to-day activity what's new in day-to-day activity what's new happening in the industry Char GTP AIML stuff referrals layoffs and what not looking forward to seeing all of you there now let's get back to the problem I have taken a slightly longer example so that you guys get a good hold of the concept and here the root of the binary T that is given to us is 10 so the question says you need to perform the zigzag level order traversal moving ahead let's start the iteration and at the zeroth level we will move from left to right direction in the level order reversal in the next level which is level one we will move from right to left then we will move from left to right and then we will move from right to left so definitely we will need a variable that will help us identify whether we are moving from right to left or left to right and the answer corresponding to this binary tree would be the first one would be 10 then we would be then we would have 0a 40 then we will have 7A 2A 1112 followed by 34A 78 and now comes the question how can we algorithmization in which you're doing the movement at any particular level so let's create a level a variable named left to right l t and let's initialize it to true because at the zeroth level we are moving from left to right let's start the iteration and as the basics of level order reversal what do we need a queue so let's get started and let's go ahead and create a queue what we're going to do we'll add root into the Q what is the root element happens to be 10 and we will initialize the left to right element to default value of true now we are done with the level order traversal L zeroth node the next thing that we are going to do is to pull this element out so this element is gone and uh what is the value of left to right happens to be true so we will simply build a new array and we will add 10 onto it awesome the first ele element of our answer is done let's move ahead and since we are removing this element what do we need to make an insertion of all its children into the Q so 40 and0 will be added onto the Q and remember we'll be adding the left element first followed by the right one so 40 get started followed by zero and this forms the boundary of the first level of the BFS reversal this is level zero of BFS reversal let's contining the process and remember since we are done with level zero of the BFS reversal what we going to do we'll be flipping this value up left to right now let's set it to false we are basically toggling this up and let's continue the process the next element that we have happens to be 40 gets extracted and it's time to build the second element of our answer and what do we see that the left to right element happens to be false so we'll simply make an insertion since it's the first element for 40 so 40 gets started and again since 40 is getting removed we will have to make an insertion for its children into the BFS Q so the BFS Q will get 7 comma 2 so 7 gets added followed by two so this is level two of the BFS reversal and let's continue the process now comes the important part where we will need the left to right variable the next element that we have happens to be zero and since 4 is gone let's delete it the next element that we have happens to be zero and since left to right element is false what we are going to do we'll make an insertion into our answer array at the starting node 0 gets added at the starting node instead of adding zero to the ending position we will be adding this zero to the starting node and this is the Crux of the problem U since we are removing Zero from the first level of our BFS traversal we should be adding its children into the BFS Q what element do we have as it children 112 So 112 gets added over here and this element is gone now let's continue the process and since we are moving to the next level we will be toggling the value of the left to right variable so now again it gets set to true and we are done with the second element of our answer which is 0 comma 40 so let's proceed ahead and it's time to create the third element of for answer uh the second level has three elements in it 1 2 and 7 so let's pull out the topmost element from it seven gets extracted and uh since seven gets extracted it doesn't have any children so no insertion is made into the Q and let's add seven as part of our answer now let's continue the process the next element that we have happens to be two so two gets extracted and does it have any children yes it has one child which is 78 so let's write 78 over here and since left to right variable happens to be true we will be making an insertion into an answer array at the end so two gets added at the end had it been the case where left to right variable would have been false we would have made an insertion at the start let's proceed ahead the next element that we have is 112 So 112 gets pulled out and it has 34 at its child so let's add 34 over here and let's add 1112 at the end of our answered element so in total we have three elements 7 2 1 2 and those are present in this particular order which is moving from left to right we are done with the third element of our answer and let's proceed ahead the next level would be three and since we are moving on to the next level let's set the left to right variable to false let's continue the process the first element that gets extracted happens to be 78 let's create the fourth element let's add 78 over here and it doesn't have any child so no insertion is made the next element that we have is 34 it also doesn't have any child so this element would be inserted at the starting point of our answer result why at the starting point because our left to right variable happens to be false so let's write 34 at the start with this we have successfully iterated over all the elements that are present in our binary tree and in total the answer corresponds to 10 040 72112 3478 and this is what the question expected us to return so without further Ado let's quickly transform this algorithm into code and I'll exactly follow the same steps as I just talked here the first thing that I've have done here is to create a list of integers that will help me return the answer result in case my root is null I simply abought the process and return the ANS otherwise I go ahead and create a BFS Q I add my root onto it I create a variable named left to right and initialize it to true the typical we of lighting any BFS reversal Q dot is not Q is not empty I extract the size while size minus is greater than zero I extract the topmost element and here I have created another subl list that will help me create the answer at that particular level if my left to right happens to be true what do I make an insertion towards the end of the subl list in case my left to right variable happens to be false I make the insertion at the starting point of my subl list and this is again typical way of writing the BFS reversal if my head dot left is not null I add it into the cube my head dot right is not null I add it into the cube and once I've done with iterating over a particular level in my BFS reversal I add my sublist on onto the result and I toggle the value of left to right once I'm out of the while loop outer while loop I simply return the result so let's go ahead and submit this up guys in case you haven't still learned this BFS reversal template it's high time you do it because this is same template that is used in all the BFS questions also it really helps in the graph problems so I would urge you guys to learn this as a temp template and you will be using it everywhere apart from this if you're interested in solving more questions of the tree concept then you can check out coding decoded SD preparation sheet here it includes all the important questions from interview's perspective so if you have an important interview plann very soon and you want to go through the entire revision process then this sheet would act as your Bible so go ahead and select trees for the BFS traversal concept and here you will see the questions that are mared with double sign as a must do before an interview and you can try all these questions using the BFS technique also in case you get stuck in any of the question then here is the video solution attaching it Link in the description below so do check this out with this let's wrap up today's session I hope you thoroughly enjoyed it if you didn't please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and I'll see you tomorrow with another fresh question but till then goodbye | Binary Tree Zigzag Level Order Traversal | binary-tree-zigzag-level-order-traversal | Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[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]`.
* `-100 <= Node.val <= 100` | null | Tree,Breadth-First Search,Binary Tree | Medium | 102 |
119 | welcome to august leeco challenge today's problem is pascal's triangle two given the non-negative index k we turn given the non-negative index k we turn given the non-negative index k we turn the kth index of a pascal's triangle is represented nicely in this graphic where every row has one more cell than its previous row and the numbers within are going to be the summation of the two cells above it notice how all the cells on the borders are always going to be one so it's only the ones in the middle that we need to calculate so let's think about how we could represent this in a programming language like python and we'll probably use a list of lists if we went straight forward we could think of what would we need to do to calculate the last row here this will be the row three and whatever row we want to move forward we need to calculate the ones before that iteratively in order to get the next row and so on and so forth so just like the graphic indicates all we care about is the ones in the middle right and we need to add up the two on top so if we represent like this like we can see that visually but how about what would that look like in uh in a programming language to make it easier try to instead of making a triangle just look at it like this um i guess it's still a right triangle but you can see all we care about is the numbers in the middle right we see that the one row before it we just want to add up the same index number as well as the index number before it here so 2 is going to be the sum of the previous row same index as well as the index minus one here in three we can see that we need to add up one and two three is going to be out of two and one and everything else at the edges we don't care about those are always going to be ones so our approach then would be to go through each row create a temporary array and calculate the ones in the middle and then add that to our output and continue this loop until we are finished and then return the last list in that array all right so let's see what that might look like so first things first we want to start off with i'm going to call it pass this is going to be our pascal's triangle and since we know the very top row is going to have just a 1 we can just begin with that now we want to do this for however many rows that we're given so 4i in range of row index and we're going to have to do a plus one because this is 0 indexed and we want to start at the second row which is going to be 1 here because we already have row 0 that's already got a 1. so the first thing we want to do is start off by initializing our temporary rate and we'll just say make this a list of ones for in range of what i guess it would be in range of the row index that we're on right row index that we're on plus one range of plus or months so plus one yes all right so after that we now we know that it's going to be like 1 at this point and we'll say this isn't a very good example because we want to save it's like the third second third row here we only want to care about the one the middle right so what we'll do is since the ones at the edges are already ones we'll just say for j in range of one to the length of our temporary ray minus one so that way we're only going to care about the ones in the middle and at that point we're just going to make our temporary index array the index point equal to our pascal's triangle whatever the previous row is the last row that we've added on as well as j plus pascals minus one uh j minus one so that's going to equal two on top of here so once we're finished with this since this updates to two now we could just add that to our pascal's triangle we'll append our pascal strangle with temporary array and then just continue the loop after we're finished with that let me just delete that here and we will return our last list on our pascal's triangle so let's see if i've messed anything up certainly might have okay looks like it's right let's go and submit that and there we go accept it okay so this works but they have a follow-up works but they have a follow-up works but they have a follow-up can you optimize our array to only use k extra space so basically just a list with k indexes indicating like our last row hmm so that's a little complicated right because don't we need to have our previous rows to calculate the next row this is like a dynamic programming solution right but if you think about it carefully let's just think about that last row here one two one we want to get to one three one right could we use this array to get to this array doing the exact same thing that we're doing here well uh the problem is uh first we might want to append a cell right so we'll say that we add one here at the very end now we just care about the ones in the middle so how about we just add up the ones from before and get that three but if we do it left to right you can see immediately we update this so now this one doesn't work because we've changed this we need that too but what about the other way well because this one is new and that's never going to change you can see that here if we just add the previous one we're kind of going uh i guess bottom up we'll add 2 to our 1 here that's 3 but we'll be keeping this 2 and i'd keep bringing the 1 here and now we've gone to this point and this is still using the same list we just appended 1 and that's going to allow us to only use k extra space so the algorithm is still the same all it is we're going to get rid of our temporary array that we're creating and instead use the same list okay so start with initializing our output it's not going to be a list of lists it's just going to be a list and we'll still go through this same thing but instead of just creating this temporary array what we'll do is append to our output 1 and the same thing here this would be the same except we want to move backwards right so how will we do that length of output minus 1 but we want to go minus 2 because we don't care about the very last one we're going to go to not negative one we're going to go to zero and we'll still decrease by negative one finally instead of having our temporary list we will say i'll put just add the one previous to it so plus equal output of j minus one we don't need to append anything now all we need to do is return the output at the very end okay so let's see if that works okay it looks like it worked let's go ahead and submit that and there we go so the time complexity is the same and we are only using k space so that's it pascal's triangle is a good one i would definitely look into it and solve variations of this problem thanks for watching my channel and remember do not trust me i know nothing | Pascal's Triangle II | pascals-triangle-ii | Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**.
In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown:
**Example 1:**
**Input:** rowIndex = 3
**Output:** \[1,3,3,1\]
**Example 2:**
**Input:** rowIndex = 0
**Output:** \[1\]
**Example 3:**
**Input:** rowIndex = 1
**Output:** \[1,1\]
**Constraints:**
* `0 <= rowIndex <= 33`
**Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space? | null | Array,Dynamic Programming | Easy | 118,2324 |
438 | Hello Hi Everyone Jasmine Chakraborty And Today Will Be Discussing Problem Number 1434 Let Code Find All Programs In History 109 This Is A Problem Dentist In Bittu Of Every Day I Am Not Challenge In Its Food Should You To Problem Avoid Yesterday I Want From You Can Be Sent out from Play List to Play List Soe Hind is the problem giving such things S&P S&P S&P that hand they have to find all exams page in this handy tool returned starting index of all 20 grams of words and from Android browser water for five years in the Letter of different water friends typically used oil generator set you want to and from physical representations of a lukewarm spring plate in software approach bring a b c all it's an order comes with baby force will be included in bsc bca editor-in-chief that RCB Ad SSC Board Result Research Adams Of ABC Okay Something Clear Soe Na How To Approach Typical Problem Take Care Due To Speed And It's Okay Fennel Will Have To Subscribe One Will Not Familiar With Lots Of Year Was Doing What Is That We Can Do The Giver size the insights and distributes prices for history for grand set n alarm of birth the same size adds patients can not be a great and fearless and fear to be considered for window size three layer and facilities and akram have descended from which produced som one shiv They know how difficult use fluid you check 1000 soon listed 80 used s monitor of booty dude video to share I currently handsfree consists of life become online country ok so wear considering all the characters and notification like share with all they know what this Chief subscribe Video subscribe window installed after computers for villagers painted advantage of this will be seen in the 11th that soegi vacancy this to is obscene equal handed over validation of from itunes store the answer has starting date for a number of years will shift window 98 ki bread cod don't see soapy mode 150 g in account and lag department z9 Vivo considers is not present in this he should withdraw it and remove all the window that airtel ko 280 b off but as they all records acid 100 comes a row That hand ac being can be included bbi was not dare previous letter this is the doctor away from studio but welcome one ko shampoo difficult and renewable 2009 will continue shifting to window like this is the anil bhai ji tentative dates year will continue for the valuable And give them but it's there in which year will have battery saver mode on the year open the acid which is singh sentence me 120 gms scene of peer 120 respectively 6 on one so normal that Ravana optimization what we can do share this and institute After taking any attachment to account for this what we can do it is decrement account declared like they never define cid comment voyager-1 voyager-1 voyager-1 middle aged department 1000 and find every day the moment when one sheet in exam in 2017 this completely hero sprint with vinod sign up Indians Devi Point Sequence Print Show Video November Of Nowhere Is Described In Later Years From The Back I Increment Annual Victory Awards And Utilize Get Here Sw0 This And Welcomes One OK And A Slack Made It Clear That Comes Forward Bases Painted Sunth Department And So Vid Ooo will again welcome involved in this included and share it well and decrement by one leg is so when we reached near this whole thing but with vidmate s well so ifin singh vikram zero day will include six years in the problems let me to go to the Code Year Celebration of Morality in this Function is Hey What So Any Significant and Mrs Pain Person's This Condition Life in First Time Bigg Boss This Condition Aa Vriksha Ek Plate Idhar Size Penal Sainik Us After Death Sentence subscribe The Channel and subscribe the Channel and in Frequency of all characters page subscribe channel subscribe now to which sliding window is initially e do not moving til servi moving that til size pet checking cba because in this element window size se zoom 12 benefit for industry don't want for this is the time building Window Plate Midnight Fever OK Hum Building's Vendor Teller m&m OK Hum Building's Vendor Teller m&m OK Hum Building's Vendor Teller m&m Exercise You OK So M Taking a Character and Thinking in This Present in the House Map and Implement One Developed Is Not Present Leaders Were Not Pregnant So I Do n't Need to Avoid It Simply Introduce Gift I Is Presented It's Present In Amazon Sub Screen Definitely That Is Not Done From 100 Ki Idea Comments It's Present In The Juice Of His And His Mouth And Noted That If She Gives Functions Check Map Of Facts And Figures Responsibly Started Now Desk Does It Check weather all is the value side and not going to later dated check all the best starting from this side start from - 30 - 30 - 30 - - 121 on that your and share later android gear shifting the window Uttar Pradesh Sliding Window 10 in this building Sliding Window And Take You Can and Should Avoid - Subscribe White on the table subscribe Video Use Two Years Boys and Boys Payment Festivals But They Don't Need Not a Single Bill Sent Content Science and Technology Department and the Initial Typing Position Gold Behind Give New Cars Present in disgusting discriminatory topic director is presented the investment and implemented by one key and share will sell on chat function and after this incident in this time which is a war has time field with jio fei this day in the year digit heading initial position of the soft to Much of the credit for this is the fool solution ok 109 left side this dual sim not interested and want to avoid you will be amazed and subscribe if someone has flowers smack and sacrifice everything is a row of any harm the middle end False evidence of wave's time complexity of all programs of nd24 loop control maximum of with 6 times ok should you go from 02351 subscribe le prince from nothing acid latin characters for divya and you will take time to paint a time when placid is near problem Problem The Best To Do Subscribe My Channel Video That And You Will See You In Next Video | Find All Anagrams in a String | find-all-anagrams-in-a-string | Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**.
An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
**Example 1:**
**Input:** s = "cbaebabacd ", p = "abc "
**Output:** \[0,6\]
**Explanation:**
The substring with start index = 0 is "cba ", which is an anagram of "abc ".
The substring with start index = 6 is "bac ", which is an anagram of "abc ".
**Example 2:**
**Input:** s = "abab ", p = "ab "
**Output:** \[0,1,2\]
**Explanation:**
The substring with start index = 0 is "ab ", which is an anagram of "ab ".
The substring with start index = 1 is "ba ", which is an anagram of "ab ".
The substring with start index = 2 is "ab ", which is an anagram of "ab ".
**Constraints:**
* `1 <= s.length, p.length <= 3 * 104`
* `s` and `p` consist of lowercase English letters. | null | Hash Table,String,Sliding Window | Medium | 242,567 |
103 | hey everyone welcome back to the channel i hope you guys are doing extremely well so today we will be discussing the zigzag traversal from the frika tree series now what does this traversal means so in the previous traversal that is the level order traversal you saw that the traversal was like one two three then a four five six now this is zig zag as the name suggests so first it'll be one then you'll go across like this that's three two then you'll go across like this four five six so that's the traversal zigzag traversal like first like this then like this so kind of this and if there were any other levels it'd be like this then it would have been like this so that's what a zigzag traversal is all about so we're going to follow the same technique as we did in the level order traversal so initially we will be taking a cue data structure so let's take initially a queue data structure and i'm going to store the root of the tree there's no doubt in that we're going to store the root of the tree in the queue data structure also we're going to take a vector of vector or a list for that reason that's the data structure where we will be storing the zigzag traversal and we'll be returning this as our answer so what we will do different is we are seeing one thing that the first traversal is from left to right then it's like this right from right to left then again from left to right then from right to left so we're gonna introduce a flag kind of a variable okay so let's introduce a flag variable which is gonna say us if you're moving from left to right or you're moving from right to left so probably we can keep a flag variable uh initially let's assign it to be zero or one you can do it as you wish so let's start the iteration of the cube so in the iteration of the queue first time when i check out the queue there's only one element so we will take it out okay and now what we will do is if there is a left there is so we will insert it into the queue if there is a right there is we will insert that into the queue once i've done that once i've inserted all the bottom notes left and right i will take this guy and i'll insert it in the same order like i took it out that's one the flag is zero very important to the flag is zero so flag zero says us that the direction is from left to right and the value one says us that the direction is from right to left in our traversal so we are done with one so once you've inserted one into your data structure please make sure you turn the flag to be one because you're going to the next iteration of the queue right and you'll get the next level notes that's two and three so let's get the next level notes to entry now you're gonna check for twos left that's four so kindly insert that into the queue you're going to check for 2's right that's 5 insert that into the queue so 2 is done next for 3 is left there is nothing 3 is right there's a 6. insert it so i can say i've done for 2 and 3 so these elements are also done now since the value of flag is one what you will do is instead of inserting it like two and three you will make sure they are inserted in the reverse order that's three and two that's why i said a flag is one it's right to left so flag one told us that it's right to left now while you move to the next level please make sure you turn flag back to zero so every time you're switching on levels you turn flag zero one right and the next you get something as four five six and it's time to check if they have left and right four doesn't have a left four doesn't have a right five doesn't have a left five doesn't have a right similarly with six doesn't have a left doesn't have a right so can i say the traversal for four five six has been completed and the flag value is zero and if it is zero i will simply take four five six and insert it into my data structure without reversing it so i've inserted that into the data structure now can i say if i look back at the queue my queue is indeed empty now hence we have traversed all the nodes and right after the traversal can i say my data structure is having the zigzag traversal that i was asked to print and i can return this data structure and this is going to be my answer so the difference that i did from the previous question was i just maintained a flag variable which was like 0 1 0 every time i went on to the next level i just converted zero to one to zero and vice versa that is what i did so again we're going to discuss the c plus and the java code so you can see the c plus code on the left and the java people can definitely follow their code that's on the right them they're mostly identical so you can definitely catch up so initially we are given the root of the tree and we declare our data structure that's result and the tree is empty we're going to return the data structure which will never have any uh zigzag traversal right after that i declare the queue and i initially push the route right and we have a flag which is initially marked as true so basically over here what i'm done is true means left to right and the opposite will mean uh right to left that is what i have been doing over here right after that i travis in the queue so you know uh always we take all the notes of that level so let's take all the notes of that level and what i do is i run a for loop okay i'm running a for loop on all the notes of that level and what i'm doing is i'm basically taking it popping it out so if your cue for an example has 2 3 i will iterate on 2 and i'll iterate on 3 using this for loop got it right after that i check what i check is left to right true if that's the case like this 2 that i'm taking out i'll put it in the front of my data structure and after that i'll put 3 if the flag is true if it is not what i've done is i've smartly made sure that two will come at back then three will come right depending on this flag i'll either insert it uh from the front or i'll either insert it from the back simple enough right simple enough constructive and the rest thing remains the same i insert that into our vector or list and right after that i check left and right and i push it once i've done this entire iteration right i can always switch on the flags and i'll keep on the data structure whatever is on the row that's three two whatever is it i'll keep on the data structure once that is done i can definitely return my result so the thing that i did different from the previous uh level order traversal is this one flag and this while storing in a array or a vector whatever you can call it what i made sure is i made sure i either push it from the front or from the back that's that is the logical thing that i did in order to get the zigzag order traversal so what will be the time complexity again the time complexity is going to be big o of n similar to level order and what will be the space complexity that's going to be bigger of n similar to the level order traversal so i hope you've understood the entire explanation as well as the code just in case you did please make sure you like this video because it took a lot of efforts to make this entire tree series also if you wish you can definitely drop in a comment that will keep motivating me to make such further series also if you're new to the channel please do consider subscribing because i'm going to bring in such more series in the upcoming future as well with this uh let's wrap up this video let's speed in the next lecture bye take care whenever your heart is | Binary Tree Zigzag Level Order Traversal | binary-tree-zigzag-level-order-traversal | Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between).
**Example 1:**
**Input:** root = \[3,9,20,null,null,15,7\]
**Output:** \[\[3\],\[20,9\],\[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]`.
* `-100 <= Node.val <= 100` | null | Tree,Breadth-First Search,Binary Tree | Medium | 102 |
1,812 | hello guys my name is Ursula and welcome back to my channel and today we are going to solve a new lead code question that is determined color of a chessboard Square we will be solving this question with the help of python the question said you are given coordinates a string that represents the coordinates of a square of the chessboard below is the chessboard for your reference return true if the square is white and false if the square is black so we have to return a Boolean value corresponding value with the byte is uh 2 and for black is false so the coordinate always the coordinate Will Always represent a valid a square bot chessboard Chase Port Square the coordinate would always have the letter first and the number second Okay so we will be given a string for example in question number one for example number one uh for example we have given a string and then we will be always given a string a character followed by a number and we have to determine whether it's a black one or a white square so if it's a black then we have to return false if it's white we have written true oh so how are we gonna follow how we are going to solve this question what will be our approach I will tell it to you so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so let's start so I will say that e C uh AC and first of all I will Target these four so why I am targeting these four so I will I'm explaining it to you that uh you see that on a c e and G they have all the means they if you see on A2 A4 A6 and A8 C2 C4 C6 C8 E2 E4 E6 E8 G2 G4 368 are all white so we will return by uh we will return true for these so let's do that and return true for this and else we will return false for these four values how we are gonna Target this I will say that if coordinates 0 so they are saying the coordinate always start with the letter first so we will Target later first so we can use this here because it will always start with a letter so if I say that if a letter is e or a letter is these so let's copy this to save our time copy and paste it four times or so let's change this to c change this to E and change this to G so we have targeted are these four values now we will see that again our nested if else condition here that if coordinates so the second condition they are seeing here is that it will be always the number second so we can Target a number here coordinate one and you will see that mod 2 is equals to zero because see these are all two multiple of 2 4 6 8 are all multiple of two so if we can uh use this for so we have to use it as an integer because it will not divide if it's a string so we have to convert this only thing here that is our coordinate one into integer so that we can see the modulus of 2 that's its mean even or not if it even then return true else return false so now we have targeted our R4 the four of these values so I will say that uh other the other than these values will be our else value so instead of this I will be targeting with values b d f h so b t e f h would be if I will write the same condition here that if int and coordinates again one uh is divisible by 2 means if it's divisible by 2 means this value h d f h so B2 D2 F2 S2 and so on I will say that return false just the opposite of that and else return true so that's all in the question hope you have understood it let's run the code and check the validity of our answer so we have quarter answer here thank you guys for watching the video if you have any doubt ask in the comment section | Determine Color of a Chessboard Square | reformat-phone-number | You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference.
Return `true` _if the square is white, and_ `false` _if the square is black_.
The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second.
**Example 1:**
**Input:** coordinates = "a1 "
**Output:** false
**Explanation:** From the chessboard above, the square with coordinates "a1 " is black, so return false.
**Example 2:**
**Input:** coordinates = "h3 "
**Output:** true
**Explanation:** From the chessboard above, the square with coordinates "h3 " is white, so return true.
**Example 3:**
**Input:** coordinates = "c7 "
**Output:** false
**Constraints:**
* `coordinates.length == 2`
* `'a' <= coordinates[0] <= 'h'`
* `'1' <= coordinates[1] <= '8'` | Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply. | String | Easy | null |
374 | hello everyone welcome to kodus camp we are 12th day of october lead code challenge and the problem we are going to cover in this video is guess number higher or lower it is again a easy category problems the input given here is an integer value n and we have to return the number we picked so the problem statement has a predefined api call the method named guess and this is going to return three possible values the numbers are going to be from 1 to n and if the number we sent to this method is exactly matching the same number then it is going to return 0 if it is less than the number then it is going to return minus 1 if it is greater than the number it is going to return 1. so we have to use minimum number of guess calls and guess the number the system has picked or we picked so let's understand this problem with an example so here is the given example the n is equal to 8 which means the numbers are from 1 to 8 and pick is not actually an input the system randomly picks a number and we have to find exactly which number the system has picked by using the guess call so what would guess written is 0 1 or minus 1 for example if we if the system picked the number 5 and we have to pass possible numbers to the guess method and find which number the system has picked for example if we are passing the number seven first the possible outputs will be zero minus one and one so it is definitely not zero because uh the number system picked this five and b cent is seven so if the number is less than the number the system has picked then it is gonna return minus one so obviously 7 is greater than 5 so it is going to return 1 so which means we can figure out 7 is greater than 5 so we have to search for the number which is less than 7 so we can put our search before 7 and look for the numbers for example if we send 3 as the second guess so the guess method we are passing 3 is not 5 so it is not going to return 0 but 3 is less than 5 so it is going to return minus 1 so in this case we can figure out the value is after 3 so how are we going to approach this the straight away brute force method would be calling the guess method from the number 1 to n that is 8 here and for every method it will be a number return for example minus 1 till 4 and guess of 5 would have 0 and then plus 1 till 8. so in this case whichever guess is having 0 that is the number the system has picked and we should return it this is a straight call and i try to brute force method that is going to take because n time complexity but how do we solve it in a better way clearly the input values are from 1 to n and they are in ascending order so this gives us a very clear clue that we can approach this problem using binary search so simply we are going to divide the input by half as usual and gonna find the mid so here the mid is going to be 4 and we are going to pass this mid value to our guess and based on the result of our guess method we are going to fix our search space so let's first fix the mid to 4 and try sending 4 to our guess method so as i said 5 is the number our program has been picked so we are going to first pass guess of 4 and guess of 4 would actually return us minus 1 which means our value is actually less than the value that the system has picked so clearly we have to fix our search space after 4. so we are going to move our left value to 5 because 4 is not our value we are searching for and right value stays the same so now our search space is between 5 and eight now again it's time to fix the mid value and pass it on to the guess method so here the mid value is going to be six we are going to pass guess of six so this is going to return one because 6 is clearly greater than 5 which means our search space must be before 6 so we are going to move our right pointer towards before 6. now our left pointer and right pointer point at the same number five which means we have reached the point where our guess is going to be zero so for confirmation let us send our guess back with five and that returns zero which confirms phi is going to be a number so 5 is going to be an output so the previous solution is much easier than this algorithm is going to work and big o of log in time complexity because of the binary search rule and we go of one space complexity so hope you're understanding the solution let's get back to the code so as i said let's fix our limits left and right to one and yeah and calculate our mid so every time we are going to call our guess method and store the result in the integer variables since we don't have to call it again and again at every if loop conditions so based on the result we are going to check if our result is equal to 0 then mid is the number we are looking for or the number that the system has picked if not we have to check so yes based on the result if the result is less than zero which is minus one then we are going to fix our search space before the minute if not we fix our uh left bound to after the bit if not we did not find the number at all then we are going to return -1 so yes that's it let's run and try okay let's submit yes a solution is accepted and we have done with our today's problem and the solution runs 100 faster of all java solutions thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you | Guess Number Higher or Lower | guess-number-higher-or-lower | We are playing the Guess Game. The game is as follows:
I pick a number from `1` to `n`. You have to guess which number I picked.
Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess.
You call a pre-defined API `int guess(int num)`, which returns three possible results:
* `-1`: Your guess is higher than the number I picked (i.e. `num > pick`).
* `1`: Your guess is lower than the number I picked (i.e. `num < pick`).
* `0`: your guess is equal to the number I picked (i.e. `num == pick`).
Return _the number that I picked_.
**Example 1:**
**Input:** n = 10, pick = 6
**Output:** 6
**Example 2:**
**Input:** n = 1, pick = 1
**Output:** 1
**Example 3:**
**Input:** n = 2, pick = 1
**Output:** 1
**Constraints:**
* `1 <= n <= 231 - 1`
* `1 <= pick <= n` | null | Binary Search,Interactive | Easy | 278,375,658 |
1,799 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximize score after n operations this one is pretty hard but it's not as crazy as you might think and if you're not super familiar with bit masks this is an opportunity to learn a bit about them no pun intended but we are given an array of positive integers and the fact that they're positive integers is only significant because we are going to be running the gcd operation the greatest common divider aka the greatest common factor if you don't remember what that is consider two numbers six and nine what's the greatest factor between them I think it is three because we can take six divided by three and it equals two we can take nine and divide it by three and it equals three so we get an integer in both cases and we can't really get a larger integer that will divide them and in this case they say the size of the array is actually two times n that's significant because we're told that we're going to be doing n operations where we are going to be choosing two elements from the array and basically removing them to calculate a score therefore we can only do about n operations until we run out of elements from the array because it's of length two times n so suppose we have an array that looks kind of like this how many operations would we do in this case three of course because let's say we're going to be removing two each time and we do that again and then we're out of elements but what we're going to be doing every time we remove two elements is calculating the gcd between them and I'm just going to tell you right now that we're not going to get super into that this is a math function and in the scope of this problem we're just allowed to call math.gcd because I think this problem is math.gcd because I think this problem is math.gcd because I think this problem is hard enough and in a real interview hopefully your interviewer would tell you that or you could just ask them but given those two numbers that we removed we would call gcd on them one and two find the greatest common divider which I believe in this case is one and as we'd make these n Opera operations we're going to keep track of how many operations we've made so if this is our first operation we're going to take the score or rather the gcd of the two numbers and multiply it by one because this is our first operation so far our score would be equal to one suppose we take two more elements three and four calculate the gcd between them three and four I believe it is also one in this case but this time we would take one and multiply it by two because this is the second time we are doing that operation and then we would take this two and add it to the score which would get us to a total of three so far and then at the end we would do that again and pretty much repeat that operation but the complicated thing here is that we have flexibility on how we want to calculate these gcds so we don't have to do it the way I showed we actually have choices we could start with one and six we could start with one and four we could start with three and four it doesn't matter we have a lot of flexibility but we want to find the way that maximizes the score so we want to find the max score we could possibly get doing it this way which is definitely not going to be easy I mean right off the bat you might think okay let's just try like The Brute Force way trying every single combination but you might think is there room for optimization here like is there some kind of math pattern behind it could we maybe sort the array or maybe numbers that are close together going to have a greatest common divider that's larger because that's probably what we want to maximize the score well once you start going down that train of thinking you kind of realize that even if there is a solution like that you must need like a math dissertation to figure it out so probably there isn't going to be some kind of crazy math solution and again if there is you probably just wouldn't be able to figure it out so then you might go back to the brute force and think if you can somehow try to optimize this but before we even optimize it let's just understand stand how we could even solve this in a Brute Force way because it's not trivial that's for sure okay so starting at the root of our decision tree because we are going to solve this recursively let's try to enumerate all possibilities how would that be like what's our first choice well we can choose any pair of values we could choose these two values we could choose this and this we could choose one and four etc how do we even enumerate those well we're going to need a couple nested for Loops right and doing that we realize that at the first layer of our decision tree we have about N squared choices that is not going to be very efficient right and when I'm saying n in this case let's say n is actually the length of the array even though in the context of this problem it means something else but I think it's more simple to just think about it in terms of n so we have N squared choices how many choices are we going to have well if we remove two elements on each choice and the length of our array is n the height of the tree is probably going to be n divided by two so overall here the time complexity is going to be N squared to the power of n divided by 2 which I think would be n to the power of 2 times n because I think this multiplies with this well I guess the divided by 2 cancels out the 2 here so this would actually just be roughly n to the power of n but clearly that's not super efficient that's even a lot worse than 2 to the power of n so this is not very efficient but there is something we can do to speed this up and the idea is caching yes this is a dynamic programming problem but it's not a traditional one we're gonna need a bit mask but first let me tell you why we can use a bit mask in the first place there is a constraint on this problem which is not shown here but it tells us that the length of this array is at most going to be 14. that's not a very large number at all now it's not enough to pass on leak code if you have a solution that's n to the power of n that's going to be a pretty big number but using this we can apply caching notice something about our decision tree here well instead of drawing out that entire tree I'm actually just going to show you on the arrays it'll be a lot simpler trust me let's say for one of the branches over here we chose one and two as our first choice and then maybe on our second choice we chose three and four that's one possibility let's say on another possibility though we chose one and three then on the second choice we chose two and four so even though we made different decisions in our tree we ended up at the same sub problem now the way we calculated the score when we took these elements and we took these elements definitely could be different I'm not saying the score is the same I'm saying after we make those choices the sub problem is the same so when we have to solve this sub problem why should we ever have to solve it again that's the idea that we can apply caching to because we see there's repeated work going on now how do we even Define this sub problem we can't just keep track of it in a single integer can we because here clearly we have an array so what should we do maybe we should use an array as the key of our cache and what that array would represent is for each element have we already used it or is it available to us so in this case we have six positions and we say for the first four they've already been used and for the second two and for the last two they are still available to us so that's kind of the information we need and yes you actually can use an array if you want to or maybe you could convert that array into some kind of a string if you want to that's like delimited by commas but the most common approach here is to use a bit mask because actually we can represent all of this information in a single integer and we can do it in an integer that's 32-bit because the integer that's 32-bit because the integer that's 32-bit because the constraint here is that the max size of the array is going to be 14. so we only need 14 bits 32 bits should be plenty for us so instead of using the array to Mark whether our value has been used or not we're going to have an integer that might look like this well it'll have more bits but we just care about the first six of them and when we use an integer like for example when we use these four we would take these and turn them into ones like this and this would evaluate to some integer I don't know what it is off the top of my head but it can be used as the key for our cache in my case I'm going to use a hash map but you could also use a array a one-dimensional array now lastly what one-dimensional array now lastly what one-dimensional array now lastly what are the parameters that we're going to keep track of as we make our recursive calls because remember not only do we have to keep track of which elements we've already used we have to keep track of what operation and we are currently on because that plays into the calculation we have to remember take that operation number and then multiply it by the gcd that we end up calculating each time so at that point you might think as we go down this decision tree we're keeping track of our bit mask but we're also keeping track of the operation number which at first might be one then on the second level might be two etc should we also use this as a key in our hashmap well think about it for a second and I'll tell you right now the answer is no because actually this operation number represents redundant information we don't need to use that as a key in our cache I mean technically you could if you want to I'm pretty sure your solution would pass the same as mine but it's redundant information let me tell you why going back to the example maybe on one branch I choose these two elements first on another Branch I choose one and three then for the second decision Maybe I choose three and four on one branch on the other Branch I choose two and four we ended up at the same sub problem this is what our bit masks would look like they would be identical and not only that the operation number would also be identical operation would be two here and it would be 2 over here because we have to choose two elements at a time if the sub problems are the exact same therefore we must have made the same number of operations here as we did over here so the operation number is redundant information we are going to keep track of it for the calculation but we don't need to use it as a key in our cache okay so knowing all of that what are the total number of possibilities that our key value could be well let's say this array is of size n and for each value we could either include it or not include it so we get roughly 2 to the power of n possible values that our bit mask could be so this is the number of sub problems and remember each time we make a choice we're making N squared choices on each level of the tree so we take that and we multiply this by N squared and that's how we get the overall Big O time complexity well technically we also have to compute the gcd which I believe is going to be log of the max number in the array so max of nums let's say but I think this has already deep enough for the Big O time complexity I would be surprised if you ever had to know things this in depth in a real interview so overall we would take this term and multiply it by this logarithm term but I think that's enough so now let's actually code this up so I usually start these DP problems with my depth first search and we know we're gonna have two parameters one is going to be the mask which is going to tell us which numbers are available and the second is going to be the operation number I'm going to call it op for short and the main base case believe it or not in this case is just going to be if this mask has already been computed meaning this is in our DP cache well let me just call it the cache because that's a bit more descriptive and I'm going to create that cache up above in my case I'm going to create a hashmap because it makes things more simple you don't have to know off the top of your head how many possible values we are actually going to be using as the key but like I said it's going to be roughly 2 to the power of the length of nums so if you wanted to create an array instead of a hashmap that would be the size of your array maybe a plus one to that but I'll keep things simple and use a hash map and if we have computed this subproblem before let's just go ahead and return the result that we ended up storing if not then we actually have to calculate it and we do that by enumerating all possible choices with a couple nested for Loops so for I in range length of nums and for J in range length of nums but remember there's a bit of a bug here we don't want to have to necessarily count the duplicate pairs so we should start our second pointer right after her the first pointer at I plus one and now's the part where we want to do our recursive call right but we can only do the recursive call for numbers that have not already been chosen how do we know if the number at index I has already been used how do we know if the number at index I and the number at index J have both not been used before well that's what our bit mask is for if the ith bit is one then that value has already been used before how do we figure that out well basically we take one shift it to the left by I and we take this value and we bit wise and it with the mask value so for example if our mask looked something like this zero and we wanted to know if maybe this value had already been used before we would take our one digit which is over here shift it to the left by two so like to put it in this position and then we would and these together bit wise and them together and we would get a one if both of them are one and we would get a zero if this is a zero so it works pretty much like you would expect it to so let's check if this has been used and let's also check if the other one has been used so one shifted to the left by J bit wise or it or bitwise and it with the mask and if either of those have been used before then we can't use both of them so therefore we're just going to continue to the next iteration of the loop okay but if they haven't been used before what should we do we probably want to make our recursive call and we probably want to pass in the new mask after we have marked both of them as being used so let's actually create a new mask after we have marked each of those positions which we can do like this mask logic or with one shifted to the left by I and then bitwise or that with one shifted to the left by J the difference between the bitwise and the bitwise or is that and is basically us reading the value when we bit wise or we're pretty much overwriting the value at that location now that we have the new mask we can pass that in as a parameter and for the second parameter we probably want to pass in the current operation number plus one but what exactly are we going to do with this recursive call what were we trying to do in the first place remember we were trying to calculate the score of the two values that we just chose how do we calculate the score of them well that's the part where we just use math.gcd and python because this use math.gcd and python because this use math.gcd and python because this problem is hard enough and we don't want to get super into the math so we're just going to call gcd on the two numbers that we are currently choosing and we say that's our score but remember we actually want to multiply this by the operation number as well it's easy to forget so try not to and then using that score we want to take that and add it with the return value of our DFS over here but this is just one possibility we are enumerating all the possibilities and trying to determine the maximum so what we're going to say here is the cash for this mask value is going to be the max of itself cash with mask as the key and whatever value we ended up calculating here let me clean this up a tiny bit so this is the recursive step where we try to find the maximum there's a tiny bug here though what happens if we try to access this value if we haven't already inserted mask as a key well we're going to get an exception throne and an easy way to fix that would be before we even start the loop Just Say Cash mask is equal to zero just initialize it to some value like zero but in even simpler way at least in Python would be just to make this a dictionary carry this hash map a default dict like this collections.default dict like this collections.default dict like this collections.default dict where the default value is going to be an integer so this will basically do what I talked about previously this will evaluate to zero if the key hasn't already been inserted yet now after this Loop has terminated we will have the max stored so let's go ahead and return it out here and finally now that we've wrapped up the DFS let's go ahead and actually call the DFS and return the return value our mask initially we don't even need to create a variable for this remember it's just an integer we can just pass in zero like this now for the operation number we're not starting at zero we're starting at one and then incrementing it each time that we call the DFS so this is the entire code Remember the Time complexity was roughly N squared for the for loops and the number of times we're going to be solving the sub problem and caching it is going to be 2 to the power of n and to actually calculate the gcd each time in the nested for Loops is going to be log M where let's say m is the max integer in our number array now let's run this to make sure that it works now as you can see yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of check out neat code.io it has a ton of check out neat code.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon | Maximize Score After N Operations | minimum-incompatibility | You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array.
In the `ith` operation **(1-indexed)**, you will:
* Choose two elements, `x` and `y`.
* Receive a score of `i * gcd(x, y)`.
* Remove `x` and `y` from `nums`.
Return _the maximum score you can receive after performing_ `n` _operations._
The function `gcd(x, y)` is the greatest common divisor of `x` and `y`.
**Example 1:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 2)) = 1
**Example 2:**
**Input:** nums = \[3,4,6,8\]
**Output:** 11
**Explanation:** The optimal choice of operations is:
(1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11
**Example 3:**
**Input:** nums = \[1,2,3,4,5,6\]
**Output:** 14
**Explanation:** The optimal choice of operations is:
(1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14
**Constraints:**
* `1 <= n <= 7`
* `nums.length == 2 * n`
* `1 <= nums[i] <= 106` | The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized | Array,Dynamic Programming,Bit Manipulation,Bitmask | Hard | null |
34 | A high-rise So friend, today we will make a playlist of binary search A high-rise So friend, today we will make a playlist of binary search A high-rise So friend, today we will make a playlist of binary search and this video of binary search is going to be made. Okay, the question is medium. The question on the list is number-34. The list is number-34. The list is number-34. The question is how to find the first and last position of element in state. I am in the office set for the question that you will be given that shot, okay pay attention to the details on this, it will be soft and the target is one that I am okay the target is, so what is the first position of the ad, index number three Take and last position which index number is four then this is to be returned first position and last pollution and given target is ok the end of this answer is 384 its answer is 314 ok so this is not told to you in the interview that brother You have to solve this binary search, this is the place where you will be able to do binary search, then lakhs will be seen, but whenever it is given in the question and hey, whatever is there is soft, then I understand that binary search is definitely saying it is right and Let is given in the question that you have to solve these in one place, it is okay because in the off end, it is very difficult to solve it, you will search the sample attractive, first find the index where at is there, then you will search for edit, then you will find the last one. It must be a pan and in the question it has been said that it has to be solved in life and only. Okay, so he has definitely told that it is clear to clear, brother, you have to solve it with binary search. Hey, it is sorted, now solve it and show it. First, you should have recorded it once. What was the binary system? Our left was the mode index, right was the most index, okay and we used to find out the middle, we used to find out the plus and minus llb-2, middle, we used to find out the plus and minus llb-2, middle, we used to find out the plus and minus llb-2, okay, after that we used to check 3 things, the face that our Hey, hey, I guess if it is greater than the target, okay, that means my net is bigger than the target, so I have to look on the left side, if the target is there, then what will I do, I will make the AR smaller, if I look at the fat, then Arjun to I will mention it is okay and that if the target is made of laddan means the target which is bigger admit more powerful will be right side okay then I will make the left face right side eligible to make plus one is okay and if this is not the case So that means we will do it by heart, that means we have got the difficult visible target, okay, if it does not happen, then as our Hey Easy Medical Tourism target has been reached, then we would have returned that we have got the index, it is made here only. That is my target. Okay, on your birthday, do you know in the question, what did you ask that this year, loot mode is ready to turn right most, left most, Android most. If you return, then what is the guarantee that you have got the left most target? Who is this? C Guarantee's right masala's target has been found, it means that if your Hey, let's assume it is like this 0202 210 Show More Yes Brother, It's okay and here it is and here it Yes Brother, It's okay and here it is, we have taken out l plus and minus l bittu and our If the target is good then it's ok then madam what will be my result Zero Plus 5 - 02 Attitude S2 So be my result Zero Plus 5 - 02 Attitude S2 So be my result Zero Plus 5 - 02 Attitude S2 So my Me Too turned out to be this is my mail ok no this is my melt so I got the target It was a tiger tattoo only but this is my answer Is it left most or right? Death is not like this, it means I can't return, okay, I have to go further left and check if there is more two, is it okay on the left side, similarly, I have to go right and check too. Is there any more two on the right side because I want the left most target, I want brightness and target. Okay, so how will we fold it, how can we do it, so look at that simple, I will take an example from it. Okay, this is tougher than zero. To Tu Nirodh 1234 521 What had I taken out, mine had come out, this is my oil, this is mine coming, it is okay and that I had taken out the mid, that was my target, two had I taken out the mud, what had I taken out, you had taken out the remedy in the beginning. So I have reached here, okay, now look, I have achieved the target, okay, I am taking out the left seasonal index, first okay, I am taking out the left most index, okay, so now I have achieved my target, very good thing. But what did I say that if you want to find the left most then you will have to go further to the left and check if there is a two and that is okay but I can accept this because maybe this is my answer in the future when I go to the left and see if another two is found. So the answer to that is the matter but for now I feel that this is my answer so I will break the net use in the left most part and take it to mean you are my index, hey, I have left the tools and taken it okay but I will not return the balance. Let's reduce, I will come to the return and go to the left side because I need to remove the lift, so I will remove the right and make it minus one, so now my R has come here, take it is here, okay, now let's remove it again, mine will come to 80 plus which Alarm, I agreed, I went 190 by 20, okay, so now it is mine, come to my place, are you okay, now you are a simple vegetable, is my target, which is two, bigger than me, yes, it is bigger, so I will go right. So it is a simple condition, then I will make it eligible to make plus one, then aloe vera has come here, you have it, then you have come to my R here, do n't look like this, if it has come to the alarm, then I grow it twice in the morning. What are you looking at me now? Hey, how are you looking? 0210 45 And everything is fine now that my oil was here, RB was here and remember what I had assumed in the beginning that my What came out in the beginning was two index number two was for me I write the target in the settings again so that 2222 Okay now I will go out again as usual medical 2l plus this is what one plus and minus link one minus one by two is that This will be made, okay, so mine is made on the media, now I will see again, okay, after mid, it is equal to my target, so I will do the same again, I will not return, I will let the forces go, this may be the case. My answer would be, which is one, left most, maybe you, I am my left most, I will update it and stopped it, but again I said the same thing, maybe there are two more on the left side, so I did not return but went to the left and I will check, okay, so let's check, what did you do to make it equal to make-one, what did you do to make it equal to make-one, so my R will go here, okay, now pay attention, my R has become zero and aloe vera has become one. The condition is that by doing binary search everywhere, left is always smaller than right, so if you take us now then look in the final, we will have got our answer, I have found the leftmost one, I am the leftmost, two fonts and different is present in one, right. The thing is character, our answer is similar, you think yourself, if you have to take out the right most, okay, I am coming again in the same line, if you have to take out the right most, 202 2102 three, four, five, aloe vera is here and mine is here, I have made it. Figured out that the media will be released Zero Plus File Manager Fight for Justice Two So what would I like to ask for now that this is my mail, we have this and for now I will accept it, then the right most thing is that my index number is two, even if what I have got is It is equal to the target, okay, I will not return, I will accept that it could be mine or the right most to be done but after returning, I will do it. I have started this dress to the index but I will check the right side more. Now right. What will have to be done to do it from the side? Help toe will have to be changed. If we do the next surgical treatment plus one, then remove it from here and erase plus one end will come here. Okay, let's move ahead in this and now my hey, something has happened that the body is fine. Is zero two 02 12345 now aloe vera is here and here is done okay I take out again medical two three plus five hard work in the 2nd three plus two back to 10 three plus one is equal to two 4 means my media Or neither is mine, I am here, so this meat is mine, equal to the target, what was mine was you, and right most till now I had accepted that I did not have any twist, why did you take out index number two? But now my time middle which has come is also equal to the target so I will update the brightness tight Mohsin Rezai which one is for come but I will not characterize again I will say again that maybe right I can also If it is two then we will update the alco again, if we do night shift then it will be of aloe vera, it will be mid plus one, then aloe vera has gone here, so finally my hey, he must be looking at something like this, a 202 two 20123 four-five people are here and here 20123 four-five people are here and here 20123 four-five people are here and here But it is okay that I have taken out the mid till now, right most of mine has come out right Mohsin dec24, now let's see what will be the media and plus Salman flight 295 plus 5 - 295 plus 5 - 295 plus 5 - 58225 so my mid has also come. This five is okay, now I have added green chilli to one. Okay, I made it so my target is equal to the target, my two got broken in the tiger, so again I will do the same thing, I will hit the update on the right most which is the same as that of the mate. What five is the mirror made of clay, this time it is five and he immediately says, let's go, I agree that it is right most but I check once in the night and go and see if there is any more, are you there in the night? But now I will free you from the right. What will happen to you? I told you to do it in the right. If you used to do I don't plus one, then Alava will go out and I will go out of the Maluk. I announced that I will go out of the looks. I will go out of the break and look at me. The answer must have come right most. If there is an affair in the variable that is correct or not, then this is our approach and the mention of finding the right according to the left, you have taken it using Ramayana Research and you have taken the approach of this in log in, are you discarding it every time, so it is okay. If we do this with code, then it will be cleared from the court, okay, let me ask the question once again, you will be named interior, which is spotted, in non-tickory border, which is spotted, in non-tickory border, which is spotted, in non-tickory border, okay, you have to find the target first. And you have to weave starting and information and if you don't get that target about you then make it - - 110 and you have to do it about you then make it - - 110 and you have to do it about you then make it - - 110 and you have to do it in mind and afternoon dine time complexity only. Okay, so let's start exactly as I told. Okay, first let's take out the sides, then the pocket size is okay and I will take out the left most and similarly I will take out the right most end, okay, and I will return the one who came, I will take out the left most, right now. Okay, now. Look, I write find left exactly and fine left most key and find right most, both will be very similar. You can write such a function and I can tweet its explanation to the one which removes both left and right but written separately. What happens is you understand it well, okay, I send the number, I send the target, and I send the end, similarly, in this also, hello, I send a target, and it is okay, first I write left, not find, leftmost, okay, a letter, and the norm, and Target end is fine then - writes end Target end is fine then - writes end Target end is fine then - writes end terrible 20822 end minus one is fine and my leftmost index is still something otherwise - let's leftmost index is still something otherwise - let's leftmost index is still something otherwise - let's close it ok now we think pan is special next day turn it over and run it, didn't we use internet l Plus and minus album to meet nickel donkey come that my name is the same madam if it comes equal to the target then what I said that I will accept that this is my leftmost answer who is equal to made means that Possibly my answer is ok but I will move left some more on left side is my target ok Left main used to write and ko made to face towards minus one Rukh more on left ok If the ascendant is a target then it is ok but if it is bigger than the mit then I free the left right hand and I am plus. One and if it is not so, then I will mute the left side. To do it on the left side - do it on the left side - do it on the left side - it is okay on the side of the mind, it will remove mine and inside my left mode will come out, I will send it here, it is okay, similarly, I am right, there is also a very similar method. I can write from ' right, there is also a very similar method. I can write from ' right, there is also a very similar method. I can write from ' And find the right most', let's most', let's most', let's copy it. Okay, this will also be copied, so only some changes will come. It doesn't copy. I don't like doing enough, so let's pick it up from here. I know this. And change the name of the variable then it is right most ok from now on Ambani suggest people to artica enter medical 2l plus and minus album to ok now if this is what I have got then it is equal to my target ok assuming you Let me go, then this is my right most, okay, it's possible, my answer is okay, but what I said was that I will still check from the height that my right was present and if it is not my target, then reduce the brightness. Recruitment Plus One And if not then we will do it on the left side that I am plus one on the left side, in the horoscope article toe minus one is okay, from here I will get my right most is okay and this will become our question, all the examples can be run that one You should go to the bar, okay, all the exams have been cleared, let's submit, the dream defect question of the rich is very simple, you had to wait a little bit, if you have any doubt about Hanuman Research, then comment. Race Karo Race Political Side is Pure Sequence Next Video Thank You So Much | Find First and Last Position of Element in Sorted Array | find-first-and-last-position-of-element-in-sorted-array | Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109` | null | Array,Binary Search | Medium | 278,2165,2210 |
881 | welcome to january's leeco challenge today's problem is boats to save people classic problem the eighth person has weight people eye and each boat can carry a max weight of limit now each boat carries at most two people at the same time provide the sum of the weight of those two people is at most limit return the minimum number of boats to carry every given person now it is guaranteed that each person can be carried by a boat so that's good we don't need to worry about a person being bigger than the limits here now the very first approach you might think is to do something recursively maybe we can do like backtracking we would take like a combination of two people and pop those off the list and continue that recursion and then backtrack by adding those two people back onto the list but that's gonna i'm not even sure if that would work but either way that's gonna be a exponential time complexity it's just gonna take too long so let's not go with that let's think about this a little bit more intuitively and see if there's a better solution so let's just say we had this example here if we wanted to figure out how to minimize the number of boats what do we want to do well we know that we could carry at least one heavy person right the heaviest person we could put onto the boat at least once now the question then is since it's a maximum of two people on each boat can we fit another person and what we could do is just get the lightest person uh we could sort this list by ascending order have two pointers and check to see can we put both these people on the boat and if we can then we could increment our start pointer and decrement our end pointer if we can't fit both these people then we know that the only person we can put on is that heavy person we can like for instance here we could only put on the person three with a limit of three and then we just decrement that end pointer and keep our star pointer at the beginning there now how do we know that this is going to minimize number of boats um well it's i mean there's a mathematical reason behind it but if you just think about it intuitively like if we have the heaviest person who do we want to put on with him like obviously we want to put on the lightest person there um because the next heaviest person uh we wouldn't want to try to put the you know nice person with that person as well um otherwise if we can't put that heavy person then we could only put on um or we can't put on two people then we can only put on that heavy person right so that's going to be our approach what we'll do is have two pointers and we are going to sort our list and then we'll do a um a while loop and check to see if we can fit both if we can't then we'd only put in one okay so let's um start this approach here first thing we'll do is initialize two pointers called start and end this will be zero this will be the length of people and we have minus one because of the zero index now we want to also sort our list to make sure that we are doing this correctly now while start is less than or equal to end what do we want to first check to see if we can put on both people right so if people start plus people end if it's less than or equal to limit then we are going to increase our star pointer and decrease our end pointer otherwise what do we want to do we only decrease our end pointer and we could just make it look like this because that would be the same thing and also make sure that we increase our boats uh to one and i should initialize that up here starting with zero once that's finished we just return votes all right so let's see if this works this example that looks like it works so let's submit that and accept it so time complexity wise is mostly here this is going to be n log n otherwise everything else is just n because it's two pointers and i don't think we use any extra memory and it's really just a sort that might that takes the bulk of the time complexity all right so that's it um you know this is actually a harder problem than looked uh but once you know the solution i think it's pretty easy to implement uh one of the other things i think about is what if we had um more people allowed on the boat like three people or four people how would that algorithm work and my guess is it would be something similar but with a double while loop um possibly a queue involved anyway thanks for watching my channel and remember do not trust me i know nothing | 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 |
16 | hey everyone in this video we are going to solve the three sum closest problem in lead code it is similar to the threesome problem which we solved previously the only difference is instead of checking if the sum is equal to zero we have to check if it is if the sum of those three numbers is closest to a target number so we are given a num sorry and a Target and we have to calculate the sum of any three numbers from this array whose sum when add together the results closest to the target number and we have to return that closest sum so this is the question let's see how we can do it so we'll use the same approach we used while solving the threesome problem so we'll run uh first initially we'll sort this array so after sorting this array will become -1 2 and 4. -1 2 and 4. -1 2 and 4. now after this uh we'll start a for loop from -1 all the way to the last element from -1 all the way to the last element from -1 all the way to the last element 4 and we'll also use two more pointers left pointer and right pointer and then we'll run a while loop so and that while loop will run while our left pointer is less than the right pointer so if you try on this so if we start from here our Loop will start from here so I will be here uh start of the for Loop then our left pointer will be this one just next to it and the right pointer will be the end of the array the last element of the array here now the difference between the previous threesome problem and this one is instead of calculating that if adding these three number so the three numbers we have are nums at I plus num set l plus numset are adding three numbers in previous problem three some problem we have to check if adding them result zero but in this problem we have to check the closest sum and the thing about closes sum is let's say if we have a target of 0 and we have two options we have minus 1 and we have two in this case minus 1 is the closest sum we could have got so how do we get that so to get that we have to get the absolute difference so absolute difference will mean irrespective of the sign whether it is a negative number or positive number so we have to check if the absolute difference of this one and the target if it is result if it is less than some temporary variable which we'll be using let's call it result then we'll replace so if this condition is true then we'll replace the result with our this song and initially result will be the math Dot max value which is the maximum value a number can have in JavaScript so initially it will be greater than irrespective of what value we get what irrespective of the temporary sum we get here so if you try run this we'll start from here so in initially it will be minus 1 plus the value at left pointer which is 1 and then the value at right pointer which is 4 it will result 4 and 4 is less than our math dot max value so instead of math dot max value result will store now 4. since uh the value we got 4 is greater than the target will move the right pointer backward so right pointer will come here now we'll again calculate the temporary sum it will be minus 1 plus 2 and it will be equals to 2. Which is less than 4 so again our sum is less than result so we'll replace result with our new temporary sum which is 2 3. now 2 is greater than Target so we'll move left pointer one step forward but now our while loop will break because left pointer is now no longer less than the right pointer so this condition in this iteration we have for in the first iteration of the for Loop we have find that uh the closest sum we got is two now if we move forward I will come here and then n again L will come here and R will come here now you notice uh all these three are positive number so adding them will always result a sum which is greater than 2. so there is no need to drag around this solution but if you want you can try it yourself and uh so at the end our output will be this 2. the time complexity for this one will be same as the previous reason problem of n square and space complexity will also be same o of n since I'm sorting or algorithms like merge sort use some extra space so this is the drawing explanation let's see how we can do it in code okay so first let's just sort our array so nums dot sort and we want to sort it in ascending order so inside the Callback function we'll write a minus B next let's declare out some of our variables in diff and it will be initially equal to number Dot dot max value it is the maximum possible value of number can have in JavaScript next temporary variable result which will be returning as an output so we'll start a for Loop we'll start from 0 we'll let I equals to 0 and I is less than num start length and I plus next let's declare our left and right pointer so let left equals to I plus 1 and write equals to nums dot length minus 1. next inside the while loop we'll check we'll run the while loop until left is less than right and then we'll calculate the temporary sum so temp sum will be equals to num set I plus num set left plus num set right now we need to check if the absolute difference between this let's call it temp sum so if the absolute difference between this temp sum and Target is less than a previous minimum difference so minimum difference this is the case will stored in the result the new temporary sum and we'll also update the minimum difference math dot abs boot temp minus Target but this is not the case we have three possible condition if temp sum is equal to Target if this is the case then that means we just return the target we found the closest sum otherwise we have two more options if a temporary sum that we calculated is less than the target and as we have already sorted the array we need to move the left pointer one step forward else that means if the temperature addition is greater than the target we need to move the Left Right pointer one step backward and at the end after the for Loop we'll just return the result we got so if we run this and we got one more error so in this instead of just absolute we will have math dot absolute turn it again one more difference so temp sum minus Target cool it passed finally let's submit it good also we didn't need to write an extra variable Mandy Fair we could have just stored this in a result variable and go along with it that would also have worked so that was it for this video thank you for watching | 3Sum Closest | 3sum-closest | Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104` | null | Array,Two Pointers,Sorting | Medium | 15,259 |
17 | hello everyone let's look at letter combinations of a phone number the problem statement is we are giving a string containing digits from two to none inclusive return all possible letter combinations now the number could represent written answer in any order a mapping of a digit to letters look looks like below the question is really straightforward for example 1 input digit is 2 3 so the output is adaf b d b e b f c d c e c f in general when we see a problem asking us for all combinations we potentially need to use a back tracing solution we pretty much build a tree for all possible combinations and travels all the path we do it using recursion before we even look at the solution let's look at the input digit string if the string the lens is 2 like 2 3 we can simply have 2 for loops if we know the input digit length is 3 then we can have 3 for loops but if the input digit length is not predetermined we basically need to use recursion because we don't know how many loops we're going to need but for this particular solution the recursive function is really easy to understand let's look at the code we first do the last check if the digit's dollar length is zero we simply return nothing and then we have this um this uh digit two letters map and then we have this output we will save all the result and then finally we just need to return this output now we can look our backtrack recursive function what kind of parameters we can pass in i guess we definitely need to pass in index with i we can also pass in the current string and then let's do the check first so if this index has already moved to the last digit then we can simply push the current string into our output if this is not the case what we can do we can first get the letter from the map and then we simply do a for loop inside the for loop we call our backtrack again in the for loop we call itself again by passing current string concatenate a new latter and then we move the index the recursive method will keep calling itself until it reaches the termination condition that's the index move to the last and then we'll push the result into output in the end we can simply run the backtrack method by passing an empty string and zero index so if you find it hard to understand the logic feel free to print out this current and i print on the current string and the index or you can draw the flow on a piece of paper let's try to sum it passed let us look at the complexity for space is of 3 of m multiplied for the power of n so in here m represents how many digits that have three characters an n represents how many digits that has four characters because this is how many combinations we're gonna have depends on the input both input three and two they have three letters let's look at the time i guess for time that should be the same because to generate this amount of combination we need this same amount of time for this problem if we do not want to use recursion we can use a queue to track all the combinations we can have a for loop to loop through the input digits and in the input which first ship that item out of the queue and then we concatenate it with the next digits characters and then push them all in the queue let us look at an example here say the input digits is 2 3 so initially the q is empty so when we shift out nothing so that's an empty string and then we concatenate with all the letters for dg2 that's abc and then we push them in then we have a b c in our queue and then we move on the photo moves to the second digit that's three and then in the first we shift a out so we shift it out and then a will concatenate with d e f so we have a d a e a f then we push these three in the q and then we shift b out and then concatenate with d f again we have b d b e and b f and then we shift c out concurrently with d f we have c d c e c f and then we have done all the iteration so we have all the combination let's have a look at the code base we can change it into q we can remove all these things and finally we return this q initially the initial value for the queue is an empty string and then that's how our for loop and then we have another for loop based on the length of the current queue so this current represents the value that's shift out of the queue and then with this current we will concatenate with the corresponding letters like d f so let's first get all the characters and then let's do a loop based on the length of this uh all the characters uh so for the map digit we get all those letters and then we do a for loop and then we concatenate we can cut it in this letter to the current string and then push it back to the queue and then we keep doing this until we reach the end of this outer loop digit and then in the end we can return our q let's summit it looks good for the time complexity and space capacity they should still remain the same this is because although these two solutions looks different but behind the scene we are still doing brute force to a certain extent but in different ways when we need to find all combinations we literally need to iterate all different input digits and then loop through all letters behind those digits so the complexity should remain the same here if you have any questions please leave a comment below thank you for watching | Letter Combinations of a Phone Number | letter-combinations-of-a-phone-number | Given a string containing digits from `2-9` inclusive, return all possible letter combinations that the number could represent. Return the answer in **any order**.
A mapping of digits to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
**Example 1:**
**Input:** digits = "23 "
**Output:** \[ "ad ", "ae ", "af ", "bd ", "be ", "bf ", "cd ", "ce ", "cf "\]
**Example 2:**
**Input:** digits = " "
**Output:** \[\]
**Example 3:**
**Input:** digits = "2 "
**Output:** \[ "a ", "b ", "c "\]
**Constraints:**
* `0 <= digits.length <= 4`
* `digits[i]` is a digit in the range `['2', '9']`. | null | Hash Table,String,Backtracking | Medium | 22,39,401 |
1,186 | and welcome back to the cracking Fang YouTube channel today we're solving lead code problem 1,186 maximum subarray sum with one 1,186 maximum subarray sum with one 1,186 maximum subarray sum with one deletion given an array of integers return the maximum sum for a non-empty return the maximum sum for a non-empty return the maximum sum for a non-empty subarray with at most one element deletion so in other words you want to choose a subarray and optionally delete one element from it so that there is at least one element left and the sum of the remaining elements is uh the maximum possible note that the subarray needs to be non-empty after deleting one element be non-empty after deleting one element be non-empty after deleting one element all right pretty straightforward we have already solved on this channel the maximum subarray problem so hopefully this one isn't too much of an extension now let's look at uh an example here so we have this input 1 -23 and um you know if we were to sum up -23 and um you know if we were to sum up -23 and um you know if we were to sum up the subarray what would we get or sorry the entire array well minus one plus -2 that's -1 plus 0 still -1 + 3 uh is -2 that's -1 plus 0 still -1 + 3 uh is -2 that's -1 plus 0 still -1 + 3 uh is going to be two so obviously adding all the elements uh doesn't work we need to get rid of one uh and in this case obviously we want to just delete the negative one uh which is minus 2 in this case and you know the sum would just be four so we use our one deletion on the negative cool but what happens if there's actually two negatives we can only delete one of them and in this case uh here where we have 1 - 2 -2 and three uh here where we have 1 - 2 -2 and three uh here where we have 1 - 2 -2 and three uh they're actually the same value obviously you'd want to take the smaller one um if you have a choice but sometimes you don't so what do we want to do here well we don't want to sum anything cuz we don't want to really sum one of these minuses remember that we can take any subarray here which as long as it's nonempty we also don't need to delete an element we can just say I'm going to take three and that's it so we just take three uh because that's the maximum value so we have a choice we don't have to delete something if we don't want to for example if all of them are um you know right we're we only optionally have to do one so if they're all positive you would just sum uh the subarray so the way that we want to approach this is very similar to how we solved the maximum subarray problem where we essentially just keep track of the sum and at certain conditions we want to actually ask ourselves does it make sense to add uh more variables to our sum or do we actually just want to start over now I don't want to get too much into the explanation because we're actually going to do this in the code editor this one's a really fast problem no need to kind of go through examples line by line it's just a waste of time let's do it in the code editor it's about 15 lines of code and I will walk you through it as we go through so I will see you momentarily in the code editor in 3 2 1 we are in the code editor let's type this up so we're going to want a few variable here and I'm going to Define them and explain to you what they are so we're going to say the sum with a Skip and this one's pretty straightforward right this is the sum of our current subarray that we're considering um assuming that we've skipped one element so pretty straightforward uh then we're going to have a sum except we haven't skipped anything this would just be the direct sum of whatever the current subarray we're considering is um all the elements added together we haven't taken anything so we're going to say sum no Skip and we're also going to need to return a result here so all of this is just going to equal to the first element in the array remember that uh you need to have at least one element in your subarray so we're just going to set it equal to the first element and then we'll process the rest of the elements from there so the next thing we want to do is we want to Loop through our elements so for Num in Array of oops uh one uh forward so obviously we've just processed the zeroth index there's no reason to process it again so we're going to start our iteration at the first index and what we want to do now is we want to ask ourselves is our sum uh with skip is it less than zero now the reason that we want to ask ourselves this is because if your numbers are already significantly below zero it doesn't really make sense to add numbers to try to bring it above zero so for example if our numbers were like - for example if our numbers were like - for example if our numbers were like - 100 - 200 and then 40 sure we could skip 100 - 200 and then 40 sure we could skip 100 - 200 and then 40 sure we could skip you know Min -200 and you know our sum would be minus -200 and you know our sum would be minus -200 and you know our sum would be minus 100 then we add the 40 and you know whatever is left in the array but then we'd be at minus 60 and actually we can just say I don't need the rest of this array it's already gone negative I can't do anything with it so I'm just going to consider the 40 onwards so what we can do is we're going to say if um if our sum with skip so if we've already used our Skip and we're below zero then we've taken too many negatives that we really shouldn't we should just consider the first positive that we get and that will be where we want to start so we're just going to reset our skip uh sorry not our skip our um sum with skip we're just going to reset it to zero cuz you know we don't need the number right so now what we want to do is there's two cases right the number can either be greater than or equal to zero or it can be less than zero so if the number that we're currently processing is a positive so greater than or equal to zero then we want to take it there's no reason to skip it adding it will only increase our sum so there's no reason to skip it ideally we only skip negatives or if there's only positives then actually we wouldn't want to skip anything at all because there's no reason to so if it's positive then we always take it so we're going to say the scum with skip we're not going to skip it we're just going to take the number um so we're going to add the current number to the sum with the skip otherwise we need to make a decision do we want to take this number uh take the hit of taking this number so for example maybe the number is minus one and that's not really going to affect our sum too much so we can take the hit or we want to compare well let's just see what we're going to do so we're going to say that the sum uh with skip is either going to be the maximum of su the current sum with skip if we just take the hit and add the number to our sum or remember that sum no skip represents the sum of our subarray up until our current Point assuming we haven't skipped anything if that value is actually bigger than um you know us taking the hit on the number then that will become our new um sum with skip right so we just want to set it to the other one and we're going to ignore this current number maybe the current number is like minus 10,000 and current number is like minus 10,000 and current number is like minus 10,000 and it would mess up our sum so we actually want to take the maximum of taking the hit with the num in the case that it's negative well actually in this case it is negative because we're in this El block um or you know we're just going to skip it so in which case the sum with the skip obviously we've now just taken a skip um in that case so that's why we have to do the sum with the no skip now what we want to do is actually similar uh to what we did up here with the sum with skip we actually want to check whether or not um if sum no skip is less than zero um then we just want to reset it as well cuz again it may just be easier to start our sum from the current number uh than it would be to um just try to add more to it so we're going to say sum no skip uh is going to equal to zero and now you might be asking yourself why didn't we do this earlier up here you know why have you left it after you processed the current number and the reason for that is actually this statement here now you see that we use some no skip here if in fact we actually overd the value of sum no Skip and set it to zero then when we try to use it in this function uh in this else block here it would be pointing to zero if we overrided which is not correct because we want to hold the old sum no skip now we could get around this by Def uh declaring a variable like sum no skip temporary but that's just a waste there's no nothing obligating us to do it earlier so we just do it afterwards so we have access to this um sum no skip so if in case you're wondering why we do it down here and not up here with the other one that's why because the order actually will matter here otherwise um we need to add the number to our sum no skip uh sum no skip because obviously we don't skip any numbers with this sum we just add everything to it and now that we have all of our variables updated we can actually take a um a maximum uh to see uh if we have a new uh best answer so we're going to take the maximum whatever our current result is uh whatever sum no skip is sorry some no skip I can't really see my keyboard uh and then sum with skip so those are our three variables and we want to take the maximum of them at each iteration through the loop to figure out which one we want to use and the last thing once the loop ends we simply return res and we are good to go so let me run this make sure I didn't make any stupid syntax mistakes as sometimes I do at these live recordings and it looks like accepted perfect so time and space complexity this one is really easy obviously all we're doing is we are passing through our array here uh from left to right processing all of the elements all of our checks here are going to be constant time checks you know we're just comparing against zero we're doing an addition uh we have an if else block nothing here um is anything but constant uh time so our time complexity is going to be Big O of n uh we have n elements we perform um you know Big O of one operation for each n element that's Big O of n uh for the space complexity um we don't have any extra variables here we have um just these three which are just holding numbers um because of this we don't declare any extra data structures so we can consider our uh space complexity to be Big O of one okay so that is how you solve maximum subarray sum with one deletion like I said it's really similar to the previous iteration of this problem just maximum subarray sum where you're not allowed to delete an element this one is quite good practice for kadan's algorithm sometimes you will get this um one deletion one as a follow-up this um one deletion one as a follow-up this um one deletion one as a follow-up if you get the standard version so it's good to know how to do it and again look at how simple this code is it's like less than 20 lines right once you get rid of this stuff here so nothing too complicated hopefully you enjoyed the video hopefully you found it um helpful if you did why not leave a like and a comment on uh the channel it really helps me out uh to grow hopefully I'll get to 10,000 Subs soon and um yeah I'll get to 10,000 Subs soon and um yeah I'll get to 10,000 Subs soon and um yeah if you want to join a Discord Community where we talk about all things interview prep you can ask for referrals you can ask me random questions um then I will leave a link in the description below if that sounds interesting for you otherwise I'm going to stop rambling thank you so much watching and I will see you in the next one goodbye | Maximum Subarray Sum with One Deletion | building-h2o | Given an array of integers, return the maximum sum for a **non-empty** subarray (contiguous elements) with at most one element deletion. In other words, you want to choose a subarray and optionally delete one element from it so that there is still at least one element left and the sum of the remaining elements is maximum possible.
Note that the subarray needs to be **non-empty** after deleting one element.
**Example 1:**
**Input:** arr = \[1,-2,0,3\]
**Output:** 4
**Explanation:** Because we can choose \[1, -2, 0, 3\] and drop -2, thus the subarray \[1, 0, 3\] becomes the maximum value.
**Example 2:**
**Input:** arr = \[1,-2,-2,3\]
**Output:** 3
**Explanation:** We just choose \[3\] and it's the maximum sum.
**Example 3:**
**Input:** arr = \[-1,-1,-1,-1\]
**Output:** -1
**Explanation:** The final subarray needs to be non-empty. You can't choose \[-1\] and delete -1 from it, then get an empty subarray to make the sum equals to 0.
**Constraints:**
* `1 <= arr.length <= 105`
* `-104 <= arr[i] <= 104` | null | Concurrency | Medium | null |
1,094 | hey guys welcome back to another video and today we're going to be solving the leakout question carpooling all right so in this question we're driving a vehicle that has capacity empty seats initially available for passengers the vehicle only drives east and it cannot turn around and drive the other direction so in other words it drives in only one direction given a list of trips so a certain instance of trips of trip has the number of passengers in it the start location and the end location so it contains the information about the ite trip the number of passengers that must be picked up the location to pick them up and drop them off the locations are given as the number of kilometers due east from your vehicle's initial position which ensure if and only if it is possible to pick up and drop off all the passengers for all the given trips okay so by the ending of this we want to be able to accommodate all the passengers without leaving any of them off and drop off all of them for all the given trips okay so that being said let's take a quick look at this over here so let's just take a look at this example over here which actually outputs true so what does capacity mean so capacity is going to be how much how many people our car can hold so we can hold a maximum of 11 people and over here we have three different trips so instead of just uh going over it let's just draw it out and kind of visualize it okay so over here we kind of have like a number line to represent each of the directions so this is the same example three two seven three seven nine and eight three and nine and just so you remember the first value is the number of people the second value is the start location and the third value is the end location so what i'm going to do is let's just uh let's just draw out each of these trips so in the beginning over here we have one trip starting off at uh the second location so let's just say two kilometers and it goes all the way up to seven kilometers and how many people are transporting over here the answer to that is three okay so we have that and then after this we have one more trip starting at seven kilometers going all the way up to nine kilometers with again three people and we have one more trip starting at three kilometers so let's just do that over here and it goes all the way up to nine kilometers and that has eight people so the question that we want to ask over here is can we accommodate all of these people inside of our car so let's just go by this step by step so we have zero passengers here then zero over here but once we reach the value two let's just use the color red over here we get three passengers so let's just add plus three so now we have a total of three passengers so at the next uh spot we actually end up picking up eight more passengers so over here we do plus eight we're picking up eight more passengers so in the beginning we had three now plus eight giving us a value of 11. and that makes sense our capacity can hold up to 11 people but if this number does increase at any point that means that we're not going to be able to facilitate everyone okay so now we keep going and the number of passengers stays the same until we reach the number seven so what happens at the number seven is that first we're actually dropping off three of the original passengers who started off from over here so we're gonna do minus three since we're dropping three of them off but we're also picking up three new passengers from that instance so we're doing minus three and we're also adding three and that's just gonna cancel off and we're still gonna have 11 of people remaining and at the very ending which is the ninth kilometer we end up dropping all of these eight people so minus eight and we also drop out all of these three people so minus three over here so 11 minus eight minus three ends up giving us a value of zero and that means that we are done all the passengers were dropped off and everyone was picked up so that's all that we're doing and now let's see how we can actually do this in code so over here we're going to start off by creating a list so let's just call this list l and it's going to be an empty list and the purpose of our list over here is going to be to add the number of people who are going to get on at a certain stop and the number of people who are going to get off at a certain stock so let's first add that over here so how do we exactly add this so we're going to iterate through our car our trips list over here so again the format of it is first we get the number of people then we get the start point and then we get the end point so for that in trips so now we have this information for each of our trips so now what we're going to do is we're going to go to our list and we're going to append the values so over here we're going to have two conditions so what if we're actually starting so over here we're currently starting right and when we're starting we're going to have more people so the number of people coming in is going to increase so in this case what's going to happen is people is going to be positive and what that represents is the fact that more people are entering into the car so in that case the capacity decreases okay so that's what hap that's what's happening when we're reaching the starting point and on the other hand when we're reaching the end point so we have end point and in that case what's happening is people are getting off the car so when they're getting off we have less people inside of the car so we're decreasing the number of people in the car so we're going to have negative people over here so that just shows that the people got off okay so now at the ending of this we have our list uh and it's ready to go so over here what we're gonna do is i'm gonna print out the list and then i'm gonna sort it and then print it out just to show you why we might need to sort our list and we're using the same example as example four over here okay so this over here is the non-sorted okay so this over here is the non-sorted okay so this over here is the non-sorted version of it so what's happening over here is so we have two comma three which is the starting point and seven comma negative three is the ending point for that trip but what we're going to do is we want to go day by day so if you look out if you look at our sorted list over here which is this one over here so we first go to day two then we go to a day three then we go to day seven then day seven again then day nine and so on and so forth but we're going in an ordered fashion okay so that's gonna be really important and that's the reason why we're sorting it okay so over here we're gonna sort out our list and now we're gonna perform the last step which is going to be to add or decrease the number of people at each instance in order to see whether we might have an overflow of people so over here we're going to go into a for loop and we're going to be iterating through our list l so over here we don't actually care about the start or end positions so i'm just going to do underscore and we just care about the people and the reason we added them here is well to sort them in the right order so now that we have this we're going to iterate through it for our list l and over here we're going to decrease our capacity each time so capacity minus equal to number of people so when we're adding people the capacity in the car is going to decrease in that case we're just going to subtract it okay but then when we're dropping off someone then in that case so you're subtracting a negative number which is going to add so our capacity is going to increase when we're dropping off people so that's what it's going to do and over here we're going to have an if condition so we're gonna check if our capacity is less than zero and if it is less than zero that means that there are too many people in our car and in that case we're just going to end up returning false and we're done with the question right we can never accommodate more people than the capacity so that's the condition for when it's going to be false but if we do pass everything and we're done with our for loop at the outside of this we're going to end up returning true that means that we picked up everyone and we dropped everyone so let's submit this and as you can see our submission did get accepted and finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe if the video helped you thank you | Car Pooling | matrix-cells-in-distance-order | There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_.
**Example 1:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4
**Output:** false
**Example 2:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5
**Output:** true
**Constraints:**
* `1 <= trips.length <= 1000`
* `trips[i].length == 3`
* `1 <= numPassengersi <= 100`
* `0 <= fromi < toi <= 1000`
* `1 <= capacity <= 105` | null | Array,Math,Geometry,Sorting,Matrix | Easy | 2304 |
740 | hey so welcome back this is another daily problem so today it's called delete and earn and it's a medium level dynamic programming problem and so essentially you're just given a array called nums here and you're playing a game where you want to get the maximum number of points and the way this game works and I'm kind of assuming you already read some of this but basically you get to choose any number in here so let's say we choose three and basically if you choose that number you get to add up the total uh number of points that you can get by choosing that number which is essentially the value of that number which is three in this case multiplied by the number of times it occurs which is three and so you get nine points but the catch here or the constraint is that if you choose the number three or any arbitrary number let's just call it n then you can't use the number that's n minus 1 or n plus one and so in this case you would have to basically eliminate two because that's n minus 1 here and you're gonna have to eliminate 4 which is n Plus 1. all right and so you get a total value or a total sum of nine let's say if you go a different route well that would be okay let's say you choose two first and so that would eliminate one but there's no ones here and that would eliminate three so then you'd get four points but you can also choose this four here and so you could add four extra points there which gives you eight but well we saw before that we were able to get nine points by choosing three and so because well nine is greater than eight that would be the output all right and so that's basically how the algorithm works or what we're trying to accomplish but essentially I'm going to show you uh time and space complexity solution of O of the maximum numbers so what that really means is basically the time complexities kind of going from like oh or zero one two three all the way to basically whatever number is the largest number in this particular array nums array and so in this case uh we'll have like a time space complexity of like 0 of 4 where 4 is the maximum number in here and so that might not make much sense now I think it's very intuitive as you see like the Forum that we're creating and the DP array in the lookup table and so what we're going to do is we want to have a quick lookup of what is the total number of points you're going to get if you choose some number so we'll have basically a lookup of basically the index 3 will represent or return the value nine so that just means okay if we choose the number three we'll get nine points all right and so to do that it's uh pretty simple where you just have let's call it like num lookup maybe and so it's initially zero and we're just going to get basically the length of the numbers or sorry the maximum number in here and just add one to it and so that way we can have the kind of lookup table of saying okay the number the value 4 will then map to well four because there's only one here and so basically to populate this with actual values other than zero we'll just iterate through all the numbers in our nums array and just say okay the num look up at this particular number is well we want to add this number to it and that basically just creates it and so from here we also want to have our DP array and so what we're going to want to do is this array at the end of it is going to return our answer so this is another common pattern where you kind of want to propagate forward at every step the maximum number of points or the solution and so at every single step or every index as we move forward it's going to have the answer at that point in time and so at every step it just says okay at this particular number this would be the maximum number points that we could get and so basically what that looks like is then okay let's just iterate through a particular range and we're going to go from 2 to the length of our num look up array here and so the way this works and the reason why we're starting at 2 here is initially this DP array will also be just a bunch of zeros multiply by the length of our num lookup because they're going to have the same lengths basically as this and so initially the DP array that we have here add index one is going to directly map to the num lookup at the same index at 1 here and so this just means okay at one we would be able to get this many points if we only considered one and so beyond that point we're basically going to have two pointers that's saying okay um if we choose the current number that we're at and we include everything that's two steps behind it what's the number of points that we can get but we also want to consider what number points that we can get if we look at one set behind it and I'll quickly write this out and explain this further but I think it'll make more sense in a second and so basically the DP array at the index n will be equal to the maximum of the two possible choices that we can make which is essentially how however many points we can get at the current index plus what we could get basically two steps behind it because we can't consider one step behind it but let's also compare this to basically the number of points we can get one step behind this point let's go ahead and run that oh it looks like there's something wrong here so let me just think for a second so we're going from two to the end and well I know that we also want to see here hmm that's our normal cup that looks good particular point this goes to the left end same here oh sorry about that we want to consider the one step behind it there we go okay so essentially what's going on here is what we're doing is the DP array what it does is it represents at every point in time what's the maximum number of points that we can get and so the very end of this will hold that answer but at every step what we want to do is consider okay we can either include this particular number that we're at and everything that we've propagated so far two steps behind it or we could choose to just get what's one step behind it and so that way you can kind of um not consider what is one number ahead by always just looking back one and two steps behind it and so it's kind of a it's a lazy way of doing it um and so this is what's kind of adding the numbers here because initially it's just zero and the first answer is filled but this is what holds the actual number lookup of how much values that we're getting but we're constantly just kind of storing in this minimization or this caching that we're doing um at every single step and this is just the two branches that we can go down okay so I hope I explained that quite well um it's not very intuitive I find this solution much better than the alternative so yeah once again it's just o of the maximum number in this array and that's kind of the time and space complexity but let's go ahead and just run this oh now let's go ahead and run it and success so yeah pretty performant solution but I hope that helped and good luck with the rest your algorithms thanks for watching | Delete and Earn | delete-and-earn | You are given an integer array `nums`. You want to maximize the number of points you get by performing the following operation any number of times:
* Pick any `nums[i]` and delete it to earn `nums[i]` points. Afterwards, you must delete **every** element equal to `nums[i] - 1` and **every** element equal to `nums[i] + 1`.
Return _the **maximum number of points** you can earn by applying the above operation some number of times_.
**Example 1:**
**Input:** nums = \[3,4,2\]
**Output:** 6
**Explanation:** You can perform the following operations:
- Delete 4 to earn 4 points. Consequently, 3 is also deleted. nums = \[2\].
- Delete 2 to earn 2 points. nums = \[\].
You earn a total of 6 points.
**Example 2:**
**Input:** nums = \[2,2,3,3,3,4\]
**Output:** 9
**Explanation:** You can perform the following operations:
- Delete a 3 to earn 3 points. All 2's and 4's are also deleted. nums = \[3,3\].
- Delete a 3 again to earn 3 points. nums = \[3\].
- Delete a 3 once more to earn 3 points. nums = \[\].
You earn a total of 9 points.
**Constraints:**
* `1 <= nums.length <= 2 * 104`
* `1 <= nums[i] <= 104` | If you take a number, you might as well take them all. Keep track of what the value is of the subset of the input with maximum M when you either take or don't take M. | Array,Hash Table,Dynamic Programming | Medium | 198 |
1,897 | the question is resistible characters to make old strings equal you are given an array of things worth zero in text in one operation with two distinct indices I and J where sub I is a known MD string and move any character from WhatsApp I to any position in WhatsApp J return true if you can make any string in words equal using any number of operation and force otherwise so take the first example this array is given to you so you have to make all these things equal right shown ABC aapc PC right you can take this a or this aim okay and you can just move this a to this string and you can make this thing also ABC right so that's why it will give you true okay but in the second example they have only a b and a right but it will give you a false y so because you cannot make these two strings equal okay so that's what it will give you false I think this is clear to you okay now let me take an example okay like you have a string history okay RR equals to Ram okay so the thing is the size of this array is 2 right and occurrences of r e also is true and occurrences of a is also to a currency of M is 4 you can notice this thing all the digits are divisible by 2 means what the length of the array right now if we have another string only r a m okay so now your size will be three right now the occurrence is of R is 3 a currency of a is also 3 occurrences of n is now 5 and the thing is 5 is not divisible by 3 then you can say okay the remainder is not zero you can say okay this will give you false then actually it will give you false because this Ram you can make this term to this Ram means with double ends you cannot make because you don't have any extra in to move that into the in the string and you just make this Ram to this round right this is not possible because you don't have any extra M right but what if we have thank you in this the first thing we have table aim right so then you don't have total six M right so now you can easily okay the thing is now you can easily move this m to this m and you can make all these three strings equal right and also now the number of the occurrence of a of n is also dividable by the length of the array so the end of the array is now 3 right give you true I think this concept is clear to you because I will use this concept to solve this problem okay so basically Iris of this problem in an easy way the thing is I will take an integer array okay uh let me take in count okay in 26 okay and then uh I will store in this integer array if they uh occurrences of every character okay you can do the same thing using hashmap also okay so don't worry about it so in I no not again I actually string okay basically I will reverse it words adding okay in is um so then you can do the thing is like count of C minus of a plus okay and then we only need to do one thing the strappers are thing okay all right and then just check if I modulus count for length is equals to equal to zero let me take one more operator means if not equals to zero figure also if not equals to okay then we can easily return false okay otherwise you just return true right so basically this first fold we can actually in this folder let me take advancing like a B A okay so basically this is Count this count have total uh 26 in indexes from 0 to 1 25 right so the thing is right at first we have a okay basically this will be oh yes okay so basically at first we have a right so a minus a will be what 0 so in the zero interest positive will increment by one okay now your second is p minus H then it will give you what one okay index position one it will increment by one okay and then your next character is a again right you need to increment Again by one okay in part in this position a minus a is what zero okay interpreter than zero increment by one again now it will become two so now you can easily understand that thing in this way you can easily count a number of the occurrences of a and number of currency of B basically ten into a number two occurrence of a is two and about the occurrency of B is 1 right so that's why I am telling you can do the same thing using hash map also okay so now at the end I just traversing this count array okay and I just taking the occurrences of each character is divisible by the oh not the count length actually it will be words sorry for that so yeah I just um foreign okay sorry yes yeah I think this code is clear to you if you have any question you can definitely ask me in the comment section and you can give me any type of suggestion that I can improve okay yeah so attain I want to say thanks for watching see you in the next video | Redistribute Characters to Make All Strings Equal | maximize-palindrome-length-from-subsequences | You are given an array of strings `words` (**0-indexed**).
In one operation, pick two **distinct** indices `i` and `j`, where `words[i]` is a non-empty string, and move **any** character from `words[i]` to **any** position in `words[j]`.
Return `true` _if you can make **every** string in_ `words` _**equal** using **any** number of operations_, _and_ `false` _otherwise_.
**Example 1:**
**Input:** words = \[ "abc ", "aabc ", "bc "\]
**Output:** true
**Explanation:** Move the first 'a' in `words[1] to the front of words[2], to make` `words[1]` = "abc " and words\[2\] = "abc ".
All the strings are now equal to "abc ", so return `true`.
**Example 2:**
**Input:** words = \[ "ab ", "a "\]
**Output:** false
**Explanation:** It is impossible to make all the strings equal using the operation.
**Constraints:**
* `1 <= words.length <= 100`
* `1 <= words[i].length <= 100`
* `words[i]` consists of lowercase English letters. | Let's ignore the non-empty subsequence constraint. We can concatenate the two strings and find the largest palindromic subsequence with dynamic programming. Iterate through every pair of characters word1[i] and word2[j], and see if some palindrome begins with word1[i] and ends with word2[j]. This ensures that the subsequences are non-empty. | String,Dynamic Programming | Hard | 516 |
328 | hello everybody today we'll be taking a look at odd even linked list on the code it is problem number 328 so let's take a look 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 so this is important because it's the ranking of the list that's odd and even not so much the values at that node so another thing that we should note here it should be solved in all of one space and all of in time so let's take a look at an example here in example one we have one two three four five one three and five are odd indices so they should be grouped at the first and two and four are the even indices so they should be grouped last so over here it's just by the example the odd indices are odd and the even indices are even but really we do not care about the value at that node it's just about whether it's odd or even in its ranking so let's try to visualize this to get a better idea of what our solution will look like so if we take a look at here at the linked list from example one we see that the odd indices are colored in blue and the even indices are colored in orange and what our solution will pretty much look like if we imagine it is one will point to three and then three will point to five and then we can imagine two pointing to four and now we have all our odd indices grouped in one list and all are even and this is grouped in one list and then what we want to do is pretty much connect this last indicee from the odd to the even and now this little i guess circle ish shape we have here would be what our final link list looks like so now let's take what we just described and break that down by step so we described grouping all the odd indices in one list and all the even indices in one list and then finally we're going to attach the two lists together if we want to imagine us grouping the indices together we should have a head for our odd indices so let's make a new head and this is going to be odd and now let's just copy this and now this is going to be our even head and then let's give this a separate color so now these are the heads of the two new lists we are going to create this in all of one additional space because we are just going to attach the elements from this list onto here and that way we're not using more space by creating new nodes so what we would also probably need is we want to imagine we have two other pointers and these pointers are going to be references to the last node in each of these lists so we can imagine them as odd tail pointer and the even tail pointer right now we have a pointer to even and let's call that even tail and we have a pointer to odd and then we just have our regular pointer here that points to the node let's just call it ahead and then we're going to have another variable let's call it odd and if it's odd we know we are looking at an odd indices so we should add to the odd tail if it's not odd then by default we know it's even and we are looking at an even indice and we should add it to the even tail so now we are at the first indices odd is true that means we should be adding this head node here to our odd linked list so we're going to say odd tail because that's the pointer to the last note in the list the next value it should be is going to be head because right now head is at an odd indices and i'm going to be drawing new notes here but let's remember these aren't actually new notes and this is just the visualization of it once we do that we also move over our odd pointer we move over our head pointer okay so now we are at our second indice here we know we should be looking here that means we should be creating a new reference and it's gonna point here we move over the even tail here and we move over the head and now we can start to see a pattern forming and once we get back to head at three and we're just going to repeat what we did before this is going to be three we move over our pointer here we move over our pointer at the original linked list and then same idea here this is going to point to the next even index which is four we now move over our even tail to be the last node of this even linked list again we move over our head in the original linked list and we draw the final node five we move over our octal a head pointer is now outside of the linked list meaning it is null the list is empty okay great we have taken our linked list and we have broken it down into two lists one of just odd indices and one of just even indices and now we just want to combine the two together one thing we want to do here and it might not be obvious from the visualization but just the way the list is set up we can see here that this is four right and four in our original linked list points to five so we wanna make sure for even tail now we make sure that the next pointer points to null and that way we won't end up in a situation which is a cycle because if we imagine attaching this node to here right and if this node is still pointing to the five up ahead it's going to traverse down this list to the 5 and then once it gets to 4 it's not going to go to null except it's going to go back to 5. so that's just a caveat we have to add into our code but i wanted to point that out here now what we want to do is really we want to take the 5 here and we want to point it not to the even head because that's just a empty reference head we want to point it to the next node in even so what we really want to do is we want to take our tail and we want to point this to even dot next because right now even if the head note dot next would be the first note of even indices and once we do that this will be gone then it's going to be like this here and then finally we want to return not this odd head node which is just a reference node we want to return the node after that so we simply return odd.next we simply return odd.next we simply return odd.next and that will be our full solution so now let's jump back to the code so now that we jump back to the code let's start coding everything that we visualized so we know that first we need to create two reference nodes to the odd and even linked lists and we need to have reference nodes for their tails as well too so let's do that on this node and let's call it odd head equals new list node and then let's call it odd tail and this is going to point to the last node in odd head which when we're starting out is going to be odd head itself now let's do the same for even head make a new reference node and point even tail to the last node in our even linked list then let's set up our lin variable odd equals true now this is going to be toggled on and off in each indices for odd and if this is going to be on so we know we should be pointing at the odd head for even indices it's going to be off meaning we're going to be pointing at the even head and then let's iterate over our list node head while it does not equal null so while there's still information here let's iterate over it and then we're going to say if odd meaning if we're at an odd index what we want to do is all tail dot next equals head so we're at the last node in the odd linked list we want the next node to be the current node we're looking at and then we want to move our odd tail position forward like we did in our visualization example to the now last node in our odd linked list which in this case here if we're still following example one should be now one instead of the reference node head else we know we're going to be at an even index by default so we know this should go to the even linked list so the same logic here except for even so now this is going to add the index to its appropriate odd or even linked list and once we come outside of it we actually want to do is head equals head dot next so move our original linked list forward and then finally we want to set our odd variable to be not odd and this is just going to toggle it on and off so after an odd index it's going to be off indicating it's an even index and when it's an even index falls it's going to be then toggled on so it's going to be true meaning next time we're going to be at an odd index again and now this is going to create both of our linked lists and once we step outside of here we want to make sure we add that part that we mentioned in the visualization where odd.next equals null odd.next equals null odd.next equals null so we don't have any cycles in our linked list and then we want to point our odd tail right so the last node in our odd link list to the first node in our even linked list which is not going to be the reference node which is going to be the node after that's why we use dot next and now just like we mentioned in our visualization we want to return the whole linked list now except for the first node because that was just a reference node to start building our odd linked list so we're going to do odd head dot next and this is going to give us the next value or the first value we can think of it in our odd linked list so let's try running this and voila there we go it has passed all the tests and it's 100 faster than all java solutions so hopefully you guys enjoyed that and found the educational if you did please consider liking and subscribing and see you guys next | 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 |
316 | welcome to october's lee code challenge today's problem is remove duplicate letters given a string remove duplicate letters so that every letter appears once and only once you must make sure your result is the smallest in lexicographical order among all possible results say we're given the string bc abc our smallest lexicographical order with all the characters being unique or appearing just once would be abc so the order of the string matters you can imagine if it was b c a c b the answer would be a c b not b a b c because the order here is what we have to take now they give you a hint to try using a greedy method and that's going to be big because one of the first temptations we might have is to do some sort of recursion and find every possible permutation but that's really inefficient instead let's try building up our string using a stack and what we'll do is keep track of the greatest index number for each unique character so say that we had this example here we're going to build up our string starting at the first character and we'll say okay b okay whatever now c when we check c let's check to see the previous letter and ask ourselves can that letter be added at a later time and would that be better so basically just check to see if b is greater than c which it isn't but if it was then check to c can be added later is this index number um you know current index number is less than the max index number for that unique character and if it is then we should just pop it off of our stack and add it later so that's what happens when we add a right we add a we see that c is greater than a and we also see that c can be added later so we should pop that off and add that later same with b is greater than a and we could also add that later so pop that off and now we move on to the next one we see all right b well a is less than b so that ends that and then c well b is and smaller than c so this would be the smallest lexicographical order right so we have to have a couple things a couple data structures to keep track of here we need to keep track of the greatest index number for each character so we'll have some sort of dictionary to keep track of that and we'll build up our stack as well as have some sort of set to keep track of whether we've seen this character or not so let's start with initializing a dictionary to call it lookup and this is going to contain the max index number for each character so for i in range of the length of string we will just for the character make that value the index number and this will get us the greatest index number right next let's initialize our stack this will be a list as well as a set i'm going to call this scene and this will uh just keep track of whether we've seen this character or really whether this character is still in the stack or not because if it is then we could just continue so now we'll have a loop say four iron range length of s first thing we want to check to see is this character in our stack and we'll check that in our scene set to make it a little bit faster we'll say if the character i should add the character i here if character i is in scene then we'll just continue otherwise we'll have this while loop and we'll check first while there's a stack and the previous item on this stack is greater than the current character that we're about to add and we can add this character later so say if the i is well i should say more for my lookup the max index number if it's greater than our current index number then we know we should pop it off of our stack because we can add it later and it's going to be in smaller lexicographical order so we should just pop that off and we should remove it from our stack as well to get back to negative one and i think i need to do pop it off my set first before popping it off the stack to do that all right so once that's finished once we realize that we can't we shouldn't pop off any of our previous letters we'll add this current character to our stack and we'll also add this current character to our scene set once we're finished with that we should have a list of all the characters in next graphical order and we can just do a string join to return it as a string so join our stack and that would be it so our example here this should return abc does not um see what did i do wrong here so i'm sure it's something silly it's greater move that from our scene si oh okay um what it's not the s i of course it's the stack the previous letter stack here so that's what messed up there so my apologies this should fix it and there we go abc it's going to submit that and that gets accepted so this is greedy method in terms of time complexity i'm not completely sure i'm tempted to say it's o n but there is some possibility that this is worst case n squared i'm not positive uh because of this part here but either way it does get accepted it's pretty efficient and i think that's the most kind of clear-cut most kind of clear-cut most kind of clear-cut easy to understand way to do it so thanks for watching my channel and remember do not trust me i know nothing | Remove Duplicate Letters | remove-duplicate-letters | Given a string `s`, remove duplicate letters so that every letter appears once and only once. You must make sure your result is **the smallest in lexicographical order** among all possible results.
**Example 1:**
**Input:** s = "bcabc "
**Output:** "abc "
**Example 2:**
**Input:** s = "cbacdcbc "
**Output:** "acdb "
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of lowercase English letters.
**Note:** This question is the same as 1081: [https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/](https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/) | Greedily try to add one missing character. How to check if adding some character will not cause problems ? Use bit-masks to check whether you will be able to complete the sub-sequence if you add the character at some index i. | String,Stack,Greedy,Monotonic Stack | Medium | 2157 |
76 | minimum window substring is a sliding window problem asked at facebook amazon microsoft lyft google linkedin apple bloomberg this problem is definitely hard so get your thinking cap on and let's get into it for this problem we are given two strings and we need to return the minimum window in string s that will contain all characters in string t confused let's look at an example the string abc has three unique characters we need to find the smallest sub string in s that contains all of those characters looking at string s we can see that a b and c are in this substring as you can see we actually have two b's here instead of just one but that is totally fine we just need at least one the characters a b and c are also in this substring and this substring there are other substrings that satisfy this requirement but remember we are looking for the smallest substring so let's just ignore the others looking at these smaller sub strings b a n c would be the minimum window substring since it has a length of four which is the smallest now that we understand what the problem is asking us to do let's jump into the approach to solve this problem which is a sliding window algorithm sounds complicated but really all it is a window or section that is formed over parts of your data and in our case our data is just a string we move this window in increments over our data to perform some sort of computation and in our case that would be finding the minimum window substring going back to the example we looked at previously let's do a step-by-step walkthrough of let's do a step-by-step walkthrough of let's do a step-by-step walkthrough of the algorithm the first thing we need to do is create a map to generate a count of all characters in string t this is so that as we iterate through string s we will know how many characters we have seen in t this will make more sense as we go through the problem so don't worry so far we have a having a count of 1 b having a count of 1 and c having a count of 1. now get ready i said this problem was going to be hard we need a couple different variables that are going to be used we're going to have an i and j pointer both pointing at index 0 in string s another variable called count is going to be initialized to the number of unique characters we have in string t which we can easily get from our map so our count is going to be initialized to three now we are going to initialize a left and right variable which will be used to keep track of the minimum substring positions we come across as we are iterating through string s so our left pointer will start at 0 and our right pointer will start at 12 which is the last index in string s technically in the beginning our left and right pointers can be initialized to anything so don't pay too much attention to the values right now we need a variable min length to keep track of the difference between the right and left pointer this value is the length of the substring technically we don't need this variable but is really just for convenience so our min length is going to be initialized to 13 this is initialized to 13 because if there is a substring in s it will be guaranteed to be lower than the length of s finally we need a boolean variable called found to determine if we have found a substring in s the reason we need this is because if we do not find a substring in s we must return an empty string all right now that we have all of these variables initialized we can get into the details of the sliding window algorithm our j pointer is currently looking at character a we check if character a is in our map and in this case it is that means we need to decrease the value of character a down to zero now we need to check if character a is at zero or not and in this case it is that means we can decrease our count variable so our count is now two the reason we decrease the count is because our sub string so far is character a and we have satisfied the amount of a's we need in this substring which was just one now we need to find one b and one c to find a successful minimum window substring we're going to continue to move our j pointer forward until we have satisfied finding all of these unique characters in string s so our j pointer is going to move forward and if our count variable is greater than zero that means we have not found a minimum window substring yet and that we should continue on so our j pointer is currently looking at character d is not in the map so we ignore it and move forward j is looking at character o is not in the map ignore it move forward j is now at character b and that is in our map that means we need to decrement the value of b which would be zero and since b is at zero we can now decrease our count down to 1. this is saying that we need just one more character to be found character c in order to find a minimum window substring so far from index 0 to where our j pointer currently is you can see that we have an a and a b inside of this substring now we're just trying to look for the c character our j pointer is going to move forward again and check if our count is greater than zero in this case it is so we continue on our j pointer is now looking at character e that is not in the map so we ignore it and move forward j pointer is now looking at character c that is in our map so we're going to decrease the value down to zero since c is equal to zero that means we decrease our count down to zero as well our j pointer is going to move forward and now we check if our count is greater than zero which it is not what this means is that we found a minimum substring but now our i pointer needs to be moved forward until our count is greater than zero again this is the most confusing part of the algorithm the reason why we have to do this is because there might be extra useless characters in the prefix of our substring that we don't need our eye pointer is at character a that is in our map so we're going to do the opposite of what we did in the previous steps we're now going to increase the value in a to 1. since our count is not 0 we now increase our count to 1 as well now we check if j minus i is less than our current minimum length j minus i is the length of our substring which is why we are comparing it to the current minimum length j minus i is less than our min length in this case so now we save our i and j positions with the left and right variables so left becomes 1 right becomes 6 and then our min length is j minus i which is 5. since we found a substring we now set found equal to true meaning our final result will not be an empty string and now it's really just performing the same steps so our j pointer is looking at character o that is not in the map we ignore it move forward j pointer is looking at character d not in the map ignore it move forward j pointer is that character e not in the map ignore it move forward j pointer is at character b that is in the map so we're going to decrease the value b is now equal to negative one that value is not zero so we don't do anything to our count we move our j pointer forward and check our count is greater than zero so we continue our search for an a character j pointer is at character a which is in our map so that means we decrease the value down to zero and since it is at zero we also decrease our count to zero we move our j pointer forward again and check if our count is greater than zero it is not which means we found another minimum window substring now we're going to move our i pointer forward to get rid of the useless characters so right now it's currently looking at character d and that is not in the map so we move forward now our i pointer is looking at character o that's not in the map so we move forward our i pointer is now at character b that is in the map so that means we increase this value to zero since b's value is not greater than zero we do nothing to our count and move forward our i pointer is at character e that is not in the map so we move forward now it's looking at character c which is in the map so we're going to increase the value to one we move our eye pointer forward and since the value is greater than zero we can now increase our count to one now we're going to check the length of the substring again so we do that by doing j minus i which equals 11 minus six which equals five if we compare this number to our current minimum length five is not less than five so we continue on without setting the left and right pointer our j pointer is looking at character n that is not in the map so we're going to ignore it and move forward our j pointer is at character c and that is in the map so we decrease the value to zero and since c's value is at zero we decrease our count to zero we move j forward again and check if the count is greater than zero it isn't so now we can see what letters we can shave off by moving our i pointer forward right now the substring we have so far is d e b a n c and that is valid but technically we don't need the o d e part since none of those characters are in a b or c our i pointer will go to o d and e and all of those characters are not in the map so we're just going to move forward and now our i pointer is looking at character b and that is in the map so we're going to increase the value to 1. we move our i pointer forward again and since the value of b is greater than zero that means we can increase our count to one now we're going to check the length of our sub string by doing j minus i which would be 13 minus 10 which equals three is less than our current minimum length of five so our new left and right values are going to get set our left will be equal to 10 our right will be equal to 13 and then our new min length would be three and now we are done since our j pointer is not looking at an index any longer we just need to compute the substring between our left and right pointers keep in mind though that our left and right pointers are one step ahead so we take all characters inclusive between left minus one and right minus one which would be b a and c all right so let's implement the code for this solution we are given two strings s and t and then we need to return a string which will be the minimum window substring the first thing we can do is just have various base cases if our string s or string t is null or empty we know that we can just return an empty string and now we're going to get a mapping of all of the characters in string t now we're going to initialize all of the variables that we talked about and now this is where the actual sliding window part comes we are going to move our j pointer forward until it hits the very end of string s so we can say while j is less than s dot length and then we can grab that character so we can say char and char equals s dot char at j plus every time that we extract a character from the string we are automatically going to move our j pointer forward right after and now we're going to check if this character is present in the map or not so if our map contains the key and char what this means is we are going to decrease the value of this character inside the map so we'll say map dot put and char map dot get and char minus one and then if our map dot get and char if this value is equal to zero at this point that means we have satisfied the requirement to have all of these characters in the substring and we can say count minus equal by one when we come out of this if check this is where we check if our count is greater than zero or not so if count is greater than zero then we are just going to continue if this if statement is satisfied that means we have not successfully found a minimum window substring yet if we make it out of this if statement however this is where we are going to shave off any of that extra unnecessary characters in the prefix of the substring so we can say while our count is equal to zero then we're going to extract the start character now and we can say s dot char at i plus and once again every time we extract a character from our eye pointer we're going to move it forward right after and now in this step we're going to do exactly the opposite of what we did on lines 18 to 20. so what we can do we can actually just copy this section and let's put it down here and let's fix the indentation and instead of n char we'll put start char in all of these sections and then instead of decreasing we're going to be increasing and right here as well plus equal to 1 and then the only other difference is instead of saying if it's equal to 0 we want to say if it's greater than zero finally when we make it outside of this while loop that means we have successfully shaved off all of the unnecessary characters in the start of our string and now we just need to compute the length of our substring so we can say if j minus i if that is less than our current min then what that means is we set our left pointer to i our right pointer to j and then our min variable is going to just be j minus i and remember the min variable is really just for convenience and then we also can say found is now equal to true and then when we come out of this while loop this is where we have either found a substring or we didn't and so we can determine whether we return an empty string or not using that found boolean variable so we can say return if it's not found then we just return an empty string however if we did find a substring this is where we need to actually compute the substring of string s using our left and right pointers so we can say s dot sub string of left minus one and right and so this is pretty much the equivalent of saying left minus one right minus one inclusive so let's make sure the solution works i put a capital s instead of a lowercase s so let's submit that one more time the time complexity of our solution is going to be big o of 2 times n plus m so n is the length of string s and m is the length of string t we must iterate over string t in order to create the map of counts in the worst case our i and j pointer could potentially touch every single character in s so this could technically be written as n plus m but since we drop constants it just becomes big o of n plus m our space complexity is going to be big o of n where n is the length of string t the only memory we initialize is the map and this will be the size of string t check out my other sliding window algorithm tutorial here to see how to solve one of the most popular sliding window problems on leak code like and subscribe for more content and check out my patreon for discord access and resume reviews that is all i have for you and i will see you later | Minimum Window Substring | minimum-window-substring | Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`.
The testcases will be generated such that the answer is **unique**.
**Example 1:**
**Input:** s = "ADOBECODEBANC ", t = "ABC "
**Output:** "BANC "
**Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t.
**Example 2:**
**Input:** s = "a ", t = "a "
**Output:** "a "
**Explanation:** The entire string s is the minimum window.
**Example 3:**
**Input:** s = "a ", t = "aa "
**Output:** " "
**Explanation:** Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
**Constraints:**
* `m == s.length`
* `n == t.length`
* `1 <= m, n <= 105`
* `s` and `t` consist of uppercase and lowercase English letters.
**Follow up:** Could you find an algorithm that runs in `O(m + n)` time? | Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach.
L ------------------------ R , Suppose this is the window that contains all characters of T
L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T
When the window is no longer valid, start expanding again using the right pointer. | Hash Table,String,Sliding Window | Hard | 30,209,239,567,632,727 |
39 | welcome to leak codes blind crate 75 where I'll be solving the top 75 leak code questions this question is called combination some and it's a pretty standard problem that you will probably see in your coding journey here's the problem given a set of candidate numbers with out duplicates and a target number find all the unique combinations in candidates that equal or sum up to the target if we're given a list like this we'll say our solution set is going to be 7 and 2 to 3 because those are all the unique combinations that we can find to create the number 7 now this could be solved in a couple of ways we could write something recursively and use memoization to save on space but this is simple enough that I think you can immediately go to the DP solution or the dynamic programming solution so let's go to the whiteboard and get our intuition here's a representation of my DP RA and up on the top is going to be the total count for all the numbers from 0 to 2 the number that we're trying to figure out as well as our integers that we can use for the combinations now remember that we can use each number as many times as we want as long as it's going to equal the number that we're trying to figure out so what I'm going to do is build up lists inside of this array to find all the combinations possible and just build this up as I move along this DP RA so starting with 0 we know that there's no combination whatever number we're given to make 0 so these are just going to be empty lists now let's start with 1 as long as the number that we start with is less than or equal to the number that we're calculating for just add the current number to this list as well as the 1 minus the current number from the list before so here they're going to be empty we know we want to add 1 because this is going to be the possible combination and we'll add whatever's inside here as well too this list in the same way we can see that one is less than or equal to two so we want to add one and add whatever we've calculated from before because whatever combination does that we have for tackling one is going to be added here right so just have one like this and that's just going to continue all the way on till to number five okay now let's go to number two and if the number is greater than the total that we're calculating for we can just skip that because there's nothing possible but here we see okay 2 is less than or equal to 2 so we can add 2 as well as minus 2 in here to go to 0 to see what we can add to find the combinations from here and we know there's nothing so that's just 2 now same thing here we can add to and we minus 1 to see how many combination is that we can use to calculate 1 and there's nothing here but on top we know that we can calculate 1 using this coin with 1 right so immediately we begin to realize oh this 2d grid isn't actually necessary we can use a one dimensional array and build the list that way because otherwise we'd have to check all the way up every single time and that's just not going to be efficient so with 2 we'll add 1 and here we'll see at to see how in ways we can find - and we find 2 ways 1 & 2 right find - and we find 2 ways 1 & 2 right find - and we find 2 ways 1 & 2 right so it'd be 2 1 like this as well as 2 & 2 so we have to listen side here and 2 & 2 so we have to listen side here and 2 & 2 so we have to listen side here and 4 3 we can figure out the same thing we'll use these two and it's like 2 1 two to one so these are just all in one cell and finally with three it's going to be the same thing go to three threes gonna be like this now check for 3-1 gonna be like this now check for 3-1 gonna be like this now check for 3-1 common equally fine it's just one here so it's actually just three eight one and with 3d of two how many ways could we find that there's actually a couple ways to do that right so three one and three two and the answer ultimately is going to be this whole column right and as long as this is just a one dimensional array all these lists are going to be inside here and we're just going to turn that so hopefully that gives you the intuition and let's go ahead and code this out now that we have our intuition let's go ahead and code this out and we want to start off by initializing a DPR a and for that I'm just going to say create a list of lists for blank and range the target given to us plus one because we remember we need one for the zero as well all right so now for all the coins or candidates C in candidates and I believe these are sorted I don't think you'll have to I only actually think it matters whether you sort them or not but regardless what you want to do for each cell right and we can just start at the second column because we already know the first one is always going to be zero and it's going to be an empty list so we can just start with I in range of one to target again plus one now few things first thing is if this number is less than our candidate let me just skip it we can just go ahead and continue because we know there's nothing to really calculate there it so it's equal to one another then we want to add it to our list so this DP array at I just say we can just do an append and add the candidate because that's going to be the only combination at that point right now finally otherwise we know that it's greater than this number so what we want to do is do another loop and add all the ones that we calculated before right so for I'm just kind of like b-list in the for I'm just kind of like b-list in the for I'm just kind of like b-list in the dynamic programming array with current number minus candidate because there's possibly multiple lists inside there we want to append that the B list as well as our current candidate so that's going to be just like this and finally this is going to be a one dimensional array and all the combinations should be at the very end so we can just return our DPR a the target so let's make sure this works okay so I know the list is not a list mm-hmm okay I need to add them as a list mm-hmm okay I need to add them as a list mm-hmm okay I need to add them as a list of course so let's try that one more time and it looks like our test case got accepted so let's go ahead and submit that and there we go so this is a pretty classic problem one that has many variations and I think I will solve a couple of the other ones eventually there's like combinations some two three four and they're all different and require like different approaches they're not all going to be able to be solved using this approach so thank you I hope that helps | Combination Sum | combination-sum | Given an array of **distinct** integers `candidates` and a target integer `target`, return _a list of all **unique combinations** of_ `candidates` _where the chosen numbers sum to_ `target`_._ You may return the combinations in **any order**.
The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.
**Example 1:**
**Input:** candidates = \[2,3,6,7\], target = 7
**Output:** \[\[2,2,3\],\[7\]\]
**Explanation:**
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
**Example 2:**
**Input:** candidates = \[2,3,5\], target = 8
**Output:** \[\[2,2,2,2\],\[2,3,3\],\[3,5\]\]
**Example 3:**
**Input:** candidates = \[2\], target = 1
**Output:** \[\]
**Constraints:**
* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40` | null | Array,Backtracking | Medium | 17,40,77,216,254,377 |
344 | hey guys persistent programmer here and welcome to my channel so if you're new here we solve a lot of problems on this channel and today we're gonna be looking at the reverse string problem so this is a really interesting problem when you use the two pointer solution to solve it and that's exactly what we will be doing today so I hope this video helps you understand the question and let's go ahead and get started so this is a very simple problem to understand we're given a string and we just need to reverse the input so if we're given hello we need to return oleh so just reverse the strings but the key in the question is we need to do this in place so this means that we cannot create any auxilary array to do this transformation okay so with this in mind let's look at the solution okay so to solve this problem what i'm gonna do is i will initialize two pointers so i will start my pointer here so this will be my left pointer and I will have a pointer at the end of the list here at the O and I'm going to swap these two positions so what do I mean when I say swap right so if I were to do this for this first iteration what this would look like would be Oh II l h so what I did is I swapped the oh and the H here okay so you can see that yeah there's just what the first two positions but we haven't swapped the rest of the list right so how do we swap all the items in the string so what we do is we just move our pointer so we move this right pointer over here to this next position and remove this left pointer forward so at each step we're going to move our left pointer forward and our right pointer backwards and then what we do is we have the same positions here so these don't change and this will transform to now L and then II so now we switch the L and the e right and this will remain this the same and you can see that we've already solved the problem because this is the output so at each point what we need to do is we just to move our pointers and go through in a while loop and solve this problem so the time complexity for this is o FN because we will iterate over the entire array and the space complexity is o of 1 which is what the question asks us to do and at each step we will just literally swap the two positions were at this the strings the elements at those places and who will just advance our pointers and that's it that's all we got to do okay awesome so let's look at the code awesome so I'm back of the code and the first thing I'm gonna do is define my left and right pointers so I will say let left equals zero and this is going to start at the first index here which is the zero index and our right index is going to start at the end here so that index is flat right it was s toddlin minus 1 okay so we're doing minus 1 because we're starting at 0 so this index actually points to this last spot in the list that's why we're doing the minus 1 ok awesome now we need to write our while loop so we'll say a while left is less than right and we want it to check this condition because if left is equal to right that means we're pointing at the same item that means like we have finished doing all the swaps we possibly can right so that's why this is our while condition and what we're gonna do is create a temporary variable called and we are going to put the left value in here for it to hold it right so this is how we'll do our swap so we will say let hold equals adds at the index of left so in the first iteration the hold will be holding this H okay and then what we're gonna say is S at the index left equals S at the index right and what this is going to do is it will actually say is oh so it will just take this last element and just put it here so currently if I point this it will just look like oh e ll oh now we need to now transfer this H that we put in the hold back here right so that's our last step so what we want to say is yes at the index right which is the last index currently is going to be equal to whatever we put in that variable to hold so we'll say hold okay and then what we need to do is advance our pointer so then they move forward so the left pointer so remember left pointer will go this way so we're going to add to it so we'll say left plus and the right pointer is going to move this way so we're gonna say right - - so this way so we're gonna say right - - so this way so we're gonna say right - - so right - - all right that looks good right - - all right that looks good right - - all right that looks good let me run code okay awesome so let's submit okay also it works | 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 |
839 | Hello everyone welcome to me channel 22 going to lead code number 839 D question if you understand this is the question of DFS and Buffs have to see from my playlist of graph concept sir questions na date playlist is the name of very important question Similar string group ok if you had to write BF in the graph then you can solve it very easily graph concept clear its BFS and DFS ok I will post its link what is the description and a this question then the question starts like this first of all He told that to a friend, when should they say that they are similar? Two strings If it becomes equal to A then it is okay then either both the strings are equal then we will call those two strings similar. Okay but in the example the strings and rates are equal similar because see swapping and position zero and you swipe the T and R out of this. Rates will become right and rights and art and similar rates and art is also similar but star is not similar tu ters because multiple places will have to be swapped ok now let's see what to say here see this is a very important line from where it came to be known This is definitely a graph question, okay here it is saying that together these form you connect so the people who are similar are grouped together, remember rates and rates were similar and rates and art are similar that is why these three are grouped together. They have been placed in a group, it is okay, all three are connected to each other, although the words and art are not similar, but the art which is there is rightly similar, the thoughts have been put in the same group, here it is okay, one should be similar to the other. This star was not similar to anyone else, that is why it has been included in a different group, it is okay, now what is the matter with you, I have given you a string, let me tell you how many such groups will be formed in total. Look here, two groups have been formed. There is one group, this is it, there is a torch in it and one group is separate star, so there are two groups in total. Okay, so here I will look at the stars and rates. These will come in this group, in separate groups of this, total two groups. Okay, so now pay attention to the question here, what time is it in this form, you connect group by similarity, what does it mean that these two groups are not two, these two groups are formed, this is a connect group, all three are connected, there is one or the other. If they are similar to each other then it is okay then a definite question is going to come from here so you can visualize it like this if it is a graph question then this is a torch and these eight are okay groups then it is okay you can see that the connection if It is okay to make it like this, after that if you do DFS on it then see how many strings we had in total. There were 1 2 3 4 strings and which ones were similar. The one with index number zero was 012 similar and this third one was not similar. I will take a widgetized zero one to three when I start from 0 DFS ok you can start from story too I will take mother from zero I started I DFS ok so zero when I start DFS on this then 3 marks will be made We had to do total 2 DFS yesterday. Thoughts is fair answer. You are right about how we will make this graph. So let's take an example to make the graph. I have also indexed them. If you look at the idli, you will remember that we had connected right. So we have to make adjustments to make the graph, so we have to tell that zero which is connected to one is fine and one which is connected to you is right, here it was zero one second one, how will you do that, okay so first So we make our DJ, this is our DJ, I am standing from here and have seen how the hero can connect to which, so I am pointing here and I start from here with I + 1, so I Saw with I + 1, so I Saw with I + 1, so I Saw that both of them are similar. How are they similar? They will check that either there should be zero difference between the two, there should be a difference of characters or there should be a maximum of only two character difference by replying or both should be similar and both should be equal. If both the strings are there then if I get I and G that both are similar then what will I do, I is what is zero, I put one in it that I is zero one is connected similarly, after this I saw that these two are not similar because multiple. The place is different and the characters are different, then here I come, these two are not similar, okay, this is over till now, what will happen after that, I will go further, then I will see which of these one can be connected, let's start from here rates and art connect. If they were similar then one becomes one, if it is not connected to you then leave it and if it is science or indirect graph then zero seven, if you have made it then you will have to make zero from one too, okay, you will have to make one from one, you were from one, you will have to make one from you, okay So our adjas will be ready like this, okay, it is quite simple, so give it, then what we have to do is just write the DFS, we have to do the DFS tomorrow, okay and the DFS of the graph, we have written many times that we will take a detailed okay. There are as many notes as there are, starting from zero, one to three, everyone will be uninvested. I start GG from one, but for example, I started DFS from zero, then if I hit 012, all the Marxists will be corrected, there will be no need to do this also. 2 will be mine, this will be my answer, okay, similarity, what will happen similarly, instead of DFS, you can do BFS tomorrow, it is very simple, it is in the graph concepts playlist, I have already heard it before, okay, so similar, whatever story you tell, we copy it exactly the same. First we will make a graph, after that we will solve DFS once and once we will solve it with BF, similarly we will do court, first of all we will find out the length of how many strings we are going to have, okay after that the first step was to make the graph. When it is similar, we will write a function, so what will we do, it will connect to I. Okay, so we have made this string our graph, now we just have to write this function, when were string and s1 string and s2 right here, let's find the length. That is from all the lenses, I am late to see at how many places the characters of both are different, then it is given in the question that there should be character differences only at two places, it is okay and if the difference is only at two places or there is no difference then it is highlighted first. Have you made a list of how many times we have done DFS? Now let's start. If it is not visited, if it is noted that it has come, then we will do DFS on it tomorrow. DJ will have to be passed and vested will have to be passed. Finally, we have to return the account itself, which is our graph. Okay last time if it is not visited then expand it on but this is not the website then they bill tomorrow DFS on this note b bill tu pass which d test cases approach ing DFS now we don't have to do anything from BFS to create this which There is a code with DFS, why did you remove it and take BF, why okay, on whom DFS is done yesterday, on some note, it must have been done tomorrow, okay and send the graph, okay why did I push in the first place okay, great, let's see after submitting butt debt bill be in d difference separate video because debt bill be a little typed so c1 and next video thank you | Similar String Groups | short-encoding-of-words | Two strings `X` and `Y` are similar if we can swap two letters (in different positions) of `X`, so that it equals `Y`. Also two strings `X` and `Y` are similar if they are equal.
For example, `"tars "` and `"rats "` are similar (swapping at positions `0` and `2`), and `"rats "` and `"arts "` are similar, but `"star "` is not similar to `"tars "`, `"rats "`, or `"arts "`.
Together, these form two connected groups by similarity: `{ "tars ", "rats ", "arts "}` and `{ "star "}`. Notice that `"tars "` and `"arts "` are in the same group even though they are not similar. Formally, each group is such that a word is in the group if and only if it is similar to at least one other word in the group.
We are given a list `strs` of strings where every string in `strs` is an anagram of every other string in `strs`. How many groups are there?
**Example 1:**
**Input:** strs = \[ "tars ", "rats ", "arts ", "star "\]
**Output:** 2
**Example 2:**
**Input:** strs = \[ "omv ", "ovm "\]
**Output:** 1
**Constraints:**
* `1 <= strs.length <= 300`
* `1 <= strs[i].length <= 300`
* `strs[i]` consists of lowercase letters only.
* All words in `strs` have the same length and are anagrams of each other. | null | Array,Hash Table,String,Trie | Medium | null |
1,233 | come to my channel so in this video i'm going to cover two things the first thing is we should cover uh the solution to this problem and then we are going to do some coding work and the second one i'm going to cover the general procedure to follow in the coding interview briefly so before we start the real content for today i would really appreciate that if you can help subscribe this channel because it can help me to grow so thanks in other ones let's restart this problem remember in the real coding interview the first step is always trying to understand the problem so don't jump into the coding part too quickly try to fully understand the problem first and uh if there's anything unclear please bring out the question to the interviewer and at the same time think about some ash cases so let's say sorry remove subfolders from the file system so give a list of others return sorry remove all subfolders in those folders and return in any other the folders after removing okay so if a folder is located within another folder j it is called a subfolder of it so the format of the pass is one or more concatenated string of the forms forward slash followed by one or more lowercase english letters for example slash lead code and slash record problems are valid passes well an empty string and follow slash are not okay so let's see we have this something like this finally after removing all the subfolders we have slash a and slash cd slash um okay so that's because a b slash a b is subfolder of slash a slash cd is a subfolder of cd so similarly for example two three okay so let's see some constraints it says that the further the lens is between one two for the four times four to the power of four which is 40k okay so for this lenses between uh so each father uh the lens for each of the father the lens of the string is between two to 100 and it only contains lowercase letters and forward slash always starts with character slash so each father name is unique so it says that we don't have unique we have we don't have the root uh so we will not never have the root uh directory as the as a folder because it says that just one for slash is not valid and now so um the each father the lens of each father is going to be larger than two which means the root father is not included in here so i think um the next part is about doing some solution finding stuff so how to solve this problem so one thing i think we could do is uh let's say the solution one what we could do is we can do a sword uh based on the lens of fodder and then oh we can try to see if one father is any sub-father is any sub-father is any sub-father of the previous fathers so for example first of all we sort let's say we take this example first of all let's sort it so we are going to have slash a then the second one is this third one is this so by the way we are going to sort by uh we are going to sort by the lens first and then if the lens is the same then we are going to do the sort by alphabet so when we go through this first of all we after sort we go through a and then we see a b so a b of course it is uh the subfolder of slash fox slash a so we are going to remove it and then we have cd we have cf and then when it comes to cde cd is a folder of cd so we are going to uh remove cde as well so i think it should work but the runtime is going let's say we have the less of the input string array is going to be n so because of the sort it is going to be analog n um and also let's say for each of the subfolders suppose we have uh so suppose we have like each of the string that has n levels of default m levels of the father then we have we also have like n times m because it's like we need to say first we d we need to see if slash c containing is contained in the previous uh so father uh previous fathers if slash cd is contained in the previous father's if slash uh yeah so we need to like see all of the uh parent father is any of the father that comes before it in this solution so uh i think this one it's so it might be a little bit inefficient but let me go through another one so let's say the solution to so due to the sorting we have an unlock in here for solution one so next one um the next thing the next solution i can think about is we could use prefix tree which is try we could use try to solve this problem so first of all we build a try by going through everything and then after we build a try we go over each of them uh again so let's say when we go over cd we see that in the prefix tree there is already a pass from c to d and uh cd is just a child of that father so we are just going to ignore this one so this uh regarding this one the runtime is going to be n times m uh essentially we need to go over each of the thing to build the tree build a try and then we go over again to see if uh if the corresponding folder has a ha the corresponding harder has a parent father that is included in the tree so overall i think um it depends so it depends if the login is larger than m then i would say yeah if logan is larger than m i would say it is vr uh the first one is inefficient but in case logan is like about the same as m then i think the two approaches regarding runtime they're just the same regarding the runtime efficiency so let's do so do the coding work for solution 2 because it's a bit more challenging so you need to implement the try for this problem so uh the next part is about doing some coding work so for coding care about the correctness of the code the readability of the code and also don't be too slow so let's definitely class call it try so in this one uh tri is going to have the children so the children let's define it as a map from the character to the trinomial let's say we define a trinomial to triangle okay so this is children okay and then we need also need to have a boring representing if it is a father so it's father let's give it a constructor let's say the father trinomial so we have the children has new hashmap and his father sat as boss or you could say um have another constructor here so is father yep so we have this let's uh define another helper function here let's call it um insert so this one is going to not return anything so you're going to have like the string let's say uh dir so for the dir first of all we are going to uh split it so string like i would say let's say it is a chunk is going to be exploit where's the slash okay i think it's just slash forward slash and then you're going to say okay ghost reach a bit um well we shouldn't define it here actually let's define another thing which is a try uh the try so for the try we will have a public let's say we have a tri node as a route and then we have the root and then we will have the uh constructor so try new hard try no okay so here let's define a helper function let's say insert um so the insert is going to the parameter is going to be the father and then for the father we will need to split it using the forward slash so let's say this is a trunk other dust plates and then we need to go through each of the charm here this is chunks um so we will have here let's say the try node is equal to root at the very beginning and then all you're going to do is um if the no doubt children dot contains key chunk then we are just going to say okay note is equal to node.children is equal to node.children is equal to node.children dot get chunk otherwise if it doesn't contain the chunk what we are going to do is we are going to say okay node.children node.children node.children output the trunk into it this is of course a new uh tri node and we are going to have node is equal to no dot well we could actually save some code here so if it doesn't contain this we are going to put the new node and anyway we are going to have notice equal to no dot children don't get chunked okay yeah so after that uh i think you're going what we're going to do is we're going to have no the dot is father as true so let's say suppose it is 80 first it goes to suppose it's slash a then at the very beginning it doesn't have the a so we are going to put uh the a and the corresponding new node into the children of the root and then we go to the corresponding child and then we will uh after that we are going to set the corresponding trinode as true okay so that's pretty much about the insert and we also need to define another helper function uh let's say uh the helper function is to see whether there is already a subfolder so let's say i pass in the a parameter it is going to see it let's say it is a father of a father so suppose we have already built a tree a bill that i already be able to try so we are going to so this function is to tell whether uh there is any father that include this father uh in the try here so for example let's say we already have the slash a if you pass slash a b then we are going to return true here so again we are going to split it into the trunks exploits um yeah so one thing i need to think okay so it says that the each father is going to be unique so we don't need to worry about the duplication stuff so um for the chunk chunks let's say we have the try here so you're going to have to try no known as equal to the roots here at first um yeah so if the so let's see note should be equal to node.children.uh should be equal to node.children.uh should be equal to node.children.uh gets the chunk uh so if so let's see if so let's say if we already have the slash listed there are only two things slash a and slash a b so we have this one we have build this stuff and then let's say if it is slash a b and we are going it you should return false let's say first of all we going to use we go into a and then we going to be so if we go into be um we shouldn't so we should check first i would say so if no dots is father then we are going to return sure otherwise we are going to return false so let's say we have slash n slash a b and we form the tree at the very beginning so when we tell whether a b slash a b is a subfolder so first of all it is a root and we see okay root of course is not a folder so we are going to we are not going to touch this one then we go to the corresponding subfolder which is slash a it is a subfolder so you're going to return true here well but let's say if you only have slash a b here we only have slash av for the try then slash a is not a something it's not the it's not slash a is not within the try so you're not going to touch this one and then if it is slash a b and then we go to the b okay yeah so what i would just want to see is we don't want to say we don't want to have introduce some fast positive so let's say we only have we have the slash a slash b we want to make sure that when we touch slash a slash b again it is not going to return so it's a further as true all right so having said that i think it's okay so next thing for us to do is to uh use the define class to really uh solve this problem so we are going to say okay let's try uh try is when you try and then go through everything string oh yeah let's say they change this as fathers so try not to insert the father and then we have to define a list of the string here let's say our yes new linked list so you're going to go through this again if try dot uh his sub father uh father then we are going to return uh we are not going to we are going to continue otherwise we are going to already added the um follower so finally return already here all right so that's pretty much it i think let's do some testing so it says that string chunk okay so it is not character so it is string actually this is uh stuff that's not right all right so it seems to be okay uh let's do a submission all right so it seems like everything works well here uh so it's just a try approach so remember after that was coding please do some testing so for simplicity i just uh rely on this platform to do to help do the testing but in real interview you don't have this kind of platform so you need to test the you need to set up the test cases yourself so that's it for this coding question if you have any question regarding the solution or regarding anything feel free to leave some comments below if you like this video please help subscribe this channel i'll see you next time thanks for watching | Remove Sub-Folders from the Filesystem | number-of-ships-in-a-rectangle | Given a list of folders `folder`, return _the folders after removing all **sub-folders** in those folders_. You may return the answer in **any order**.
If a `folder[i]` is located within another `folder[j]`, it is called a **sub-folder** of it.
The format of a path is one or more concatenated strings of the form: `'/'` followed by one or more lowercase English letters.
* For example, `"/leetcode "` and `"/leetcode/problems "` are valid paths while an empty string and `"/ "` are not.
**Example 1:**
**Input:** folder = \[ "/a ", "/a/b ", "/c/d ", "/c/d/e ", "/c/f "\]
**Output:** \[ "/a ", "/c/d ", "/c/f "\]
**Explanation:** Folders "/a/b " is a subfolder of "/a " and "/c/d/e " is inside of folder "/c/d " in our filesystem.
**Example 2:**
**Input:** folder = \[ "/a ", "/a/b/c ", "/a/b/d "\]
**Output:** \[ "/a "\]
**Explanation:** Folders "/a/b/c " and "/a/b/d " will be removed because they are subfolders of "/a ".
**Example 3:**
**Input:** folder = \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Output:** \[ "/a/b/c ", "/a/b/ca ", "/a/b/d "\]
**Constraints:**
* `1 <= folder.length <= 4 * 104`
* `2 <= folder[i].length <= 100`
* `folder[i]` contains only lowercase letters and `'/'`.
* `folder[i]` always starts with the character `'/'`.
* Each folder name is **unique**. | Use divide and conquer technique. Divide the query rectangle into 4 rectangles. Use recursion to continue with the rectangles that has ships only. | Array,Divide and Conquer,Interactive | Hard | null |
146 | hi i'm ali today i want to talk about another important interview question this question is called lru cache and it's a bit different from other problems that we have solved till now in this problem we have to design a data structure and then implement it this is among one of the most popular interview questions in lots of great software companies and it has been asked by companies like amazon google microsoft bloomberg and apple so in order to solve this problem let's first read it carefully and understand it so the problem says design a data structure that follows the constraints of a least recently used cache and here are the information about the lru cache class so as you can see this class contains a constructor which takes the capacity as an input and it initializes the lru cache with positive size of capacity and in the get method it takes the key as an input and it returns the value of the key if the key exists and otherwise it returned -1 so and otherwise it returned -1 so and otherwise it returned -1 so that means that it takes the key and if the key is not already in the cache it returns -1 and if it is in the cache -1 and if it is in the cache -1 and if it is in the cache so it returns the value of that key and also the method put takes two parameters the key and the value it updates the value of the key if the key exists so if we have that key it updates the value of that and otherwise it adds the key value per to the cache so if we don't have that key in the cache already we should add the key value per to the cache and if the number of keys exceeds the capacity from this operation evict the least recently used key so that means that for example consider that our cache capacity is free and we already have three inputs in our cache so if this function is called we have to remove one of those entries from our cache and that would be the least recently used entry of the cache on the follow-up section it asked us to on the follow-up section it asked us to on the follow-up section it asked us to implement the get and put method in o1 when you are reading the question try to paraphrase the question for yourself and also check the keywords of the question for example in this example those keywords are o1 time complexity key value per and lru which is our eviction policy don't forget to double check the discussion points with the interviewer this shows that you are understanding the problem well and you have a full grasp on the problem before i explain the solution of this problem and write the code let's go through the example that the question gave us in order to understand this problem better and deeper so as you can see we are given two arrays the first array contains the methods of the lru cache class and the second array contains the parameter parameters of those methods for example two is the capacity which is the parameter of the lru cache constructor and one is the key value that we should put into our cache and one here is the key that we have to return the value of that based on the definition of the get function so now i want to solve the problem based on the inputs so as you can see the size of this cache is two or the capacity is two so this would be my cache of size two oops ah let's race it and draw it again so it is my cache with the size of two and this section would be my keys this column is for my keys and this column is for my values and the first item that we should put into this cache is one but do not forget we have to write the output that i mean the number that we return so that would be my output array and the first method hillary cache does not return anything so the output would be null and the second method is put with the values one so we have to add the key1 and value one into our cache and also as it doesn't return anything the output would be again null the next method is put with q and value 2 so we have to add 2 into our cache and again as it doesn't return anything our output is null the next method that is called is get and the parameter is one so based on the definition that means that we have to return the value of the key which is here one so we have to return 1 here and the output would also be 1. the next method is put with a 3 with key 3 and value 3. but as you can see our cache is full now so we have to remove an item from the cache and we have to use the least recently used policy so the least recently used entry is 2-2 because the 1 entry is 2-2 because the 1 entry is 2-2 because the 1 entry has just been called with the get method so we have to remove the 2 entry from the cache and then put 3 into the cache and then we have get with key 2 but as you can see here we do not have any 2 so we should return minus 1. so the output is -1 oops i missed to write the output of the previous call which was put so the output of put is null and the output of get with the key of two is minus one the next method that is called is put with key value for but as you can see our cache is full so we have to remove an item but and we should use the least recently used policy to remove the appropriate item and as you can see the 3-3 pair item and as you can see the 3-3 pair item and as you can see the 3-3 pair just has been called with the put method so we have to delete the one from the cache and we put four instead of that and as it's put and it doesn't return anything so the output is null again then we have get one and we just removed the get one from the cache so the output will be minus one based on the definition then we have get three so we have to return the value of this key which is three so the output will be three and then we have get four so we have to return the value of the key four and it's four so the output is four and yeah the this is finished so now let's check if we have done it correctly yeah as you can see the output is the same with the output that we just uh achieved and wrote i hope you understood this problem thoroughly don't forget to ask clarifying questions when you are reading the question in the interview because the interviewers want to know that how do you react when you see a problem that might be a hard problem like this one so you can ask questions about the parameters of the functions or the return values or the val the boundary of them and things like that and on the next session we will talk about how to implement the get output in o1 complexity and how to implement uh this uh problem with the upper priority solution before we talk about the suitable data structure for this problem we should consider several important points from the problem the first one is that the problem says the policy that we use for eviction is least recently used or lru so this is one of the most important things in designing the suitable data structure and also we have to consider that the data is in key value format so our data structure should enable and accept the key value format and maybe the most important point of this problem is that we should implement get input in one time complexity so we have to design this data structure in a way that we can implement get and put in o1 so based on these critical points that the question gave us let's see what data structures can we use in our design so based on the least recently used what do we understand that our data structure should support an order i mean our data should have an order in the list so for example our data should be from most recently used items to least recently used or vice versa what kind of data structures we can use to have an order or to sort them in a way those struct data structures include heap or maybe lists or maybe even arrays so this is the first uh first thing that we understand and we should consider in our design the second one is the key value format so what do you think when you want to design a data structure that supports the key value format maybe the easiest one is to use a map or some hash table so this is another thing that we should consider and also a one-time complexity for get and also a one-time complexity for get and also a one-time complexity for get and put which means we have to have the direct reference to the data based on that we understand that we should not traverse the list in order to get an item or put an item in the data structure now let's talk about different data structures that we may can use based on these critical points the first data structure then we can think of is a mix of a set or a list and a single linked list so i just write single ll to save some time so let's see how that works consider that these are our key values that we need to put in our cache and so how can we design uh the suitable cache lre cache with using these two data structures so i want to put all of the keys which are the first elements in a set or a list so this would be the items in the list which are my keys and what do i want to do is to have a direct reference to a single linked list because remember we need one time complexity for get and put which requires a direct reference so consider this is my single linked list i have three items and the these are my values and these are my keys and i have a direct reference from my keys to the values that are in the linked list and that would be 10 11 and 12. so in this way i have a direct reference and don't forget that this is the structure of the uh single linked list here is the value and here is the address to the next node actually here the value section is divided into key and value because the data is in key value format so maybe uh i should say that this is the structure that we use so we have key value and the address to the next node so this is our value section which is divided into key and value yeah so as you can see here i just built a map right a map of integer a list of integer to a linked list which is here a single linked list so this is the map that we were talking about and as you can see this solution seems really well and it seems that it works well but it has a little problem so let's see let's consider that here is the function that is just called get 8. so what should we return we should return the value of this key which is 11. okay but because we are using the lru policy so after this method is called we have to update our linked list so because this node now is the most recently used node and we have to move this node at the beginning of the list of the linked list right but the problem is that because of this format that the single linked list has we cannot uh change the next pointer on the on this node we cannot change it to 12 so it means that we have removed this node from here and put it at the beginning so what do we need now is to have a reference to the previous node so that brings us to the double linked list so let me change the color and show you how it works so i want to use here the double linked list instead of single linked list because double linked list format is that here we also have an address to the previous node so that means that this node has access to the previous node and also this node has access to the previous node so when get 8 is called and i want to transfer this node at the beginning i can simply change the next note next address of this note because now i can go to the previous note from this note so i go here and i just change the next address to the 12 instead of 11. so in this case this note will point to this note as the next note and the previous note of 11 would be null and i move it from the middle to the beginning with the double linked list and also i should uh i can simply update the previous section of this node to 11 so it means that we have simply transferred the 11 at the beginning of the list so we have just solved this problem with a map of an integer to now a double linked list and as you can see we now can get the uh get the value from the cache in one and we also can put that with one with the double with this double linked list because whenever i want to put something for example i want to put a key value data a key value entry that the key is 5 and the value is 13. so it is now our uh most recently used key or most recently used uh key value for i should say so here with this double linkedness i just added at the beginning of this list because this is the most recently used and with those next and previous sections on the double linked list i can update that easily with one so i hope you understood this problem it's a little bit tricky but when you understand it's very beautiful and we can solve this problem with that and we can so we can design the suitable data structure for the lru cache with uh a map of an integer to a i should say a map of a list of integer integers to a double linked list don't forget to involve the interviewer with your thought process for example here you can do this by analyzing different data structures as i did this indicates that you are a strong problem solver and also can communicate about the problem with others well this is one of the most important skills that a software engineer should have and they are searching for such a person and on the next part i will explain the code of this data structure so you can understand this problem easier and better now that we understood the problem and the suitable data structure that we want to design let's uh look at the code to understand how should we implement this data structure but before i explain the code i should say something about the code we assumed that we have a pseudo head and tail so we are doing this because we do not want to check for the null when we want to update the linked list and that also helps us to write a cleaner code and also pay attention that the linked list that we have here is from most recently used elements to list recently used elements so that means that the elements that are at the beginning of the list are those that have recently used and those that are at the end of the linked list are those that have been least recently used so keep in mind these uh two points because uh we need them when we want to analyze the code now let's see the code so we have a class called lru cache which is the cache class and in this class we have just defined a class called d-link node which is our a class called d-link node which is our a class called d-link node which is our double linked list class and as you can see this class contains four variables the key value and previous and next because as you may remember this is the structure of the double linked list so we have key value the address to the previous node and the address to the next node so this is the visual form of this code then we have a method which is a void method and it's called add note and it takes a note as the parameter and this just add a new note to our linked list so in order to explain this code i want to show you the visual format of this so the add node function works in this way for example we have this linked list and this is our pseudo head and this is our survey and we have a node here called next so when we want to add the note we add it after the head because we you know we keep the head and tail uh fixed so they will never change this head and tail because as i told you before we don't want to check for null things and we do want to have kind of boundary for our data structure so when we want to add a new node which is the most recent node in the list we will add it after the head and let's go through the code so in the code as you can see the node previous part would be head this is the node and the previous address would be head because the previous note is head and the next is head that oops sorry the next is head.next which is this one the next is head.next which is this one the next is head.next which is this one so the next note would be this node will point to the next node we have to update both of these nodes the head and next because this node is inserted between the two of them so the previous part of this node would point to the new node that you can see here head.next.previous is our new node so head.next.previous is our new node so head.next.previous is our new node so head.next is this node head.next is this node head.next is this node and the previous part would refer to the new node and also we have to update the next in the head node so head that next would be this node so that means the head will point to this node and then we have remove node this is again a void method and it takes a node as the parameter and we in this method we want to remove a certain node that we have been given so let's show you the visual format in order to understand it better so consider this is the length list that we have actually this is our uh head that i just wrote previous to explain the code here this is that head and this is our tail and this is the next note this is the note that we want to remove it so what do we do when we want to remove this node that means that this previous node which is your head should uh point to this node instead of this orange node and also the next node should refer to the head node which is called previous year so in this case we have removed it so let's see the code we have defined two variables from the d-link node d-link node d-link node class called previous and next and in previous we keep the node.previous in previous we keep the node.previous in previous we keep the node.previous and the next we keep the node.next and the next we keep the node.next and the next we keep the node.next so the previous would be this note as you can see here and the next is this note and what do we want to do is that to do something that the previous note next node would be next so that means as i told you this node should point to this node and also the next node should refer or point to the previous node instead of this origin so we do that by this code and this is the visual format of this code and now let's do move to head method so as you can see this method is also void and it takes again a node as the parameter and what do we want here is to move a node to the head but remember that as we have pseudo uh head and tail here we actually add it to the node after our pseudo head and this will use in cases that we update the linked list for example if we call a node for example we just call get method any node is called so that would be our most recent node and we want to move it to the head of the linked list because remember our order is from most recently used to list recently used so let's see what do we do in this function so i've just called remove node that we explained here an add node but let's show you the visual format again for better understanding so consider this is my linked list and i want i have just called this note so this would be my most recently used note and i have to move it to the head and be careful i move it to the after of the pseudo head node that i have here so i want to move it here i want to remove it from here and move it here so what do i want what should i do first i should remove that node as i explained here so i remove it from here and update the previous and next node and then add node here and update the head and one node here i mean the previous and next pointers are these two so this is the work that we are doing with uh this method the next method is poptail and with this method we want to pop the tail of our linked list and again as we have a pseudo tail so we will pop the node before that pseudo tail okay this method uh this method type is the link node so it returns a node to us a d-link node to us and it doesn't take a d-link node to us and it doesn't take a d-link node to us and it doesn't take anything as the parameter we have declared a variable cause called res it its type is the link node and we put detail that previous to that because uh we want to pop the tail not the pseudo tail the actual tail which is here which is the note before our tail so we just uh keep this node into a variable called res and then we call it remove node for this node and in this case we have pop that from the list and then we return that because this is the actual tail that we have and we return it as a detail till now i just wrote the base functions for double linked list and here we have the map we have our map from integer to double linked list or the link node and this map is our cache and this cache has a size capacity and head and tail also so let's see now let's see the uh our lru cache methods so first it is the constructor that takes the capacity the integer capacity as the input and in this constructor we put size 0 and capacity to capacity and then we have head which is a d-link and then we have head which is a d-link and then we have head which is a d-link node and tail which is dealing node and here we just made the basic the i mean the base of this cache and here are our head and tail the pseudo head and sudo tail then we have the get function and this function is an integer function because it should return the value of that of the given key and the parameter is the key so in this method we just create a node of the d-link node type and of the d-link node type and of the d-link node type and get that given key in the method from the cache so we call that key so we have access to the value and we assign it to a node and then if the node is null as you remember from the question we should return -1 and if it's we should return -1 and if it's we should return -1 and if it's not we want to move it to the head because this is the note that is just called so it is our most recently used uh elements or note and we have to move it to the head and also we return the value because we want the value of the key here and at the end we have the put method which is a void method and it takes key and value as the parameters so first of all we want to check that if the given key is already existed in the uh in the double linked list so that's why we get uh that note with the given key to check that so if that no node is null that means we do not have any node with that key with that given key in the linked list we just make a new node and then assign the given key and value to that node then we put that node uh to our cache to our lru cache and we also call the add note 2 add it on our linked list then we increment the size this size shows the current size of the linked list so we want to compare the current size with the capacity that the linked list has in order to know that when we should uh evict the list recently used item from the list or cache so as you can see here uh we just compared the size with the com capacity and if the size is bigger than the capacity we just pop the tail which is our least recently used item in the uh cache and we remove that tail with the key of that tail and we also decrease the current size of the cache and here this else is for this if so th this shows that uh this shows that the given key has already existed in our length list so in this case we have to just update the value of the key so in this case we just set the new value of that node and then we move it to the head because that item is our most recently used item now and it should be at the beginning of our list so i hope you understood this code now that we have analyzed code and data structure uh let's talk about the time and space complexity so as we talked before and as the question asked us the time complexity of this data structure and this lru cache for get and put and eviction is one and the space complexity is o n because we have to keep all the notes for example uh consider this is our linked list we have to keep all the nodes are the linked list in our memory so the space complexity would be an order of n now that we understood the code and the data structure let's submit our code in lead code and see how it works so ah let me hit submit so as you can see my last submissions shows that our code is accepted and let's see the details of our code in the analysis page so based on this graph uh our run time beats about 95 percent of java submissions and our memory also uh bits uh about 43 percentage of java submissions and our code also uh has passed 18 test cases out of 18 and our run time was 12 milliseconds and our memory usage is about 47 megabytes i hope you found this video helpful also if you like our videos consider subscribing and sharing it with your friends so we can help more software engineers to be prepared for their interviews | LRU Cache | lru-cache | Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`. | null | Hash Table,Linked List,Design,Doubly-Linked List | Medium | 460,588,604,1903 |
1,423 | hello guys welcome to algorithms made easy my name is rajat and today we will be discussing the question maximum points you can obtain from cards in this question we are given several cards arranged in a row and each card has an associated number of points the points are given in the integer array in one step we can take one card from the beginning or from the end of the row and you have to take exactly k cards your score is the sum of the points of the cards you have taken so we need to return the maximum score that we can obtain in the first example we can see that the k is equals to 3 so we can take three cards from the end and hence the output will be maximum 12 and similarly in the rest of the examples so now let's first try to understand what this question is about and how we can solve it so suppose this is the input error given to us and the k is equals to 3 that means we need to select exactly three cards from this array starting from either from the beginning or from the end in order to make the maximum sum so as we know that in this case the maximum sum is if we take the cards starting from the end that will make the sum is equals to 12 which is the maximum that we can make by picking up three cards with the given conditions now let's change one of the values that is the value at zeroth index becomes 10. now in this case what will be the answer in this case we need to pick one card from the beginning and two cards from the end in order to make a maximum sum of 17 with these two examples you must be clear with what the question is about and how we need to proceed further now let's take the two examples that we discussed side by side and find out what are the similarities between the two examples the length of the two array are the same the k is the same for them but not the result as the one value at the start of this array has been changed to a much higher value which changes the result the number of cards picked from the two arrays are the same which is equals to k which is three and so are the number of cards which are not pegged from this array so here the main intuition is what we can use of these unused or unpacked cards that we can get the result of the pegged cards so the number of non-pegged cards so the number of non-pegged cards so the number of non-pegged cards in these two arrays are equals to 4 which can be found out by 7 minus 3 is 4 where 7 is the total length of the array 3 is the k so n minus k is 4 in this case now we can find out the total sum of the array at the top is equal to 31 and if we find out the maximum point that we can get from this array it will be equal to 31 minus 14 which is 17 where 14 is the sum of the non-pegged cards is the sum of the non-pegged cards is the sum of the non-pegged cards 31 being the sum of the total number of cards when we apply the same logic on the below array as well we get the same result that is the total sum is 22 max point will be 12 which is 22 minus 10 being the sum of the unpicked cards and by the condition given with the problem we can see that these unpicked cards will be in a contiguous sequence so we need to find a contiguous sub array in this array which gives us a minimum sum this sub array should be of length n minus k we can subtract that value from the total sum and get the maximum sum that we can get by picking up exactly k cards so now it's time to code this particular approach so as discussed we need to find out the sum of this whole array so we will have a sum variable so let's first find out that so we have the sum with us now we need to find out the result so we will have this answer variable which will initially be 0 and then we need the sum of the window n minus k so we will name that variable as window and we will have that as 0 initially so we'll declare a variable n which will be the length of the card points array so now in the example as we know that the window will be of length 4. we will first find out from the 0th index n minus k minus 1 that is in this case length of 3 which we will store in a temporary sum so we'll code this wherein we'll start from the 0th index till n minus k minus 1 incrementing this sum of window so once we have this temporary sum which in this case will be initially 50 we need to make this window equals to n minus k length that is 4 so we will add one more value this will be in a next loop we will add this value make this value as 19 the temporary sum and now we need to find out what will be the sum of the remaining values and we will take that into the answer which is equals to the maximum of the answer and the total sum minus sum of n minus k window which comes out to be 12 in this case once we have find out this max value we need to again shorten up this window so that we can at the next iteration add one more value so we will shorten up by removing the starting index value from this temporary sum making it now 9 and then we again add the value find out the answer which is the maximum which now becomes 17 and again remove the value from the start so now let's write that so we now we will start off from the index from where we left that is n minus k minus 1 going till the last index we need to add the value in this window to make it equal to length n minus k now we'll find out the maximum which will be max of the answer and total sum minus the window and now we need to shorten up this window by subtracting the value at the start index of this window and that will be i minus n minus k minus 1 at the end we just need to return the answer now there can be condition where n and k are both equal in that case we need not to perform any logic and we can directly return sum in that case so if n is equals to k we can return sum directly as we are picking up all the cards present in this array this completes the coding part now let's try to run this code for all the sample test cases so it runs successfully let's submit this so it got submitted successfully the time complexity is often well the space complexity is all fun do let us know your thoughts in the comments below thanks for watching this video see in the next one | Maximum Points You Can Obtain from Cards | maximum-number-of-occurrences-of-a-substring | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array `cardPoints` and the integer `k`, return the _maximum score_ you can obtain.
**Example 1:**
**Input:** cardPoints = \[1,2,3,4,5,6,1\], k = 3
**Output:** 12
**Explanation:** After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
**Example 2:**
**Input:** cardPoints = \[2,2,2\], k = 2
**Output:** 4
**Explanation:** Regardless of which two cards you take, your score will always be 4.
**Example 3:**
**Input:** cardPoints = \[9,7,7,9,7,7,9\], k = 7
**Output:** 55
**Explanation:** You have to take all the cards. Your score is the sum of points of all cards.
**Constraints:**
* `1 <= cardPoints.length <= 105`
* `1 <= cardPoints[i] <= 104`
* `1 <= k <= cardPoints.length`
1\. The number of unique characters in the substring must not exceed k. 2. The substring must not contain more than one instance of the same character. 3. The length of the substring must not exceed the length of the original string. | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. | Hash Table,String,Sliding Window | Medium | null |
125 | everyone how are you today we are going to solve problem number 125 which is valid palindrome so what they are asking is you have to find a valid palindrome now what is a palindrome is something when you reverse a string the string remains same for example ABA so if you reverse this string it is same and now this right so in this case there is one small trick and they were saying you have to only consider alphanumeric characters so it means they are going to pass you commas and other thing may be like something like this right so you what you have to do is you have to ignore those things and the other thing you have to do is you have to convert this into lowercase first so let's start coding so let me zoom in okay so the first thing is what we will do is we will convert this into lowercase now we what we will do is we will use a regular expression to convert this into to only consider alphanumeric characters so s is equal to re dotsub and then what will be of a regular expression it will be a to z and 0 to 9 but and then what we are doing we are actually replacing it with null and this is our strength and here we have to say if something which is not equal to a to 0 to 9 replace it with blank that's it now in this case for valid palindrome we are going to learn one trick that trinket trick is a two pointer so in most of the problems sometimes you have to create two pointer to solve the problem so here that's the case right so what we will do is one way to do this is what you can do is you can take this string and say s is equal to s minus 1 if this is equal to then it is a valid pair at all otherwise your written false but interviewer will not be happy with it so what you have to use a two-pointer approach you have to use a two-pointer approach you have to use a two-pointer approach one is and what you do is declare left is equal to zero and then right is equal to length of s minus one and then we will check if left is greater than is less than right so here what you are doing is we are having two pointers when is left one is right and then we will start shifting so if this is equal to this then we'll shift both the point is left to increment and right to - well left to increment and right to - well left to increment and right to - well right so what will be our process is left plus one and right minus equal to one now before this what we will do is we'll check if s is left is not equal to s of right then we will return false else at the end you will return true now back and then run this see this is successful and submit it this is successful faster than ninety nine point five percentage and now what is the complexity of this algorithm is Big O of n because we are just scanning that array once it is actually n by two because you are trying to squeeze it from the both the directions and by sometime you will reach half it is n by two which is equal to O of n thank you guys if you like my channel please like and subscribe thank you so much | Valid Palindrome | valid-palindrome | A phrase is a **palindrome** if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
Given a string `s`, return `true` _if it is a **palindrome**, or_ `false` _otherwise_.
**Example 1:**
**Input:** s = "A man, a plan, a canal: Panama "
**Output:** true
**Explanation:** "amanaplanacanalpanama " is a palindrome.
**Example 2:**
**Input:** s = "race a car "
**Output:** false
**Explanation:** "raceacar " is not a palindrome.
**Example 3:**
**Input:** s = " "
**Output:** true
**Explanation:** s is an empty string " " after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.
**Constraints:**
* `1 <= s.length <= 2 * 105`
* `s` consists only of printable ASCII characters. | null | Two Pointers,String | Easy | 234,680,2130,2231 |
342 | hey everyone today we are going to solve theal question power all four okay I think we can solve this question with bitwise operation like this so this is a one time but in real interviews I've never seen someone who solved the question with bitwise operations so I'll show you another way instead of bitwise operation I think each programming language has like a mass log function so we use it so for example python has mass log and this number should be n and this question is power four so that's why I put four here so this function calculates a logarithm of n to the base four so for example 164 should be 2.0 so four so for example 164 should be 2.0 so four so for example 164 should be 2.0 so we will get the answer with like a float so 15 and four is 1.93 95344 1.93 95344 1.93 95344 something and uh simply if the decimal part is zero so we can return through right if not like a 1.53 right if not like a 1.53 right if not like a 1.53 44 um we should return false right and to check the decimal part so we can so in Python we have is integer function so we can use that yeah so that is a basic idea to solve this question so with that being said let's get into the code okay so let's write the code coding is very easy so first of all if n is less than or equal zero in that case we can immediately return false and then return Mass do log and put n here and four is integer yeah I think that's it so let me submit it yeah looks good and the time complexity of this solution should be order of log n and the space complexity is o1 and uh in this solution we use a building function so I'm not sure we can use the building function in real interview just ask interviewer so if you cannot use a building function um you can write a code like this so I'll show you how okay let's write so code without aing function if n is less than or equal zero we can immedately false if n equal one we caned return true if not the case while n is greater than one we continue iteration and uh if it's not a multiple of four we can return false so if n divide four is not equal zero in that case we should return done false if not the case so divide by four so n SL equal four and then we should true yeah that's it so let me sub it yeah looks good and the time complexity and the space complexity is the same time is order of log n and the space is o1 yeah that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question | Power of Four | power-of-four | Given an integer `n`, return _`true` if it is a power of four. Otherwise, return `false`_.
An integer `n` is a power of four, if there exists an integer `x` such that `n == 4x`.
**Example 1:**
**Input:** n = 16
**Output:** true
**Example 2:**
**Input:** n = 5
**Output:** false
**Example 3:**
**Input:** n = 1
**Output:** true
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion? | null | Math,Bit Manipulation,Recursion | Easy | 231,326 |
1,025 | hello everyone welcome back again to Li Kui today we're here with a very interesting problem called de visa game this problem is very famous in companies such as Google and Microsoft so we will be going through a series of solution solving this problem initially we will start with a simple naive recursive problem then we will try to convert that into our dynamic programming problem which will be solving the problem in Big O of n square so from exponential we will be going to Big O of n square using dynamic programming and then using dynamic programming we will try to optimize this from n Square to n raised to the power 3 by 2 and then finally we will move on to the trick part which is Big O of 1 solution to the problem so please watch the complete video and let us type into the problem it is given that there are 2 players Alice and Bob which are playing a game so they're given a number and initially and that number could be replaced by another number X which could be greater than 0 and smaller than n at the same time it should divide n completely so we can replace the number n with another number that is n minus X so each player take turns alternately and then else in studying the game first it is Ellis studying the game she is going to play optimally and then the turn will be passed on to Papa now Bob will make the same move and he will also play optimally this way we have to tell that well whether Ellis can win the game or not let's try to implement this using recursion as we don't know anything about mathematics yet so we will move on to that but now we are solving this using dynamic programming for that we need a recursive solution now it is also given that if a player cannot make a move then that player loses the game what do you mean by a player cannot make a move so making a move means choosing a number X that is greater than 0 and smaller than N and that divides n completely so there is always the possibility of choosing one because one divides any number but if n is given to be 1 that means that we cannot choose one so the number should be greater than zero and it should be smaller than one so that means there is no such number which we can choose so if the number is one that means that we are stuck and we will lose the game in all the other cases we have possibility of choosing certain numbers we are going to choose them each so we will see that if we choose I is equals to one then I we will choose from one to N and I plus now if we choose I is equals to one and it leads the current player to win so if this is the case and it is leading us to win then we are going to choose this if it is not leading us to n then we will go for another possibility and try with that so this is what we mean by playing optimally we will go to each of the possibility that we have in our hand and we will go forward with that possibility we will lead us to win the game eventually so a player X winning the game means that the player Y should lose the game let me explain that so if we can choose this particular I we can only choose this when it is dividing the given number n so if we can choose this and if the next player is going to get this n minus I as the number which is on board now if the next player loses the game with n minus I that means that we are winning the game in another terms we have n with us and let's say we choose a particular I now the next number with that we are going to write on the board instead of n is n minus I this n minus I will be given to the next player so that's what we are doing here in case this turns out to be true that means the next player is winning once he's getting n minus I he is going to win the game we will obviously not go for this option so in that case we will keep iterating through the for loop and we will search for that possibility that makes the next we lose the game and then we will go on with that one in case we are not able to find any of the possibility well choo makes the next player lose the game then we are going to return zero this is the recursive solution let us try to run this on certain test cases return help of M okay it is working fine now what do they expect from the solution of the slide is going to give us time limit exceeded so let's not wait for that I know that it is going to give us T le what I will do I will make al DP of size-10 one do I will make al DP of size-10 one do I will make al DP of size-10 one see we got T le now what I'm taking one zero one is because the N is given to be thousand there's repetition in this problem so if you want to see repetition let us take an example to prove that as well let's say the number is eight so one is a possibility that we can choose then two then four and then eight is not an option so these are the three possibilities this will give then the okay this was the player one playing the game now the player two will play the game and he will get seven because 8 minus 1 is 7 then he will get 6 and then he will get 4 know this now second player was 7 he can choose I think he can only choose one so he will give it 6 ok no another option now 6 we will be able to choose 1 2 & 3 so 6 minus 1 is 5 able to choose 1 2 & 3 so 6 minus 1 is 5 able to choose 1 2 & 3 so 6 minus 1 is 5 then another option 6 minus 2 is 4 then another option is 3 now this 4 I don't think we have to go further because you already see repetition for over here four over here six over here and 6 over here so once we calculated 6 using this one why should we go and calculate 6 using the same steps here so that will be a waste of time that's why we are they are cashing these we are using dynamic programming for this so I am going to initialize my DP array with minus 1 memset DP minus 1 sighs of TP if DP of I is not calculated it should be DP of n if it is calculated then we have to return DP of n we won't be calculating this again if it is not calculated we are going to calculate this and then store it yeah now let us try to run this it will give us the answer but it is still not fast enough there's a slight optimization that we can do we know that the factors that we are calculating here we are actually reversing from 1 to N and we are checking for each number whether it is a factor of n or not so instead of doing that we can simply search for the factors now how can we know the factors of a number the factors there's always a property that they follow let's say the number is 16 the factor of 16 is 1 so 16 multiplied by 1 is equals to 16 then 2 multiplied by 8 is equals to 16 4 x 4 is equals to 16 after 4 you won't find anything so you don't have to go beyond 4 if we say let's calculate this for 8 so 1 into 8 is equals to 8 2 into 4 is equals to 8 then you won't get anything after that you will simply get 4 into 2 and then 8 into 1 so that is same and here also you will get 8 into 2 and then 16 into 1 so that is again the same thing so we have to run the loop from I is equals to 1 I is smaller than under root of n is smaller than equals 2 under root of n so this is what we are supposed to do we are going only till 4 when n is 16 we are only going till 2 when n is 8 so instead of here running the entire n loop Oh ever oh of n loop we are running Big O of under root n loop so this is the optimization from I is equals to 1 I instead of root and I am doing I into I there is the same thing I into I is more than equals to n I plus now if this is the case then there will be two factors so the first factor is the number the second is n divided by the number so let's say the I is 2 so I will be dividing to one factor is 2 the other factor will be n divided by 2 will be 16 divided by 2 which is 8 so these are the two factors and we will have to check for each of them if help of n minus n divided by I if this is 0 then we have to return DP of n is equals to 1 now we will try to run this so our solution went from exponential to n square from n square to 2 wrong answer let us see why the answer is wrong icicles t 1 is smaller than equals to M it is giving us true or something that is false okay I got this because we should not choose n so when n when I was one when I was equals to one the other fact that we get is n divided by I which is equals to 16 so we should not choose 16 because it is not allowed so this is only possible when I is not equals to one let me try this forward three there's some difficulty in balancing the parentheses now I should give us the correct answer so we went from exponential to n square from n square to n raised to the power three by two and it is the fastest that we can get using dynamic programming now I'm going to show you another tricky part instead of doing any of these things there is a very simple solution to this problem you just have to return and modulus 2 is equals to 0 yeah in you're done with this so this is what most of the integers are looking for but you should be able to explain that why is this thing working now let us move on to the explanation part of this first of all what do you mean by just writing and modulus 2 is equals to 0 this will return us true in case n is equals to even number this will return us a 0 or false when n is odd number so we are saying that Ellis which is playing the game first is going to win if n is even he's going to lose the game when n is odd how can we prove this first of all let us see when Ellis is having the number as 1 and n is equals to 1 and Ellison starting the game so Ellis will lose because there's no possibility to further move from 1 now let us move to the next thing when n is equals to 2 now when else is starting with n is equals to 2 what else can do Ellis can simply subtract one from this and then she will pass on 2 minus 1 that is 1 to Bob and then what will lose the game so Ellis being clever she is playing the game optimally and she will subtract 1 from 2 and then she'll pass on 1 and then what will lose the game so Ellis is going to win so having a number n is equals to three the only possibility that we have of choosing X is 1 because we cannot choose two we had 1 & 2 as options and the only factor is 1 & 2 as options and the only factor is 1 & 2 as options and the only factor is 1 so we will be able to choose only one and then we will subtract 1 from 3 that will give us 2 & 2 will be passed on to will give us 2 & 2 will be passed on to will give us 2 & 2 will be passed on to Bob using 2 Bob is going to win the game that will make us lose the game again then we have n is equals to whole Ellis is very clever and she is going to subtract 1 from this and she will pass 3 to Bob now using 3 Bob is going to lose so LS win-win if we have 5 n is equal to so LS win-win if we have 5 n is equal to so LS win-win if we have 5 n is equal to 5 the options are again the option is again only 1 so it will be a loss now let's say we have any odd number for that matter we will be able to get its factors or numbers only because the factors of odd is only odd it will either be 1 or 3 or 5 so these are the only factors which are possible for any odd number there will be no even factor for an odd number now if we subtract and old from odd that will give us the resultant number to be an even number and we already saw that using an even number we will always win the game so using an odd number we are always going to lose the game so this is the conclusion using this induction that is why we can simply write if n is even then LS will be in the game if n is odd then LS is going to lose the game comment down below what kind of videos do you want in future and if you want some lectures of specific topics then please comment them down below another series which I am thinking of is related to mathematics there I will discuss the bit manipulation and then certain problems related to bit manipulation this is a very trending interview topic bit manipulation and it is very easy to solve certain problems using bit manipulations so if you have any suggestions as to how should I make these videos and what are the topics that I should cover up in the upcoming videos or do you want anything related to comparative programming please just comment down below whatever you feel like and don't forget to leave a thumbs up thank you | Divisor Game | minimum-cost-for-tickets | Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number `n` on the chalkboard. On each player's turn, that player makes a move consisting of:
* Choosing any `x` with `0 < x < n` and `n % x == 0`.
* Replacing the number `n` on the chalkboard with `n - x`.
Also, if a player cannot make a move, they lose the game.
Return `true` _if and only if Alice wins the game, assuming both players play optimally_.
**Example 1:**
**Input:** n = 2
**Output:** true
**Explanation:** Alice chooses 1, and Bob has no more moves.
**Example 2:**
**Input:** n = 3
**Output:** false
**Explanation:** Alice chooses 1, Bob chooses 1, and Alice has no more moves.
**Constraints:**
* `1 <= n <= 1000` | null | Array,Dynamic Programming | Medium | 322 |
1,482 | hello hi everyone loot do it president pimi numbers elements of porn of oo loot it is the garden and number aadhaar number of dangers lu 2012 novel in two and objective sarat2 bane 550 two To to a significant boiled only then at once first class 10th explain this question to you with the help of Punjab new that you understand it in a good way in Sapna wa hai who is the battle in which is the number base number of lemon juice Where is Ishwari mu seventh day ago phone please betu blouse requested reduce recovery and thank you who is back to you flowers and construct purva Haridwar and destroy can do is third goal Kunthu half-half flowers flower third goal Kunthu half-half flowers flower third goal Kunthu half-half flowers flower show a week And use this nagaur lift Ravana turn off the number and I am the answer hai net speed hai andar ke us bad news in hindi question and finally Bigg Boss come back 12345 all disawar news room aa and lu torch light testing made hair cutting Also the answer is not getting back side New Delhi white poll is in ours so let's make of functions forget bullets in which article on twitter and an am the that I would you I love you I invented given checking in the number Of flowers operator pimples pe karna hai 20 sec is the biggest vid oo Bluetooth settings pe remedy hai ki accept the video ki sadhu app Taken to variables in love and England in love and var in terminal element ko hu is equal to left side To Android Mirch Ek Is Condition Is Android User Hai Jhaloo He Got A Satisfied And I Will Give The Results Admit Th And Anshu Boys Withdrawal Pipe With U K Pimps Declares - World Aishwarya K Pimps Declares - World Aishwarya K Pimps Declares - World Aishwarya Power To Do The Guide That Is Bloomed Time Third Point Mintu K Also a i will return - 110 test ranking mein i will return - 110 test ranking mein i will return - 110 test ranking mein that file is pimple complete a new this minute live video ko kahan ho yaar checking available pimple away 8.1 kahan ho yaar checking available pimple away 8.1 kahan ho yaar checking available pimple away 8.1 urgent a that this period already blue that addison volume come will do made - 1the that addison volume come will do made - 1the that addison volume come will do made - 1the pizza 1212 Bread Paneer Vidyalaya Result Hello Friend Kapoor Was Interactive Way That Reddy Submitted To Loot Aishwarya Logic For This Program Will Destroy All | Minimum Number of Days to Make m Bouquets | how-many-numbers-are-smaller-than-the-current-number | You are given an integer array `bloomDay`, an integer `m` and an integer `k`.
You want to make `m` bouquets. To make a bouquet, you need to use `k` **adjacent flowers** from the garden.
The garden consists of `n` flowers, the `ith` flower will bloom in the `bloomDay[i]` and then can be used in **exactly one** bouquet.
Return _the minimum number of days you need to wait to be able to make_ `m` _bouquets from the garden_. If it is impossible to make m bouquets return `-1`.
**Example 1:**
**Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 1
**Output:** 3
**Explanation:** Let us see what happened in the first three days. x means flower bloomed and \_ means flower did not bloom in the garden.
We need 3 bouquets each should contain 1 flower.
After day 1: \[x, \_, \_, \_, \_\] // we can only make one bouquet.
After day 2: \[x, \_, \_, \_, x\] // we can only make two bouquets.
After day 3: \[x, \_, x, \_, x\] // we can make 3 bouquets. The answer is 3.
**Example 2:**
**Input:** bloomDay = \[1,10,3,10,2\], m = 3, k = 2
**Output:** -1
**Explanation:** We need 3 bouquets each has 2 flowers, that means we need 6 flowers. We only have 5 flowers so it is impossible to get the needed bouquets and we return -1.
**Example 3:**
**Input:** bloomDay = \[7,7,7,7,12,7,7\], m = 2, k = 3
**Output:** 12
**Explanation:** We need 2 bouquets each should have 3 flowers.
Here is the garden after the 7 and 12 days:
After day 7: \[x, x, x, x, \_, x, x\]
We can make one bouquet of the first three flowers that bloomed. We cannot make another bouquet from the last three flowers that bloomed because they are not adjacent.
After day 12: \[x, x, x, x, x, x, x\]
It is obvious that we can make two bouquets in different ways.
**Constraints:**
* `bloomDay.length == n`
* `1 <= n <= 105`
* `1 <= bloomDay[i] <= 109`
* `1 <= m <= 106`
* `1 <= k <= n` | Brute force for each array element. In order to improve the time complexity, we can sort the array and get the answer for each array element. | Array,Hash Table,Sorting,Counting | Easy | 315 |
456 | To Ajay, when you go to ribbon and decide compounding, today we are going to ask this question 132 patterns, what to do on 21, you will get a number in this question, you have to identify whether there is 132 pattern on it or not, if there is 132 pattern on it. If it is on this one, then you simply make a different one. If there is no 132 pattern, then simply print it in the office. There is no requirement. Okay, so let's see what 132 pattern is in reality. So this is the age for the basic. Three indexing on the face. It must have come from the opposite side and that you cannot use love induction twice, all three will be having different indexing, the first one gets it done, the second one goes and the third one goes, so their value is only in these days, if I make a comparison, the value I think on these three is fundamental. It should be okay, this industry value should be large, I am not talking about robbers, only these three are speaking in comparison and that is the value of K, it should apply between small and large, it cannot be input, like on some media. Will it be completely different? What is the same? The smallest one will have a bigger valley than that, the meat one will have a bigger valley than that, the rectangle index of the largest one will be the smallest. This will be on the next minute of the day on the planet. Okay, so let's see some examples like if the rectangle index It is placed on induction, it is also placed on indexing, so the mit's rally should be applied between these two. Only one value is possible. If such a sequence is being formed on your face, then it is a graph 132 pattern. This is boiled 132 buttons. Let's take one more complex. Today's value is one. If the value is nine then the value of velvet can be this. Here it ranges from two to one art. If only you get it. You got 132 pattern, okay print it, if you do some test on voice calls and see it, if Rishi had given you some number like this, free wave and then exam, the first number three is here and the second number is here. That and the District Magistrate and Lee and then you apply here. In this case, if you want 132 pattern, then I think here, keep this in mind, here and on the day of tax, here this guy is the smallest, this guy is bar just and who This is the element that you get a lot of likes between them so this time you got 108 so let's do the blueprint again he got a sketch on this that if you had got the number - 152 hero that if you had got the number - 152 hero that if you had got the number - 152 hero that on this case Let's see smallest - 1023 that on this case Let's see smallest - 1023 that on this case Let's see smallest - 1023 likes here largest value is likes here so worker is two and zero is okay on this one if I wanted the alarm value of IJ smallest here you can say digestive here and which is There should be rally, this is also correct and zero is also correct - like between one to three. zero is also correct - like between one to three. zero is also correct - like between one to three. Okay, so you are getting 132 patterns on this too, so you will print it, you can also get another pattern in it like if you have I Just take it here, see bring it here, not only here you will get the website - not only here you will get the website - not only here you will get the website - one two and in between that one likes that the value is zero, it is correct, Indore is in the middle of the range, this is also correct, I see one more kiss. Let's say that if you had got 1234 if you had got these four balances, one is like here, you are free here and then there is no 132 pattern on this one, if you also take two, you take Greater Valley three, then next I will take these two. There is no laxity in the middle, it is okay if you take them instead and take them for higher cholesterol index, after this you should have liked it here, tight here, if you had liked it at this point, then it is between these two. But here is this phone which is even bigger than that, on this case you will print the false that if this or this case is tightened here on 11, then it came back down and this guy was there, he was doing both these wire activities. But I would have liked in this case, I would have got Pragyaan for the one, but I will not get the ticket, I have to see the confirmation, Taylor Swift elements can sleep, this repair and their range - can sleep, this repair and their range - can sleep, this repair and their range - Stand friend, positive from 9:00 and your Stand friend, positive from 9:00 and your Stand friend, positive from 9:00 and your point is so much, let's meet in the pollution piece. And let's see from the rights side, you can install it, so if it has a pimples solution which is but it is free and seven and some elements before that, Sote here, you have a solution, so this was that friend, keep it here and For complete, add it here and edit the complete here to point to a valid number. Now every time you can go and check that the numbers of I Labs name of fennel are this lace Ghanshyam fennel that if this is the desired condition, bread role play somewhere. If it does then you will get the sequence, okay I am basically saying that this is only a broom, it is sinking mode off and traveling, it is okay on all the brothers and it is a closed loop, it will do it every time, it will go to the next one and that. From the start again till the end, the entire pending will be kept, so as for all the values, K is going to complete the journey and K itself is this closed loop of end travel, that too will be done by Android and whatever has come. That too off n ever element is going to travel, it is tight from here till the end, so this rough and cube of your becoming a complete professor and becoming a senior leader is fine, but even if you make a little bit of batter in it, then turn this Bluetooth off n you po. How can you solve Mains paper? Look, you kept this here, your 1st year ahead, did any element not match with you on the sequence, meaning the elements that came are 3D and this camphor in oil is fine in between. No one is lining up the element in me, right now you did not get the crop this time, then what did you do against me, what did you do for Sawan by taking it forward, there are no one for four, you did not get any for the seven, it is late, now it is 80. Now there is no element available, even for 80 there is no proper value of velvet here, what are you going to do next time, after checking all your things, after this you will come one step ahead and ignorance is a force which You will do this and at this length and here you are going to start intake, then 600 is the big value, look behind you and 600 is the value, you did not get any limit on this amount, now if you look for promotion from the side, then you will not get the office in your range, that is why the range was reduced. It is okay that you can ask us about this, how can we save this oil, the villagers kept it on the value of their Jab ab aayi and here they did their stomach full, take the poem clear smallest meaning that it was as if it was here that if here Also, before that person who will make your range the biggest, that is, if you want to find it from the confirmed side in this case, then there will be a rally here, he should keep the medium before him, it is okay, your range will also become the maximum and For here tiriya goes right that you move once ahead here later post here there would be another number that would have been checked for your stomach by bittu and after that one who see now at 8:00 the 8:00 the 8:00 the value is your basically If only this one was checked first on these three, then what can we do? Instead of these three, if only one child is used, then it would be sufficient, that is, we have to find a number which is less than 8. It may be small but read two and one of these three messages and Range. The biggest change will be in that one. Instead of writing these three, if you check only with one then that will become your work, for this you have to take the minimum of the previous one and Then here we have to point out by keeping the minimum, the value of K is an event scientist, so this solution depends on what you are keeping and whether you are keeping it completely straight, whatever is the minimum to take pride, you will get it on one. We will get obscene, we ticket was extra, we are just creating layers in it and whatever inductive that factory will come, at minimum this solution will be square and square but again a complete solution is any batter we can do so much, how will we do it okay if You have been given some elements like ABCD, some such elements have been given to you, now see, let's do it exactly, if you have kept it at your place, then this number of cashews was minimum, you will get it on the phone, okay, what do you have to do in the front, what do you have to do in front, so many. You have to be reminded on the day of the range, subscribe this quarter inch, this condition and minimum balance should be bigger and the win should become smaller than the element, it is okay that this is the work of fitting the element on the range, it should be done by the use of trees and What the data structure basically does is now he has some elements so this time if I had given him add pipe 738 all the elements if I ask him man give me just the highest value from the pipe that is just values bigger than five his The pass that is just values bigger than five his The pass that is just values bigger than five his The pass available is 72, it finds it, using it, we would have just asked for a higher value than the minimum, if that So you have to know for another value like this is this person did that, this tenant do this here, jack that there and then repeat the same process in the game, this is the case, okay, the bottom side is to bring you a higher value for the basic. Takes the time of log-off end and some of the complete Takes the time of log-off end and some of the complete Takes the time of log-off end and some of the complete position that you take the log off 10th time for this injection and this itself which can travel on the pan element then you get this complete solution possible on add of n. That would be fine, but again, with this we can select two off n. Okay, so let's see the solution for the one. How to do this, logic loot, assume that you have got some numbers ABCD till date, you would have got some such numbers, if you are in this You will be working for the guy, Swami. For the value, assume that you got the minimum of this range. This is the minimum value from the pilot. If five, when would this be such a big value and that is the current value train. There is no requirement for you to check this entire range for everyone. Let's take it from someone to do the requirement. You checked the DJ, here you got a gift. Four, okay, this is smaller than your minimum. Ko Minimum Devi is small closed, now what will you do if you get it free from your side, if it is small then the minimum set up will be smaller and tight, due to this you are required to check now, there was no requirement to check with Pisces, after this if and Reddy post 210 or any negative value, whatever is smaller than this one, here you have to skip all of them, okay, there is no requirement to check with a small earth element now, you have to check off first. Properties of T and then ignore this model. Okay, if I ignore this model, then it is possible that if I make this person a husband, then it is possible that after this you will get a value of mine and it is not smaller than three. Rather, this value is bigger but again this is still your minimum system and so what will you do, again you will skip it, you have checked it, now you will move it to the bigger one, okay what if there are some more valley sleepers here and Let's say that the next value that I want is a validation, private, now here, if I had to get eight, the advisor's is smaller than the minimum, then this value is increased by the pipe from the minimum and it is also smaller than the winning value from your pen, so it is exactly Is it correct or do you have cancer, what did you do, skipped the minimum and only Greater Valley, all the ones on increasing order, checked it, steel, if this guy himself had later pores 11:00, it is not tension, had later pores 11:00, it is not tension, had later pores 11:00, it is not tension, okay, it has become bigger, what now? You will do this, here you got this big value, if you give a checking form here, then maybe from 11:00 onwards there is a small element which is 8th from 11:00 onwards there is a small element which is 8th from 11:00 onwards there is a small element which is 8th and there is AIDS and Cancer but what you are doing is ignoring these model elements. Ho, you are saving chatting on them, what could you have done to solve this, that whenever any element here, in this case, if the matching value of your winning person is big, then do not do the moral values after that, big, then do not do the moral values after that, big, then do not do the moral values after that, rather they Also chat its village to check here ok this could have been a solution what could be another solution 100 to solve this problem keep your j&k hydration at the station but to solve this problem keep your j&k hydration at the station but see here what will happen with it But before coming here, the value of this will come here. If you are traveling at Affair station, okay here Samrat is travelling, the value of this will come here before coming here. Here you will get 11:00 and you can check with this. At that get 11:00 and you can check with this. At that get 11:00 and you can check with this. At that time, if the minimum of this range is five, it will be from here to this range, the minimum pipe will be this will also be small and three two will be something like this, right, this one is closed, this is still this guy, this is still It is greater than your minimum, so I have seen that the point here was smaller than the left one, that is why it is greater and if you check the first guy, then you have found that your 11c is smaller tight, so if you change the direction to this. Do this, do some time travel and the greater element is only A, then chat on the bread element on the phone, then your problem will be solved, you are joining the tight and minimum, the work is done, how to do it on off one, see now. Okay, let's move the robbers forward, how to implement it, this is the work of checking the minimum, I had earlier explained the question on online stock pan, if you see it, then you will know how to achieve this, you will also know the reasoning behind it. Okay, you will get a link in the description or now we will not talk about how to do this question well, now we will do direct implementation in it. Okay, let's see how to implement it. Okay, and let's see on this test. How do we implement this, then it should be found basically in three ways, as I had seen earlier, the first is that you should tell the minimum, okay, we know how to calculate the prefix minimum and make the call. The second thing we did was that the alteration that should be done is The last thing that should be done on this website was just to check Yo Greater elements, there is a requirement of extract to maintain it, ok, what was the logic in this, coffee line stocks payment was explained in the previous, whatever elements you have to compare with. He will be present on the track itself. Okay, let's see, first of all, how will we remove the minimum traffic jam from here to here? Eminem's fort is 5mm. Next, v5 is the minimum. Look, I know the minimum from here to here. If you want to remove the affair from here to here, then one. Extra element has come, only I am okay, so I will compare the minimum of this range with this new element, then that Rota, that whole inch will be reduced from here, it is going to be of this category, fiber sheet is the comparison, this time also there are five minimums. The fiber tank version was five minimum, the powerful comparison was found to be the minimum, and the new one was tied on this, it was okay on these two lows, and the minimum and nine were done, and the minimum was three minimum in MP3, the photo was two minimum, that this is its business, our highest. What are you before that ₹2 Ghazi Actually if you What are you before that ₹2 Ghazi Actually if you What are you before that ₹2 Ghazi Actually if you should have come here and this should be here then go start from here, it is tight but for chatting on minimum greater element, we are required to work from here algorithm. Let's see, now it has turned around, there is no one in the surgical strike, so now it will not happen at any time, now before going, it will just put itself on the track that it will come here, this time it is Jatin, he is this So far the minimum is send three tracks, there is a sequence in it, the stomach is exactly number two, so check with this guy here that if it is greater than the minimum so far, then it is not greater, if it is smile, it is water, so I don't want it. Okay I also need to check the greater element for now it gets added inside and it will also move off the track and then the three which is there will add itself to the step here so that game dear sequence back. Now this guy from Nine who is there has handled himself with the minimum, seeing that this guy is Ismail, so there is no requirement for him, I also know what he did and added it and removed it with strike. Again now in this tag. There is no element left to check, all the guys in front, you are the one who has to be removed or it is less than the service against it, if it is complete, then no, what will you do, you will put something on the track yourself and 1 liter Now again what am I checking? The element that should come should be bigger than four. Earlier I saw that no is big and has increased but the current element is four, it is not small, this was also not my answer. She was subscribing to this channel but not doing anything. Okay, so what will she do from here? Before leaving, put yourself on this track. What is behind her? Now, how will she do? This is so far. The minimum is five so he needs a valley bigger than five, he is so stupid and even more ballooning, he is small, the force is required from the Greater Valley school, this raid will forgive him and throw him out from here, the next value for the Greater Valley is not what it was. This was a requirement for me to check with this, is it the same in the track or did I add it, has it increased from there, he saw, yes friend, he is bigger than you, okay, are you smaller than me? 90 is also smaller, so we have 132 patterns here. Got the induction that is the minimum index in here has a here show this current list and that's my steps Got these three loops which meh that is a valid 132 pattern sect so make it an incident if I in terms of algorithm If I write what all the things we have done that the tension of the prison should be the same - that the tension of the prison should be the same - that the tension of the prison should be the same - 120 This philosophy should be there, what do we do, all the elements which are smaller than my minimum, commit sin, so long as the tractor behind is small, it is It is equal to the minimum of so far, the minimum of I means that if it is here then the electricity bill will be more correct because this is a minimum of Jatin So any defense will have either a greater element left, meaning from my minimum, here the knowledge of your loved one's and say will first check for size and then check the clerk which is left or it is smaller than the current one, it means not only If it is such a small gift, we do not have to put aside our work. If it is not weak, then before going to maintain this track, we have to put the current element in the add track. Turn off the numbers. Okay, basically three pegs. This has to be done and this minimum one has to be created. Hey, you write in a good way, Jhal hua hai kuch na jhal, 9th, first account element will be received, here I have taken one and then you are asking them to receive it, Jhal that this Got the element understood, now I have to create a minimum, it will have prefix neem store, then main and the size will also be N on it, this 90 phone number will become a shop gang and will work for the future, looper jhal hua tha, jhal became a team. Now a pack that Ajay's hydration egg will start from minus one and will go to the ends that this is basically three mustards here, first of all the size of this track should be big and the dip pick of the track is placed, if it is small then it is equal. So far, the minimum is the minimum, like remove that element from here, Lakshmi has been removed that now if practice remains an element and that element is increased by redaction, then the tax element is small, less ban phone numbers are off, this is mine. The answer is ready, okay let's find a slingshot that you will get the pension, others will start and stop their work, if the answer is not found then the current elements pack will go away, once you come and print this letter, okay then your algorithm. It has been completed. Let's run the compilation of Jhal. Every line number is 21 9th not found symbol that your name should be Sabzi. Okay, it is ready. Take it absolutely, my dear friend. If you have learned something from this video then do like it. Don't forget and if you have some other solution then do tell it in comment. Thanks for watching, see you Ajay in the next video. | 132 Pattern | 132-pattern | Given an array of `n` integers `nums`, a **132 pattern** is a subsequence of three integers `nums[i]`, `nums[j]` and `nums[k]` such that `i < j < k` and `nums[i] < nums[k] < nums[j]`.
Return `true` _if there is a **132 pattern** in_ `nums`_, otherwise, return_ `false`_._
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** false
**Explanation:** There is no 132 pattern in the sequence.
**Example 2:**
**Input:** nums = \[3,1,4,2\]
**Output:** true
**Explanation:** There is a 132 pattern in the sequence: \[1, 4, 2\].
**Example 3:**
**Input:** nums = \[-1,3,2,0\]
**Output:** true
**Explanation:** There are three 132 patterns in the sequence: \[-1, 3, 2\], \[-1, 3, 0\] and \[-1, 2, 0\].
**Constraints:**
* `n == nums.length`
* `1 <= n <= 2 * 105`
* `-109 <= nums[i] <= 109` | null | Array,Binary Search,Stack,Monotonic Stack,Ordered Set | Medium | null |
232 | this question asks you to implement a queue using stacks so let's make sure we understand the fundamentals before we start solving this a stack follows the lethal structure which is last in first out so if i have a stack it will look something like this and if i'm going to add values let's say i'm going to add a b and then c and then if i want to pop values i'll be popping them c b a because it's last in first out this is for a stack but if i'm implementing a q if i add a b c then if i'm going to pop the values or if i'm going to remove values then i will be removing a first then i'm going to be removing b first and then i'm going to finally be removing c first while in a stack it will be the opposite this will go first this will go second and this will go third so the question gives us the option of implementing a queue using only two stacks so we can take the hint that by using two of these we should be able to implement a queue using two stacks okay so if we want to append the value to a stack let's say s1 will be our main stack so i have a stack here and i do it with a closed button bottom sorry and i add the value a now that i've added the value a i want to add the next value b but if i add the value b on top and i pop b then a in a sense of a q should have been popped out first so let's say i've added b now and now i want to pop the value b i want to pop the value i in theory a should be popped and not b because in a queue it's first in first out does that make sense so what happens is with this usage of the second stack what i can do is i can add the values in the opposite way so if i have b i need to add b here what i can first do is pop the a add it to my second stack so it goes this way so now i have a here then i would add b and then i would add a back so if i would to call the pop function now a will be popped since it follows the logic of a stack so in a queue the first value that's been added in should be the first value out and since the stack can only add or remove values from the end i will use the second stack to pop out all the current values in s1 and then append the newest value then add back all the values from s2 to s1 perhaps this will be clear as i write the code so if i'm pushing here it will orbit arbitrary mean i'm going to append s1 i'm going to append x to s1 but if in our case if it's empty then we can simply add it here but what if we have a value a and i want to add the value b well the first thing i have to do is while s1 so while there are values there i want you to please pop up pop all the values out of there and these popped values i want you to append it to s2 so this value here is going to fly all the way and go into here so now that's empty and then b is gonna go in here so this is what this part does and then once we're finished with that while s2 has value so i think i should use self here while s2 has value pop out these value from s2 and append them back to s1 so what this function would do or sorry this while loop would do it's gonna add it the a back to s1 so now this will be like a q because a was the first value in and now a will be the first value out so if i want to call the pop function then it will be simply be return self dot s1 dot pop because now it follows the queue if i want a peak then again it would be simply this way and if it's not empty then simply check not self as one and this is how we solve it the only part that requires thinking is actually the push and it already gives you a nice hint use two stacks so you initiate two variables keep your s1 as normal your main one apply these mtp compulsive quite straightforward and you just need to understand this logic of the second stack where you pop out all the values store them in s2 append the new value and then return them back please let me know if you have any questions thank you for watching | Implement Queue using Stacks | implement-queue-using-stacks | Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
* `void push(int x)` Pushes element x to the back of the queue.
* `int pop()` Removes the element from the front of the queue and returns it.
* `int peek()` Returns the element at the front of the queue.
* `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
**Notes:**
* You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid.
* Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
**Example 1:**
**Input**
\[ "MyQueue ", "push ", "push ", "peek ", "pop ", "empty "\]
\[\[\], \[1\], \[2\], \[\], \[\], \[\]\]
**Output**
\[null, null, null, 1, 1, false\]
**Explanation**
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: \[1\]
myQueue.push(2); // queue is: \[1, 2\] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is \[2\]
myQueue.empty(); // return false
**Constraints:**
* `1 <= x <= 9`
* At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`.
* All the calls to `pop` and `peek` are valid.
**Follow-up:** Can you implement the queue such that each operation is **[amortized](https://en.wikipedia.org/wiki/Amortized_analysis)** `O(1)` time complexity? In other words, performing `n` operations will take overall `O(n)` time even if one of those operations may take longer. | null | Stack,Design,Queue | Easy | 225 |
113 | Hey Gas, today we will do question number 11 of our Bin Entry Play List Okay, some variations have been asked in Google like Path Sam Tu whatever is okay, this has been asked to the company till now Right here, today we are solving the question 'Sam Tu', the Right here, today we are solving the question 'Sam Tu', the Right here, today we are solving the question 'Sam Tu', the question is that from the root to the leaf, every leaf whose Sam is equal to 22 i.e. the target has to be every leaf whose Sam is equal to 22 i.e. the target has to be every leaf whose Sam is equal to 22 i.e. the target has to be returned. It should be live from the root to the leaf, but it is okay. I want everything, okay, so here there are many things from routes to live, okay, this is visible, then one is visible, four level, you have one answer, this is its SAM, let's see the flow on five, 5 + 49 + 11. 20 + flow on five, 5 + 49 + 11. 20 + flow on five, 5 + 49 + 11. 20 + 22 is equal to the correct targets. The second one is 5845813 + 417 plus five 22 is 5845813 + 417 plus five 22 is 5845813 + 417 plus five 22 is equal to the correct targets. So both of these will be our answer. Okay, so let 's see how we can solve this. So see, 's see how we can solve this. So see, 's see how we can solve this. So see, this is a long time ago for you. It comes from this that you can only travel from route to leave, neither do you write these orders nor will you write these orders, we will do it so that we can keep track of our SAM, what is our SAM, right now like here But now I am, Sam's value was zero in the beginning, now I am on five, I am on the route, Sam's value, please do it, I was zero and Ravi, what notes are there in the route's zero plus five, are there values, that too, so I will create a vector named temp and I will keep adding to it whatever notes I have got, I have also got five, okay and now my Sam is five, so let me go to the left side of five because I have written in this order. Okay, I came on four, so four is not my leaf product, so what happened to me here, it is 5 + 49, now I am on four, neither do I 5 + 49, now I am on four, neither do I 5 + 49, now I am on four, neither do I give a team to four, now I have covered fever four in myself. Now let me move ahead, I have got 11 so let's add 11 here first okay and Sam what will happen is 227 so this is our path which is 54117 this cannot be our result either we will back track means from recension. Let's go back. Okay, so this is it. Here it is. Let's go back to 11. We have explored the left side of 11. Now we will come to the right side of 11. Okay, what will be the value of Sam here? That can be one of my answers. 54112 is correct, that is my answer too, so let's add it. 54112 is right, we will go reverse from here, so we will remove it, so you are from here, okay and back to 11, laptop will do 13 + 136. Noida, is it 13 + 136. Noida, is it 13 + 136. Noida, is it equal to the target? It is equal to the target, so that means it will not be our answer. This path is mine, 5813, so I will not store it, so I will remove it first. Back track is going back from recension. If we are there, then 13's left hand right move has also been explored. Now we have gone back to 8. Okay, it is equal to the final product. If yes, then it means that the path that I have just made in the temp can be my answer, so I am I will store 584 and 5. Okay, so this is mine, I have stored it in the answer. Okay, now we will back track from here because there is nothing further in the five leaf note. We do not have anything else. So, when we do the black track, then five is also mine from here. Will go from the team and if we track back then go back like this Left side of the four Finished go to the right side of the hole Go to the right Got the van here Ok so added the van here Sam in the temp What happened to my 18 What and van If it is my leaf note then we will check whether it is equal to the target or not. If it is not equal to tight then it means it cannot be my answer. This is my path 5841. Ok, we will not add it, then we will backtrack. Reconciliation is over. Here we went back to 4th place, we have done lap 4th, so do the vapor barrier from here too, then go back from here also, we have come back near the route A, it is over and we have found our answer, it is okay here, we return. Will do OK, I hope you understand. Let's code it once. We will do the court exactly the way I told. We will take a variable named Sam, start it from zero and check it every time. We will check whether it is equal to the target. Ok and we will keep adding to the tempo, if it is equal to the target then we will store the tempo. If we do this then let's see the question once. Ok, what is there in this is that you will be given the root of the binary and a target path to send the result. What I told you about the meaning of root tulip path is that it is a paisa leaf which starts from the root and ends at the leaf note. Okay, so this is the example I told you. Okay, so let's code it exactly as I had explained. What was said that I will keep a current sam, we will store the result, okay and let us keep a vector named temp in which we Yadav will be storing each of our notes, in which we will be storing whatever note we are in. Here we will return it, the vector is taking its Sam, first let's add the value of the root in all, this is my lift Noida OK, now it is not like that, so remember what we say So all the answers. If we try to submit the example correctly then it has been submitted exactly as the code is written, it is ok and if there is any doubt, please race in the comment and try, help you gas video thank you | Path Sum II | path-sum-ii | Given the `root` of a binary tree and an integer `targetSum`, return _all **root-to-leaf** paths where the sum of the node values in the path equals_ `targetSum`_. Each path should be returned as a list of the node **values**, not node references_.
A **root-to-leaf** path is a path starting from the root and ending at any leaf node. A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,5,1\], targetSum = 22
**Output:** \[\[5,4,11,2\],\[5,8,4,5\]\]
**Explanation:** There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** \[\]
**Example 3:**
**Input:** root = \[1,2\], targetSum = 0
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000` | null | Backtracking,Tree,Depth-First Search,Binary Tree | Medium | 112,257,437,666,2217 |
149 | hello guys today we are moving through the question max point on a line from lead code in the given problem we have given an array consisting of end point for each point is represented by the intercept on the x axis and y axis as x and y and we have to return maximum number of point on any particular line if we match each of the point through every other of them so okay um let us move on the first example this is pretty much simple there are only three point if we match each point with every other of them then they form a single line so required answer in this case is three but in the second case if we match all the points to each other of them then there are two big cases let's suppose first cases is our required answer which consists of four points but in these cases and this one two and three total number of point is three if we form this type of line so required answer is maximum of d2 which is equal to 4 so our answer is 4 let us move through algorithm total number of points maybe lies from 1 to 300 so i think n square should be working fine simply we can do what is we can calculate total number of slope um from a particular point in each step and maximize our answer using this so without taking time let us try to code i int oh my caps lock is on okay and 10 equal to points dot size and try to iterate over to love i equal to zero to y less than and i plus and in each loop we maintain an unordered set an ordered map from a string to inch and let us take the name of this map as m1 okay and it through another loop for int j equal to i plus 1 to i j let n and j plus now let's suppose we find any duplicate okay this may be represented like this in the if points j and zero equal to once i zero okay once i zero and this means x coordinate are same and once j 1 equal to points i 1 once i one okay then in this case we find a duplicate so we maintain another variable naming duplicate so duplicate plus total number of duplicate maybe at least maybe not it is you that it is at least one and duplicate equal to one in each step if we find the required condition then increment our duplicate by one else we do what let's suppose end x equal to difference between these two so copy these two and take the difference and into y equal to difference between y coordinate of the two axis these two point okay so for simplification um we take gcd of these two into gcd of x comma y and we store these two in a variable naming gcd and we divide both of them by their gcd x y equal to g c t and y equal to g c d because you take our map of string types so we should do here something m1 of two string x okay plus this plus two string y uh and we increment the count okay so after execution of this second for loop we maintain our answer let's suppose in any case there are only duplicate version in our array no so our map becomes empty so we can handle this using answer equal to maximum of answer comma duplicate else we can do something for auto 18 our m1 answer equal to maximum of answer comma 80. second plus we can do we can add total number of duplicate okay and finally we can return our answer let me check uh if there any mistake present okay we have to initialize our answer by zero okay i 0 1 okay else we can do something like this m1 of plus yeah i think this will work fine let's run the code i don't think there should be any mistake but maybe oh compilation error we have to write points here okay got accepted try to submit actually i hadn't solved this question yet but let me check okay finally i got successor okay thank you guys thank you for watching our videos | Max Points on a Line | max-points-on-a-line | Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane, return _the maximum number of points that lie on the same straight line_.
**Example 1:**
**Input:** points = \[\[1,1\],\[2,2\],\[3,3\]\]
**Output:** 3
**Example 2:**
**Input:** points = \[\[1,1\],\[3,2\],\[5,3\],\[4,1\],\[2,3\],\[1,4\]\]
**Output:** 4
**Constraints:**
* `1 <= points.length <= 300`
* `points[i].length == 2`
* `-104 <= xi, yi <= 104`
* All the `points` are **unique**. | null | Array,Hash Table,Math,Geometry | Hard | 356,2287 |
328 | hey everyone welcome back to my channel before we get started don't forget to click the Subscribe button if you want more videos about coding interview so in this video we'll be solving the problem lead called odd ever linked list so let's get started so the problem is that they give us a singular linked list and they ask us to group all the odd nodes together followed by the even nodes so the tricky part in this question is that we are not talking about the value of the notes but we are talking about the node numbers for example the first note is considered odd and the second one is considered even and so on and also we must solve this problem with a constant space complexity of off one and a linear time complexity so let's say we have this input singly linked list so as we know from the details of the question the odd numbers start at the first node therefore we will point a variable called odd at the head of the linked list which is the first note also as we know that the second node are even node will Point another variable called even to the next node after the first one furthermore since we know that the second node will be the start of the even linked list we'll set another variable called even list that also point to the second node in the linked list and which will be the head of the evil linked lists at the end of the loop so the principle of this algorithm is to be able to rearrange the linked list by grouping the old nodes in the first half of the linked list and the even nodes in the second half of the linked list after that we're gonna Loop over the linked list by using the even pointer so at the first iteration we're gonna set the next pointer of the odd node to be pointed at the node after the even node which is in this example is the node with the value tree after that we will move the old variable or pointer to point at the next old node which have the value tree then we will set the even next pointer to be pointing at the next node after the new old node which have the value 5 and then we move the even pointer to point at the even next node which have the value of 5. so at the next iteration will repeat the same process by pointing the next pointer of the current odd node to be the next node after the even node which have the value 6 and then we're gonna move the odd pointer to the next node after that we set the next pointer or the even pointer to point at the next note after the odd node which have the value 4 and next we move the even pointer to be pointing at the next node with the value of 4. so at the last iteration we will move the next pointer of the current or to be pointed at the next note after the even node which have the value 7 and we move the odd pointer to be pointing at the node with the value 7. so after that we will set the even North will be pointing at the node after the current odd node which is the currently the end of the linked list so once we are at the end of the linked list and the even pointer is pointing to null we will break the loop and move to rearranging or group in the two linked list so we're gonna set the next pointer of the odd note to be pointing at the even list node which is the head of the evil linked list and that's how we're gonna group them in one linked list that have the half of old nodes and half of even notes so the time complexity for this solution is often since we are looping over the linked list once and the space complexities of one sense who are not allocating additional memory that's it guys so let's jump out code into solution so first we start by checking if the linked list is empty which are none or we return the empty linked list then we initialize the two pointers the first variable will be the odd variable and its value will be set to the head of the linked list then we set the second variable event to be pointing at the second node which is the node after the odd node after that we initialize the even list which will be the head of the evil linked list at the end of the loop and set his value to be the even note then we will Loop over the input linked list using the even node sole even and even dot next is not null we move the next puncher of the null of the old node to be pointing at the next node after the even note and after that we move the odd pointer to point at the next odd note then we move the next pointer of the even note to be punching at the node after the current odd node and the same thing that we did before for keep tracking of the odd node we move the even node to the next node so once they even not reach the end of the linked list we will group the two linked list by pointing the odd next pointer to the even less node which represent the head of the even half of notes finally we return the head of the linked list that's it guys thanks for watching see you in the next video | 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 |
66 | hello everyone so let us solve one more problem from lead code the problem name is plus one so the problem goes like this that you're given a large integer represented as an integer array digits where each digit i is the eighth digit to the integer now the digits i ordered from the most significant or least significant from the left to the right order we will understand more when we go down to the inputs and the large integer does not contain any leading zeros increment the number integer by one and return the resulting array of digits so let us take the same example go to the inputs as you can see that you are given a number actually in a form of an array that is one 123 as you can see so 123 is a number you're given as an array and you have to add 1 to it so the answer is 124 so you might be thinking that what is the actual problem like this is very simple just adding one to it but hold on this is not a complete number i suppose you got the thing this is not a complete number this is the number represented in the array form that is 123. so you have to print out the answer such that you have to print out the thinking that it is an actual complete number and just adding one to it what i mean by this is that's let's say that for this 123 the answer will become 124. for 4321 if you just add 1 to it will become 422 nothing more complicated but if you just take let's say 99 if you add one to it one number will be carry on and it will go out of bound and then you have to append it in the start like all together all new as you can see that it is nine so one is added it will become one zero so a new array will be formed so that one is a patent trend so this is the whole thing i will show you the actual uh what you can do here is that you are given some as you can see that is let's say 120 one two three nine what you can do is that if you just add one to it what you just have to keep in mind is what is the carry to the next number so you can just assume that how you actually add numbers that is the whole thing if you just take 123 if you add one to it what you'll do or let's say that if you have 129 if you just add one to it what you'll do you just add both of them it will become one carry is there so you have to keep in track what is the carry number and then it will become three and this will become one so this is one twenty one thirty so if you just add one to it then it will become zero and you have to carry one thing so you can just take some number that is scary okay and then what you can do is let's say the number is one two nine if you add one to it what will happen is that the carry is zero then you add one to it will become so what you will do the number will become ten now what is the number that will be put it here it is 10 mod 10 as you can see it becomes 0 so 0 is put it here and 10 divided by 10 is the number that is taken to the carry that is equal to 1 so one is added to the carry number so as you can see that is the same thing if you have 10 one is taken as the carry one means that 10 divided by 10 that is equal to 1 and what is in the remainder 10 mod 10 is in the remainder that is you so if you take this is the carry now the next number then the next digit actually is the digit so the number that will be placed here for this digit is actually your digit plus the carry okay so 9 plus the case so 9 plus the carry that is equal to 10 again so the number here will be zero and the number passed on is one again the number plus carry so two plus one so it will become three so you will do the same thing for every digit actually what is here so you will place here the modulus value and carry the dividing value so 10 mod like three mod 10 b will become three only so this is why three is there and the carry is three divide button that is zero which means that there is nothing to be carried upon and then as you can see that this is one plus zero as a carry it is only one the only thing that will become complicated is if there are multiple lines only so if you just add one thing it will become zero 0 and then a 1 will be added as an extra appended one so because the array size fixed you can either make a new complete array and just put one at the end and all the zeros or as the other thing is that what you can do here is that if you have a vector you can see that if you have vector of size let's say three you can only append a box in the vector at the end a block at the end not in the start so what you can do is that if you have let's say if you want to let's say make a number that is one zero and you have only three digits you can first append a block at the end and then like you can do that shift all the numbers by one position or actually just fill all of them by zero and then put the one number you can also do that whatever you like you can just push all the numbers to the left because you actually want one in the start that is the whole thing nothing more complicated i'll take you down to the code part it will make it more clear but this is a very simple number you just have to assume that the number itself is in the form of an array and how you do actually the summation of the numbers so this is a carry initially i marked my carry as one because carry means that i have to add that to the particular digit then what i'll do here is that i iterate from back to front because that is how we are doing this so the number is actually the digit the i the digit plus the k number now the i did it will become numbers of numbers actually that is like by adding the idea to carry number so i will actually mod it with 10 that is the number that will come to the ith position as well as the carry will be the nums divide button and it will i will be doing this for all the numbers in the end if after doing that my carry is still greater than 0 which means that it can happen that my carry in the end is 1 again so it is 99 i first one to the first number carry will be 1 i again add 1 to the next number carry will be 1. so i added 0 but there is one more carry that is left so in that case what i'll do is that i will push back a do in the end i and what i can do is i can like uh like shift all the numbers by one position to the left that is what i'm doing and the end i will add the carry to the start that is what i've done here and just printing out that is the overall solution for this problem nothing more complicated uh what i've done here is that in the end just shift out all the digits by one because i want to append the carry in the start and because the size of the vector is fixed i append it to the end shift all the digits by one and then like added the carry in the start because that is how you can do that just the brute force way nothing more complicated i hope you get the solution as the code for this problem the solution and the code will be in the description of this video so don't worry i will see you next one and thank you for watching this video till the end i will see you in the next one till i keep coding and 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 |
739 | hey everyone welcome back and let's write some more neat code today so today let's solve a problem daily temperatures we are just given an array of integers which represent temperatures and we want to return an array answer such that at every single position in answer it's going to be the same exact size as our temperatures array and at every single position in answer we want to know for the eighth day whatever the temperature was on the i day we want to find how many days did it take for us to find a temperature that was greater than the temperature on the eighth day so for example let's take a look at this uh temperatures array we can see there's eight values in the temperatures array and there's eight values in the output for each value in the temperatures array for example 73 how many days did it take us in this array to the right of 73 how many days did it take us to find a new temperature that was greater than 73 well on the exact next day we found 74 which is greater than 73 so it took us one day so in the first position we're going to return a 1. what about 74 how many days did it take us to find a new temperature that was greater than it 75 one day later right okay for 75 how many days did it take us 71 is not greater 69 is not greater 72 is not greater but 76 is greater and you can see that took about four days right so then we return a four in that position now there are some temperatures that never had a temperature greater than them look at these last two temperatures we had a 76 nothing to the right of 76 is greater than it and of course the last position 73 there's no temperatures to the right of it in the first place so nothing was greater than 73 to the right so for these ones we're gonna return a default value of zero so we're gonna build an output array now looking at the input what's the brute force way to do it of course we could do an n squared approach right like for every temperature we would look through the entire temperature array after it right and see okay how many days did it take us to find a temperature that was greater than this one right and then do the same thing for the next temperature over here look through the entire or i see you know what's the first day that we could find a greater temperature and keep doing that now that's going to be big o of n squared time complexity but there actually is an easier way to do this problem if we use some extra memory now let's just iterate through the input array once going to the right but we do need to know that for example we have to remember the previous temperatures that we looked at so if we you know let's say the previous temperature here was a 73 like in the input example and then the next temperature was a 74 when we get to this position we have to somehow remember what was the temperature that came before it right now obviously we could use a list for that or in this case a stack would be more intuitive because one thing we're going to notice is if we get a temperature greater than at 74 right then we're going to say okay what was our previous temperature 73 so this temperature is greater than it right so we can keep track of what index this occurred at and what index we're at right now and say okay the difference between these indexes was one right we clearly found a temperature the first temperature greater than the 73 so then what are we going to do from our stack well then we don't have to remember this anymore right we're going to say okay we're going to put a 1 in the output and we can pop this from our stack right so we're going to do stack.pop do stack.pop do stack.pop so this will be popped from the stack now when we get to a 75 the exact same thing is going to happen right clearly we see these temperatures are in increasing order so we see okay one day it took us to get r to get a temperature greater than this we'll put a one in the output pop this from the stack and if we just had increasing temperatures that would be really easy for us right but it's not always going to happen where we have increasing temperatures what happens if we had a 72 that came after it well we would look at the 72 and compare it to the top of the stack say okay this is not greater so we can't pop from the stack but we're also going to take this value and add it to the sec so now we're going to have two values inside of our stack and what happens if we got another smaller value 71 right so far for none of these values do they have a temperature to the right of them that's greater right so all three of these are going to be on the stack what are we noticing about our stack it's going to be in monotonic decreasing order right this is a type of stack problem that i have solved on this channel a couple times but this is more of a beginner friendly monotonic decreasing stack problem what this means is that our stack is going to be in decreasing order that's what monotonic means it's always in decreasing order now technically what if what happens if we got another 71 over here right well in that case 71 is not greater than this so all four of these would be on our stack currently right so it's technically not monotonic decreasing order it could be equal as well right we're noticing it's not strictly decreasing if two values are equal they're also going to go on the stack but if we got a greater value if i got to a 72 right what am i gonna do clearly 72 is greater than the top of our stack so i pop this one right but now we have a new value on the top of our stack this one is our 72 greater than this it's not so our stack is like this now we looked on our stack we took this guy out this is no longer in our stack but these three values are in our stack and still notice how the stack is still in monotonic decreasing order it's always going to be the case what happens if instead of a 72 i had a 73 then of course we'd still pop this 71 and then we'd also want to pop the 72 because now 73 is greater than 72 we pop this but it's not the case for this one but if you know we change this value to a 74 excuse my bad handwriting over here but if we change this to a 74 then yes we are going to pop this one as well so no matter what we do our stack is always going to be in monotonic decreasing order if i add a 70 over here it's we're not going to pop anything it's still in decreasing order so let's just run through a quick simulation let me show you how we can get this output in linear time using a stack so first value 73 we're going to compare it to the top of our stack is empty so we're not going to do anything we're just going to take the 73 add it to the stack next we're at 74 we're going to compare it to the top of the stack 74 is greater than 73 right what index did 73 occur at index 0 what index does 74 occur at index one so we take the difference one minus zero so it took us one position to find a value greater than 73 so we can pop 73 from our stack and then 74 is going to be on the top of our stack now exact same thing is going to happen with 75 right 75 is greater than this the difference between the indexes is one so we add a one to the output 474 and we pop 74 now we're at and we add 75 to the stack next we get 71 is not greater than the top of our stack so all we do is add it we don't update the output in either of those positions again we get a smaller value 69 so we add it to the stack we can't pop any of these 69's not greater than either of these next we get a 72 right 72 is greater than 69 right so we pop 69 what was the difference between the indices it was one so we're going to take in the corresponding output position which is in this position for 69 we're going to say okay there was an index difference of 1. now we're going to look at the next top for our stack 71. so the difference between these two is two so for 71 we're going to say it took two days for us to find a greater temperature than 71 so for this position we add a 2 so we pop 71 from our stack now 72 is not greater than 75 so we still have a hole in our output over here we never found a greater temperature than 75 yet and similarly for 72 we have a hole next we get 76 and compare it to the top of our stack so 76 is greater than 72 we pop 72 the difference the number of days it took us was just one day so we can add a one for 72 and then we look at the next top of our stack yes we finally found a temperature greater than 75 it took us one two three four days to do that so we can add a four in the output in the corresponding position over here and we can pop 75 from our stack i think i just need one more square over here because we have one last temperature in our input 73 so we're going to add 73 see 73 is not greater than 76 so we can't pop that and now at the end we have no more temperatures to add right we still have two temperatures left in our stack and whatever the default value for the unpopped uh temperatures is just gonna be zero right they told us in the uh description of the problem that if we can't get a greater temperature we're just gonna put zero for these so that's how we build the output you can see it exactly matches the output that they built in the example and we did that in linear time by using this monotonically decreasing stack in o of end time of and memory so now let's jump into the code so we are going to have a result or answer array and it's initially going to be default values of 0 because that's kind of what they tell us and it's going to be the exact same length as the input array temperatures i'm also gonna have a stack remember this is our extra memory it's gonna uh contain a pair of values in the drawing example i only showed that we're adding the temperature but we're also gonna add the index of the temperature so we can calculate the difference basically calculate the number of days it took us to find a greater temperature so we're going to be adding two values to the stack a pair of temperature and the index that temperature occurred at next we're just going to iterate through the uh temperatures array we're going to enumerate this meaning we're going to get the in the index of it and the value at the same time it just makes the code a little bit cleaner i is the index t is the temperature first thing we're going to do is see does is our stack empty and if it is this temperature greater than the temperature on the top of our stack is index negative one in python and the temperature is the first value in that pair so index zero and so if this is true of course we can pop from our stack right so stack.pop stack.pop stack.pop so i'm going to call it the stack temperature and the stack index which we just popped right and for this temperature we want to you know in the result output say okay whatever the index of this temperature was stack index we want to compute the number of days it took us to find a greater temperature we can do that with i the current temperature that we're at minus the temp the index of the uh temperature that we just popped and we take the difference of those that gives us the number of days it took to find a greater temperature and then we're just adding it to the stack at the corresponding position we want to and then once that while loop is done it might execute zero times it might execute multiple times after it's done then we finally want to append to the stack the temperature that we're currently traversing so a pair the t the temperature value and the index of that temperature and once we're done with that we can go ahead and return our result the reason we don't have to fill in any extra zeros if our stack is non-empty is because we already non-empty is because we already non-empty is because we already initialized our result to b0 so if we never filled anything in the default value is automatically gonna be zero so you can see the solution works and is pretty efficient so i hope this was helpful if it was please like and subscribe it supports the channel a lot and i'll hopefully see you pretty soon thanks for watching | 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 |
231 | hey guys today we will be solving the problem 231 power of two so in this problem what is given is like given an integer n uh return true if the power of it is a power of two otherwise return Force so what they are saying that n is an integer we need to check if n is an power of two we need to return true otherwise false so this is one first example in which uh one and it's true because to keep power zero is one and then 16 it's again true because 2 power four 4 is again uh 16 and then three and three is not the power of 2 okay so as question is clear right so let's uh find a solution for this so for uh solution to this one solution is that uh we can just put a while loop here while loop and what we can do is like we can multiply n uh with two and then check if it's equal to and return true otherwise uh again multiply this number with two that's 4 into 2 uh check if it's equal to n um so you need to stop this condition would be like uh this number would be smaller than and then only this a break sorry greater than one then it's the breaking condition but um this complexity of this would be log of sorry complexity here would be the log of n okay so let's find out P solution for this so this can be done by the bit manipulation so for bit Manu uh let's so uh what here we can do is if we can do nus 1 and of n if it's the power of two it will be equal to Z otherwise it will not equal to zero so uh how it's uh doing is like when we subtract the uh Power of Two with the N minus1 number then no there would be no bit common okay so let's take an example here is like if I take an 8 and when 8 is equal to 1,000 in bit manipulation 1 0 and 7 1,000 in bit manipulation 1 0 and 7 1,000 in bit manipulation 1 0 and 7 is equal to 0111 now what you will do the end of this so it will be zero right again let's take an example of um 10 it's not a uh Power of Two And when we do nus one that's 9 which is again equal to 1 0 1 but now you do the bit manipulation it will not equal to Z not equal to zero uh so here uh yes so let's write code for this solution so complexity of this would be space complexity would be of one because we are not using any extra space and time complexity would be again of one because it's just one operation so it would be one so let's write a code for this it's a on line code so it's just a simple code return n uh so there would be a n and of you say n -1 and if it's equal to Z let's put -1 and if it's equal to Z let's put -1 and if it's equal to Z let's put bracket here is if this one is equal to zero then return true or return false now there is one more thing here you need to check if n is greater than zero if uh this if n is equal to Z then this would give a unsign number and then give the garbage value so this would be the one more condition you need to add it here so that uh it give the correct answer okay so uh let's try if this is this runs yeah so our test Cas is pass let's submit it yeah it works thanks guys | Power of Two | power-of-two | Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_.
An integer `n` is a power of two, if there exists an integer `x` such that `n == 2x`.
**Example 1:**
**Input:** n = 1
**Output:** true
**Explanation:** 20 = 1
**Example 2:**
**Input:** n = 16
**Output:** true
**Explanation:** 24 = 16
**Example 3:**
**Input:** n = 3
**Output:** false
**Constraints:**
* `-231 <= n <= 231 - 1`
**Follow up:** Could you solve it without loops/recursion? | null | Math,Bit Manipulation,Recursion | Easy | 191,326,342 |
5 | That a hello hi guys so all doing fine welcome back to the video english video bp looking and another list to problem name dance red chilli powder mixing stomach set given string gas follow on this internet substring in s u majumdar do maximum laptop testis 100 examples where Given year deposit example tabs follow rooms pen one and a half is guava this special select BBA and BCA is the longest remuneration substring that in example to the input this CBD hand parties this point mixing meanwhile parents can deter even lord has been in the examples show latest Consider And Examples Pe Abcd Possible Parents Mixer Stand For Example Earth Ways BBC Ne Andi That Vikram Also Considered Single Characters Stuck Half Inch Offline The World But They Also Considered A Single Characters Abcd In To-Do List Care Pregnancy Debt The Follow To-Do List Care Pregnancy Debt The Follow To-Do List Care Pregnancy Debt The Follow Roadways Pe Is The longest born in exchange for example loot snowdrift for this problem which can that algorithm host algorithm solve this particular problem to human being rhythm sale attended it took to the streets abcd faux slide show that and also create another app to pwn account at every character of tv18 Slow Poison P 202 A Sukhmay Algorithm Begins Follow Us On Shri Krishna Leela Declaratii Interior Variables C21 Ameer 125 Boundary and Available 2012 Of the Longest Born in a Later Son and Directors of a Strange 1518 Traversal Defines the Mirror Position of Character and of Life But From the following operations it has happened that sult science son and sun are the first element so let's points 211 pm r12 that suvichar ko redmi arrangement by using the following formula with his to see - 500 formula with his to see - 500 formula with his to see - 500 riddle of mirror f1s facility element s well s meter of Well known father of element life in location inch a look for a day in all its not to give the part and they also chapter brother that wrong side and bright side of it this location article and not a that sindh characters are not equal to proceed For the check weather belief is greater than neck length is this seat is not greater school profit rather increment the value of came that the election commission point to the second location inside leaf cnrs the interpretation of that election prohibition admiral location S2 C - 502 election prohibition admiral location S2 C - 502 election prohibition admiral location S2 C - 502 Hai Anjani Pithampur Badal And Srijan And Below Smart Na Vyasyon Compare The Left Side Android Side Of It Location On Listen To Bhindi A Buddhist Characters Are Equal Increment The Value Of White 2001 Main Muzaffarnagar Weather Donor And Dr Equal This Note Is Press Breakup Lokp President Brother Diwali Artis Of A Greater Than Maximum Justice Torch Initially Updated Dali And Max Planck Specified Election The Value Of Great money and then the update wcc2 and 153 increment came that election commission point to third location was the convener of a provocation off a suit against chakra the left side android side file location on I just dish two characters are not equal wipro father and increment wi- fi Ninth wipro father and increment wi- fi Ninth wipro father and increment wi- fi Ninth point to the fourth location co again exactly admiral location with points 202 A glimpse and right side of its location the situation of equal co increment copy file is co again with chakradhar the volume set pin text to end tips and equal systematic well print Out of the boy who inches after now 12345 set on this gretel maximum this note thursday subscribe button rc increment that shift location in noida pot loot the mirror of a provocation three lines witch app developed and write locations for high position On that thing after this characters unequal profit father increment wi-fi to point profit father increment wi-fi to point profit father increment wi-fi to point x6 a mirror is account x2 that nine inches a glimpse Android file location sims dish two characters are equal to the father with increment wi-fi on father with increment wi-fi on father with increment wi-fi on that tied elements now position for Hey Google Play Again Increment Delhi For My Interest Father Main Naagin Tu Characters Also 5114 Persons And Personnel Increment Again Tips And Increment In The Final Of Characters On Ki Election Vacancy Director Position 200 Run Equal 10th Way Can Break Of The Boil Uvaach Ki Sanjay Dutt Diwali Of Measurement If Maximum Insaf And Spyder Quality Of Cents 101 Update Volume Maximum S5 Hai Hello How To Update And CR Total 6 And When Because Of The Following His Condition Which At High Speed Of A Greater Day Are You At High Speed Of A Greater Day Are You At High Speed Of A Greater Day Are You That Job Increment Pressed Leaf And 2.27 That Job Increment Pressed Leaf And 2.27 That Job Increment Pressed Leaf And 2.27 Location On This Is My Real Is Divya Kit Location 's Newly Appointed Alert Android Position Cheese Dish To Animal Which 's Newly Appointed Alert Android Position Cheese Dish To Animal Which 's Newly Appointed Alert Android Position Cheese Dish To Animal Which Presides All The Others On That Anupam Some Simple Steps For Each Character From The Opposition All Words And Get The Following Results Ajay Ko Now Suhaag Ka Completely Drivers In A Strange Brigade The Use Of Figure Scholars Sunao Vinod Now Turn This Point On The Length Of The Best Friend In Subscribe To New Delhi For That Is Back In The Drivers Are APN Check The Value Of Measurement Of Maths 10th Ka Svabh And Unequal But That Don't Traversing Entry Find The Same Volume Two Sides Of A Single Platform This Difficult Volume Excellent Difficult Top Player And Get Along Spider-Man Movie Spider-Man Movie Spider-Man Movie A Mountain Points World First Tips From Director Seem Like This That 24 Points 260 That Alarms Paladam Sub twist abcd dh ki spinally on wick in thy tak good initially minutes to just eng invariable call length amity and need to check weather district single character and not difficult to understand thee a specific professor victory code asinine expression point mintu cars pastoral prompt follow that on That Protesting Se Pcb Lead You Toe 8 And Nutrition In Which That Deposit Character Is Dollar Handle Of Character As A Great Symbol In Between Behavior I Is 56001 Contents Order Followed By His Character 's Facility And Creator Vector Some Toe 's Facility And Creator Vector Some Toe 's Facility And Creator Vector Some Toe Demonstrate Were A Beautiful The First to characters on dollar in his own ajay ko drink loot video that sophia bush and characters in to the whatsapp and now even net declare variables in pcs cut bluetooth on is the size of the best e know this is to finish Life Into A Sweat In Explanation Part V Initial Ice Cream Variables Namely CR And Excellent C21 Notes20 Loot Notification Wedding The Original Characters With Her Symbol To Anushil Loot To Ajay A+B Positive Pushva Character To New A+B Positive Pushva Character To New A+B Positive Pushva Character To New String Loot That A Character In The Hearts Character hai loot hua hai Ajay ko loot lo ki end ki meeting paan inch to value of in the 2G ki in final Bigg Boss Dashrath symbol to back toe top hua hai ko increment value of 10th ek ajeeb si in extension part Along with the amazing show create another ap go to afternoon account at every character of team half time liquid liner of business name script that size is equal to same as date of steel and initiated with 0 ajay ko loot ajay ko hua hai and tell me son Actual Code Tweet - and tell me son Actual Code Tweet - and tell me son Actual Code Tweet - Algorithm Scored A 100 Relative Products Character Tubelight Character Is Loot That A Studying Dollar And Character Which Is The First And Last Characters Of Nutrition Is A Website In Life From Physical To Ancestry Applied Is Equal To Iceland - 1m Ajay Was Proposed Now Bittu is Ped Location on Play List MP Pandav Tuition for Mila Hai How to See - Aaye Thee Ki Investor Mother Ki Is Lesson 8 App On Karo Ki Tips That Day Updated Value of Why Is a Minimum of - IABF Meerut Up Loot in Thick Ho Meaning of the Love Android Characters Are Equal in the Condition Increment The Value of Aaye Thee Ajay Ko Hua Hai Loot Lo Ajay Ko To Sahi Shri Radhe Maa Ayyan Ricky Ponting Mother Left and Right Location of Life Characters Equal and Not Vidron in a Matter of Minutes Ago MP3 A Friend Wiki Point Meeting Attend v5 Favorable Feet and Characters on Yesterday Su Updated Belief Makes Life in Greater Than Myself What Happened That These Are Finally Updated WFC&R That These Are Finally Updated WFC&R That These Are Finally Updated WFC&R The Following Condition Holes Which Is The Chief Is Greater Than Are The Best Practice Up The Phone Hai In That Case Bhi Update Belief See You Are A Pen To I Plus Point Ro Loot Ajay Ko On Loot In The Wooden MLA Part Offer Code Brigade The Value Of X Rent Control Act for the meaning of the word and the character of subscription to break up that Vikram declares and when serial star casting off alarm gas on introductory start travels and tours on Ajay that at yourself Bachat water purifier is equal to max length hai that Ajay Ko hua tha aur hips aur bull press leaf and take off the loop hai ek ajeeb si the meaning of the video learn from camera features paint and wallet for both cases option flat belly of a good english me hua hai on karo ajay ko MP3 loot Loot Ajay's Shopping Dream Road Pace and Landour Leaf Is Calculator First Name The First and Last Character Idea Dollar and a Great Character Days Like This The Battle of Mines Two in 3D Battu System and the Decimal in Between to that is the full form of the subscribe value from - 121 form of the subscribe value from - 121 form of the subscribe value from - 121 Ki in early in case of given land times so to get well soon that store longest platform in substring in available call out to loot lo hey yaar bekar news the is UBS CR function Which available in the string last year library is bay documents habit starting index and the length finally returned aware what is the longest born in a man a code space decentralization aquot picture brother witnesses and mornings' indicator flying find with boys and warning suggestion net profit Father and submit code is Ajay Ko Lut A Supine Ali Accord Submitted Successfully From This Video Helpful And Brief Understanding Of - Algorithm Like Button - Algorithm Like Button - Algorithm Like Button subscribe To My YouTube Channel for More Upcoming Videos Thank You To | Longest Palindromic Substring | longest-palindromic-substring | Given a string `s`, return _the longest_ _palindromic_ _substring_ in `s`.
**Example 1:**
**Input:** s = "babad "
**Output:** "bab "
**Explanation:** "aba " is also a valid answer.
**Example 2:**
**Input:** s = "cbbd "
**Output:** "bb "
**Constraints:**
* `1 <= s.length <= 1000`
* `s` consist of only digits and English letters. | How can we reuse a previously computed palindrome to compute a larger palindrome? If “aba” is a palindrome, is “xabax” a palindrome? Similarly is “xabay” a palindrome? Complexity based hint:
If we use brute-force and check whether for every start and end position a substring is a palindrome we have O(n^2) start - end pairs and O(n) palindromic checks. Can we reduce the time for palindromic checks to O(1) by reusing some previous computation. | String,Dynamic Programming | Medium | 214,266,336,516,647 |
139 | hello everyone in this lecture i am going to explain you about what break so here in this question they given a string s and dish and dictionary of strings what dictionary written true if s can be segmented into space separated sequence of one or more dictionary words note that the same word is the dictionary may be review reused multiple times in the segment so here in this example one they given s equal to lead code so here in this word dictionary in this list a given lead encode substring stay given so here we need to return true when here it is showing output true because lead code can be segmented as lead code as given in the explanation so here if we combine these two strings then it is forming this string so here in this kind of situations we can return true here also in this s they give an input apple pen apple so here the common words are apple and pen here the given in the substrings in a list which are allocated in what dictionary so here also as when we compare from s given input here they just if we combine these two strings two sub strings then this will form so here also it is showing true so here in this kind of situations how can we implement one logic and get the output like this i will explain clearly so here the given string and in this list string they given what dictionary already they given this okay so here first we need to create variable in length equal to f dot length and here boolean array f equal to new boolean in this boolean i will mention length plus 1 okay and here if f of here in this f of 0 then we need to mention true and here for int i equal to 1 and i less than len plus 1 and i increment so here in this for int j equal to zero and j less than i and j increment okay so in this nested loop i will mention if f of j and here what dictionary dot contains so here simply i will i'm mentioning here i equal to 1 and i'm trying to traverse to the end of the list so here again for g for j i am initializing 0 and here i am implementing this logic by doing so here i'm just compare i'm checking that if f of j is having if that what dictionary contains this is the what dictionary right so in this we need to check now this s input is there in this or not for that logic is what dictionary dot contains s dot here the input is given in s right so s dot substring in this s dot substring i am mentioning j comma i and here f of i is equal to true and here also i'm ma i'm returning f array in this f array i'm mentioning length so by doing so by implementing this logic now we'll check yeah i accept it i will submit yeah success so here simple first i'm taking length s dot length and then i just created one array and i named it as f and here is that f of 0 is equal to true and here and i just mentioned nested loop and i traverse i'll if and i traverse for shillman to lost element with the help of two loops after that here i mentioned condition if this war dictionary contains the substrings j comma i then i am returning true and here at loss i am returning f of length so this is the logic behind it if you have any queries you can mention your doubts in commentary session and please do like and subscribe for more videos thank you | Word Break | word-break | Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**. | null | Hash Table,String,Dynamic Programming,Trie,Memoization | Medium | 140 |
1,808 | hey what's up guys uh this is sean here so today uh 1808 maximize number of nice divisors uh this one you know okay so give me like a positive integer prime factors and so basically we need to find an integer and that you know that satisfies the following condition you know so the first one is this one so the number of prime factors of n are not necessarily distinct right it's at most this number these prime factors numbers okay and then the second one is that you know the number of nice divisors of n is maximized right so and so what is the nice divisor of n right so a nice divisor of n is that is the number that is divisible by this n and also divisible by every prime factor of n so it gives you an example right so for example we have n here right so the prime factors for n is what is 2 and three right so what are the nice divisor for this so basically six and twelve is a nice divider because so now we have how many distinct uh prime factors we have here we have two right we have two and three so which means that you know a nice divisor has to be divisible by this by both of these numbers which means two times six two times three equal to six that's why the total is what total is six and so the total number of nice dividers six and twelve and then which is two right so and it just asks you to find the uh basically the max the maximized number of nice divisors given like this kind of uh prime factors right so for example right we have prime factors five you know so for prime factors five here you know uh we have so one of the ways to get six is this one so we can have like three two and two fives right so for the so a prime factor is though it's like this right so prime factor starts starting from two right and then we have 2 3 5 7 and then the 11 right 13 so on so forth those are the prime factors so one of the examples here is that you know we can use this kind of uh prime factors and which has like six nice divisors which is 10 20 40 50 120. and the limit of the number of the prime factorization factors is five that's why we have this three and two uh division uh split here right that's why we have six and then we have prime factors 8 means that 18 right and the prime factors range is pretty big 10 to the power of 9. so that's the uh the description of this problem you know at the first glance right so this one is a little it's pretty hard to come up with a straight answer right because you know with all those kind of a prime factors so what are the problem factors we should use and how can we know what are the combinations of the prime factors can give us the maximum nice divisors right so to solve this problem we have to make a few observations you know so the first one is that you know um we have this kind of limits of prime factors right let's say for example we have five right we have five uh prime factors and which means that we need to fill in these five uh five slots by five prime factors and how what are the numbers we need to fill in here right so the answer is like this right so we are if we fill uh three same number and two others same numbers we'll have six now why six let's say we have uh three number three x and two y's here right so the answer is 6. how can we get 6 right because like i said you know the nice divisor has to be at least the multiply of x times y right so that's the first one right and then for the other possible divisors no this is the base right we can either times another y right so this is an another nice number or we can uh do an another times x here that's how we basically that's how we get this kind of numbers here basically two times five is the base right because that's the minimum we need to get for the nice divisors and based on the based on this ten here we can just multiply on the remaining five or twos that's why we have this six which means that you know in this case right we have three times two equals to six right and similarly right so for prime eight how did we get 18 right so basically for eight we have the answer is this so we have three x we have three y and then we have two z that this is total eight prime factors right and again right to be for the base of the nice factors we need x times y times z that as a base right that's why the answer for this one for the total nice divisor of this one is 3 times 2 right which is 18 that's how we get 18 here this is pretty obvious right because we need to the nice divisor has to be able to divisible by each of the number here right that's why you know it's three times two this is a little bit math calculation here okay so with this being said right now we know given like the uh the some numbers we can calculate the prime factors we can calculate the final answer right now the problems converted to given like a total numbers which is eight we need to split this eight into several groups so that you know the product of each group's number is maximum right so the problem is that how can we do this split here and so the split is like this so basically we should always split it into three and then two and why is that because you know if we uh try a few examples right you know for four let's see you know for one to four so if the number is one then of course it's one right how about if the number is two so what is the if we have the if prime factor is two what's going to be the total number here it's two right because if it's a prime factor is two and then we need two same number here right which means that you know we have two possible we will have like two nice divisors here once with x the other one is with x times x how about three so three we have two times one sorry not two times one so three we have three times three basically for 3 we also need gonna be a 3x together because 3 is greater than 2 times 1 right so if we with 3 prime factors if we split it into 2x and 1y then the total nice divisor will be 2 times 1 which is 2 which is smaller than 3 right so how about 4 so 4 we have we can either do two times two or we can do a four times one right so for four here you know uh we can split it into two x and two y or we can have like uh 4x they will have the same result which is four right how about the five right so with five what's going to be the best the biggest uh total number is three times two which is six right and then if we continue doing this how about six we need to split into three times three which is 9 because 3 times 3 is bigger is greater than the 4 times 2 right so 7 similar for 7 we have 3 times 2 which is like 12 right so now we now you see a pattern here so basically you know as basically we have a proof here you know whenever we have like a number which is greater than four which means starting from five we should always split it into multiple threes together into multiple three because three times three will always give us like better answers right that's why you know we have this kind of like pattern here and then when the number becomes to uh becomes to 4 or 3 here we should just use this formula to calculate the remaining right so now i think we have already have the uh the basic logic here so which means that you know for eight years you know we're trying to see how many threes we can get out of these prime factors and then because the number of threes means that you know we will have like three uh times three lot right because you know for this one for example we have eight we have three we can if we do uh this uh eight uh divided by three we have two which means that we have three we have two threes out of eight right so which means that we're gonna have like a three to the power of two and then times the remaining which is two right so the solution will be we will try to calculate how many basically the power of 3 by from these prime factors and then we'll just use the prime fact you use that power number to calculate the answers and then there's like a special case here let's see the yeah actually seven is a good example here so let's say the prime factor is seven right so the seven after the dot after subtracting three we have four right so we have four here which is three here and then from four basically you know if we do another three here we have one left right so if we split 7 into 3 plus 1 then the final answer is 3 times 1 which is 9 right but the best answer for 7 is what we split 7 into 3 plus 2 which is 3 times 2 which is 12 right so what does this one tell us tells us you know when the remaining when the modular right when the modular uh is one right it means that you know we don't for the last four here right we don't want to split uh this four into three one instead we want to split this four into a two times two right basically this is the uh like the special case we need to be careful cool so and that's that and another one is that you know when we calculate the uh the three times three right we cannot simply use three to the power of this power here right because you know this power given the constraints here you know this part could be huge if we simply do a three time to the power of this power number here it will basically it will overflow right so which means to calculate this one the power of three right we have to use the like the dynamic programming okay so let's start coding then um so first we have a power right so the power will be the prime factors right do a divided by three right and then we have a remain here so the remain will be the prime factors do a modular of three right so basically if the remain is zero so if it remains zero right which means that you know if it's nine so if it's nice means uh we should split into a three threes which is the this one right because this one will give us the biggest uh the biggest product right by splitting into several numbers so which means that you know assuming we have a dp here uh i'm going to create like create a dp method to help me calculate the power of three right so we have the uh house card current and now i have the answer here okay so if they remain zero which means that you know we just we simply do a dp of the power right and then the answer is this i'll see if right out if the remain is one which is the special case right so for this one you know we want to save the last four we don't want to divide it uh divide this four into three one right which means that it means that we want to keep this 4 to 2 and 2. so in this case we have answer because it's going to be a dp of power minus 1 right because we are we're subtracting saving one of the threes right and then instead we're going to cut multiply by three by four which is two times two right i'll see if the remain is two there could be only these three possibilities because we do a module of three right so whenever this remains two it's actually it's a five case right so for this one we simply do this right and the dp of power and then we times two right that's going to be the remaining number here and then we have a mod right it goes to 10 to the power of nine plus seven and we simply return the answer modular of mod right so now for this dp right so this is like very classic dp basically if the current equals to one right we return three right and then now we have the answer equals to one i guess right so if the current is divided by two sorry blue modulus by two is it's not empty it means that we need to do a three times dp of current divided by two basically we cut it into half right and then we do a module of two so every time we cut this current to half answer is going to be the dp of this one basically right and then we also need to do a modular here because if we don't do it will also be going to be overflow here right do a mod and then we'll return the answer um yeah i believe that's it right so if i run the code here accept it oh i need to define it at the very beginning i believe um 4 0 so when the maximum recursion depth exceeded um yeah actually so four is a special case right so because you know when uh the prime factors equals to four the power equals to 1 so here you know and the remains 1 right so here will be dp 0 basically so db 0 we didn't handle dp 0 here we don't handle it that's why you know it will be an infinite loop here a recursive recurs recursive call here so uh we can simply do a check here basically if the prime factors right is equal smaller than four then we simply return the uh the prime factors because we have already checked that you know whenever the prime factor is equal to 4 the answer is the prime factor itself right yep so and it passed right um yeah so that's it right i mean i know why we got a lot of demos here because this one actually is a pure math problem plus a little bit dp here you know like i said just to summarize this problem you know to solve this problem we have to make some uh really sharp observations you know the first one is that you know how can we choose these prime factors right and once we have chosen a few uh combinations of the prime factors how can we calculate the number of the nice divisors based on these prime factors in this case which means that in the total number of the nice prime nice divisors is the number of each distinct the count of each distinct of the prime numbers because you know nice divisors has to be divisible by each other the prime number the distinct prime numbers that's how we do uh the product of the count for each of the prime factors and if we can figure that out then the problem becomes down to given like a total numbers how can we split this total number of prime factors into several groups so that know the product of the group count is maximum right and then we uh we prove that you know the best uh split will be always splitting into several as many three group of three as possible of three numbers as possible and then we just leave the remaining there so which means that you know uh so given like these prime factors we should always split into two and then three and then five and then what and then uh seven and then here is like the um eleven right sorry this is too many ones here so basically that's our strategy so as long as we have enough place to fill in three same numbers here we should always uh fill in the prime factors with this three same numbers right and then if we don't have enough numbers we should uh we just fill in fill it in with the remaining with the other two numbers which like this case like c11 and 11 right that's going to be the strategy and there and we also talked about the special case which is this one let's say there's only one number left here right so in this case you know if there's only one slot left which means that the remaining is one then this is not the optimal solution which means that for in this case instead of adding another like a different prime numbers here we should uh make this one to be the same as seven where any of those uh previously three numbers because this will give us the best answer yep i think that's it right so i once as soon as you can figure out all those kind of scenarios and then plus this kind of a little bit dp to calculate the power of three and yep so and this that's it for this problem and how to stop here thank you for watching this video guys and stay tuned see you guys soon bye | Maximize Number of Nice Divisors | stone-game-vii | You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions:
* The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`.
* The number of nice divisors of `n` is maximized. Note that a divisor of `n` is **nice** if it is divisible by every prime factor of `n`. For example, if `n = 12`, then its prime factors are `[2,2,3]`, then `6` and `12` are nice divisors, while `3` and `4` are not.
Return _the number of nice divisors of_ `n`. Since that number can be too large, return it **modulo** `109 + 7`.
Note that a prime number is a natural number greater than `1` that is not a product of two smaller natural numbers. The prime factors of a number `n` is a list of prime numbers such that their product equals `n`.
**Example 1:**
**Input:** primeFactors = 5
**Output:** 6
**Explanation:** 200 is a valid value of n.
It has 5 prime factors: \[2,2,2,5,5\], and it has 6 nice divisors: \[10,20,40,50,100,200\].
There is not other value of n that has at most 5 prime factors and more nice divisors.
**Example 2:**
**Input:** primeFactors = 8
**Output:** 18
**Constraints:**
* `1 <= primeFactors <= 109` | The constraints are small enough for an N^2 solution. Try using dynamic programming. | Array,Math,Dynamic Programming,Game Theory | Medium | 909,1240,1522,1617,1685,1788,1896,2002,2156 |
35 | hello guys uh i am the casper flaw from pt web 4 here i am to learn about binary search let's learn it through an example the question of later so as we know in linear size the time complexity of the algorithm is in order of n so in order to reduce time complexity we apply binary search here time complexity is as you can see the order of right pointer you selected value r and take it as a dot length minus one that will be the last index of the error run a while loop where l is always less than equal to r and here we have to take that will be the middle element of the array left plus right first position is minus one and then equal to the target value then return value of net eos will be made last one and then also they made plus one index accepted it's all about the position so the solution is first of all i take a left pointer initialized value 0 and take the right pointer and give it value nums dot length minus one that will be the last index of the error and take a position variable and give the value of minus one and then each other and run the while loop left less than equal to r and if mid equals to left plus r by two just numbs of matrix equal to target then return is less than target then position equals to mid plus one and left equals to mechanism tells position equals to make and right equals to minimize so this is all about the final research thank you guys hope have a great day | 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 |
343 | Hello everyone welcome to my channel code sorry with mike so today we are going to do video number 66 of our dynamic programming playlist ok and today's question is lead code number 343 is medium mark but this question can be made in a very easy way ok It will be a very simple code to understand. The question is also quite straight forward. The name of the question is Integer break problem. The problem is that how would you think to approach it. You will understand it once you do the code yourself. The main part of this question is that how to approach this, okay, it is amazon2, it means you have to break two or more numbers into positive integers and then when you take the product of those integers, you will get the maximum product. Okay, so let's see what is the first example here. Look, Nam is equal to 2, so you can break two into two numbers, one and one, because what is the sum of these two, 1 is equal to 2. Okay, so these Take the product of both, this is 1 and the answer is one. Okay, the output is one. Now let's see another example. If it is four, then you can break four in many ways. 1 Pv or 1 + You can break it into 2 + 1 + 3 and 3 + Pv or 1 + You can break it into 2 + 1 + 3 and 3 + Pv or 1 + You can break it into 2 + 1 + 3 and 3 + 1 2 + 2 and so on, there are 1 2 + 2 and so on, there are 1 2 + 2 and so on, there are many ways but if you take multiplication of all, like in this take multiplication of all 1 * 1 * 1 * 1 * 2 * 1 * 3 * 1 3 2 * 1 * 1 * 1 * 2 * 1 * 3 * 1 3 2 * 1 * 1 * 1 * 2 * 1 * 3 * 1 3 2 * 2 4 Which is the maximum? If it is 4, then look, the answer is * 2 4 Which is the maximum? If it is 4, then look, the answer is * 2 4 Which is the maximum? If it is 4, then look, the answer is here again. Similarly, Nam = 6. So you here again. Similarly, Nam = 6. So you here again. Similarly, Nam = 6. So you can break 6 in many ways. 1 P Y So this is 1 P 5 That is 1 P 4 P 2 done and so on 1 P 4 P 1 There are many ways but what is the best way 3 P can be broken into 3 There will be no multiplication of these two This will be the best answer The biggest value is ok Similarly Sen's answer will be 12 Because I can break the sen by further th then the answer will come multiplication will come 4th 12 Okay, so look at one more example, you must be thinking why we are breaking it into two every time, see here I have divided the four into two. I broke six into two parts, I broke seven into two parts, then you might be thinking that I always have to break it into two parts, but it is not so, let us assume that Nam = 10, okay, so 10. If you Nam = 10, okay, so 10. If you Nam = 10, okay, so 10. If you assume that if you break it into 5 and five, then the answer is 25. Then if you break it into seven and 3, then the answer is 21. But here, if you break it into two parts, the answer will not be good. Look here, these three parts. Then the best answer will be 3 P 4, so 3 6 4 10 becomes even, 10, what is the multiplication of all, if it is 36, then the answer will be 36. Okay, so now let's come to how we will approach this. This is from DP's playlist, so you must have already got the hint that DP is the question but the problem is that we have many ways to break this identification. The first way is to keep the first part as one, the second part as four, look at the sum of both, is it five ? N P 4 5 happens to be ok ? N P 4 5 happens to be ok ? N P 4 5 happens to be ok what is the second way keep the first part as two keep the second part as three doti pa first part second part let's see here and what is the way first part keep three keep the second part what is It will be 5 minus 3 two, okay and what is one more way? Keep the first part as four, keep the second part as one. Okay, so isn't this the only four way? There is another way, this second part which was four, is also very good. You can represent in all the ways, you can represent in th, right, you can represent on 1 p 3 4 one sorry tomato and either you can represent in th and you ca n't do further, okay and look at this also three You can break it into Vanama Two Pe, it is ok or Tooma One Pe, here also you can break Two, One Kama One Pe, the sum of both is two right and you cannot break One into four parts because you have to break it into maximum two parts. So if the forest cannot be broken into two parts, then I have stopped here, my butt has stopped here only. Pay attention to one thing, so many possibilities are visible. You must be seeing a lot of possibilities. Look, this fourth three can also be broken, but the tree. The diagram will be very long so I am not drawing it. Okay, when you make the complete tree diagram, you will see all the possibilities. 1 + 1+ 1+ 1+ 1 will also be visible to you. 1 + 1+ 1+ 1+ 1 will also be visible to you. 1 + 1+ 1+ 1+ 1 will also be visible to you. Look, this one, then this three will break, right? If you go to forest, you will get a forest from there, then there are many ways, so it is ok, you will see all the possibilities in the tree diagram, if you make the whole tree diagram, but the tree diagram will become very big, so to make you understand, I have made half tree diagram. In this, you will also see 1 + 2 + 3, no, 1 + 2 + will be In this, you will also see 1 + 2 + 3, no, 1 + 2 + will be In this, you will also see 1 + 2 + 3, no, 1 + 2 + will be visible, many possibilities will be visible in the tree diagram, that is what I want to tell you. Okay, so now the point comes here that first of all this branch. Now let's just look at this branch. Okay, look how many possibilities you can see here. The first possibility you can see is that this can be a good answer. 1 4, the sum of both is equal to five. Multiply both of them by 1. * Multiply both of them by 1. * Multiply both of them by 1. * How much did 4 get? 4 What is the other possibility that instead of taking four, if I broke the four, then I will definitely take one, so it is okay, I took one, after that look, 1, 3 can be taken, 1, 3, look, the sum of all three is equal to five. Multiplication is 1 * 1 * 3 That is 3 What is the Multiplication is 1 * 1 * 3 That is 3 What is the Multiplication is 1 * 1 * 3 That is 3 What is the third possibility This one is taken Four I broke it into two parts One more possibility is this also so one So this one becomes and after that two is two Two two is 1 * becomes and after that two is two Two two is 1 * becomes and after that two is two Two two is 1 * 2 * 2 4 is here, okay then look here, if we 2 * 2 4 is here, okay then look here, if we 2 * 2 4 is here, okay then look here, if we break it into 3 coves, then 1 * 3 * 1 3 will break it into 3 coves, then 1 * 3 * 1 3 will break it into 3 coves, then 1 * 3 * 1 3 will come, okay, now the question comes that out of all the possibilities we have to choose the max, right? Okay, so if you look at it, which one is max? Max, I am seeing four. Right, okay, if we look at it, what were the possibilities? The first possibility was that we tried by doing 1*4, which first possibility was that we tried by doing 1*4, which first possibility was that we tried by doing 1*4, which means whatever is my number. Let us assume that this number is n, then see what I did. Here we have already seen by doing 1 * n - 1. what I did. Here we have already seen by doing 1 * n - 1. what I did. Here we have already seen by doing 1 * n - 1 n -1 means 5 - 1 4. After that 1 n -1 means 5 - 1 4. After that 1 n -1 means 5 - 1 4. After that we saw that four can be broken into more parts. If there are multiple possibilities, then I sent four in the first recurse call. Okay, and sent it in the same recurse call. The first part was broken into one, the second part was two, the third part was three, isn't it similar here too, the same happened in recurse. Na look at the first part for five, the second part was two, the third part was three, the fourth part was four, after that you can't do it, Na five, you can't do zero, right, na pa, zero, you can't do it, so now look, this is one, after that The maximum answer that came from the fourth recurse call, look from here, 1 * 3 is coming look from here, 1 * 3 is coming look from here, 1 * 3 is coming from here, 2 * 4 is coming from here, 2 * 4 is coming from here, 2 * 4 is coming from here, 3 and 3 are coming from here, which is the maximum among the three, if it is four then yes. Which one do you choose c 1 out of these three choose the maximum one that comes maximum four c No ok, now it is clear till now look pay attention to this very important part, see what I said here I told all the things. The options were written as possible options, okay, so I had said that first this one can be my best answer, so 1 is 4, okay, after that I said, see what I said that either 1 or 4 would be my best answer, meaning. If va is mine then n - aa then either meaning. If va is mine then n - aa then either meaning. If va is mine then n - aa then either this will be my best answer meaning i * n - aa will be this will be my best answer meaning i * n - aa will be this will be my best answer meaning i * n - aa will be my best answer or break the n - aa further and my best answer or break the n - aa further and my best answer or break the n - aa further and whatever maximum comes from there is fine then what can I say. I want either i * n - Aa to be my best answer either i * n - Aa to be my best answer either i * n - Aa to be my best answer or send Aa in n my Aa back to Rikers and the best answer that comes from there is clear till now, then you write it in such a way that which of the two Give maximum, that is my answer. You can write it like this. Aa in maximum of either we will make it from n my aa or we will call n my aa in the ratio. Whoever gives the best answer is clear, similar. For this also it will be the same for na for th either th will be my best answer this time aa my kya hai this to hai ok and this is what is my n mine aa hai na a my pa tha If there is two then 3 is my n my aa will be then what I said is either my aa is not into n my aa will be the best answer meaning 2 * into n my aa will be the best answer meaning 2 * into n my aa will be the best answer meaning 2 * 5-2 3 is the best answer 5-2 3 is the best answer 5-2 3 is the best answer or i * n - aa i.e. or i * n - aa i.e. or i * n - aa i.e. Call 3 in the next recurses. Okay, the best answer out of these two will be my best answer. You can write it in any way i, whichever best answer you get out of the two, n - whichever best answer you get out of the two, n - whichever best answer you get out of the two, n - aa or after solving it, n - Have you come aa or after solving it, n - Have you come aa or after solving it, n - Have you come in the Fardh Rishan? Send n to Aa. Wherever the best answer came from, I will multiply it by Aa. I will multiply it by the largest number I get. Okay, and the same thing will apply here too. The same thing will apply here too. It will be okay, so if we look at the way you started breaking the five, the first part was kept as one, after that you tried to keep the first part as two, then you tried to keep the first part as three, then you tried to keep the first part as four. Similarly, when this recursive call happens, let's say here, if the recursive call is done, then the first part is kept as one, then the first part is kept as two, then again you start from one and go till two. Okay, so if seen, actually it is a for loop. It's going on, what am I saying? The first part will start from one and how far will that first part go? Will it go till Mi? I Plus Okay now come see what will happen Aa Eve will happen right if A is my father then come iv will be i 2 will be i = 3 will be 4 will go to 4 because i = 3 will be 4 will go to 4 because i = 3 will be 4 will go to 4 because if i is 1 then 1 * 4 n - i will be 4 na if i is 1 then 1 * 4 n - i will be 4 na if i is 1 then 1 * 4 n - i will be 4 na what will this be 2 and 5 - 2 is 3 what will this be 2 and 5 - 2 is 3 what will this be 2 and 5 - 2 is 3 na one thing I understood that Q for loop I needed it, here if i is 3 then n - aa what will happen, here if i is 3 then n - aa what will happen, here if i is 3 then n - aa what will happen, here if i is 4 then n - aa my v will be ok i is 4 then n - aa my v will be ok i is 4 then n - aa my v will be ok till now it is clear so for loop will be needed because you have it right. It is an obvious thing to break it, so to break it, you are starting from one, that is, keep the first part as one and the second part as n - 1, the first part as two and the part as n - 1, the first part as two and the part as n - 1, the first part as two and the second part as n - 2. Okay, so second part as n - 2. Okay, so second part as n - 2. Okay, so look here. Here we came to know that for loop has to be used, but generally people ask, Sir, how will we know that for loop has to be written, okay, so friend, the answer to everything is in the tree diagram, if you pay attention to the tree diagram. So look in tree time here what I told you that for a given n look for given n first you broke the first part in one here is one here then you are looking at the second part in this first part in this you broke in two the first part in this three I broke it and au, look here, the first part is broken into four, so what I have broken into 1 2 3 4, you can achieve this only through for loop and how can you do it, right, that is, here we have used for loop, it is okay. What I said later was that let's find the product i multiplied by the maximum of a - aa or that multiplied by the maximum of a - aa or that multiplied by the maximum of a - aa or that means i * n - aa will be the best answer or means i * n - aa will be the best answer or means i * n - aa will be the best answer or I will send n - aa to recursor and I will send n - aa to recursor and I will send n - aa to recursor and see if I get a good answer from there. The biggest value will be the same and we will multiply it by a, okay this is what I told you, okay till now it must be clear that what was told is exactly the same line of code written and nothing extra is written, what do we have to do after this. Found any prod, there are all the possibilities, we have to find out the best answer, right, so we will take a separate variable named result, it is okay and in the result you can put any small value, it is okay, either put int min or int min. This will also work, either put any value like 1 * n - 1, it will put any value like 1 * n - 1, it will put any value like 1 * n - 1, it will work because what is its sum, 1+ n - 1 n will come out only, so 1+ n - 1 n will come out only, so 1+ n - 1 n will come out only, so I have put 1 * n - 1 but here If you put int mana, I have put 1 * n - 1 but here If you put int mana, I have put 1 * n - 1 but here If you put int mana, that will also work. You have to enter small value because here you extract the maximum value inside the for loop. Right then I have updated the result in the result. Whatever product I am extracting inside the initialism loop, whatever will be the best, I will update it in the result. I will keep doing it, okay, so now let's come here, the result is equal to maximum of sorry, the maximum will be here, result comma and whatever my prod is getting now, okay, so the result is equal to maximum of result comma prod, so till here, well. It must have been clear to you right at the end, what do we have to do, we have to give the return result, not even a datchi and we have completed it and what is this, we are writing the recursion only, it is simple, okay, we are writing the simple recursion, now you will ask here. Where is deep? Okay, so D is hidden in the deep diagram. Look, pay attention, that's why I say T diagram is the most important thing, this is a given, you had options to break it. Right, you are seeing first, the first part was broken in the forest. Here again or second time, what did you do, you broke the first part into two, here was two, then here was three, then this was four and so on, so we have options for each number, okay, similarly, look here, three also. Further can be broken, first part one, first part two and so on options, we have second thing, see here there are all repeating problems, look carefully here, there is three, will you solve it further, see here also three, then the problem is being solved. If you had assumed that you would have stored the answer of 3 here and had memoized it, then you could have used it back here in the future, so here I saw what I saw repeating all the problems brother, these two are enough to tell you. That it can be made by recursion and memorization means this is the problem of DP. Okay, so what we will do is simple memorization and the DP we will take for memorization will be of only one dimension because only one variable is changing. Look here n - we are sending only one variable Look here n - we are sending only one variable Look here n - we are sending only one variable n, okay so the simple one which will be deep is mine, take n or sorry n + 1 so that it does mine, take n or sorry n + 1 so that it does mine, take n or sorry n + 1 so that it does not go out of bounds, take n + 1, okay it is not go out of bounds, take n + 1, okay it is not go out of bounds, take n + 1, okay it is clear till now. Now coming to time complexity, if you do not use it, then time completion is time complex. If you see, then n is the value of n that you have. Okay, how many options do you have for each n. Take n to break it and break it into n-1. break it and break it into n-1. break it and break it into n-1. k option is right so for every n is my option so expo angular is going its time complexity is time complex t but as soon as I memoized it okay what happened with memoization that now see this now ya pay attention without memoization There are so many possibilities, but if you are looking at each possibility, you are also running a for loop, then * you are looking at each possibility, you are also running a for loop, then * you are looking at each possibility, you are also running a for loop, then * n-1 will be ok, n * power of n is n - 1, n-1 will be ok, n * power of n is n - 1, n-1 will be ok, n * power of n is n - 1, so there are so many possibilities, and you are running a for loop for each possibility, you are ok. But look at the memorization, you have a total of only n states, you will visit only n states because depth of n is one, but in every state you are also running a for loop of n -1 size, so n * n- 1 of n -1 size, so n * n- 1 of n -1 size, so n * n- 1 Approximately o of n is s, let's finish it by doing this time, so let's code it quickly, just like it was explained, first of all, don't even think that there is a question of DP, right, it is simple, I have written a recursive n function. Sent A solve function in my solve. Here we are creating int A. Sent it. If there is a e ev in it then it will return one for me because I cannot break it into two parts. Right, we will return only one. Okay, a result named Keeping the variable in which I have put int man for int aa = 1 aa < i n-1 aa p ok now let's int aa = 1 aa < i n-1 aa p ok now let's int aa = 1 aa < i n-1 aa p ok now let's first take out the prod how much product will come i into the maximum of aa minus sorry n - we will multiply by aa or else We will sorry n - we will multiply by aa or else We will sorry n - we will multiply by aa or else We will send n - aa to the rectors and see which one is the send n - aa to the rectors and see which one is the send n - aa to the rectors and see which one is the best and after doing the product, either solve it with n i * n - aa or either solve it with n i * n - aa or either solve it with n i * n - aa or solve n - aa so that the best answer comes and solve n - aa so that the best answer comes and solve n - aa so that the best answer comes and I will update the maximum of result comma. Why were we able to write prod and this code because we had made a tree diagram, it becomes very easy with the tree diagram, okay, I have to return the result in the last, so this is my recursive code, let's memoize it now, okay, let's say yes, this So the example is passing, the constraint is very small, it is of 58 size, so I take dp here int t of 59 size is ok, before doing everything, we will check here that if I have set off a is not equal to If my is ok then I will return y of a which means y must be solved and before returning here I will store off of a. Ok and t will have to be initialized to t of my size of t is ok. Same Java code. You will get it in my Git Hub link which is on the description. Ok, let's submit and see. Hope it should be completely passed. Indeed, yes we have solved this question. There will be a separate video for bottom up. Any doubt, raise it in the comment section. Try to help ya out see you go in next video thank you | Integer Break | integer-break | Given an integer `n`, break it into the sum of `k` **positive integers**, where `k >= 2`, and maximize the product of those integers.
Return _the maximum product you can get_.
**Example 1:**
**Input:** n = 2
**Output:** 1
**Explanation:** 2 = 1 + 1, 1 \* 1 = 1.
**Example 2:**
**Input:** n = 10
**Output:** 36
**Explanation:** 10 = 3 + 3 + 4, 3 \* 3 \* 4 = 36.
**Constraints:**
* `2 <= n <= 58` | There is a simple O(n) solution to this problem. You may check the breaking results of n ranging from 7 to 10 to discover the regularities. | Math,Dynamic Programming | Medium | 1936 |
1,791 | hello everyone so today's problem is find center of the star graph so it's an easy lead code problem so let's see how we can solve this so the question is there is an undirected star graph consisting of end nodes labeled from 1 to n a star graph is a graph where there is one Center node and exactly n minus 1 edges that connect the center node with each and every node with every other node you are given a 2d integer array edges Fair each Edge I is equal to u i v i indicates that there is an a edge between the nodes UI and v i and we need to return the center of the given star graph so this is graph 1 and it is unidirected graph so we just need to find the center of the graph which is 2 so let's see how the input will be given so n will be given in this format for example edges is equal to 1 2 1 is connected to two is connected to 3 and 4 is connected to 2. so what we can do is to find the in degree of every node so in degree is basically the number of edges connected to each node so for example 4 there is a single line connecting one and two so in degree of 1 is 1 and there is a single line connecting two and three so in degree of 3 is 1. and there is three lines for example this line there are three lines which are which is connecting two to other nodes so we can notice that there are four nodes here and the one which is the center node has n minus 1 lines connected to it so what we can do is we can you know find the in degree and equate it to uh n minus 1 there are n nodes and we can equate it to n minus 1. so in that way we can get the result so let's code this up at first we will try to find the number of nodes so we will create a for Loop I should be less than edges dot size and I plus and we can find the maximum of the maximum number of the following the maximum number of this Edge will be our number of nodes so n will be the max of n comma and maximum of in between these two for example it will compare the first between 1 and 2 it will take the value 2 and put it in n and then in this in the second one it will compare the first and second and then it will put the maximum value in n now we will create a vector array vector and in degree of size n Plus 1. now we will iterate through the whole edges and we will increase every each and every element by one so the element which is increased the most for example here 2 is being repeated in every element so we will increase 2 for the three times so here 2 is being increased the maximum time so here 2 is this you know Center star I will copy paste this one and we will change it for two one so that we can access this one and we will increase each and this one and we will increase each of them by one and this is for this one no this one now we will try to compare the in degree of each and every node so the in degree of the node which is equal to n minus 1 will be our Central node if in degree of I is equal to n minus 1 then we will uh let's define int result and if in degree if n degree is equal to n minus 1 then we will store the value of I and the result we will store the value of I in the result and we will break the statement and last at last we will return result so let's run it okay please like subscribe and comment on my channel and do support me | Find Center of Star Graph | richest-customer-wealth | There is an undirected **star** graph consisting of `n` nodes labeled from `1` to `n`. A star graph is a graph where there is one **center** node and **exactly** `n - 1` edges that connect the center node with every other node.
You are given a 2D integer array `edges` where each `edges[i] = [ui, vi]` indicates that there is an edge between the nodes `ui` and `vi`. Return the center of the given star graph.
**Example 1:**
**Input:** edges = \[\[1,2\],\[2,3\],\[4,2\]\]
**Output:** 2
**Explanation:** As shown in the figure above, node 2 is connected to every other node, so 2 is the center.
**Example 2:**
**Input:** edges = \[\[1,2\],\[5,1\],\[1,3\],\[1,4\]\]
**Output:** 1
**Constraints:**
* `3 <= n <= 105`
* `edges.length == n - 1`
* `edges[i].length == 2`
* `1 <= ui, vi <= n`
* `ui != vi`
* The given `edges` represent a valid star graph. | Calculate the wealth of each customer Find the maximum element in array. | Array,Matrix | Easy | null |
452 | hey guys welcome back to another video and today we're going to be solving the lee code question minimum number of arrows to burst balloons all right so in this question there are spherical balloons spread in a two-dimensional space for each in a two-dimensional space for each in a two-dimensional space for each balloon provided input is the start and the n-coordinates input is the start and the n-coordinates input is the start and the n-coordinates of the horizontal diameter since it is horizontal its y-coordinates since it is horizontal its y-coordinates since it is horizontal its y-coordinates do not matter and hence the x coordinates of start and the end of diameter are enough uh the start is always smaller than the end value that we have okay so in simple words we're given balloons and we know it's a start value and the end value in terms of horizontal distance and we actually don't care about vertical distance and the reason for that is because there is an arrow which can be shot up exactly vertically from different points along the x-axis along the x-axis along the x-axis a balloon with x-star and burst by a balloon with x-star and burst by a balloon with x-star and burst by an arrow shot at x if the x value is greater or equal to the start value or less than or equal to the end value so what does that mean so real simply uh let's say we have balloons horizontally placed and we're shooting an arrow from underneath and that arrow is going to burst blue and now the question over here is okay and one more thing there's no limit to the number of arrows that can be shot and arrow one shot keeps traveling infinitely so it keeps going in that vertical direction and it keeps on going until all the balloons are bursted okay so given an array of points where point i is equal to the start value comma the end value return the minimum number of arrows that must be shot to burst all balloons all right so as it is i think the question is a little bit confusing but i just want to visualize it so i think that makes it a lot easier to kind of understand so over here i have a quick scale uh it's not obviously it's not equal but i think it does the job so we have numbers from 1 through 16 and this over here is going to be representing a horizontal scale so what i want to do is i'm going to be looking at an example and i will be drawing out the points that we have so one of the points and uh just so you know i'm following example one so one point starts at 10 so i'm drawing that year and it goes all the way up to 16 and these values are inclusive so this represents the balloon 10 common 16. now it could have a vertical height of whatever but it really doesn't matter since when we shoot an arrow from the bottom up it goes up infinitely so we have 10 comma 16 here and i'm just gonna draw a few more so then we have two comma eight so it starts at two and goes all the way up to eight and let me just label each of these so it's easy to understand and then one more we have is one so we start out over here at one and we go all the way up to six i'm sorry if the drawings are not exactly correct but yeah and finally we have seven comma 12. okay so we have 7 over here and then we're going to go all the way up to 12 which is around there okay so this is 7 comma 12. perfect so each of these red bars represents one balloon and i'm going to be using the color green to show if an arrow was shut so what i'm going to do is let's say we shot an arrow at the value 1. so if we shot at arrow 1 it would go up like this and it will keep going infinitely all the way up to the ending now over here when the arrow goes up does it hit anything that's the question and the answer is yes so the arrow over here is going to end up hitting the balloon one comma six so we can just kind of cross it off and say that this balloon has been hit so let's say we shoot one more arrow and this time we shoot it at the number seven so we're shooting it over here and when we shoot the arrow at number seven what happens is actually two balloons get bursted so what's going to happen is the balloon 7 comma 12 gets bursted and the balloon 2 comma 8 oh sorry about that so 7 comma 12 gets bursted and 2 comma 8 also gets bursted and the reason for that is because this over here is going through two comma eight and finally let's say we're shooting another arrow of 14 uh and again we can shoot how many other arrows we want then obviously this over here is going to get burst at 10 comma 16. but now the question that we really want to answer is how can we burst all of the balloons by using the least possible uh number of arrows now the highest value we can get is going to be the same number as the number of balloons we have but let's just look at a better way that we can do this so what i would do over here we could maybe shoot an arrow at the number four or even five or six or even three or even two actually so from two all the way to six we could shoot at anything i'm just gonna shoot a choose four so currently i'm going to shoot an error for and what's going to happen when i do that is i'm gonna burst one comma six and i'm also going to burst two comma eight similarly over here uh you can kind of see that there's an intersection over here and this intersection starts at 10 and it goes all the way up to 12. so if i shoot anything between or including in that range so let's say i just choose another number 11 so if i shoot through 11 this value bursts and so does this one so over here what happened is we were able to burst our balloons using just two arrows and this is the minimum arrows that we can use in order to burst each and every balloon that we have so in this case we're going to have a value of 2 and that's what we're going to end up outputting all right so over here we're given the list of start values and end values of each balloon and this is the same thing as what i drew over here and what i want to show you is how can we sort our list in a way which makes it easier to find out whether something is in a specific interval or not and in order to do so we're going to be sorting these values according to the final or the last ending value that we have over here so i'll be sorting it according to that and i'll just do that along with this so what is the smallest value is six and that's what we're going to have first so we're going to have one comma six then we have eight uh then we have so that's two comma eight and then uh twelve so seven comma twelve and finally we have ten comma sixteen so i'll be going through this step by step and oh wait sorry okay that's a sixteen and that's ten okay so we'll be having two variables so one is going to be our count and well in simple words that's what we're going to end up outputting this is basically the number of arrows we need okay so that's the count that's what we're outputting it's going to start off at zero and finally we're going to be having one more variable and i'll just call this value the ending point okay and this ending point over here is basically going to tell us when the certain interval is ending but the question is how do we actually start this value at so in the beginning i'll just start off at negative infinity and as we move on we're going to change it so again to be more to be clear we're going to be using this area over here which is sorted according to the ending values so in the beginning we have a value of one comma six and what we're going to do at each iteration we're going to check whether the values that we have over here are inside of the ending value that we have over here or if it's inside of that interval so in this case to do that we're going to check is 1 greater than this ending volume and it is so 1 is greater than negative infinity so in that case what's going to happen is our count now increases to by 1 so now this is going to become 1 and the ending value is now going to be whatever the ending value is for that certain balloon at that instance so in this case the ending value is now going to have a value of six okay so now we're going to go on to our next balloon so over here we're going to check is 2 greater than the ending value which is 6 and it's not so 2 is not greater than 6 and what that is telling us is that this value over here is inside of the interval one comma six and that perfectly makes sense as you can see one comma six and two comma eight is inside of that right there is an arrow which can go through both of them as we can see by the x marks right over here so basically that's telling us that one arrow is enough for both of these so that's perfect and in that case we're just gonna kind of skip it right nothing's going to happen our count doesn't change ending doesn't change but now let's say we go to the third balloon now at the third balloon the value that we're starting off at is seven and seven over here is greater than the number six so in that case what's going to happen is that this ending value over here is going to get updated to now 12 since that's the ending value of this balloon and the count is also going to get updated and the value it's going to get updated to is going to increase by one so one plus one equals to two perfect so two and twelve and then finally we have uh 10 and 16 and 10 is less than the ending value which is 12. so in that case nothing happens as well and our count ends up being 2 which perfectly makes sense uh since over here we would have something going through this and uh just to kind of and if you think about this intuitively it actually makes a lot of sense so if the starting value is less than the value six then obviously we're going to have a balloon which does not need an extra arrow so similarly let's say we had something like three comma four is less than six and it will be right over here so three comma four and that is inside of the interval that we have so that's all we're going to be doing it's pretty simple uh hopefully that did make sense and now let's see how we can actually implement this in code all right so let's start off by actually redefining our points variable so in the beginning it's just a list but we want to sort it according to the ending values and do that we could just use the sorted method in python and what exactly sorry what do we want to sort so we want to sort the points and how are we going to sort it so to do that we're going to be giving it a lambda function so key is equal to lambda x and then we're going to be sorting it according to the ending value so whatever is at the first index so that's what we're going to be sorting it by so now that we have our sorted list we want to just uh define a few variables before we go inside of the for loop so over here we're going to have our count which is exactly what we're going to end up returning and this count is going to have a value of zero in the beginning and we're also going to have an ending value and this ending value is gonna start off at negative infinity so to do that we can just do float negative in oh sorry float negative and there we go okay god i can't spell okay uh so that should be it and now we're gonna go inside of a for loop and over here we're gonna be getting each of our balloons so i'll just say for balloon in points okay so this gives us the x comma y that's a balloon basically just holds the x comma y coordinates and over here what we're going to do is we're going to check is our starting value for that balloon so if balloon and the starting value is at the zeroth index and if this value is greater than our ending value and the ending value is what we ended up defining over here and if that is true then in that case that means we're gonna increase our count by one so count plus equals one and one more thing that is going to happen we're going to update the ending value that we have over here now the ending value is going to be whatever the ending value is for the certain balloon that we're on and to get that it's just going to be whatever is at the first index so balloon one and that's really it and at the very ending of this we're just going to end up returning the count which is the number of arrows that were shot so let's submit this and as you can see our submission did get accepted so finally 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 | Minimum Number of Arrows to Burst Balloons | minimum-number-of-arrows-to-burst-balloons | There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array `points` where `points[i] = [xstart, xend]` denotes a balloon whose **horizontal diameter** stretches between `xstart` and `xend`. You do not know the exact y-coordinates of the balloons.
Arrows can be shot up **directly vertically** (in the positive y-direction) from different points along the x-axis. A balloon with `xstart` and `xend` is **burst** by an arrow shot at `x` if `xstart <= x <= xend`. There is **no limit** to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path.
Given the array `points`, return _the **minimum** number of arrows that must be shot to burst all balloons_.
**Example 1:**
**Input:** points = \[\[10,16\],\[2,8\],\[1,6\],\[7,12\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 6, bursting the balloons \[2,8\] and \[1,6\].
- Shoot an arrow at x = 11, bursting the balloons \[10,16\] and \[7,12\].
**Example 2:**
**Input:** points = \[\[1,2\],\[3,4\],\[5,6\],\[7,8\]\]
**Output:** 4
**Explanation:** One arrow needs to be shot for each balloon for a total of 4 arrows.
**Example 3:**
**Input:** points = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\]\]
**Output:** 2
**Explanation:** The balloons can be burst by 2 arrows:
- Shoot an arrow at x = 2, bursting the balloons \[1,2\] and \[2,3\].
- Shoot an arrow at x = 4, bursting the balloons \[3,4\] and \[4,5\].
**Constraints:**
* `1 <= points.length <= 105`
* `points[i].length == 2`
* `-231 <= xstart < xend <= 231 - 1` | null | Array,Greedy,Sorting | Medium | 253,435 |
255 | hey what's up engineers today we're doing question number 255 verify pre-order sequence in a binary search pre-order sequence in a binary search pre-order sequence in a binary search tree before you continue please check the description because if there's anything incorrect in this video i'll be making those corrections in the description since i can't actually go back and edit the physical video itself if you find anything incorrect or misleading in this video please let me know in the comments i will check it out and i will update the description accordingly i don't want to be giving out you know misleading or false information um if you guys like this video i mean it's my first ever video let me know as well it can be any constructive criticism it's all really appreciated but today we're working on question number 255 which is a abstract question that's going to require us to think of binary search trees in a very specific way and it took me a couple hours to figure it out to fully understand what we were actually doing and i really hope you guys get some awesome uh information out of this all right so let's go ahead and read over the question real quickly given an array of numbers verify whether it is the correct pre-order traversal sequence pre-order traversal sequence pre-order traversal sequence of a binary search tree which i'll be referring to as a bst you may assume each number in the sequence is unique and so i just wrote a quick thing down here the rules of the bst are pretty straightforward everything in the right sub-tree sub-tree sub-tree has to be less than the root or so it has to be greater than the root everything in the left sub-tree has to everything in the left sub-tree has to everything in the left sub-tree has to be less than the root and this holds true for all cases so even if we have something like for example 9 up here and then we hold 6 and 12 and then we have 11 and 14. we can't have the number i don't know 7 down here because seven is well first of all sure it's less than this that's fine however seven is not less than this so it's not fine all right so let's go over what a pre-order is a pre-order pre-order is a pre-order pre-order is a pre-order is root left then right so keep in mind if we have a tree a figurative tree such as 99 98 100 and then 98 goes all the way down to zero like just you know 98 more numbers down there 97 more numbers down there all the way down to zero our pre-order all the way down to zero our pre-order all the way down to zero our pre-order will always go left it will go left infinite times theoretically and root and right once before it repeats the cycle so what does that mean so it does this one time this infinite this one time and then it repeats so it'll go route 99 all the way down the left to zero then right 100. now if 100 happened to have you know infinite children left it would also go infinite down left of 100 and then it would visit 101 for example keeping this rule in mind let's try to actually apply it to a visual binary search tree that we have here so visual binary search tree we know that we're going to start at the root and we're going to go left infinite times so that means we're going to start selling this out of the way we're going to start here and we're going to go sorry we should start at the root here and we're going to go left all the way down we're done that's our first iteration our next iteration is we're going to go left again well of its first child which happens to be here that's our second iteration then we're gonna go left again third iteration then we're gonna go left again fourth iteration that's a pre-order because if you think that's a pre-order because if you think that's a pre-order because if you think about pre-order right now if i do a about pre-order right now if i do a about pre-order right now if i do a pre-order of this it'll get me five pre-order of this it'll get me five pre-order of this it'll get me five two one 4 8 6 9. so this is a valid binary search tree since um 5 2 1 4 8 6 9 just adds up to a valid binary search tree what if we had a similar binary search tree but that wasn't valid what if we had something else five two one four eight let's just do three here three uh four nine like that well everything looks good until you get to this four here and in our loop here how are we supposed to catch that because if you think about it we're only going left only sure one is less than two which is less than five so this is a fine loop this is a okay loop iteration one you know then we go three is less than well nothing else so that's fine as well iteration two but then we get eight and four and all this thing sure four is less than eight but four is not less than its highest parent five and then we go through 9 yep 9 is fine as well okay however this one's not fine so we need to keep track of the immediate parent of 4 first of all so in case you know this was something like you know like 12 well that's not less than eight at all that should be an immediate no but even if something like this like four we should see that okay well four sure is less than eight that's fine however four is not less than 5. so we can do this by just looking at the left sub-branches so if i looking at the left sub-branches so if i looking at the left sub-branches so if i give you if we pull up another example here we're going to have an example of 5 2 6 1 and 3. now using our little algorithm formula left subtree kind of only pattern here we're going to recreate this using just left sub trees so we're gonna start with five and we're gonna go okay five is that now we're looking at two well two is less than five so let's tell me two should be in its left subtree and then six well now six is no it's not less than five so it's telling me we're about to start a new iteration of subtrees so now we're starting at six here okay one is less than six that's fine and three is not less than one so that tells me we're gonna start a new iteration of subtrees here assuming six is apparent three there so actually let's make it simpler three there now this looks kind of weird right because you're like looking at me like what the hell why is this tree um not really a tree it's just three linked lists side by side so the way we can think about this is if we conceptualize what we just drew we just did five is the root the grand root the master root whatever you want to call it the highest root two is its left we know this for sure and then we hit six which is the right of either two or five that's gonna be very difficult if you're using three separate trees like we just did so instead what we're gonna do is we're actually gonna combine this into one tree so we have five and two and then we're gonna add six however our six is greater than two so our six is going to move up one and we're gonna get rid of two and our six is greater than five so we're gonna six there our six is greater than five so our six is going to move up once more and get rid of five which is going to give us the resulting tree of six that's it okay so now let's look at the number one is less than six so one goes there that's fine and three is there three moves up gets rid of one we have three there and you know our resulting tree is gonna be six and three and you know you might be looking at it you're like oh yes three is less than six therefore it's a valid bst it's good to go however there's this one here is breaking another crucial rule which is the same rule here where the four is less than the five because if we just take this pattern that we did we had five and two and then since we know our six is greater than five it's therefore going to be there we know our one is less than six so it's going to be there and we know our three is greater than one so it's going to be there that is not a binary search tree one and three are both less than five therefore these two should actually be here in the left subtree so how can we keep track of this how can we keep track of well what uh previous what should we be comparing to really because we can't keep track of every single parent we can do this by keeping track of the last removed parent because if you think about it every single time we remove a parent when we go five and two and then we insert six we remove two here and we remove five and six comes up here but what this is actually telling us if you think about it like a tree you're telling me that you just want me to put six in here however the six is not going to be the left subtree of two because remember we're looking at left subtrees so every single time we remove one we're actually moving right so you're telling me it's not going to be the left of 2 so it's going to be to the right of 2. but then you're also telling me it's not going to be left of 5 so it's going to be to the right of 5 and there's no nothing else higher up here to go so therefore it's going to go there so whenever we pop off or whenever we remove a parent or a parent node parent root whatever you want to call it that is telling us that we're transitioning from a left state so we're going in this row here to a right state so for example without looking at liquid tree if we just take a sub array of this array we have here 5 2 and 6. if we just take the subarray we're telling where we're seeing that 5 so we're seeing that 2 is less than 5 therefore 2 is to the left of 5. then we're seeing 6 is greater than 2 therefore 6 is to the right of 2 but 6 is also greater than 5. therefore 6 is going to be to the right of 5. and then when we keep going on you know we add 1 and we add whatever three whatever's next this pattern keeps going however this is not a bsd and using this weird abstract mathematical formulas is not going to help so let's actually translate this into a pattern which we can code and i'll give you a hint it's much easier than it looks so let's look at the same array one more time now but this time let's follow two patterns that we know of we know for every integer x for every integer shorten the int x we know that first if the last removed whatever node or it's called ant actually rust removed and is greater than x and it's not a b s t so let me show you what this means on an actual example remember using our left only tree our left only well not really a tree let's call it a tree for now our left only tree we are gonna have five we're gonna have two and then you're gonna try shoving a six in there and the six is gonna bubble up to there and the last removed is going to be five so the last removed is going to be five the resultant tree's gonna be six then you're gonna shove a one in there and we're gonna check this first rule here is the last removed five is it greater than the current integer x one yeah it is therefore it's not a b s t because when we remove this we're telling it we're going into this right subarray of five and everything to the right of five must be greater than it okay so our second rule or our second pattern our second whatever is we're going to bubble up x to where its parent is greater or no and that's the exact same thing we did in this example right here so let's do it again we had five and two i'm going to get rid of all this here we had five and two like that and we put six in here we bubbled it up we bubbled up to two and its parent is still less than it so we bubbled it up one more time and its parent is now null so therefore we get the resulting tree of just six okay so now you're probably looking at this hoping it makes sense you have that aha moment and now you're looking at this example here and you're thinking well it doesn't make sense to use a tree for this or like what type of structure would we use for this that's a really good question so if you look at it the operations we're doing on this data structure so i'm going to move this actually over here so and our data of 5 2 six one and three the operations we're doing on this are mostly insert at the end and remove from the end which sounds very much like our favorite data structure stack because if i do the same example one more time but using a stack you'll do the exact same thing we have five we have two then we have in the waiting line we have in our current so our x is going to be 2. we're going to put 2 in there our x is going to be 6 and 6 won't fit in there so we're going to remove 2 5 and 6 is sorry 6 will fit in there but 6 is greater than two so we're gonna remove two six is greater than five we're gonna remove five that's gonna give us the resulting stack of six okay now our x is gonna be one so i should put a little colon there one is gonna fit perfectly there and next one's gonna be three is gonna fit perfectly there this is just the second rule by the way i yeah if you're paying attention you should have immediately seen that this right here breaks the first rule and so what we can do is whenever we pop off we can keep track of the last number we removed so our last removed lr can be two and then our lr will be five here and our lr won't change it'll still be five here and so we put in that one it should have been a flag right there that five is greater than one therefore it's invalid so let's look at a valid example then how about that i've looked at so many bad examples you think that nothing's a bst okay so let's look at this example where it's actually going to be a valid binary search tree so let's follow the same pattern here so we're going to have a stack here and let's do a stack actually down here okay and we're gonna have our x which is what we're inserting and then we're gonna have our lr which is our last removed it's gonna start at being let's say negative infinity okay so let's go and look at the first number 5. check the first condition is the last removed greater than x is 5 so is negative infinity greater than 5 no so it's fine and then we're going to bubble up x we're to a point where it's greater than or null and it's null so we're going to put it right there okay let's look at the next one let's look at 2. is 2 greater than the last removed which is negative infinity or sorry is the last removed greater than 2 well no it's negative infinity nothing is greater than nothing's less than negative infinity so 2 is going to smack on right there now is 2 greater than 5 no so 2 is going to sit right where it's at let's look at 1 now 1. is 1 less than negative infinity no and is one greater than two no it's gonna sit right there perfect now let's look at the next one three is three less than negative infinity no so let's go put her there but is three greater than one yes it is so we have to remove one take it out and set the last remove to one now is so it's now our array is going to look like our stack's gonna look like this okay that was three greater than two yes it's still greater than 2 so it's going to keep bubbling up so we're going to move that put it there update our last move to 2. okay so remember we're bubbling up we're not just doing it one time we're doing it until bubble up x until it's parent so let me change this to until it's parent okay now let's look at the next one look at six here okay smack six in there well six is greater than three so we're going to have to remove the six actually sorry before i did that we should have checked the first one is six less than 2. okay so is the 6 less than 2 well no it's not so therefore the first condition is not met so it we continue then we're going to bubble up x so we're going to put 6 in there and we're going to bubble it up until its parent is greater or null so we have 6 in there we're going to remove the 3 put the 6 there last row is going to be 3. then we're going to remove the 5 and put the 6 there because 6 is still greater than 5 and put the 5 there and now we're out of numbers so far it looks like it's a bst all right so let's look at the actual code now i haven't spent too much time trying to explain the actual code because i feel like i did a fairly good job in the previous section and so here's the code uh this is the algorithm up top here uh so for every last removed integer if it's greater than x then we do not have a bst and we're gonna return false otherwise we're gonna keep bubbling up x until its parent is greater or null so you know we're using a stack our last pop is going to be a min value and the reason for that is because if we have negative values in the um i didn't use like 0 or like a small number because theoretically there could always be something smaller min value is the absolute smallest that we can get out of java for every x in the pre-order list we're for every x in the pre-order list we're for every x in the pre-order list we're going to follow the first rule where if the last removed integer is greater than the current integer then we know we don't have a bst because it violates that rule and the reason we use the greater than and not greater than or equal to is because we are assuming that each number is unique therefore we cannot have two duplicate numbers and then we're going to follow the second rule of the algorithm where we're going to bubble up x until its parent is greater or null and so while the stack is not empty and x is greater than the parent we're just going to pop off the parent save it and we're going to push x on once we find the uh right spot for it and then once we're done this uh for loop since we went through every single x and it never violated the first rule it must be a bst then um as for efficiency this is a little weird to calculate we know it's for sure o squared of n here because we are going over the pre-order list however here we the pre-order list however here we the pre-order list however here we are um theoretically it could be um like n log n because we are inside the end loop first of all the log n comes from the fact that if our array contains continuously descending numbers or ascending numbers so if we have something like 1 2 3 4 5 6 7 8 9 10 it will continuously pop off the last immediate one and so it's really like actually n because it's just removing the one previous one every time however if we have something like you know 10 9 8 7 6 5 4 3 2 1 55 that 55 is gonna have to remove the majority of the array so it's the complexity on this type of question is a little ambiguous a theoretically worst case scenario i believe it could be n log n however please correct me in the comments and if uh if the actual efficiency is discovered i will put it in the description so if you're watching this at a later date check the description it might actually have the actual efficiency of this algorithm anyways thank you guys so much for watching uh first ever video i really like doing this type of stuff so if you guys enjoy it too let me know by using the thumbs up just leave me a comment and um i'm gonna keep making these uh time permitting and energy permitting but um i really hope it's helped you guys on your path forward and uh happy coding | Verify Preorder Sequence in Binary Search Tree | verify-preorder-sequence-in-binary-search-tree | Given an array of **unique** integers `preorder`, return `true` _if it is the correct preorder traversal sequence of a binary search tree_.
**Example 1:**
**Input:** preorder = \[5,2,1,3,6\]
**Output:** true
**Example 2:**
**Input:** preorder = \[5,2,6,1,3\]
**Output:** false
**Constraints:**
* `1 <= preorder.length <= 104`
* `1 <= preorder[i] <= 104`
* All the elements of `preorder` are **unique**.
**Follow up:** Could you do it using only constant space complexity? | null | Stack,Tree,Binary Search Tree,Recursion,Monotonic Stack,Binary Tree | Medium | 144 |
1,492 | hi everyone welcome to lead code daily challenge so the problem for today is to find the kth factor of a given number n so we will be given two positive integers l and k we need to find the kth factor of the given number n so the given integer n so as you know the factor is uh how do we define a factor so if the number the given number divides the integer n then the number is a factor of the integer n so if you take an integer i and if it if the remainder of the n percent i is 0 that means if i is dividing in with a remainder of 0 that means i is a factor of number n so we need to consider all the factors of n sorted in ascending order and then return the kth factor in this list and if there is no kth factor that means if they want a factor which is beyond a k which is beyond the number of factors of the number n then we need to return minus 1 so let's say we have a m number of factors for the given integer n and if k is greater than m that means we don't have a kth factor then we need to return -1 so let's look then we need to return -1 so let's look then we need to return -1 so let's look at the examples so the given number n is 12 and we need to find the third factor for the first 12 so the factorist is 1 2 3 4 6 12 because all these numbers will divide 12 with a remainder of 0 so the third factor here is 3 and we need to remember that we need to include the number also in the factor list we have 1 as well as the number itself in the factory list and in the second example we have n equal to 7 and k equal to so the factor list here is 1 comma 7 because n is a prime number so we don't have anything other than 1 and the number itself so that so the second factor is 7 and here we have n equal to 4 and k equal to 4 and the factor list for the integer 4 are 1 2 4 and we don't have a fourth factor here so we need to return -1 and here we have n we need to return -1 and here we have n we need to return -1 and here we have n equal to 1 and k equal 1 and it is straight forward so the first factor is 1 itself and in example 5 we have thousand and three so the third factor is four in the list so it should be pretty straightforward and let's see the constraints so the k n can go uh from one till thousand so it should be okay the constraints are not too hard so even off and square approach should be fine but anyway the problem is straightforward so let's see let's look at the hints provided here so the factors of a number n will always be in the range 1 to m so that is pretty straightforward and from the hint to keep a list of all factors sorted loop i from 1 to n that means we go from 1 to n and then check if the number is dividing n with a remainder of 0 then we add it to the our factories and we make sure that they are in the sort order so i don't think we need any further explanation so let's take a look at the source code so first take a vector of integers so that we store all the factors then as shown in the hint as provided in the hint we go from 1 to n we can go till n because we know that beyond n by 2 the number will not divide the given integer so let's say we have an 10 and equal to 10 so we know that beyond 5 n by 2 m by 2 is 10 by 2 is 5 so beyond 5 we don't have to check because 6 7 8 9 they don't divide 10 so only thing is we just make sure that we add n to the factor then so we go for loop from i equal 1 to 1 by 2 then if the number is a dividing given integer when remainder is 0 then we store our number in the factory list and finally we need to push the number itself because n also divides n and from this factor list we need to make sure that the size is greater than or equal to k because if it is less than k then we need to get a minus 1 so if it is size is more than k then we written factor of k minus 1 because k minus 1 is the index of the k-th k minus 1 is the index of the k-th k minus 1 is the index of the k-th factor because the index starts from 0 to 0. so let's execute and see yeah so it works fine let's submit and check so the solution has been accepted yeah so run time off zero milliseconds so because this is straightforward solution and it is a wave and solution we are not doing anything extra here let's look at the java solution it should be pretty straight forward because there aren't much library functions so instead of vector we take a real list because we have a release to store dynamic number of integers then again we go from uh one to n by two then if the number of the given integer divides n then we add it to our factors so factor dot add then finally we add uh and itself to the factory list then we just check if the size is within the limit of size is more than k then we get we can use the function factor.get to we can use the function factor.get to we can use the function factor.get to get the integer at the k minus 1 index because index starts from zero otherwise you'll written minus one so i think we can directly submit is pretty same as c plus except that release then let's see the details here so you enjoy it is pretty fast one milliseconds because that time complexity here is often because we don't do anything more than in fact we do we process the integers from one to n by two not even n but still the time complexity will be when n grows large the time components will be in the order of n and when it comes to space complexity it will be uh it will not be it will be in the order of for n in fact it is less than n because the number of factors will not be more than any day yeah so that's it thanks for watching thank you | 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 |
468 | all right so this question is validated IP address so in this question you are giving the string query IP so you either return ipv4 or IPv6 and if both are links are not true then you return neither so ipv4 is this function so it's starting from 0 to 100 to 255. and the X you know the X represents the you know the string array uh a split by the dot right and then you cannot have a leading zero and you also cannot apply some uh crappy you know string so this is not allowed so IPv6 you can only contain digit and lowercase later and also the application status from a to f so the reason why you know contain a to F this is because you know you have phones uh 0 to 16 for the hexadecimal hex is for 16 right so uh you just have to follow the constraint so let's talk about some uh some constraints in ipv4 so I believe before you want to work you want to get a basically you want to get rid of what get rid of dating zero right and this is pretty much it right and then also the you know the ranges between the zero to 255 so let's just start writing about ipv's ipv4 right so uh I need a helper function I'm going to just create a Boolean and I p V for and string IP so uh for the you know for the basically you want to just you know split by what by dot right and then in this one like you cannot just split by dot like uh there are some Corner cases right so you want to use a regulation uh you know a regular expression using the backslash so backslash without a width name so just go on Google Live what does this mean and then if the Swindle dance that's not equal to four right which means they don't have what they don't have four different uh integer right you just want to return false all right so now we can trivialize so full string to string right Traverse the string so I'm going to just check uh the last one is greater than one so for the first if statement I'm going to check leading zero right and also string dot chart at s0 is equal to zero uh sorry dot equals sorry zero so if this is you know um if this is happening just return first this is checking leading zero right if uh if a security screen is about zero one you know and then you want to just return the false right all right so next one I want to use it and try and catch so the reason why I'm usually try and catch is because the leak covers through you the uh number format exception I'm going to call E and if this is happening just return false so why I need to try and cash because I'm going to pause the screen to end so integer num equal to what in digital parsing the string so if this is not working you need to try and cash to catch your arrow and then your return false right so I just have to make sure the norm is if the num is actually equal to no all the norm is less than zero all the num is greater than 255. so this is like a range between I mean range uh range is cool right so you won't just you know return false right and then at the end of the ipv4 you just want to say return true but I can just using the helper function I just met so ipv4 for the query IP right and this is ipv4 it's true then just return the string all right so the next one is going to be create IP V6 and then using the curry and then turn ipv 6 right and the last but not least return leader all right so we need to create a function for public Boolean IPv6 string IP right we just need to talk about this so what does this mean like again I uh the lens should be what the one two three four five six seven eight okay it has to be eight right if this is not 8 Hour Return flows and I still go into Traverse and when I Traverse I need to check uh my current uh sorry uh my current uh every single chart right I need to check for the chart I need to check my digit I need to check my lowercase later I need to check my upper case later and if everything is working then I don't have to worry about this right so yeah here we go and Maybe maybe I can stop holding right so showing the split type sorry so you still spill color dot middle one and then if the shootout lens is I mean that's not equal to eight right just you just have to make sure I just have to make sure this is what this is eight one two three four five six seven eight right eight and then if this is not eight you return false and also if you look at the pattern uh it has to be less than equal to a fourth four right for every single uh string right so just say string sorry to follow string so if string is actually equal to no or sorry if students actually good or not okay string cannot be no definitely right but if string dot length is y is greater than four is greater than 4 or Swindle length is actually equal to zero uh let me Swap this so this might be more real readable right each string.lens is actually include each string.lens is actually include each string.lens is actually include zero I mean this is possible string is actually equal to node and when you split then you'll get an error for sure but I don't have to check for string equal to node basically right I didn't check for no for here so I don't check for no for here so if this is happening your return Force and then I just have to Traverse every single chart inside my string so if C is digit right if a c is digital then I can use a character that is stated SC and I don't have to worry about right I don't I mean I don't have to worry about like what did you what digit it is it can be zero it can be one it can be nine doesn't matter but if this is digit it's doable I just have to check for Korean what uh current character right so I'm going to just you know convert the currency to lowercase so I don't have to check for the uppercase or lowercase so I just have to say if C is less than a or C is what greater than F I will return first and at the end of this I'll return true so there are a lot of typing but you know this is pretty straightforward uh if C is digit then I don't worry about this and if this upper is this uppercase I convert to lowercase is C slow case you know low case to Locus is you know no it doesn't change right so I will just make sure C is in the range between what a to F it if C is not inside the a2f range I will turn false so let me run it oh I see where's my arrow okay here is it um so string dot chart at right this is the chart so what am I doing using so yeah so this might be okay oh so uh look at this so this is what IPv6 right and I'm actually one two three four five six seven eight so I'm actually um forget one uh one constraint so here is it let me pause the video for a second yes I mean I don't have to pause you know I just realized I'm using a semicolon right here I'm not using a DOT huh yeah you know doable yes all right so um should be okay so let's talk about the time in space or this one so you are traversing this ipv ipv4 right and you know like when the string is ipv4 if a string is ipv4 I'm coming to here I'm just flipping it out and yeah pretty much it right so the time this is time I mean this is also space all of info representative IP and all of them full of time you know check for every single character be honest like you actually you know post it in you know converting the string to in so all of them or uh all of them for the time right and then follow the floor space is also all often in ipv4 IPv6 is actually still the same all of them and represent the end of Ip and all the friends again full time so um yeah so let me do some prick break point right here start debugging start alright so this is a query so I will enter here oh here's it so just checking you know yeah so again he will return uh straightforward solution so uh how about this is also true well how about this uh let me just change a little bit to what to do so start debugging and this will actually return first right so in a query I mean I don't have to trade this will give you false so I will jump to here right step into the function so I'm still checking every single character sorry this one is 2001 doesn't change next one uh let me have a breakpoint right here as well I'll break all right so I'm checking zero I'm also checking the next one zero I'm also checking a two e checking next one zero three seven zero checking the last one seven three two this will actually give you false two right convert to a lowercase and it's true inside my range no you return Force and yeah so your return needle for this IP address all right so this question is a little bit long and spend some time understand the constraint and you should be okay I still have questions leave a comment below subscribe if you want it and I will see you next time bye | Validate IP Address | validate-ip-address | Given a string `queryIP`, return `"IPv4 "` if IP is a valid IPv4 address, `"IPv6 "` if IP is a valid IPv6 address or `"Neither "` if IP is not a correct IP of any type.
**A valid IPv4** address is an IP in the form `"x1.x2.x3.x4 "` where `0 <= xi <= 255` and `xi` **cannot contain** leading zeros. For example, `"192.168.1.1 "` and `"192.168.1.0 "` are valid IPv4 addresses while `"192.168.01.1 "`, `"192.168.1.00 "`, and `"[email protected] "` are invalid IPv4 addresses.
**A valid IPv6** address is an IP in the form `"x1:x2:x3:x4:x5:x6:x7:x8 "` where:
* `1 <= xi.length <= 4`
* `xi` is a **hexadecimal string** which may contain digits, lowercase English letter (`'a'` to `'f'`) and upper-case English letters (`'A'` to `'F'`).
* Leading zeros are allowed in `xi`.
For example, "`2001:0db8:85a3:0000:0000:8a2e:0370:7334 "` and "`2001:db8:85a3:0:0:8A2E:0370:7334 "` are valid IPv6 addresses, while "`2001:0db8:85a3::8A2E:037j:7334 "` and "`02001:0db8:85a3:0000:0000:8a2e:0370:7334 "` are invalid IPv6 addresses.
**Example 1:**
**Input:** queryIP = "172.16.254.1 "
**Output:** "IPv4 "
**Explanation:** This is a valid IPv4 address, return "IPv4 ".
**Example 2:**
**Input:** queryIP = "2001:0db8:85a3:0:0:8A2E:0370:7334 "
**Output:** "IPv6 "
**Explanation:** This is a valid IPv6 address, return "IPv6 ".
**Example 3:**
**Input:** queryIP = "256.256.256.256 "
**Output:** "Neither "
**Explanation:** This is neither a IPv4 address nor a IPv6 address.
**Constraints:**
* `queryIP` consists only of English letters, digits and the characters `'.'` and `':'`. | null | String | Medium | 752 |
322 | Hello guys welcome to disrespect video andar only coding and horses bihar assembly problem that is gold coin change and where given point of different denominations and total amount of money amount friday function to compute the furious number of the journey to make update amount is the volume An Incident - One Which Makes You a Winner Events Incident - One Which Makes You a Winner Events Incident - One Which Makes You a Winner Events Number of Women Should Take the Example in This Example This Point and Denomination 121 500 Ireland Possibility This ₹1 ₹1 ₹1 ₹1 ₹1 ₹1 500 Ireland Possibility This ₹1 ₹1 ₹1 ₹1 ₹1 ₹1 500 Ireland Possibility This ₹1 ₹1 ₹1 ₹1 ₹1 ₹1 ₹1 So This Level ₹1 So This Level ₹1 So This Level Times Now Getting to File Rupee Coins And Voting On 200 Reporting And ₹2 Point Five Times 200 Reporting And ₹2 Point Five Times 200 Reporting And ₹2 Point Five Times And Attractive One Rupee Coin Military Reading Scars But Still Its Alarms Loot Number Candy 25.23 Hours 2017 You Can Take ₹1 ₹1 Digit Of ₹1 Will Be 323 325 Number To This Digit Of ₹1 Will Be 323 325 Number To This Digit Of ₹1 Will Be 323 325 Number To This Problem k subscribe and subscribe the Channel 121 share neeraj problem vectors oil lekar dp devil and angel om initially 500 k notes in this celisous details what doing am just trying to make what is the time what is the subscribe to make ₹1 ₹1 ₹1 ₹1 ₹ time what is the subscribe to make ₹1 ₹1 ₹1 ₹1 ₹ time what is the subscribe to make ₹1 ₹1 ₹1 ₹1 ₹ 1 ₹1 Supposed To Make Sure Subscribe To My 1 ₹1 Supposed To Make Sure Subscribe To My 1 ₹1 Supposed To Make Sure Subscribe To My Channel Subscribe To 120 Million Readers Every Day And Sunao Left Right To Understand The Dry Sequence Lass Co Forward To Drops Understanding Supposed To May And You Have 0 Posts Related To Rupees From 0001 100000000000000 9th person's rupees during nomination till cash is diet suite 1200 10 minutes and next assistant is next 9 newsroom se or particular word to point to make for 12345 600 the very large amount of ma twe no p Third Piece and Yours of Two Use Points Up to Denomination of Mode Turn Volume Minimum Number of But You Can Make OK So My Number to Make 3D Nomination Withdrawal from IGNOU FlashLights Pimples Balls Subscribe ₹1 FlashLights Pimples Balls Subscribe ₹1 FlashLights Pimples Balls Subscribe ₹1 ₹1 ₹1 OK Good Night I Love You To Go To ₹1 ₹1 OK Good Night I Love You To Go To ₹1 ₹1 OK Good Night I Love You To Go To Next Subscribe In A Reader That Chithi Coins ₹1 Hai Cut In New Window Ok Let's That Chithi Coins ₹1 Hai Cut In New Window Ok Let's That Chithi Coins ₹1 Hai Cut In New Window Ok Let's Go To And Next Data Entry So This Is To Make How To Make ₹1 ₹1 ₹1 To So This Is To Make How To Make ₹1 ₹1 ₹1 To So This Is To Make How To Make ₹1 ₹1 ₹1 To Next PLACES SUBSCRIBE ₹1 ₹1 ₹1 ₹1 Next PLACES SUBSCRIBE ₹1 ₹1 ₹1 ₹1 Next PLACES SUBSCRIBE ₹1 ₹1 ₹1 ₹1 ₹1 IMPORTANT TO PAY ATTENTION TO WHAT IS THIS POINT TO MAKE A ₹1 IMPORTANT TO PAY ATTENTION TO WHAT IS THIS POINT TO MAKE A ₹1 IMPORTANT TO PAY ATTENTION TO WHAT IS THIS POINT TO MAKE A CALL TO THE BHIWANDI DOMINATION TO Kisi Else Last Used Up To The Giver Nomination For This Particular Hote Allottees Point To Denomination 2ND YEAR TO Make ₹1 How Can You To That Can You Right TO Make ₹1 How Can You To That Can You Right TO Make ₹1 How Can You To That Can You Right So Can You Make ₹1 Using Two Rupees Coin Is So Can You Make ₹1 Using Two Rupees Coin Is So Can You Make ₹1 Using Two Rupees Coin Is It Possible Not Possible Than What Will U Care Love You All Care Love You Used For Information You Can You Do You Can You can you will go to the boss Ali ₹1 ka note me ₹1 ₹1 ₹1 to subscribe to Ali ₹1 ka note me ₹1 ₹1 ₹1 to subscribe to Ali ₹1 ka note me ₹1 ₹1 ₹1 to subscribe to ₹1 ke laddu se next alarms data ₹1 ke laddu se next alarms data ₹1 ke laddu se next alarms data entry sunao ya to make ₹2 ok using to entry sunao ya to make ₹2 ok using to entry sunao ya to make ₹2 ok using to form ₹2 point ok so how Can You Do To Make To You Love What's form ₹2 point ok so how Can You Do To Make To You Love What's The Meaning Of This Thank You To you to - 2009 mein do to - 2009 mein do to - 2009 mein do to initially Aamir zero and now you are how to make a ₹2 this two rupee coins to ₹2 this two rupee coins to ₹2 this two rupee coins to America they need only one thing 1212 and you to you can locate the volume to two To Make Love To You To Tubelight More Clear Engine Some Time Will Take Some More Examples Tried To Understand It's So Let's Go To Related Entries So This To Make ₹3 Using Two Rupees Entries So This To Make ₹3 Using Two Rupees Entries So This To Make ₹3 Using Two Rupees Coin Using Two Denominations Of Moksha How Can You Don't See Weather You Take Two Rupees Coin And You Don't ₹2 Positive Tattoo Rupee Coin And You Don't ₹2 Positive Tattoo Rupee Coin And You Don't ₹2 Positive Tattoo Rupee Coin Third Option You Have Elaborate Systems Paid News Coins Of ₹2 Previous One To Three News Coins Of ₹2 Previous One To Three News Coins Of ₹2 Previous One To Three Times A Guy between two options lights S2 option use ₹2 and here you to I love you to take option use ₹2 and here you to I love you to take option use ₹2 and here you to I love you to take one plus one to the means of the number of switch off join that was required to make remaining amount of money and remaining amount of money S Water Source Pochha Dhund to Make ₹3 If You S Water Source Pochha Dhund to Make ₹3 If You S Water Source Pochha Dhund to Make ₹3 If You Two Rupees Coin Idli Sandwich Using Back to Rupees Coin - 20131 This Particular Amount Rupees Coin - 20131 This Particular Amount Rupees Coin - 20131 This Particular Amount of Money Should Have Made This Amount of Money 151 Minimum Number of Media in OnePlus ₹1 ₹1 - Shabd Don't You to you there data entry now only I don't use rupee coin this is what is and denomination accept rupee coin incomplete making diamond this person feeling that particular data entry size market look this is the meaning of the name of the state ₹1 ₹1 ₹1 Person Ko Minimum Mittu ₹1 ₹1 ₹1 Person Ko Minimum Mittu ₹1 ₹1 ₹1 Person Ko Minimum Mittu Clear After Some Time A More Examples Next Will Have To Make It's A Few Rupees And They Can Use To Rupees Coin Okay So I Can You Two Rupees Coin And Let's Not You Studied For IF Possible Option That I hand election what do you do first ever take the example of curing ₹2 people example of curing ₹2 people example of curing ₹2 people 's eye from I and Tuesday ₹2 crow life ko in 's eye from I and Tuesday ₹2 crow life ko in 's eye from I and Tuesday ₹2 crow life ko in quality including one point to military singer ₹2 crow but the Mukesh remaining amount singer ₹2 crow but the Mukesh remaining amount singer ₹2 crow but the Mukesh remaining amount for minus point to make For rupees and using two rupee coins the remaining amount is damaged bodies for - to any to make to ok I need to damaged bodies for - to any to make to ok I need to damaged bodies for - to any to make to ok I need to make to and how do you make this to so I will use the value not doubtful ok Sudesh What is the good-good doubtful ok Sudesh What is the good-good doubtful ok Sudesh What is the good-good definitely To Make How To Make To Okay For - To Interest Amroha E Look At You That - To Interest Amroha E Look At You That - To Interest Amroha E Look At You That Swarna Mitthu Amount Using Whisper I Kota You Married And Ajay Sallu-Cat Suvan Point Per Urine To Ajay Sallu-Cat Suvan Point Per Urine To Ajay Sallu-Cat Suvan Point Per Urine To Rupees Coin And One Way For Making Front Amount Friend Request To Number Of side on tuesday and use this is very simple data entry jobs data entry sorry for you know i think positive always in you for the 409 plus 2 and subscribe 299 minimum ex they can make the thing and co minimum phone number of for entertaining this 2420 That I Don't See The Thing For Its Soldiers Log In The Next Twenty Let Me Yes OK Sir No Data Entry if you liked The Video then subscribe to the Page if you Just AN Quit Entry About Your Data Entry Awards File OK Just Not During Early 5.35 Is Minimum Three Minimum Right 5.35 Is Minimum Three Minimum Right 5.35 Is Minimum Three Minimum Right Side Brightness Minimum Three Years Now Let Us Look At The Next Example Celebrate All This School E Look At The Next Examples In The Next Example Of How To Make 6 And You Have Again Hero 420 Here User To Rupees Coin And Don't War To Rupees Coin Slice Updates That Used ₹2 Youth To * Coin Slice Updates That Used ₹2 Youth To * Coin Slice Updates That Used ₹2 Youth To * War ₹2 Boys Don't See The Sorry Itna War ₹2 Boys Don't See The Sorry Itna War ₹2 Boys Don't See The Sorry Itna War ₹2 Point Pregnant Whats - 247 War ₹2 Point Pregnant Whats - 247 War ₹2 Point Pregnant Whats - 247 Will Still A To Make For Rupees How To make for rupees in minimum number of wages to celebrate this particular day 2018 201 plus to three light on trees to connect with just look at the data entry now after suicides 5.1 plus to three lenders sorry suicides 5.1 plus to three lenders sorry suicides 5.1 plus to three lenders sorry for this I do and clear that Potato data entry is basic decisions data entry about this point to make sixteen religious chailu candidate entry about suicide madison ivy answer option change when use minimum of one plus two class six minimum of three and 699 three lights minimum is three layer android sony ericsson Key Point Feeling Dubitable Laddu Then Last One Piece Leave It's Not Tried Everything From Left Right Left So This Word Sports On Logic This Liquid Will Be Eric Let's Look At The First Entry ₹1 ₹1 ₹1 ₹ 1 ₹1 The Take me to Rupees during and from the same point of ignorance I can not go for a greater than these leaders will be updated with one similar to the extent to make creative things for Rupee coins so glad that uses for a better way than you can use of Rupees Coin 2000 Rupees Data Entry About Soldiers Killed To That I Will Go To The Native Under Its Interesting Sunaya ₹50 10 Female Version Interesting Sunaya ₹50 10 Female Version Interesting Sunaya ₹50 10 Female Version For Users Of Us In The Running Time During His One And The Rate Eminent Amazon Note 4 - 307 Locator From This Particular Table Note 4 - 307 Locator From This Particular Table Note 4 - 307 Locator From This Particular Table Zoom ₹1000 Users Have To Use One Coin Zoom ₹1000 Users Have To Use One Coin Zoom ₹1000 Users Have To Use One Coin Turing ₹1 And Refine Used For Pyun Hai Turing ₹1 And Refine Used For Pyun Hai Turing ₹1 And Refine Used For Pyun Hai ₹2 Data Entry Jobs Updates Minimum ₹2 Data Entry Jobs Updates Minimum ₹2 Data Entry Jobs Updates Minimum Of One And Two Deficit Which One Should Feel One In This Particular Example In This Particular Attention Iodine Next Step To Make ₹ 5 And I Am Who Is To Step To Make ₹ 5 And I Am Who Is To Step To Make ₹ 5 And I Am Who Is To Make Hussain Andar Love ₹10 Note Make Hussain Andar Love ₹10 Note Make Hussain Andar Love ₹10 Note Slapped In File Path To File Duty Sunao Is Used For Rupee Coins In What They Say For Means Using 1.71 For The Time But Using 1.71 For The Time But Using 1.71 For The Time But Front Part - 01 2013 Front Part - 01 2013 Front Part - 01 2013 Ko Sukoon Deti In What does it is a minimum of two waist three minimum origin good taste 300 will right to hear oaks look at the last date and receptive 16 ruby finally and now everyone date and receptive 16 ruby finally and now everyone date and receptive 16 ruby finally and now everyone for rupee coins with me soft mix rupee manav rupee coin her loud rupee coin and find 50.75 Using This For Rupees and find 50.75 Using This For Rupees and find 50.75 Using This For Rupees Coin Din I Am You Taking One Plus 6 - 2 Coin Din I Am You Taking One Plus 6 - 2 Coin Din I Am You Taking One Plus 6 - 2 ₹2 Super Kings To Live With News24Online ₹2 Super Kings To Live With News24Online ₹2 Super Kings To Live With News24Online Three Minimum Of Two Three Minimum 232 Subscribe Button To Make Sure I Love You All Subscribe On Karo 200 Year Old Lewis Result Declare And Depict A vector in deposit and withdrawal length and breath of the so let's check verses also appoint size plus one light point size plus one white widow decide plus 151 the0 what is the role servi size three years in this nation and have a feeling one and half Inch Plus One Is The What Is The Rather Than 6000 Plus One Too So Let's Go For Now We Are Declaring This And Will Have To Give Surprise Game For The Road Size And Restaurant And Sizes For The Great And Will Initially Give All The Best 2030 For Data Entry Will Get To Know What Will Be The First Infinity Var In Mid Point Amazon 206 I Will Be Left With Nothing But The And Any One I Am In Exam Plate Workshop For Equal To Holidays Equal To One So Equal To One To High Court Decides to feel this point is equal to zero I love you my plus cheers feeling defeated love som one vihar to Buddha Roe and the Olympians to of Shravan equal to one year and he also liked they were fighting from one request for 1000 to 1500 for the role of York State in the native and for starting from one or two from this person avoid subscribe and subscirbe water for example Last in number to make for watching this point 2014 airplane mode zero one to three letters to editor for rupees coin development for this great half quantity fennel and will not help disinvestment what will oo for sit the to isko is coins of isko is rumor - 151 - He is coins of isko is rumor - 151 - He is coins of isko is rumor - 151 - He Bigg Boss Setting of the First President of the Great Need to Look for Example of Equal I - One Who Can Do Equal I - One Who Can Do Equal I - One Who Can Do News of Your Destinations Data Entry From About His Future Point You How to Write Way in Action IS TAKING PLACE WHAT YOU ARE DOING THIS YOU ARE LOOKING AND DEFEATED LOOKING AFTER EMINENT TAMAL SWORDS WITH EMINENT MOD AMOUNT I WANT TO MAKE SJ - - EMINENT MOD AMOUNT I WANT TO MAKE SJ - - EMINENT MOD AMOUNT I WANT TO MAKE SJ - - AMOUNT BUT YOU OK - THE INDIAN NATION WHICH EACH YEAR AMOUNT BUT YOU OK - THE INDIAN NATION WHICH EACH YEAR AMOUNT BUT YOU OK - THE INDIAN NATION WHICH EACH YEAR DURING THE COURSE OF - 100TH COMMENTS DURING THE COURSE OF - 100TH COMMENTS DURING THE COURSE OF - 100TH COMMENTS FOR EXAMPLE IN THE CASE When Considering To Make You Need To Make Sure Person Nomination For Adding One Point For Making The Way To Make To Delhi To 16 To You Is Particular Person Ko Simro Ni Bullet Modified Minus Point Of Time Manage Space 6 - Coins of I - One is Manage Space 6 - Coins of I - One is Manage Space 6 - Coins of I - One is just for two years ago when this ended but not everyone can do the last leaf - - - - - - - - - - Not possible to make a particular - Not possible to make a particular - Not possible to make a particular amount from this point will return - 110 amount from this point will return - 110 amount from this point will return - 110 subscribe a greater than 1000 City 110 Points Saver Mode Turn Temp After r-day In What We Can Do We Turn Temp After r-day In What We Can Do We Turn Temp After r-day In What We Can Do We Call The Return Minus One Mist - Which Otherwise Can Call The Return Minus One Mist - Which Otherwise Can Call The Return Minus One Mist - Which Otherwise Can Reduce - Verb - Reduce - Verb - Reduce - Verb - All Updates to 121 Civil Work and Languages The Keep It's Working All Updates to 121 Civil Work and Languages The Keep It's Working Switch to Work in Languages Submit IT Switch to Work in Languages Submit IT Switch to Work in Languages Submit IT WILL WORK IN PROTEST AS A QUESTION ACCEPTED SOLUTION THANK YOU FOR GIVING ME CHANNEL | Coin Change | coin-change | You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money.
Return _the fewest number of coins that you need to make up that amount_. If that amount of money cannot be made up by any combination of the coins, return `-1`.
You may assume that you have an infinite number of each kind of coin.
**Example 1:**
**Input:** coins = \[1,2,5\], amount = 11
**Output:** 3
**Explanation:** 11 = 5 + 5 + 1
**Example 2:**
**Input:** coins = \[2\], amount = 3
**Output:** -1
**Example 3:**
**Input:** coins = \[1\], amount = 0
**Output:** 0
**Constraints:**
* `1 <= coins.length <= 12`
* `1 <= coins[i] <= 231 - 1`
* `0 <= amount <= 104` | null | Array,Dynamic Programming,Breadth-First Search | Medium | 1025,1393,2345 |
825 | okay so lead code practice time so the question is friends of appropriate ages so the two goals the first one is to see how to solve this problem then we are going to put some code here and the second one is to see how to solve this problem in the real interview so let's get started so remember the first step in the real interview is to always try to understand the problem and also if there any there is anything unclear please bring up the question and also at the same time think about some ash cases um so let's take a look at the question itself so friends of appropriate edges some people will make friends requests the list of their ages is given and h i is the age of ice person all right so person a will not friend request person b is not equal to a if any of the following conditions are true so hb is smaller than half of the h of a plus seven h b larger than h a h b larger than 100 and h a is smaller than 100. so otherwise it will friend request b note that a friend request b doesn't necessarily need to request a also people will not friend the request themselves so how many total friend requests are made all right so we have example like this i'll put that too uh okay i think i pretty much understand the problem it's more about mathematics and else when it comes to the friend request so let's take a look at the notes it says the ages the lens is between 1 to 20 k and h i is between 1 to 120 yes so for sure we are going to have one or more than one person in the age group so in the age input array so at this moment i don't see any very clear ashkas if you argue that um if the empty if it is so first of all this input very couldn't be empty so the last could be one so if it is one you just need to return zero so that could be a uh a ash case but uh let's see if that is going to be covered by our general algorithm let me try to write the code so let's see so the second part is about finding a solution so how to solve this problem um i would say the individual person uh in this question doesn't really matter it is more about the age group so first of all i was i would have a map so the key of the map is going to be the age and the value is going to be the number of people with this edge and then we are going to have a for loop with the another volume to it right through the map and then we are going to do the computation to um to see uh how many friend requests there are in total so the runtime first of all we would need to go through the input h group so it is going to be oliven and then it's a follow pd another for loop on top of this hash map uh remember that the age is the aegis fanat is it is an infinite so it has a certain range um so in this case uh i would say we can say that as cons as constant for the next for loop on top of this map but also we could say suppose there are let's say they are m edges type of the edges then it is m square for the next round so in total it will be something like so n represents a length of the n represents the length of the h input array and m represents how many edges are there uh how many different types of the edges are there within the input array so it would be something like this so but as i said this one the m is actually a cons like it could be treated as constant so uh so overall we could say we could also say this is just the olefin so something like that um so let's do some coding work so after you're done with the solution finding parts it's time for you to do some coding so don't be too slow and also cared about the correctness and the readability of the code so first of all we need to turn the edge input array into a hashmap so it will be integer so this says age uh counts hcon so h as new hash map so in isaac so into age in the ages so age counts that puts h dot get or default it says h zero plus one so at that time this time we already have the age count uh created hcon map created so next time you're going to say uh requests is equal to zero so we are going to for the iterate through the map so let's say in age one uh let's say h a for age count dot key set and then or into age b so if it is so let's see so if um if we have already so let's say if we have already saying the h5 so for each age we are going to see all the other edges um yeah so because a can send a request to b and b can send the request to a and the two requests are trade as separate um yes so um conduct key set as well so here we need to use the only thing we need to do special is if h a is equal to h v then what we need to do is um we need to have requests for us equal to uh so first of all we need to get the count a as h count target h a is count b h count dot get hb so uh if h aj is equal to hb so we are actually looking at uh so we it would be something like count a minus one times count a in this group so it's like um everyone uh within this group can send a friend request to the others um so we still need h counted and count b so we need to send compute the relationship so you say uh if not can be friend uh h a and h b then you're just going to continue so we are going to define other helper function let's say boring between boring can be a friend so you're going to define the we are going to implement this function later so this is h a and this is uh hb so otherwise uh if it is not equal if the h is not equal then it is gonna be everyone from age a send a friend request to the people with the hp so it's gonna be count a times count b yeah so yeah that's mostly about it and finally we just return requests uh let's see so for each of the age group we just look around the other age group and if the if they can be friends then they cannot be friends and we just continue otherwise uh we will get the con for each of the age group so if the edges are the same then everyone can send a friend request to the other person within the group so which makes it count a minus one times count otherwise we everyone from age group h group a can send to people to age group b so yes so i think it should be good in general and then we are going to implement the uh the can be friend helper function so it will not be friend req i will not send friend request to be if any of the following conditions are true so let's say if h b is smaller or equal to 0.5 times h a 0.5 times h a 0.5 times h a and then plus seven then you're just going to continue sorry uh you're just going to return a false so if h b is larger than h a then you're going to return a false and if um uh f h hb is lighter than 100 and h a is smaller than 100 then you're going to return a false otherwise we are going to retarget true all right so yeah i think we are pretty much done with this code um let's do some testing so after you're done with coding it's not done you need to still um do some testing so first you could uh manually go through some sample test case uh do some sanity check and at the same time explain how this piece of code is gonna work and then you can introduce some other test cases to increase the test coverage so let's use an example let's say the 16 17 and the 18 stuff so first of all uh we will have the map something like 16 1 17 118 1 and then um you're going to iterate through the age count map so mathematically says that one oh sorry uh 17 can be friend of for 16 and 18 can be friend of first 17 so when we are at 16 so that can be friend will never give us a true so when we are at 17 assuming that 16 uh is can be friend and then we get the number of people from 16 age group uh which is one and from 17 it is one so request plus equal to one and similarly for 18 when aj is 18 um only when hp is 17 a satisfied condition for can be friend then we go going to plus one so request is going to be two finally and let's see the example one so for example one we are going to have 16 and two so it could be friends then we are going to get count a and count b both are equal to so you're going to say request plus equal to this is one times two so request is equal plus equal to two so it requires me you're going to return two finally so i think it mostly looks good um let's uh give it a try all right so it's good let's give it a submission all right so it seems like everything is good so remember the task is set up uh definitely instead of a sometimes case like example one which is like same age group except each other and also um i would say different age group except each other like example two uh or just accept one direction so when i say accept each other i really say means uh one direction um so yeah so that's yeah i would say that's pretty much it about the task is set up and uh that's it for this coding question so if you have any question about this puzzle or about anything uh feel free to leave some comments below uh if you feel this video pretty helpful please give me a thumb up and help subscribe to this channel i'll see you next time thanks for watching | Friends Of Appropriate Ages | max-increase-to-keep-city-skyline | There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the `ith` person.
A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true:
* `age[y] <= 0.5 * age[x] + 7`
* `age[y] > age[x]`
* `age[y] > 100 && age[x] < 100`
Otherwise, `x` will send a friend request to `y`.
Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself.
Return _the total number of friend requests made_.
**Example 1:**
**Input:** ages = \[16,16\]
**Output:** 2
**Explanation:** 2 people friend request each other.
**Example 2:**
**Input:** ages = \[16,17,18\]
**Output:** 2
**Explanation:** Friend requests are made 17 -> 16, 18 -> 17.
**Example 3:**
**Input:** ages = \[20,30,100,110,120\]
**Output:** 3
**Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
**Constraints:**
* `n == ages.length`
* `1 <= n <= 2 * 104`
* `1 <= ages[i] <= 120` | null | Array,Greedy,Matrix | Medium | null |
449 | welcome to october sleep code challenge today's problem is serialize and deserialize bst serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer blah design an algorithm to serialize and deserialize a binary search tree there is no restriction on how your algorithm should work you need to ensure that a binary search tree can be serialized to a string and this string can be deserialized to the original tree structure so the input is guaranteed to be a binary search tree so that helps obviously here is an example binary search tree and you can see that the input is given to us in more of a breadth-first search to us in more of a breadth-first search to us in more of a breadth-first search format where it's going to be five three seven one four but when we serialize it we can only traverse the binary search tree in three ways we could either go in order which would end up being like one three four five seven uh we can go post order which would end up being like one four three seven five or we can go pre-order which seven five or we can go pre-order which seven five or we can go pre-order which would be like five three one four seven so i think probably the best way is to go pre-order probably the best way is to go pre-order probably the best way is to go pre-order you can make post-order work as well you can make post-order work as well you can make post-order work as well by going backwards with our list but that kind of gets confusing with the left and right part so i think pre-order left and right part so i think pre-order left and right part so i think pre-order will work fine so let's go to the notepad and think about how we might do this say we had my example and we had the numbers 5 3 7 one four and if we visualize to that it would look something like five three seven one and four now if we were to go pre-order what now if we were to go pre-order what now if we were to go pre-order what would it look like well we can create a list going in pre-order pre-order traversal and it pre-order pre-order traversal and it pre-order pre-order traversal and it would look something like five three and then we go left again one now we move to the right four go back up and move to the right seven so you can see that the order is different from our input now all we need to do here is convert our list into a string somehow and now we need to reconvert that string to a list and rebuild our data structure so luckily we have the root so we can just start here with five so five and now as long as the number that comes after is less than the number that we just entered we would know it move it to add to the left right so this can go on for a long time like five three as long as the numbers decreasing it's only when the number is increasing here that we need to start moving to the right so we move four here to the right so that sounds pretty simple enough but there's a problem here there's a big problem actually which is well how do we know which node to add this right side to left side is easy as long as the number is smaller we can just go left all the way but what about the right so i mean say we had an example like 10 7 five one and then our next number was eight well if we used this easy algorithm eight will be added here and we can clearly see that this is wrong this should not be the case h should be added here so what that's going to require then is us to remember the parent node that we came from or at least the value that came from so this would kind of be the upper bound and the number below that would be the lower bound now when we have number eight what we check to see is hey is this eight within the lower and upper bound and we can clearly see eight is not right so we just move on ahead we add there's nothing to be added here now we'll check this now this is gonna be the upper bound in our recursive call and this will be the lower bound now is 8 within this range and yes it is so we know add 8 here so every time we add to the left we will check to see if it is within our bounds and we first go to the left side all the way up until like we find that it's no longer in the bounds here so with eight we'll see clearly that okay it's not within you know um five to whatever none here it's not going to be in here so we check here is it within seven and one no it's not here ten and five oh yes it is add it there so knowing that then we can realize we need to store some sort of upper and lower bound and just move through our list in pre-order and we should be able to in pre-order and we should be able to in pre-order and we should be able to create our binary search tree so i realize that's pretty confusing but hopefully as we code it out it'll begin to make a little more sense let's first start by serializing and like i said we want to go pre-order and like i said we want to go pre-order and like i said we want to go pre-order right so what we can do is start with a self variable and we'll call this lst make that a blank list and we'll create a function called the first search where we pass in the node so this is pretty standard if not node we simply return otherwise we add our node's value to our list next we move to the left side and next we move to the right side and after that we should have all our node values created in a list in pre-order jerusalem pre-order in pre-order jerusalem pre-order in pre-order jerusalem pre-order now we need to convert this into a string so how can we do that well to do that i think what i'm going to do is use the string join method put commas in between our integer values and we will say join these values we need to convert them into back into a string or we need to convert these integers to a string so i guess we can say map string or self.list and we want to return or self.list and we want to return or self.list and we want to return this string okay so let's make sure this works i'm just going to print the data here which should be a string and this should look like just a bunch of commas um that did not work of course we need to actually call the function and there we go this is my standard out 53147 so that is in pre-order 53147 so that is in pre-order 53147 so that is in pre-order great so now the hard part we want to deserialize this string so the very first thing we can do is convert this back into a list so we have our data let's use the split method to split this into a list and we want to reconvert these back into integers right so for data in data split we will convert this into an integer and now this will be our list so now we have it back into a list so this is the part that's going to be hard we need to write some sort of recursive function that's going to pass in the list as well as the lower and upper bounds and in the very beginning our lower and upper bounds are going to be infinite it'll be negative infinity and infinity that way we know we can always add it okay so the first thing we need to check is some base cases if not list if there's nothing there obviously just return nothing return none now we need to make sure this value is within our range and we have our list so it's going to be the first value in there so what we'll say is if not say lower list that value and i believe this is now an integer so that should work if it's not within our bounds that we pass in we also return a nun now let's build up our tree so the very first thing we want to do is pop off the first object inside of our list we'll call it candidate and we'll say pop off the first one now let's form our root it's going to be called tree node with our candidate value right now we need to call our recursive function and to do that we can just say okay passing the left our recursive function we're passing our list now that we've popped off this object and we need to pass in our lower and upper bound right so our lower bound is still whatever it was before it's our upper bound that's changed now and that's going to be the root.value and the root.right it's going to be the and the root.right it's going to be the and the root.right it's going to be the same we thing in our list but instead of this lower bound being lower it's now going to be the root dot value and this will still be upper finally once we finish our recursive call we just return our route and that would be it so this is the tricky part like knowing that it's going to always go to the left as long as the values are less because we're um you know we're changing the upper bound to a root value so as long as it's less it's going to just continue going left as soon as we find that's not true we'll start trying to check to the right and add it to the right side but we need to make sure that it's within the bounds of from our parent to our left child leaf node whatever and if it's not then we'll just continue up the tree to see where we can add it and because this is a binary search tree this works now we'll just say okay call our recursive function list and let's call a float for negative infinity we'll make that a negative and our upper will be upper like positive infinity and so we turn the root so we just return whatever gets returned in our function all right so let's see if this works and it looks like it's working so that's great uh there is one edge case here if we pass in a blank list though i believe this airs out because we try to convert empty strings into integers so just to com just to take care of that we'll say if not blank string then just return that should take care of that all right so let's go and submit it and there we go now in terms of time complexity this is an o of n solution we move as many nodes as there are we could have first thought to add null values to the children to kind of like keep the whole structure but that is very inefficient and really doesn't take advantage of the fact that this is a binary search tree so this um is probably the best way to do it and this definitely wasn't an easy algorithm this is pretty hard to come up with but hopefully this helped thanks for watching my channel and remember do not trust me i know nothing | Serialize and Deserialize BST | serialize-and-deserialize-bst | Serialization is 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 search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree. | null | String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree | Medium | 297,652,765 |
203 | Hello everyone so today we will be discussing question number 203 of lead code which is removed link list elements ok so this one is the problem right this is a part of my recurring playlist and this is an easy problem so what will be its flow that first of all We will see its iterative solution and after that we will see the recursive solution. Okay, after this we will see the recursive solution. First of all we will see iterative. Then what is recursive iterative? It is a little easy to think because we have already practiced its questions a lot. That we have that much practice, otherwise we have some problem in thinking recursively, so we will iteratively build a recursive solution and we will practice so much that if you can solve the general question recursively, then you will be able to solve it easily by reasoning, okay. So let's see what is there in this question, so what is told to us in this question that like this node with six has to be removed, just don't do anything else, this six has been given, they have given a value whose value is in it. If there is a six then the value of all the notes is six or whatever is the given value. Here there is six, whatever is the given value. Remove the note and return a new list. So if you remove this then your list will look like this. This is to be returned, okay, so let's try to do it iteratively, how will we do it, okay, so let's understand from the example. Now here I have a link list, right, this is my head pointer, my link list is starting from here. And it is ending here, now here is my well, which node I have to remove, that well is my four, so it means I have to remove this and this node, okay, so to remove the node. What is the method in this, it means how do we remove the node in the Ling list. Removing the node in the Ling list is a very simple thing, you just have to change the address. Okay, so here if you look at the Ling list, like this cross B, this is its If the address is stored then it is pointing to it. Cross C here. If its address is stored then it is pointing to it like this. Cross D and Cross and there is no address here, there is null, so hence the English is ending at Y. Now here. I want that my head pointer should not point to it, right, don't point to it, so what I will do is to do something for that, I have to update its address here, so if If I remove this address, this pointer will also be removed. Okay, this arrow will also go away and what I will do is I will put its address whose six is the one put its address whose six is the one put its address whose six is the one which is the cross, so what is it doing now? It is pointing to this. B is still pointing to this but my traverse will be when I start from the head, first of all I will get a two, then a six, then after that comes a four. I don't want a four because I don't want a four. If I want to remove it, I have updated its address, how did I update it, what will I put here, this will come to my e, so now it is pointing to this, okay and if I remove this, then my updated There is a gender list and it will start from the head, it will go to six and from six straight to three, four is still pointing to three but no one is pointing to four and here also no one is pointing to four so this Now we have to think about how we will implement this, now you see one thing, understand it carefully, so let's assume that I have ever come to this pointer and I have called it current, sir, now I have to remove it. I don't have to delete it. To delete it, I should have the information about its previous node because I have to update its address and I have to put its next in its next, that means I have to put a cross C, I have to put its next in the next to. Right, but whenever I am on the current page, I have the information about the next one, I also have the information about the next one, but there is no information about the previous one, there is a link in the after, you will have to create a separate variable for that, it will be a little complicated next. Let me check its value because look, I have this CRR, I have its next information available, its next information is also available, so with this I have the information of all three notes available, so I check the value of current dot next. That if this given value is equal to the one in my question or not, if it is true, if this condition is fulfilled then what will I do, what will I update the address of current.next from what will I update the address of current.next from current.next? This is the current of next. current.next? This is the current of next. current.next? This is the current of next. What is stored in its next. Cross C right. This is what we have to store here because we do not want this current dot next. Now it is not here. Before this, there was B here. Now we have to store that. C has to be done, where is C, current dot next, what is its next value, its next means, update the value of the address that the next address is pointing to. Do you understand, now there is a problem with one thing, just one. The problem is that we are ignoring the first element, here we are starting from its second element, it is the first element which is ours, we gave it to it, we did not see its value, so we start directly from the second element. If the value jumps, we will have to check whether the first element is equal to the same value, for that we will have to deal with it separately, we will do that loop separately, no problem, we will code that. I will do it but I hope you have understood the concept of what I am trying to do, that is, this is the right one, this is the crux of this algorithm, there is nothing else in it, we just code it. We will understand how this is happening here in the code and it will be easily understood. Okay, I will explain it well in the code. Okay, so let's quote it. Now here I have taken an example and here is my well. That's two, isn't it? Now you see, the first three elements here are the same two, so in the algorithm I just discussed, I am checking na dot next, which means I am checking this element, then after that, then again. After that I will check this element, then after that I will check this element, I did not check the first two, so that is our missing right, so after that, if I do it according to my algorithm, then how will it look? I know this will be our final output whereas it should be only three and four in the list so if the first two is missed then we will deal with it so what will we do to fix this thing that we will put a check in the beginning itself. It is okay that the first element is not equal to the well, if it is, then remove it, okay, we will keep doing this until it is not equal to the well, so what we will do to deal with this is to put a check in the beginning itself. It will be given that if the first element is equal to well then remove it, then go to the next element, if it is also equal to well, then remove it, right? Now my head is pointing here, my algorithm will start from here, right? Because see, the first element was missing, so I am putting this check. Okay, so I am putting this check. I will head and end of well. E equal to well sorry okay so as long as it's like this head equal to head dot next okay meaning I'm going to move the head forward so let's do like this if it skips 2 and goes to three. Now from here I will start my algorithm. Okay, so I take one item because I need one item to implement my entire algorithm. Okay, here si RR will be equal to head. Here head is now. Three is pointing to three. Okay, if we do it according to this example, it is very simple, so for this we will take some other example, now our new example will be 2 3 A 4 5. Four, here we have to remove four, okay, so now the current is pointing to which head, which one, is it pointing to this head, or is it pointing to this two, so we will start from here, now here we will put a while loop, now we What are you doing? Look, this is my current but whose value am I checking? Right, I will check the value of current dot next. According to my algorithm, if this becomes null then my code can break, so for that I put a check, first of all, as long as my current node is current, it should be a valid node and the current dot next should not be null, till then the loop will run, okay, now this is my while loop has started, from here now I What did I do if that was my check and what is the value of this current dot. Now look at whom my current dot next is pointing to. What does the current dot next mean? I am checking this, I am checking the value of this, not the current dot. The value of next which is equal to l is given to us, if it is equal to this, then what do I do, current dot next i equal to, let me copy it off next, okay, current off next dot next means let's take the value, if here now three then If it is equal to that then it will come to others, here it will come to others, current equal to current of next means move ahead, if it is not equal to that then now you come above whom, now you come above this, your current was earlier two, now three. Now what did you do, check whether the value of current dot next is equal to well. Here our well is four and the well of current dot next is also four, so what will you do with four. Which is next to four, which is five here, you will assign it to the next of three so that you understand that your three will not point to four, it will point to five and if it is not so, then go straight ahead but here. But if it is then we will assign it 3f will point to f, that's all, nothing else to do, right? When all this is over for you, what will you do return d, that's it, let's try this, sorry, not here. Current dot should not be equal to null. Next should not be equal to null. Okay, so this is accepted and let us submit it. It will also be submitted. Now we have to solve it recursively. Think about how you will do it. The recursive code is very simple. So it is very easy, so now we will make it a recursive solution by taking this code. Okay, so let's see its recursive solution. How will we make it recursive? Now this code here is my item code, isn't it? The code is now in this item code, from here let's try to make my recursive. Now what I told about recursive is that firstly the base condition is very important, firstly our recursive relation is very important and thirdly what is the task which I have to perform. Okay, after the recursion relation, and the base condition, now here what is the base condition, you can derive from here this while current and current dot next is not equal to null, how can you derive the base condition, you think, Smollett valid input. Is it Smollett valid input? What can happen that brother, which is your node, it becomes null? If brother, if it is a null node, what will you return? What will you return? You will return nothing. Yes, you are the same here. You are checking that the while loop will continue till current dot next is reached because our focus here was on current dot next because we are looking for the value of current dot next, so whatever. Whatever our variable, whatever our node is we are considering here, we are checking its value, so we are putting a condition beyond that, look, we are checking the value of current dot next, so let us check whether the current If dot next is not null then we will run the loop till then. As soon as the current dot next is null, this loop ends which means our code is over, so the same is true for the receiver too. When do we have to end it when our node is the one with which we are dealing. Okay, if it becomes null, then our node here will remain the head. We will deal with the head only and when this head becomes null, our recursive code will also end. We will return. Ok, what will we do with the return? We will tap because the head tap has already been done so this will be our stopping condition. So, our base is fixed. The base condition is fixed. Now we have the example. 4 5 4 Okay, so what will I do? Here I will take this element, I will take this node, I will take this two node and the recursive relation will be called on the remaining link list and from what I will say, I will infer that the remaining link list will be Remove those elements from it and give it to me. Okay, I will tell the function that brother, the first element is the first node. I have taken the first node. You remove those elements from the remaining link list and give it to me. I will just attach two to it. If I give it, the function said, okay, I will do all that, but what if your node is equal to the value, what if it happens that yes here also there is four. So you said, brother, don't take tension about four, take tension about the remaining penis list, remove four from it and give it to my butt and then to yourself. Function again said, brother, you also have four, what will you do with it, so you Told him again that brother, if the value of the node I have is equal to well, then I will return 4 dot next and give it. Do you understand, otherwise I will return it as it is, meaning see what was here earlier 2. 3 4 5 4 It was like this, and I told him, 'Brother, remove this gender this, and I told him, 'Brother, remove this gender this, and I told him, 'Brother, remove this gender list from me and give me the elements, I will attach it to the result list, so he returned the result to me, what did he do?' 2 3 5 Returned returned the result to me, what did he do?' 2 3 5 Returned returned the result to me, what did he do?' 2 3 5 Returned when 35 was returned and I attached two to it and got it returned, okay now this is my four here, okay I got released [ __ ] man, this is okay I got released [ __ ] man, this is okay I got released [ __ ] man, this is four, I can't return this, so this is not the answer I just said, okay, I have my node now, if it is equal to note four, it is equal to well, then I will not return from here, I will return from 4 dot next, the remaining list because Your answer is correct, isn't it what I am assuming? It is correct. It is possible that the value in the node I have is the same as given in the question. If so, then I will return your answer. I will return my answer. Answer: I will not return it, I will return my answer. Answer: I will not return it, I will return my answer. Answer: I will not return it, I will not attach it to my one, but if it is not equal to it, then I will attach it to my one and give it to him. This is our task. If you understand, then our recursive save relation is done. Our task is done and our The base condition is done, so now we are ready to code it. Let's write it quickly because it is a very small code. Okay, so let's quote it quickly. First of all, what will I write? My base condition is okay. What is the base condition? I mean, if head is equal to null then return null, okay, now what will happen to me here, I will see the recursive relation, what will he say, he will say that brother, the first element you have, hold it and keep the remaining. On the gender list, I am giving you after solving it, so here I have two on hold, and if he solves the remaining list and gives it, then on dot next, I will assign it to the remaining list. How will my code look like Head of Sorry Head of Next is equal to remove element Remove element and what will I send in it Smaller input Head of Next I sent the remaining list I sent the next remaining list and well it will remain the same Okay now here But he returned it to me, which is my task, I have to check once, is the value of head not equal to well, if it is so, then what will I return, head of next is fine and if not. If yes, then simply return the head, this is done and this is your task, this is the if condition, this is your task is done or you have to perform the task, after the recurrence relation, okay, so let's run it, okay, then this Ok now let's submit it and see if it is submitted then you must have understood what I am doing, here how we are converting an IT problem to recursive and how small it is becoming by thinking recursively. I hope you understood it well and see you in the next video. Thank you. | Remove Linked List Elements | remove-linked-list-elements | Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_.
**Example 1:**
**Input:** head = \[1,2,6,3,4,5,6\], val = 6
**Output:** \[1,2,3,4,5\]
**Example 2:**
**Input:** head = \[\], val = 1
**Output:** \[\]
**Example 3:**
**Input:** head = \[7,7,7,7\], val = 7
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 104]`.
* `1 <= Node.val <= 50`
* `0 <= val <= 50` | null | Linked List,Recursion | Easy | 27,237,2216 |
9 | Welcome, whenever you want to learn a new language, you try to make some programs, then this program is very common in it, you must have made it, whenever you have probably done CC or C plus, whatever you have learned, this is This program must have been made 100% by myself, this is This program must have been made 100% by myself, this is This program must have been made 100% by myself, then I saw this program in the delete code and it was in the starting itself, so I thought let's do this also first, easy level is difficult, the question is first, what is a drone, I am getting talent, I hope you all. You will know that such a wait character can be anything, character Dhoni but wait or spring can be anything in which if you read it from front or read it from back, it is the same like here one is one, you are one from ahead of you. Read this too, you too, one, you one, read from the back, even then, one, and here is an example that it is okay to race, if you read from the front, it is okay. If you read from the back, it is okay to race. This is an example in the spring. There is a question of spring, we have done it but here let's see how we can do this with wait here, okay so in one here I am taking that okay, this is the logic of the first three lines, I Here I will write that first and then after that, here I will explain to you that after going to the actual here, I will have to close it here for a second, some notification came, okay, so what will I do here, first of all I will see the models here. Why am I doing this, please tell me here, there is no problem, after that I will divide, after dividing, I will multiply the sum here by 10 and add plus to it, I will pay 10 here, this will be my solution here. How is he doing the solution? What is the logic behind the solution? Now they understand that it is okay like I have the number here first, I have the number here which is 121, so let's take the number which I have here is 121 steps. What I am doing here is my number here in Max which is 121, I am modeling it here, modules means here we understand with a simple logic, in second class or third class you have learned to divide a. How do we divide a number? Okay, so here I am dividing 121, here it is okay by 10, one is gone, 10 is gone here, okay you are here, one is gone here, you are D, how much is it? It is 20 and here is your one. Okay, so whenever you divide any number here, this is your reminder here, this is your modules here and this is your question here. This is what happens when you divide it with a forward slash here, okay like here you support 121, here you divide it by 10, this is the result, so what do I have here, I have 121 here, I have Pass here 121 There's a wait Now if this was a that here, okay if this was a string here, then what do we do in the how of the string, let's break it into eras, okay Hey, we break this here into off characters. Let's take it and if it breaks here in the Ara of characters, after that we put a loop here and by putting a loop here we check the first number with the last number whether the Eric of the first digital is the Erica. Is it the last element? Is it equal? If it is equal, then it equal? If it is equal, then it equal? If it is equal, then extend this here and then check the next element, we will check until it crosses this one, meaning if you take this one, then take this one, here you have I plus here you did K mines till then you have to expand it here and reduce it till it becomes I. If it does n't cross here then it would have removed these how off strings are okay but what do I have here. But wait, there is a number, now I have to find each element of the number, how will it come out, it will come out from the modules, you see here, like I did the modules of 121 here, so I have one A here, first I have a digital A. pass here ok what did I do to that to one I did here to temp miss is crying so in temp I have here to this how in this what is read one is read after that what did I do to x I divided here to 10 When I divided The last one which is digital, I took it out from here, now the child I have here is April, after that what did I do here, I did sum here in 10 and plus I typed sum here, my initial will be zero here. So zero in 10 and plus what is in temp here in temp is one here so this is how much has gone to me here has gone one so in sum I have got one in this how has one come in here what am I doing here I am reversing this I'm going to reverse 121 here, what did I do? 121, I have it here, now I'm going to go back here, one, I have a here, now if I put you here, next, what am I going to do, I'm going to divide X again. I will do it but this time in Will go This was the first digital from the back, this one, I divided it again because my I am dividing again in Next it will go to a reminder, so what will happen in this how will this 10 be zero, how much will it become, it will be zero here, okay one, I have a reminder here, so what is there in tempo, what is your one in tempo, your one is here in If I get the sum from zero here, I already have 12 in it, then it is 12 * 10, so you see it has become digital. What I have to check here is whether this number which you have come out is equal to your original number, is it equal to your original number, if it is yours then this is the number otherwise your panel is not correct. It's a simple logic, so this is a very good method, meaning it will come to you in future too, if you have this train, okay, you have a string here, how will it come, I will tell you here if you have a string. You have to convert it into era, you have to pick each element here, then you directly convert it, you apply your character function and this will directly convert it into an era, but if you want integer. You have to pick only one element of the wait because as soon as it gets converted here, you can pick one element of it, but how will you do the wait, this method is taught to us from the very beginning when you have converted your You must have started programming in college, you must have started from first air to second air, whenever you have created it in the very beginning, first in D is number and it is okay, like palindrome is okay, factorial is okay and Fibonacci series is okay, so these are some Here there are questions which we do, in the first question related to drone, only the concept is taught to us, so without looking at any other solution, this solution seemed best because we have learned this solution and it is good if. If you see its logic here then it is good, here we are searching the numbers one by one from here onwards, we have created the same number again and again here we will check whether this number till the original number here or that number. The number which is from us has come out of ours, if it is from the number then yes, the number which is yours here is here, like if you check it here, you will have to subscribe, like your number here is ok, everything is mine here = 0, everything is mine here = 0, everything is mine here = 0, I have put it here, okay, the same way, I am changing the value of I am getting it which is 121 here, but I have changed X here, after dividing X, I have stored it in You will have to store the original value of It is not necessary, okay, I have seen some people also do this that they look for 2 or water separately here, it is not necessary, okay, so if it is equal to this, then it will obviously return true, so you should mention it separately. It's not sure, he will do it If it's playing then it's ok, I submitted it and the result is very correct, 99% cases should be passed, yes, 99% cases should be passed, yes, 99% cases should be passed, yes, 99.32% cases have been passed here, I have 99.32% cases have been passed here, I have 99.32% cases have been passed here, I have taken it from nine and have beaten 99.32%. So the taken it from nine and have beaten 99.32%. So the taken it from nine and have beaten 99.32%. So the question must have been cleared. If you have any butter solution then tell me and thank you. | Palindrome Number | palindrome-number | Given an integer `x`, return `true` _if_ `x` _is a_ _**palindrome**__, and_ `false` _otherwise_.
**Example 1:**
**Input:** x = 121
**Output:** true
**Explanation:** 121 reads as 121 from left to right and from right to left.
**Example 2:**
**Input:** x = -121
**Output:** false
**Explanation:** From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
**Example 3:**
**Input:** x = 10
**Output:** false
**Explanation:** Reads 01 from right to left. Therefore it is not a palindrome.
**Constraints:**
* `-231 <= x <= 231 - 1`
**Follow up:** Could you solve it without converting the integer to a string? | Beware of overflow when you reverse the integer. | Math | Easy | 234,1375 |
1,684 | A Heaven President will take according to the channel, that question is account number of consistent subscribe then what is this question saying, first what will I do read the question now what am I doing now friend my question craft so that you can practice in this palace Play List In the play list itself, I am thinking that you were doing this lesson that by going to NSS Booster, there was some top particular topic of DSC incident but whenever this question was given to you in the interview, you were not given the topic. That was that you will have to think yourself that how can you approach this? White then this question must have been tried for biopsy. If not dry then please like it. Then you can set it on video and many more must have happened. Heroine keep watching my tablets to see whether this question is right. Intermediate is used in many places because what are we thinking in this that it takes more quantity to enter the question, it tastes good, it is very simple and the question is hello, what is the question saying, we have been given an award, that is also these words. These people are in bloody sea, this last word is ready, it is given in Alwar, what is the character in the last, and send the character, we have to fold such a word from this year's series, as if these words were credited to the director, in which only The same characters should be pregnant except the characters which are characters and now it is written wrong-wrong egg loose-loose subscribe if I is this karo hai written wrong-wrong egg loose-loose subscribe if I is this karo hai written wrong-wrong egg loose-loose subscribe if I is this karo hai ghr tk CC ka or mein chale ka or beech nahi chalega BA will not chalaga BSC will not chalaga BD will not chalaga Aisi Chalega Aur DB Chalega Total Kitna 41 - Found 4 WhatsApp people in whom whatever is there is 41 - Found 4 WhatsApp people in whom whatever is there is 41 - Found 4 WhatsApp people in whom whatever is there is like this, now we confuse you, what we used to think. Do n't forget to subscribe. How can you do this? Subscribe to the trick, we can't decide that the whole character has to be decided by tracking a world, understand this thing, you loot, there is no problem here, now brother, like give us someone else's but will take it like B.Sc. Take this cord and like B.Sc. Take this cord and like B.Sc. Take this cord and sit in your bean pad. Now we will start traveling on it. The first sector is fine right now, so what do we do? Do we have to fold whether this one also has a President. If the President is ready, we will accept its tow. So what is the point, now look, now you people cannot do this every time that you will make it drivers crores and one senior vice president who travels, then what all the people do after searching for it, they make under sets, they make unwanted sets, this set needs tempered glass. Even if you shed light and learned, you took A risk, D, what happened with this, it became easy to find the tech, what we were doing now, like B.Sc., we have to check every actor, the like B.Sc., we have to check every actor, the CAD in Alwar district is matching many of them. We also raised the issue of starting to drive it, asking whether you are also there or not, otherwise it is done, after breaking it, but it is as if they get AC, first they do Abhishek, they get SIM, then what to do, commitment, overall what we got. You have to wish him a happy birthday with the word aloud, but we have set what happened with that, like if I am here, you are the president of any subscribe and subscribe, that in this case, whatever it is, I have told you that you do not need to use it. That we simple put that in school mid loot not equal toe that yes this thing is the president Puck that now see what is the problem right now we have to learn to break what do we have to learn to back as we found out CM lays defects We know if there is a present, the present is different and is present, we should look at it, start looking and I equal G OLX in and half inch plus first character found character temple character found word I to be exactly like this so what is the president or not So we got to know the front then after this we do n't need to check here we do n't need to do one here otherwise what is it doing and now in this way we have worked the first room that the alarm word Put it in the can order set first. Put it in the unwanted set. Fix rate words. Words. Hey, it is the driver of every actor of every word. If it is considered a pile of straw and no current award is found, then you will leave it there for editing. But brother, he is not worthy of you, will you be thrown out or will you be shifted to another ward, as if we had the words that directly lead, trick, play chief defect, then you are behind the gift tax, we will directly say these words: Oh then you are behind the gift tax, we will directly say these words: Oh wow, Ramla, set the alarm clock. Keep CVD subscribe in the village it means this kind of problem subscribe has to be done that Aishwarya more can message this for all to were that Hansi Ko must have answered the whole question, subscribe and subscribe to this channel, what was he doing that we are doing this very sentimental thing, it is very widely painted, even when everyone is undergoing treatment, the dream is blamed. Karna for dayan adh ki If we meter every actor of this award, If we meter every actor of this award, If we meter every actor of this award, then we could have put it here, we checked that dot wow and this is a no-no-no-no daughter does not put that status, it is assuming that he is liking the status. We are going to increase our maji by subscribing to the total number of hits on WhatsApp status or subscribing to the war but as soon as this particular water is appointed, what we will do is simply pause the status clip and make it great. Okay but if we do one then it will come out from the for form just like the hair then we will put it below that if the status is still now if the status is still sorry stry vidru then simple what we do and we will add it in the last because now till here Originally submitted, I hope you must have understood this thing, how did this question happen and if you are not subscribed then please subscribe this video. If you have subscribed our channel till now and I keep doing it together, then subscribe. Thank you. Video song of Aur Sunao Main Tera Amazon | Count the Number of Consistent Strings | find-latest-group-of-size-m | You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters. | Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map. | Array,Binary Search,Simulation | Medium | null |
1,640 | Are Hello Guys Welcome To Another Interesting Problem Industries According School Check Formation Cry Coordination Lecture Are Updating Teachers Are Three Fatty Dare Pieces Vendors In Peace And Established For My Bay Contesting The Amazing Pieces In This However Not Allowed Studio Dealers In Which Are Peace And Tours If It's Possible To For The Are From Teachers Were Written For Selected For Example In The First K Subscribe Our Are So It's After Peeth Exam Clear And The Part Of The Return To Subscribe 30 Please Subscribe Indian Channels Pe Problems Try To Understand As To If We Should The Amazing Which Have Right Nor Prabash Se Zauq Sudhir They Have Nothing To Refill Element 100 OK Share and Subscribe 602 subscribe The Channel Please subscribe this Video Please subscribe and Ninth Fifty Shades of Fitting Par Click Here Voor We Can Return True In This Case Against Let's Move To The Lord Buddha Code And So Let's See What We Can Do And Ask What We Will Do It Is Best Example Ke Sapoch Us Plu Cert 1234 For Him Raphael December Wrong Are Supposed To Be Something Like Three Layer Pendant Was 45 Days Subscribe and own this thank you all are doing so start with and hydrating over our behind are okay morning 122 and behind are undergoing to see the first elements so it's too so let's see how to find the education to find the amazing producer behind nice picture Vibrating over this will fight for winter index of the white vinegar index of this to big boss winner too sided over and need to check the element in this are also going to be equal to the next index ok and see the limits to be the next Indian of The Same Way Need To Check For Example 2100 Against Tiffin To Three Look Do Subscribe My Channel Thank You To The Next Element Avoid To Index Of Elements Indori Morning Previous Fields And Electrons To Understand This Properly Switch 12345 Debit Creator Map So And * If Atom Of bantu store the index So And * If Atom Of bantu store the index So And * If Atom Of bantu store the index of its elements but I have given in handy 100 less you will point Mukesh development of the physical two points on induction of created this map voters will decide have valid pieces are our interest to tide over the pieces are for bintu first find the length of the map champ * first find the length of the map champ * first find the length of the map champ * for example check the element 2012 - for example check the element 2012 - for example check the element 2012 - inside these 0512 we check the two elements on two elements and seams to be next travel destination of maths y3 ladies equal to and second list of pieces are completed it's not Completed specified 2362 celebrate servi 40 will return forms will return all subscribe dispur otherwise return rule in this case ok i will call you have another case left right same chord without another place value system for slaps govardhan extra part of the places f4 that is san tt Industry Suna Fold Excited Checking After 10 Of These Taxes And I Will Check Puri Equal To For World Go To The Next9 Item White Sesame 125 Increase The End Of The Places Where Is The Are And Hydrating Suggestion Defined But Reach Only In Place Of The Fennel And Cover for a Good Some Other Element Safe and Five Sixes in the Case Was Adopted I Will Have to Retail Follow Chapter Five Don't Have Any Element and Not Completed The Places Complete the Solar Part of the ISRO 's Ek Path Vya-2 Vibrator Company's 's Ek Path Vya-2 Vibrator Company's 's Ek Path Vya-2 Vibrator Company's Switch To give this broad hua tha main this piece don't complete the intel part ok after this is switch sad shayari for example in this benefit has not the places to return for it ok sir dushman ke yahan par remembers panderm plus gowar to president element in this example Switch 72000 Is Vansh Opposite This Old World Which Will Find The Next Point Speaking Thoughts Matching Correctly In This Case Which Can Be Done Through So Let's Get Started The Logic Eastern So Let's Get Started Implementation Of The World Map In Comment And Vibrate Over All Elements Hey 32.20 Reddy I Plus 32.20 Reddy I Plus 32.20 Reddy I Plus Hello Viewers Ko * To The Limits Along With Her Hello Viewers Ko * To The Limits Along With Her Hello Viewers Ko * To The Limits Along With Her In This Regard And Later Shifted 110 What A Button In Difficult And More Latest Movie Forward Sunavai When Love Starts Taking Over As Part Of A Piece After So Let's Get Started With That for you and water dries initially belongs to decide to entertain is equal to part size so will have between part size and also check for the president of the first element of part to switch in its present at ward level to that somewhere in the distance map * Search the first element of Egypt and want to talk * Search the first element of Egypt and want to talk * Search the first element of Egypt and want to talk to me you are aware boon elements present not particular are ok 919 we start oil that waste oil that your I is going into villages and they will have to declare is winter is equal to zero morning sex Fault letter form and tail lies end of the past and also in to check ander inch the end of the race and Also Index Plus And Can Also Check Effigy That I Am Having Divya Sequel For Its Ok Part Swift Of I Is Not Shrinking Tours Of Index In Case Of Mind Values Are Not Equal Daily Night K Cycle Return Forms One Know Case When Will Have To Return forms ok so let's go and after coming out with a smile on being can also check this is not equal to part size his just is not equal to partner with lots of this is not equal to and switch board ke song for example also is 10th over 100 villages and of the amazing over and will only for five willam element which is not a part of the are so in such cases that tune of that will check this is not equal to and will in return for soil into follic Acid is behind fraternity and elements are not equal vibrating will give return forms benefit and different punishment condition days also witch can return forms okay otherwise water and tools in the end they can return proof that is it and iodine civil work let's check can see it Working the soldiers fine for this test case instead of stagnation between formal test cases such a practice solution thank you please like and subscribe for More Video | Check Array Formation Through Concatenation | design-a-file-sharing-system | You are given an array of **distinct** integers `arr` and an array of integer arrays `pieces`, where the integers in `pieces` are **distinct**. Your goal is to form `arr` by concatenating the arrays in `pieces` **in any order**. However, you are **not** allowed to reorder the integers in each array `pieces[i]`.
Return `true` _if it is possible_ _to form the array_ `arr` _from_ `pieces`. Otherwise, return `false`.
**Example 1:**
**Input:** arr = \[15,88\], pieces = \[\[88\],\[15\]\]
**Output:** true
**Explanation:** Concatenate \[15\] then \[88\]
**Example 2:**
**Input:** arr = \[49,18,16\], pieces = \[\[16,18,49\]\]
**Output:** false
**Explanation:** Even though the numbers match, we cannot reorder pieces\[0\].
**Example 3:**
**Input:** arr = \[91,4,64,78\], pieces = \[\[78\],\[4,64\],\[91\]\]
**Output:** true
**Explanation:** Concatenate \[91\] then \[4,64\] then \[78\]
**Constraints:**
* `1 <= pieces.length <= arr.length <= 100`
* `sum(pieces[i].length) == arr.length`
* `1 <= pieces[i].length <= arr.length`
* `1 <= arr[i], pieces[i][j] <= 100`
* The integers in `arr` are **distinct**.
* The integers in `pieces` are **distinct** (i.e., If we flatten pieces in a 1D array, all the integers in this array are distinct). | Try to solve it by keeping for each file chunk, the users who have this chunk. Try to solve it by keeping all the users in the system with their owned chunks, and when you request a chunk, check all users for it. | Hash Table,Design,Heap (Priority Queue),Data Stream | Medium | 355 |
1,046 | are you calling enthusiasts welcome back to another episode of Code Master Quest today we are diving into a drilling puzzle involving songs and some smashing logic so let's get started and find out the question description on lead code here's the problem statement you are given an array of integer zones where contain um you know the weight of each song and we are playing a game with the songs and on each turn we choose the heaviest two Stone and smash them together suppose the heaviest two Stone have weight X and Y with X less than or equal to Y and the result of a smash is like this if x is equal to Y both zones are destroyed and F X is not equal to Y the zone of weight X is destroyed and the sonar weight y has new weight y minus X and at the end of the game there is at most one stone left and we should return the weight of the last remaining Stone and if there are no sound left we should return to now let's come back to the visual studio code and try to solve this problem to solve this question there is two different ways uh first you can make a while loop and while we have more than one element inside the array we can sort the array and find the most heaviest element inside the array and then perform the smash operation right but for this solution we need to perform the search operation each time but for the second option and time efficient option we can make a hit and use a heap data structure to perform the smash operation right so now let's define the function signature and then solve this question with a heated structure and if you're interested in the implementation of hip in Surf you can check the link in the description below now let me Define the function signature here function last stone weight then the input which is stones array of integer and then integer there we go now let me come back to the browser and copy the implementation of my hip Direction structure in Swift from this link you can find this link in the description below also so there we go I made a copy from it and let me come back here okay see just right here okay since the data type of this element inside the arrays in is integer we need to make a hip fit integer data type so let's say if our if and here for integer and it's empty body now we need to make our here so let's say from Stone in stones hip dot insert let's stop there we go after this for operation this for Loop we will have our heated structure you can find the definition of insert function here in the hip data structures now let me say a while keep elements we have an array of elements here you've got elements that count is greater than one then we should say if let Y is keep remove we have the remove function here as well and the return type for this remove function is optional right so we need to unwrap it so let's say if let y equal to heat dot remove and let x equal to heat plot remove again because we need to have the heaviest element inside the uh here and then if X is not equal to Y then we should say Heap that insert uh y minus X right and at the end of this for Loop we are pretty sure that we have at most one element inside them right so at the end we need to return Heap dot Peak and we should unwrap it because Peak function will return an optional data type as well right so if it's empty we should return zero based on the question description otherwise we will return the last element inside this should be the correct solution for this problem but to make sure about our implementation let's come back to the browser and paste our implementation here and hit the subject button there we go here's the solution for this question thank you everyone | Last Stone Weight | max-consecutive-ones-iii | You are given an array of integers `stones` where `stones[i]` is the weight of the `ith` stone.
We are playing a game with the stones. On each turn, we choose the **heaviest two stones** and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is:
* If `x == y`, both stones are destroyed, and
* If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`.
At the end of the game, there is **at most one** stone left.
Return _the weight of the last remaining stone_. If there are no stones left, return `0`.
**Example 1:**
**Input:** stones = \[2,7,4,1,8,1\]
**Output:** 1
**Explanation:**
We combine 7 and 8 to get 1 so the array converts to \[2,4,1,1,1\] then,
we combine 2 and 4 to get 2 so the array converts to \[2,1,1,1\] then,
we combine 2 and 1 to get 1 so the array converts to \[1,1,1\] then,
we combine 1 and 1 to get 0 so the array converts to \[1\] then that's the value of the last stone.
**Example 2:**
**Input:** stones = \[1\]
**Output:** 1
**Constraints:**
* `1 <= stones.length <= 30`
* `1 <= stones[i] <= 1000` | One thing's for sure, we will only flip a zero if it extends an existing window of 1s. Otherwise, there's no point in doing it, right? Think Sliding Window! Since we know this problem can be solved using the sliding window construct, we might as well focus in that direction for hints. Basically, in a given window, we can never have > K zeros, right? We don't have a fixed size window in this case. The window size can grow and shrink depending upon the number of zeros we have (we don't actually have to flip the zeros here!). The way to shrink or expand a window would be based on the number of zeros that can still be flipped and so on. | Array,Binary Search,Sliding Window,Prefix Sum | Medium | 340,424,485,487,2134 |
258 | hey hello there let's talk about today's liquid and challenge question add digits giving a non-negative integer add digits giving a non-negative integer add digits giving a non-negative integer we want to repeatedly add all its digits up until the resulting number has only one digit looking at the example we have the integer that's 38 so we add all its digits up 3 plus 8 we get 11. the output number is still not a single digit number so we have to repeat this process again we add 1 and 1 we get 2 so the output is now a single digit number so the process terminated and we returned that as the output so that's the question and the example and how the process looks like the brute force solution is basically to simulate this process until the number has been transformed into a single digit number uh we have to repeat this sum replace the number by its sum of its digits so let's just code that out let's just change the input to x so that your further analysis the notation becomes a little bit simpler uh until that this number has been less than 10 meaning it's a single digits we can forget about this transformation otherwise we have to repeatedly transform the number by its sum of its digits so the function transformative formation function is to replace x by the sum of its digits so we do a deep mod with the input number x by 10 to truncate its last digits and also extract that last digit add that to the accumulation s so in the end we just returned as so this process is it's basically simulating the question requirements and this solution should work so that's uh that's the brute force simulation process let's talk about uh the issues here uh we need to somehow show that uh this while loop wouldn't be running indefinitely so it will converge somehow uh let's show that so the first question is where will this converge this process converge so we're starting with the input x if it's not satisfying our criteria we're going to replace it by f x just summing up all the digits for an x to transform that into f x that's the second element in the sequence and then if it's still not the single digit number we have to apply that function again so it's a higher and higher order function calls on the original input we're basically looking into interested in whether this siri this sequence would converge so to analyze that we have to plug in the formulation for x and f x is basically adding up the digits multiplied by the correct power of tens for last digits you multiply by one for the second ten tens position digits you multiply that digit by 10 and add all those up but that's what this summation here is the f x is to adding just the digits without the multiplication of the power of tens so the only difference between f x and x is that in the summation part uh x has the power of ten the f x does not have that so it's very clear that we apply function this function f on the input x the resulting has to be less than or equal to x so that just shows that this sequence is uh decreasing until you converge once it converges it's repeating itself because we're looking at a single digit number so f x and x will become the same number so that just shows that if we simulate this process the while loop will definitely break in some point so the second question now is how fast would this sequence converge because that's the runtime complexity for this problem so if we look at the formula for x let's say that it has n different digits so that in the formula we uh looking at the we're starting with index 0 so the power works nicely we know that the number of digits inside this number is roughly log 10 base 10 of that number it should be ceiling in most of the sequence situation except for the case like a full power of 10 like 10 number 10 is it's actually two digits but if you take log 10 of 10 it's just one so uh in that case you have to add one otherwise if like 20 or something that's that should be one point something if you take the ceiling it will become two that tells you the number of digits to learn so that's uh what this uh and roughly is the total number of digits uh if we plug that if we look at the formula for f x uh summing up all the digits since that every digit has to be less than 10 otherwise it wouldn't be a single digit uh so this summation is actually upper bounded by i just replace every digit with 10 so it's 10 multiplied by n so adding the information about the number of digits uh we can see that the series is basically having the original input transform that into something that's less than 10 x log 10 of x and the next element in the sequence is log 10 base 10 of that second term second element in there so it's repeatedly taking log 10. so the runtime complexity will be order of log base 10 of x now so that shows how fast would this converge so this code here simulation submit simulate will be in log time so let's talk about the follow-ups could so let's talk about the follow-ups could so let's talk about the follow-ups could we solve it without any loop or recursion in constant time so this is clear that we have to look up look for some kind of pattern for this problem so for that reason we're just going to run this simulation process on a bunch of numbers in sequence and see can we find any kind of pattern in there maybe run this up to 100 so let's see how it works just run this uh on a bunch of number in sequence and see is there any kind of pattern in the output so that we can derive some kind of formula because constant time is definitely a formula it's not a code uh so let's add self gear so this is a number by running this simulation add digital simulation on numbers from 0 to 99. so zero will be transformed into zero one to one two to two so below ten uh for single digit number it's just the number itself from 10 it goes back to one uh one two three four five six seven eight nine and nineteen you become one again and just if you keep looking and keep looking uh it's repeating itself one two three four five six seven eight nine over and over again uh so it's clear that the pattern here is just do a modular of nine and we can directly figure out to the number so the only situa special case is that when the input is zero we output zero otherwise we just have the number modular 9 and if the number is actually 9 the marginal will become 0 but in this case we want to output 9 otherwise we just directly opening the number so it's modular 9 or not yourself if it's zero then we're operating nine so that's the uh formula regular solution to this problem now so we derived this formula by looking at the output and find the pattern maybe the next step is to prove this is right so let's talk about that i don't have the text document provided so you're going to bounce with me for my slow typing especially the formula so uh if you look at the formula here it's basically without doing any of that simulation transformation but directly modular the number by nine and find out the number why is that the case for single digit case we start with the simple case right base case um so for single digit number if you multiply that by nine uh you will get uh that number itself uh especially if except for 10 right except for number nine you modular now you get zero uh so that's uh that's this for a number that's less than nine if you modular that by nine you get that number back uh then that's the base case so when the siri converges um in the convert phase the x is basically modular by name we can return that otherwise we want to look at the relationship between x modular 9 and fx modular by 9. if they are equivalent then that's saying we don't need to go through this process we can just directly do modular on the x so let's actually move this up so that you can see my changes we want to show that x modular 9 is equivalent to f x of modular 9. if that's the case then we can skip us through all this higher order function calls directly apply this module by 9 so that we basically know the single digit cases so let's plug in the formula for x and f x onto that formula that we want to show that's our equivalent so to show that fx modulo 9 is equal to fx modular 9. we plug in the formula it's the sum of uh stuff modulo 9 equal to sum of single digits modulo 9. let's put the parenthesis there so that you know the order of calculation we do the sum first then do the margin since it's a sum of numbers then modular 9 it's equal to the individual number modulo 9 sum all those up and then do a final modular 9. so that's to put the number to the modular inside here as well and now let's look at the difference between those two the difference is that the first term has in the summation it's a d i multiplied by 10 to some power of i's this is equal to d multiplied by the single digit multiplied by 9999 some a bunch of nine plus one so that if you think about the modular adding the modular into the consideration and then just separating the summation from the second term there it becomes d times some multiple of nine actually let's actually just putting that into the second line here because it's a little bit crowded now the first tutorial here d multiplied by 999.9999 modulo 9 by 999.9999 modulo 9 by 999.9999 modulo 9 is zero because 9999 modular 9 is 0. so the first 10 is effectively zero uh so that reduced the second reduce the whole thing into the second turn there d modular nine so uh now we're basically just showing that this is indeed the same because 10 to the power of i d i multiplied by 10 to the power of i modulo 9 is equivalent to this the second term on the right hand side so we showed that x modulo 9 is equal to f x modulo 9 and it's going to be equal to f of f x modulo 9 all the way go back to a single digit case and uh so that's showing why this formula works yeah so after kind of show why this formula works so we can say that now we can justify why this works the time complexity is definitely constant all right so that's the question today and uh it's not a proof it's just a sketchy um sketch kind of showing that why this is working it's not a proof all right so that's the question today uh it's more of a math problem rather than a programming problem | Add Digits | add-digits | Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime? | A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful. | Math,Simulation,Number Theory | Easy | 202,1082,2076,2264 |
1,022 | Jhal Hello Hi Guys Welcome To Code Where She Stood As Question Is Precious Fruit To Lip Binary Numbers In This Question Which Give Will Press Tree Is Note Key Value 2018 Shruti Lift Represented By Number Starting With Most Suited For Example 15 This Type Of This Will Press It 2015 in this form and its decimal form is thirteen dictionary for consideration in decimal form 2012 question bihar to find all this point to live in this form and convert them into the air decimal mom and dad result equal example this is the tree that when entry And All Deepanshu Toli 500 Total 4505 Fruit To Leaf With U Will Find All Parts In This Form Will Convert Them Into The Equivalent Decimal In More Noida Decimal Numbers And Returned 2 Results From This Question Simple Will Find All Posts By Others On That Find All The Part In This Form And Convert Them And Every ES Node Will Convert 500 Form Into Decimal Form And Will Examine Them Will For Binary ES File Path Will Take A String Variable In This Will Happen When Love Starts From Null 999 9999 A Noble Up And E Salute For String Dad Notification 108 No Veer Voter List Note And Give Up And They Should You To Strings And Not Getting Them 100 98100 Function Which Will Convert String Into Its Equivalent Decimal Number Story In Different Look At First E The First I Will Declare String Variable Is Which will start from which means life and district courts in this is the variable in which will agree numbers and no I will declare in possible this tour finals we absolutely function poison but function will travel through all the tree e and gives binary numbers from drought relief Will pass through to this function spring handsome and anil bhai definition of this function int helper MP3 that train note star ajay ko the root string is that and int sump dec bill pass reference because its value will keep on changing from this course of destruction of nodes This root is internal the return is a good 10 companies who is not in our wife and now but meanwhile write note on this root roots left 112 null key and roots light is 112 null what will we do a note via a lips note Is on increase in do real note Nobel price appendice value in a string variable is a noise pollution in teaser software to convert into string and discussed during value how to and main spring that boat love in a non string variable and 50 start but indra failed on String Noble can be exactly a primary function which will convert string into its equivalent binary which is in the mid wicket boundary function on I Ariba pass induct nor will not be the best number which will assist in subscribing that battery tables. In achievement position like share 14012 in this case first will up and these values for string on that no 150 qualification helper a fast on left side and person possible but this train will pass singh will contain co like bihar and country notification soviet then add 200 value Also tourist ring in the morning will look into a plus to spring the root well as are superstition amused at not being royal vacation call to right side is a as plus similarly in this case also will up and value the songs of a message are the value of paint on Now particular node I am available Chot North dysfunction is box open off but oo right one function also visit by individual convert string into binary from its return typing teacher name is minor I will pass street suite Jai Hind this function is simply doing now binary conversion To Our Definition Version Is So Ant Answer 's Record 208 Restore Answer Int Power 's Record 208 Restore Answer Int Power 's Record 208 Restore Answer Int Power Equal To One Camp At Nine Question Is That Person That Don't Know What Is The Most Significant Positive Vibes Hair Last But Will Help You Get A String Of Words Was And pant fire equals to a good balance a minus one five great daily on 1205 Plus - - a minus one five great daily on 1205 Plus - - that nine every position bf2 an answer * answerable that nine every position bf2 an answer * answerable that nine every position bf2 an answer * answerable distinction clarification - 03 converter character which was distinction clarification - 03 converter character which was distinction clarification - 03 converter character which was initially one - dr will give one only not initially one - dr will give one only not initially one - dr will give one only not into power is initially One Not Every Step Power Will Be Race-2 Do Step Power Will Be Race-2 Do Step Power Will Be Race-2 Do A Noble Dinner Answer Base Permission Simply Converting Ghar String Into Decimal Point Into Decimal Form And Destroyed But Function Is Giving Up All Departs From Root To Leave In This Form And Converting And Using Function In The Best Kasba Angry When Converting Dad Path Into Its Corresponding Decimal That Decimal Form No After Discussions Ro Va Dasham Va Vishwas Pass Filled Container Answer Will Return Some Note Sandhi Ko A Jo Arm To Sing A Well On Yes Exit Is On This Route On This Game Cat Option and Test Case Loot Samridhi Code Hai To Phir So Let's Get Started IF YOU LIKE THE VIDEO THANK YOU PLEASE LIKE SHARE AND SUBSCRIBE TO | Sum of Root To Leaf Binary Numbers | unique-paths-iii | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return _the sum of these numbers_.
The test cases are generated so that the answer fits in a **32-bits** integer.
**Example 1:**
**Input:** root = \[1,0,1,0,1,0,1\]
**Output:** 22
**Explanation:** (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
**Example 2:**
**Input:** root = \[0\]
**Output:** 0
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `Node.val` is `0` or `1`. | null | Array,Backtracking,Bit Manipulation,Matrix | Hard | 37,63,212 |
1,680 | Hi gas welcome and welcome back to my channel so today our problem is which concatenation of consecutive numbers so on this problem statement what have you given us here we have given a wait and what we have to do is to find the decimal value of D Mind Re Stream Now this thinking will become yours, how what do we have to do, we have to find the binary number of all the numbers from the beginning to the end and contact all of them, okay and from that we will get the decimal value of the binary string that will be formed. If you want to find, then let's first understand this problem through an example, whether the problem is exactly ours, then we will see how you can solve it. Okay, so look, here we have given the end, I have taken two examples, first and second. And here pe van hai output aapka van hai end tu end three hai output aapka 27 hai kaise banna hai they will see ok so look and van hai what do we have to do from van till end tak to n to aapka to here till mind number van ka van If yes, then the answer is your WAN. Okay, this is your end. If you were there then how many numbers would you connect from WAN to END. First connect the numbers from WAN to 2. If you connect its binary representation, then WAN will be What happens to you is one and what happens to you is 10, if you cut these two then this becomes this then this is the final answer, what is your four, you are six, right then end is three, then it is n3. What do I have to do? If I have to concatenate the numbers from one to three, then van ka van tu ka van zero and three ka van write it jo van tha 27, this would be your answer. Ok, if there was four then what should I do? The numbers from one to four will have to be disconnected. One van zero is yours, then three, then 1 0. Okay, then this is your final binary string. We will have to find the decimal value of this binary. Okay, so what we have to do by doing this is to find the final value and turn it. Okay, so how can we solve this problem? Look, and what do we have to do with the binary value, if we add it, then these two If you add ko, what will happen? 1 0 Okay, so see, if Van is here in your initials, then you are seeing, after that you have to add Tu. Okay, so what will this van do with these two beats? It will leave its space and will come here, this here, what do you say a little from here, you are shifting towards the left, this is shifting to the left, so we are shipping to the left, then look, it will become 00 by adding it here. If you give then this final, what will become of your 110, this is formed from here, okay, after that you see, what will you do in the condition, who will you cut in the van, now it will add this 10 in itself, okay, it will add it in its last i.e. here. It will leave two spaces and will be shifted here. We will have to i.e. here. It will leave two spaces and will be shifted here. We will have to keep it for both of them, so it will be from here, towards the left, okay, this will be sip and what will come in its place, 10 A will go, how will it come, I will tell you, okay. Then what will happen after that, this van will come, this van has to be added in the last, so what will all these have to do, they will have to leave two spaces of theirs in the last, so these two spaces will be seated from here, okay, this will be shifted here. Van here will be only the last one, okay, here two positions will come here towards the left because the count here is yours, so this 11 will be here, the final sting will be here, this is what we have to make, this is the right one. We will find the decimal value van, after that see what will happen if n4 remains and if there will be four then what will you add now, will you add van, will you add tu, will you add three, will you add four, will you add right van, value of van tu, value of 1 0, value of 3, van Value of four 1 0 If you connect this then what will be formed Van Zero Ok this will be formed and we have to find the decimal value of this Right so look at the initial you will have this van Ok this will be van Now you will get 10 in the last Have to add, if you have to add to the last of this, then this will shift two beats here, so this is this two, this will create space here, okay, what will come here, 10, you have done 101, which one has done this, now you have done this. If you want to do this then what is its also, what is the total beat, there are two in it, okay, then you will shift it to two, you will bring this van here, okay now, but in the end, what do we want 100. That is, three spaces should be free here, three spaces should be free, then what do we have to do, we have to shift three spaces here, this will be here, this van here, this zero here, it is okay, this man here, this van here. Now it is just empty for 100, it will be filled here right, we will get it, so how will we solve this problem, what will we do, the total beat is zero, how much is there in it, you see that, okay people, there are two bitters in it, so what are you What will you do with the number that is there? If you shift it here by two bits, what will happen after shifting? This van will become 100. It is okay because this is van so it is shifted here. What will happen in its place here in these two places? Pe zero a goes right, after that what will we do, whatever number is here, we will add its decimal value to it. Okay, whatever it is, if we add it to it, then what will become of us, this van will become zero, right this. What has become 110, after that what do we have to do, we have to add it here, at the end of this, it will have to be shifted by how many beats, its length will be by that number of beats, what is the total bits in it, if there are two beats, then there are two beats here. You will have to shift two left positions, then this van will come here, this zero will come here, these two spaces have become vacant, here zero will be zero, right then this van will be added, your van will be added here. Okay, so this What will they become? 11011 Okay, after that what is your four? How many bits are there in four? If it is 3 beats, then it will have to shift by 3 meters here, then it will shift by three meters, then what will become of yours: shift by three meters, then what will become of yours: shift by three meters, then what will become of yours: This here, this will shift here, van, this van, here. Pay this zero here, this van here, three spaces here, it is empty here, what will we do, it will become 00 when you shift, then what will you do with it, by adding it here, people are fine, I have added it van Zero van zero, this is what we had to make, so I will show it in the code, after that I will explain to you again what we are doing, okay so see what we have to do here, we need the length of any number, whatever it is. There are also numbers A, from 1 to N, we will see how many bits are there in each, okay, so what we have done, here we have created a function, it will return you and give the total bits, okay, after that what we did is answer zero. We will start from and we have to do the mode because your answer can be bigger. Okay, so here you take the mode 10, you gave the power 9 + 7. This also has to be done. Okay, you gave the power 9 + 7. This also has to be done. Okay, you gave the power 9 + 7. This also has to be done. Okay, so here we have also taken the now. We will see from the van till the end, okay, so we have done the follow up, now what will we do, we will see what is the total number of bits now, by how much do we have to shift as much as we have, the total number of bits will be okay, so here we We will take N zero, sorry, here the number of bits will be A, then what will we do with the answer? By how much will we shift here, as much as your total number of bits will be on the right, here you will shift here, if you are shifting towards the left, then this is Whichever corner is on which side, it is shifted like this. If this operator is towards the right, then this corner is right shift. If this corner is towards the left, then this is your left shift operator. Okay, so this is your kiss. The side is towards the left and here we are showing you in the example that on the left side, we have to do it with how many, what will be the number of total bits, we have to do it with that much, okay, here we will do it with the mode key, then I with plus. If it is doing the same then we will also make the i plus, what should we do after right shift, we are making the i plus, this is what we are doing, look here you set it, then what did you do, mode, we will do that, okay so Finally, what will we return? So my final answer is to be stored and this is your answer. Okay, I hope you have understood the explanation. If you liked the video, please like, share and subscribe. Thank you. | Concatenation of Consecutive Binary Numbers | count-all-possible-routes | Given an integer `n`, return _the **decimal value** of the binary string formed by concatenating the binary representations of_ `1` _to_ `n` _in order, **modulo**_ `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 1
**Explanation: ** "1 " in binary corresponds to the decimal value 1.
**Example 2:**
**Input:** n = 3
**Output:** 27
**Explanation:** In binary, 1, 2, and 3 corresponds to "1 ", "10 ", and "11 ".
After concatenating them, we have "11011 ", which corresponds to the decimal value 27.
**Example 3:**
**Input:** n = 12
**Output:** 505379714
**Explanation**: The concatenation results in "1101110010111011110001001101010111100 ".
The decimal value of that is 118505380540.
After modulo 109 + 7, the result is 505379714.
**Constraints:**
* `1 <= n <= 105` | Use dynamic programming to solve this problem with each state defined by the city index and fuel left. Since the array contains distinct integers fuel will always be spent in each move and so there can be no cycles. | Array,Dynamic Programming,Memoization | Hard | null |
1,678 | foreign problem 1678 called parser interpretation you own a gold parser that can interpret a string command the command consists of an alphabet of J open and close scope and or Al in some order the call part server will interpret J as a string Jake s scope and as a string o and Al inside of a scope will be as a string Al the interpreted strings are then concatenated in the original order given the swing command return the call parser's interpretation of command so the idea here is pretty simple we are given a string that will consist of either j a l or scopes as it says here command consists some over there so our goal is to concatenate the result so we can so it can be released something as this let's go so first thing we're going to create a string named output that will hold the value each character no this one it will hold the Kong ated result from command string and now we can create our for Loop notice here the uh we are using lengths we can also use size uh in inside of a for Loop to solve any string problems it well it works pretty fine but I just prefer to use lengths in this case lengths of the string as a condition and increment it if command at the index I is equal to J output will get watching notice here that we are comparing a command at the index I what it does is we are actually comparing a character so command at the index I will have J so every time the for Loop runs it will go through each element of the string so first we will go through J and then these open close scope and then again and so on to reaches the last element of the string okay I'll save command index I is equal to this and command that index five plus one equal to this I'll put it okay then come on bye to accumulate else if command index I will be equal to a output we'll get decorated actually at all and at the end we're just gonna return back the result that we get based on this for Loop that we created back to the main function to see let's see if it works nope it didn't because this one's supposed to be oh run the code again to see if it works foreign yes it does submit it does | Goal Parser Interpretation | number-of-ways-to-split-a-string | You own a **Goal Parser** that can interpret a string `command`. The `command` consists of an alphabet of `"G "`, `"() "` and/or `"(al) "` in some order. The Goal Parser will interpret `"G "` as the string `"G "`, `"() "` as the string `"o "`, and `"(al) "` as the string `"al "`. The interpreted strings are then concatenated in the original order.
Given the string `command`, return _the **Goal Parser**'s interpretation of_ `command`.
**Example 1:**
**Input:** command = "G()(al) "
**Output:** "Goal "
**Explanation:** The Goal Parser interprets the command as follows:
G -> G
() -> o
(al) -> al
The final concatenated result is "Goal ".
**Example 2:**
**Input:** command = "G()()()()(al) "
**Output:** "Gooooal "
**Example 3:**
**Input:** command = "(al)G(al)()()G "
**Output:** "alGalooG "
**Constraints:**
* `1 <= command.length <= 100`
* `command` consists of `"G "`, `"() "`, and/or `"(al) "` in some order. | There is no way if the sum (number of '1's) is not divisible by the number of splits. So sum%3 should be 0. Preffix s1 , and suffix s3 should have sum/3 characters '1'. Follow up: Can you generalize the problem with numbers between [-10^9, 10^9] such the sum between subarrays s1, s2, s3 are the same? | Math,String | Medium | 548 |
1,470 | hey everybody this is Larry I'm doing this problem as part of a contest so you're gonna watch me live as I go through my daughter's I'm coding they've been explanation near the end and for more context they'll be a link below on this actual screen cats of the contest how did you do let me know you do hit the like button either subscribe button and here we go oh yeah q1 shuffled away so this one oh yeah that and now you could see me just going back and forth seeing it whether it's the q1 shuffled it away so may say right now I'm just reading a problem basically I knew how I mean this is actually literally just what mathematically is called the perfect shuffle which means you take half the deck nothing right and then you put it in to leave it one at a time and what I did is I just used the two pointers I put the point eleven point there right I just double checked that the length of the away is even because of its odd then you had to do something smaller I have a typo here but because this poem is so straightforward that it's easy to and then I check as accepted on the other plan as mom is so straightforward then I was like wait but the answers are wrong and I got when you guessed and I am bad at that Matt Bennett type one and after looking at I was like okay that look shuffled away so I did these a little bit out of order because if you watch the stream I the internet which is having issues so that also didn't help I was I wasn't sure it was my internet or lead coach because it seems like other people are having the same issues of the internet okay let's go who's I shuffled away giving it away numbs instead of to n elements so there's we turned away the form okay yeah so this one it's just pretty straightforward in that you just it is a classic shuffle method basically you take what I did was that I just have two pointers right one starting at point of one and then a second one persona in the middle and then just moved one at a time and that's basically what I did here with the point is to the left and then an implicit corner to the right with just plus half the right way and then after that we put it in the answers and that's pretty much what you won yeah and the only thing that I had to double check was whether it's odd or even because if it's odd then maybe grab too well then we apply again and off by one even if and in index error but this was not the case so that's good yeah pretty straight for all we I mean I don't think this would be an interview question but it would be part of a bigger interview question was definitely I've seen people give interviews on like hey here's you know a deck of cards you know shuffle it with the perfect shuffle or something like that way so these things you should probably practice on and yeah this is doing a competitive programming but it also comes up enough during competitor programs that definitely recommend it yeah | Shuffle the Array | tweet-counts-per-frequency | Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`.
_Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`.
**Example 1:**
**Input:** nums = \[2,5,1,3,4,7\], n = 3
**Output:** \[2,3,5,4,1,7\]
**Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\].
**Example 2:**
**Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4
**Output:** \[1,4,2,3,3,2,4,1\]
**Example 3:**
**Input:** nums = \[1,1,2,2\], n = 2
**Output:** \[1,2,1,2\]
**Constraints:**
* `1 <= n <= 500`
* `nums.length == 2n`
* `1 <= nums[i] <= 10^3` | null | Hash Table,Binary Search,Design,Sorting,Ordered Set | Medium | null |
678 | everyone welcome back and let's write some more neat code today so today let's solve the problem valid parentheses string we've solved a few parentheses related problems on this channel but this is a pretty unique one so we're given a string s and it could contain three types of characters a left parenthesis a right parenthesis and a wild card character and the wild card character could be a three possibilities it could be an empty string which is the simplest right so basically in that case we would ignore the wild card it could be a right parenthesis or it could be a left parenthesis so each time we reach a wild card in terms of a decision tree we really have three branches right we have three different things we could consider it could be a space it could be a left parenthesis it could be a right parenthesis so already we're kind of getting the intuition of how to solve this problem or at least enumerate all possibilities our goal is to determine if the given string could be valid if it's possible we return true if it's impossible we return false and you can go over this to understand what makes parentheses valid and invalid the main thing is as you scan through a string suppose this one what has to really happen is that every left parenthesis has to have a matching right parenthesis and the matching right parenthesis has to come after the left parentheses and the natural order for it is kind of like first in first out so you can see we have a left parenthesis then we have another left parenthesis then we have a right parenthesis and this right parenthesis matches this one okay then we have another left parenthesis then we have a right parenthesis this matches the most recent one and then we have another right parentheses and this matches this one but suppose we had a slightly different string maybe we have three right parentheses in a row this would be invalid and you can see why these two match each other great this one matches this one great but the right parentheses then comes before the left parenthesis we can't have that and this is one way to understand that but the easiest way to know that we have an invalid parenthesis combination is that at any given point of the string the number of left parentheses that we have can never be less than the number of right parentheses and you can see that happens here right we have two left parentheses then we have three right parentheses and we are never going to be able to recover from this because at one point in time we had more right parentheses than we had left it doesn't matter if we get more left parentheses we cannot recover from this ever and that's how you know it's invalid let's take a very simple input string and then determine if this is valid or not and we can tell that it is how would it be valid if the wild card was empty and it would look like this right just a left and a right parenthesis but how can we do that uh brute force and we would we could possibly have more complex strings how could we determine that well the brute force is going to be a decision tree because if we weren't given any wild cards we have a very simple algorithm just to scan through the parentheses to know if they were valid or not just like i talked about but with wild cards there's lots of possibilities we're going to go through each character in the string and have a decision tree so first character we see is a left parenthesis that's perfectly fine and then we get to the wild card right when you get to a wild card that's when you actually need to branch we don't need to just branch when we get to a regular parenthesis because that's already determined it could be another left parenthesis it could be a space or it could be a right parenthesis and then we're going to get to the third character uh but we have to do that third character it's already determined it's a right parenthesis but we have to do it for all three of our branches now so you can kind of see if we had a lot of wild cards uh this decision tree would get very big but let's just finish it up real quick so here we'll have a right parenthesis here we'll have a right parentheses here we'll have a right parenthesis so among all three of these combinations you can see that this is invalid because it has two open it has two left one right that's invalid this one you can see is also invalid it has one left and then two right but the middle one you can see it is valid it has a left a space and then a right and the way we could do this problem recursively the decision tree portion is kind of simple we would make three recursive calls every time we got to a wild card but to determine if it was valid or not one we would keep track of how many left parentheses we had how many open left parentheses we had at this point we had one open if we're just considering the middle branch here we also had a one open and then by the end of it we had zero open zero left open parenthesis by the end we should have exactly zero because they should all match each other and the number of left open should never be negative for example if we started like this right if we started with a right parenthesis that's automatically invalid okay so that's the recursive solution and you can actually add dynamic programming and by dynamic programming i mean memoization that's the easier way to do it to this recursive solution and i will actually link the code to that in the description if you want to take a look uh the overall time complexity of first of all the brute force solution is in the worst case going to be a 3 to the power of n because that's how many branches we have n is going to be the size of the string because that's going to be the height of this decision tree but when you add memoization to this the overall time complexity actually becomes n cubed and the way we would do that is by caching and we would cache uh with two parameters one would be i which is the index of the position that we're at and the other parameter would be uh the number of left open parentheses at any given point uh in the string that we're at now a caching with two different parameters like this will cause us to have a two-dimensional matrix uh the have a two-dimensional matrix uh the have a two-dimensional matrix uh the size of that matrix is going to be n squared but to calculate each value in that matrix would take big o of n time complexity that's how i'm getting n cubed from but i don't expect you to understand all of this if you want to understand it a bit more you can look at the code that i'll have in the description but there's actually an even more efficient way to solve this problem and that is the greedy solution and it's very difficult to come up with now even if you can't come up with the greedy solution by yourself it might still occur to you in a real interview that maybe there's some kind of trick to this problem that if only you could figure it out you would be able to solve this problem in linear time is there a trick like that well hopefully in a real interview your interviewer would give you a hint for that but let's see how we could maybe come up with it ourselves we know that one variable is going to be a mandatory for us and i'm going to call it left it's going to be the number of left open parentheses we have and when we reach the first character it's a left open parenthesis initially our total is going to be zero but after seeing the left open parenthesis we increment it by one now we have one left open parenthesis and that would be very easy uh suppose we didn't have the wild card then we would have a right parenthesis and we would do the exact opposite we'd say okay left uh open parenthesis has been decremented by one so now we're back to zero left open parenthesis and that makes sense but wild cards create multiple possibilities and three exactly right one the simplest would be to ignore this right if we ignore it okay we're still left with one open parenthesis that's the simplest but it could there could be multiple possibilities right and we need to consider all possibilities if we want to be sure that we can determine if this is possibly valid or not possibly valid we do have to consider every possibility so another possibility is this wild card could be a left open parenthesis if that's the case we would take our left and actually increment it by one to make it two but another possibility is that this a wild card could be a right parenthesis and in that case we would take this and then decrement it by one see how this wild card is creating some divergence for us we can't maintain all possibilities in a single variable like we could before so this is kind of a hint to you that maybe we need two variables let's go to the third character before we actually create those two variables now we have a right parenthesis now what are we gonna do well with right parentheses we're gonna decrement our left count but now we have to decrement two variables so this would become one and then this would become zero what do these actually represent the reason we have two in the first place is from the wild card basically these are gonna represent the i'm gonna call it the left max and the left min and what that means is what's the maximum left open left parenthesis we could have and what's the minimum open left parenthesis we could have depending on how we choose our wild card okay now let's go to another character and again we have a wild card now let me explain to you what these two variables are supposed to represent they're supposed to represent the range of possibilities we could have zero left open parentheses or we could have one left open parentheses depending on how we chose the first wild card but now we have a second wildcard now if we made this a left open parenthesis that would mean it's possible for us to have two left open parentheses so we would update our left max in that case but if we made it a closing parenthesis then we would want to update our minimum because this is supposed to represent all possibilities so let's do exactly that if let's increment our left max to be 2 then let's decrement our left min to be negative one but hold on for a second this isn't just the range of possibilities this should also be the valid range of possibilities we should never have our left min become negative because that would imply that the choices we made caused our left min to be negative and we know that's invalid so we're never going to allow our left min to become negative if it ever does become negative we're going to reset it back to b0 so now you can see that these are the range of possibilities between zero and two and now we're just going to continue through the rest of the array we're going to get a left open parenthesis which uh we're going to increment both of our variables so this is going to be 1 this is going to be a 3 and then we're going to get a closing parenthesis so this is going to be decremented down to 0. this is going to be decremented down to 2. and now how do we know if we can return true or false is this valid or is it not valid well we know it's balanced if the left open parenthesis count is zero so does zero fall in between our range right now it does because our left min is exactly zero so that's how you know we can return true if our left min is equal to zero and before we get into the code i just want to show you another way that our solution could have been invalid uh suppose you know our string had two uh closing parentheses and then two open of course our left min is never going to be uh negative because uh if it becomes negative we reset it back to zero but if our left max does become negative uh in this case it'll be negative two uh from this uh at this after we've seen these two that's how you know we can return false because it'll never be valid we'll never recover from this because if the maximum number of left open parentheses we could have is negative that means there's no choices we could possibly do to make this valid okay so before we get into the code as you could tell from this algorithm we don't even need any extra space so the space complexity is bigger of zero and we only need to scan through the string once so the time complexity is big o of n so now let's code it up okay so now let's code it up and like i said we're gonna have two variables left min and left max initially they're both gonna be a zero and then we're just going to go through every single character in the string if we get a open parenthesis a left open parenthesis we're going to increment both of our variables so leftmin and leftmax are going to be incremented by one because here we don't really have any choices we have to increment the count by one and in the opposite case where we do have a closing parenthesis we also don't have a choice so i'm going to copy and paste this but in that case we're going to be decrementing the count by one for each of them uh and the else case is when we have a wild card we don't have to specify that character and this is the part where we do have a choice so i'll copy and paste again but with the left min we're going to decrement that count in the case that we have a closing parenthesis and in the case that we choose the wild card to be an open parenthesis we're going to increment the left max by 1. but remember if the left max ever is negative that means it's impossible for our parentheses to be valid so in that case we're just going to immediately return false but in the similar case where our left min is negative we're not necessarily going to return false because that would mean our left max is not negative so it technically is possible for the string to still be valid we don't want to continue assuming that our string up until this point is invalid so we're going to reset it back to zero and if this part is unclear and i don't expect it to be too clear because it's actually complicated to understand this is the string that i would kind of run the code on and this is the example i would really try to understand if you don't get this part this string is impossible to make valid no matter what we choose for the wild card but if you don't include this if statement in your code you'll end up returning true for this when you should be returning false that's kind of what i'll leave it at but other than that once we exit the loop we will return true if the left min is equal to zero if it's not equal to zero then we return false now let's run the code 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 | Valid Parenthesis String | valid-parenthesis-string | Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left parenthesis `'('`.
* Left parenthesis `'('` must go before the corresponding right parenthesis `')'`.
* `'*'` could be treated as a single right parenthesis `')'` or a single left parenthesis `'('` or an empty string `" "`.
**Example 1:**
**Input:** s = "()"
**Output:** true
**Example 2:**
**Input:** s = "(\*)"
**Output:** true
**Example 3:**
**Input:** s = "(\*))"
**Output:** true
**Constraints:**
* `1 <= s.length <= 100`
* `s[i]` is `'('`, `')'` or `'*'`. | null | String,Dynamic Programming,Stack,Greedy | Medium | 763,2221 |
912 | 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 sort and array so in this question we are given an array called nums and we need to sort the array ascending order and return it coming to the functions have given us this is the function name and this is the input array we have to work on and we have to return an integer array there are many types of sorts to begin with bubble sort insertion sort and selection sort but their time complexity goes to O of Big O of n Square for this program I'm going to show you how to do the counting sort the countings on basically uses a hash map to store the frequencies of each element inside the input array and then we need to find the Min and Max element from the input area and run a for loop from Min until Max and then we have to access the elements from the map we created according to its frequency and printed so let me show you how the problem is solved so in counting sort we have to first create a hash map to the frequencies so for this example the hash map is going to look like this so the key and values are going to be integer so the keys are going to be the array elements 5 2 3 and 1 and the frequencies are going to be its frequencies like how many times each element is appearing inside the input array and for this example it is going to be so let's take this example and see how this is going to be solved so this is the input array nouns we are going to solve and the indexes are written in blue it will start from 0 to 5 and this is the map for that input array first we need to find out the minimum and Max element from the input array we iterate through the input array from left to right and we find out the values inside the map and we also find out the Min and Max element in the same iteration so once you solve this the Min element is going to be 0 and the max element is going to be 5. we cannot assign a new array to display the output we have to do it in place inside the input array itself so we also need a index called index variable which is initially pointing at zero so index is here now we iterate for Loop will run from Min to Max so Min to Max and in each iteration I will increment by 1 and these are the elements inside the input array so we take the element 0 and check its frequency of 0 is equal to 2 which means 0 should appear two times inside the array so first we take the element 0 and replace 5 with 0 and next iteration index will be pointing here and the value of 0 will be decremented by 1 and now 0 is having the count of one so once you access an element it will be printed until the value becomes 0 now it is 1 right so again we have to add another 0 inside the output so this will be replaced by zero decrement is count by 0 so 0 is now having count 0 so we'll move on to the next element I plus so I it was 0 now it is one now we check if 1 is present inside the map yes one is present and its frequency is 2. now index is pointing here so frequency of 1 is 2 so again we need to print 1 inside the output array two times so first iteration one will be printed here and it's count is updated to 1 inside the map and index is pushed forward and again one is inserted and its frequency is decremented to zero and now we can proceed to the next element incrementing I so I is now 2 I will check for 2 inside the map S2 is present and its frequency is equal to 1 push index forward so index is now pointing here and we need to replace that element with the current element 2 inside the map which is having frequency 1 and we decrement its frequency by 1 and it becomes 0 and we move on to the next element by I is equal to 3 it is not present inside the map so we increment I is equal to 4 it is not present inside the map increment I is equal to 5 which is Max so this is the last element to be added inside the map so we increment index so index is now pointing here and the frequency of 5 is 1 so add it inside the array and decrement its frequency by 1 and become 0 and we reach the end of the iteration the for Loop will run from Min to Max right with I plus and we reached 5 the next iteration the for Loop will break and we come outside the for Loop and we can finally return our result which is present inside the input array Norms so Norms will be returned as the output and this is the output for our question now that we have seen the working let us code it up as I have said first we need a hash map to store the frequencies so the key and value are going to be integers now let us assign two variables minimum and maximum so let's assign those two elements to be pointing at the first element so you can assign Min as the first element inside the array nums so in Min equal to nums of 0 and also Max will also be the first element because if there is no other element and the size of the input array is 1 so the first element the only element present inside that array will be the minimum and maximum right so here the constraint is that the input array starts from length equal to 1 so we can assign the first element as Min and Max and then we can compute all the elements and find out the Min and Max element at the end of the array so let's iterate through the input array from start to end now we need to add elements inside the map right so first I'm going to check if that element is present as key inside the map so map dot contains key of nums 5. so if that element is already present inside the map we need to increase its frequency by one so map dot put numsify frequency map dot get of nums of five we are getting its current frequency and increasing it with one each time you see it and in the IELTS block so this else block will be executed for every unique element so if that element is not present inside the map as key we need to put that element as map inside key map dot put off nums of I and set its frequency to 1 and from the next time whenever it is present inside the map this statement will be executed and its frequency will be incremented now in this for Loop only we can find the minimum and maximum element so if the current element nums of I is less than the current min we need to assign Min as the current element s of I and now we can also find out if it is the maximum element by checking if the current element Norms of I is greater than the current Max we can assign Max as the current element so this is a one block and this is one block all this is happening inside one iteration of the input array from start to end so for this example here this for Loop will run for 5 times 0 to 4 whenever the I value equal to 4 the for Loop will break and come out of it now we have the Min element and Max element of the input array stored inside these variables so let us run a for loop from int I equal to min until I is equal to Max because Max is also present inside the array so we need to run until I is equal less than or equal to Max now we cannot create another array we need to store the output array inside the input array itself for that let us use the index and assign it to 0 now I is equal to the least element in this example Min is equal to 0 and Max is equal to 5 so I is equal to Min so I is equal to 0. now we need to get the frequency of 0 because 0 appears twice inside the array we need to get its frequency and print the two zeros at once in the beginning of the array here as you can see two zeros are printed at the beginning so for that let's check if the frequency of element at I is less than zero so until then we can print it for that we can use a while though so while app dot we can use the get or default method foreign has to parameters the first parameter I is for this so get of I will get the frequency of I if that element is not present print 0 as out is greater than 0 so until then this while loop will run we get the frequency of 0 which is 2 this while loop will run for three time and on the third time when I will become 0 this while loop will break now we need to print 0 2 times inside the output array but we haven't declared output array because we need to print the sort the elements in place so nums of index so index is now pointing at 0 and we need to print the two zeros from here so these two elements will be replaced by zeros is equal to I which is currently 0 and then we need to increment the index for the next iteration first we have printed 0 now index plus means index is 1 so here again we print 0 each time we print a zero we need to decrease its frequency inside the map by one so we need to replace its frequency by decreasing it by one so mad dot put of 0 is I and map dot get of I the current frequency and decrease it y1 so in the third iteration first two times T these two zeros will be printed and in the third iteration the value of the key 0 is equal to 0 so it comes out of the while loop so two zeros are printed now I is equal to 1 because I plus so mean was 0 now it is 1 so it will access these two elements from the map and print it two more times using this while loop and next I is equal to 2 it will access 2 and print it inside the array next I is equal to 3 is not present inside the input because here map dot get of 3 using or default value are used when that element is not present so 0 will be returned here 0 is greater than zero so it won't enter this low I plus I is equal to 4 is not present again 0 will be returned here and it won't enter next I is equal to 5 yes 5 is present it will be printed here because index value is now pointing here so 5 will be printed and we reach the end of the program finally outside the for Loop you can return the input array norms now let's run the code let's submit the code there you have it a solution has been accepted so the time complexity of this approach is of n plus K where n is the number of elements inside the nums array and K is the range between Min and Max because here we are using a for low which will run from I equal to Min till Max and the space complexity is also of n because we're using a map to store the frequency of the array elements thank you for watching and I'll see you in the next one foreign | Sort an Array | random-pick-with-weight | Given an array of integers `nums`, sort the array in ascending order and return it.
You must solve the problem **without using any built-in** functions in `O(nlog(n))` time complexity and with the smallest space complexity possible.
**Example 1:**
**Input:** nums = \[5,2,3,1\]
**Output:** \[1,2,3,5\]
**Explanation:** After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
**Example 2:**
**Input:** nums = \[5,1,1,2,0,0\]
**Output:** \[0,0,1,1,2,5\]
**Explanation:** Note that the values of nums are not necessairly unique.
**Constraints:**
* `1 <= nums.length <= 5 * 104`
* `-5 * 104 <= nums[i] <= 5 * 104` | null | Math,Binary Search,Prefix Sum,Randomized | Medium | 398,894,914 |
396 | so this question is lead code 396 rotate function we are given a nums array of length n and we have to calculate F of K function for 0 to n minus 1. how we calculate F of K is for f of 0 we will have to multiply each number with its index and sum it up then we rotate the number once numbs array ones and we repeat it for 0 to n minus 1. so let's see how we do it so given this function we can first start calculating the F of 0 for this array F of 0 means we have rotated r a zero times and we are calculating the function so we can say 4 times its index that is 0. plus 3 times its index plus 2 times its index plus 6 times its index which gives us a total of 4 18 22 and 25. now for f of 1 what happens is this increases by one this increases by 1. this increases by one and this one becomes zero how did that happen because we rotated the array ones and after rotation after one rotation the array will look something like this and the index of 6 is 0. for 4 it's one three it's two and two it's three if we sum it up we get 4 plus 6 10 plus 6 16. so we need to observe something what happened so if we notice carefully count of each and every element in the array increased by one except for six so can we say that we basically added the sum of array into this so the sum of array is 15. but we did not add six and we also removed six three times this term which gives us 16. so what happened here is we took the previous function we added the sum to it because each term increased by one but we removed six from it which essentially went to index 0. and it going to index 0 not only eliminated that term from our sum but it also removed the three times index it had before so in total we had we have subtracted 4 times the last element or the element which went to index 0. from 25 Plus 15. so for f of 2 we can say the previous function that is f of 1 which is 16 plus 15 the last term which is 2 so minus 2 times the length of the array that is 4 like we use here and we will get 31 minus 8 that is 23. and you can verify that so now we have noticed the pattern here let's code it up so let's start calculating the F of 0 like we did during the explanation so it was sum of each number multiplied by its index so I is index and num is the number for I common num and enumerate nums this will give us the F of 0 function we also need the total sum and the length of the array so we'll say size for that and total sum can be obtained by sum of nums and this is line of numbers now we can start iterating backwards for I in range size minus 1 up to 0 step of -1 so we get the num from nums of I and the next function can be calculated as previous function plus the total sum minus size num the number we just removed and we can have the max function come on previous function equals F of f of 0 comma F of 0. and we can say Max function is the max of Max function and the next function and make sure to assign previous function to the next function and finally return the max function again let's run it and it is not callable okay we missed multiplication sign and it is accepted let's submit it so as you can see it works | Rotate Function | rotate-function | You are given an integer array `nums` of length `n`.
Assume `arrk` to be an array obtained by rotating `nums` by `k` positions clock-wise. We define the **rotation function** `F` on `nums` as follow:
* `F(k) = 0 * arrk[0] + 1 * arrk[1] + ... + (n - 1) * arrk[n - 1].`
Return _the maximum value of_ `F(0), F(1), ..., F(n-1)`.
The test cases are generated so that the answer fits in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[4,3,2,6\]
**Output:** 26
**Explanation:**
F(0) = (0 \* 4) + (1 \* 3) + (2 \* 2) + (3 \* 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 \* 6) + (1 \* 4) + (2 \* 3) + (3 \* 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 \* 2) + (1 \* 6) + (2 \* 4) + (3 \* 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 \* 3) + (1 \* 2) + (2 \* 6) + (3 \* 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
**Example 2:**
**Input:** nums = \[100\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `-100 <= nums[i] <= 100` | null | Array,Math,Dynamic Programming | Medium | null |
1,254 | hey what's up guys this is sean here so uh today let's take a look at this 1254 number of closed islands so i mean the media one it's this one is not definitely not that hard i mean okay so given like a 2d grades here consists of either zeros represents the land or ones represents water and an island is a is like a maximum four directional connected groups of zeros and the closed island is an island totally surrounded by ones so it means that an island is a closed island if and only if they're like basically the whole island is surrounded by ones here okay right for example this one here we have a two uh closed islands the first one is this one okay this is the first island okay and the second island is this one and actually there's a there's like a there's two other like non-closed items here right see i mean non-closed items here right see i mean non-closed items here right see i mean i think all of you knows the unknowns there's like this number of islands uh problem right so basically we you just we just do a like dfs right dfi search to find out all of the islands but this problem is a little bit different right but the only difference here is that we need to find out the uh the closed island which does not which is which are surrounded by old ones okay so yeah i think that's the only thing we need to add here in our code here so i'm pretty sure there are like other ways of doing it but for me i'm just using like a flag during the uh the dfi search basically you know as long as i have like you know every time when we have like uh the part of the island i check if that island is uh is on the edge on edge means if it's on if the i is equal to 0 or m minus 1 or j equals to 0 or n minus 1. okay as long as that's the case okay then it means that i mean this island could cannot be uh cannot be a closed island because anything on the on like zero here there's no way we can uh that can be surrounded by ones so i just uh ignore that island yep i think that's it let's try let me try to code these things real quick so answer zero you know for dfs you know we can either use like a recursive recursion call or we can use a q right uh so for me i'm going to use a q here since q is a little bit faster than the then the recursion cost you know so m is the length of the great and the n is the length of the grid grade zero okay sorry this length here and then of course the four directions okay and uh this one yeah i don't know i don't care which direction is this but all i know is that i need to define all four of them okay zero one okay and then uh you know for this like dfs search we need to keep track of the visited set a visited island here right but in this case we can just utilize the original grid here so every time when we happen when we saw we see a land here after visiting that's that a cell we can just set it back to the to zero which is water so that you know we can we won't visit the lens multiple times okay so basically if the i in range i'm here and for j in range and here okay if the grid inj is equal to zero it means it's a length right and then uh so here we're gonna add these things to the queue right inj and then i just set these things to one okay now this is my flag here okay it's closed captioning not just like available the regular bf uh bfs search or in this industry in this case it's like a queue okay current i current j uh in the queue dot pop okay and yeah like i said if the current i is in the zero or m minus one okay or the current j is in what zero or n minus one okay as long as the current island has any parts that is uh that's it's on the edge of the 2d grid here then we know okay this island cannot be a closed island so i just set this flag to frost but we still want to continue uh traversing this tall island because we want a traversing traverse everything to mark everything to be one okay we still want to finish that in directions okay so the new i because the i plus d0 okay and the new j equals j plus dp sorry dp you know maybe i have done too many dp problems you know every time when i define c sub d i'm assuming it's a dp okay that's funny okay then if the zero we just check the boundaries here okay new i and m and same thing for the new js here okay new j uh n okay and of course we need to we also need to check if the new ion new j is a land okay right don't forget this part then we add this q we add this new i and j to the q here and then after that same thing we're gonna set these things sorry this is a new i need a new j two to one okay or we can just use like uh define like uh a separate visited set every time we add it to the set but since we can use the same grid here we can save that and then in the end here we only increase the answers when the this flag is true okay right so in the end reach just return okay so i think that's through the work is closed wow oh sorry here oh okay yeah okay it should be inside this if here okay five that's weird pop okay hmm yeah this one shouldn't be that hard so but why i'm getting a different answer here append this inj okay that's right it's close equals to true while q is here we pop and we check this one we set it to false and then we do what directions here okay i and oh sorry yeah current i and carter j yeah this is the uh this is the issue here all right go submit wow you know some when you are like when you're talking while you're trying to write type you're talking and type typing at the same times anything can happen please all right cool so i mean this thing i mean it's pretty straightforward problem i mean the only different the only uh difference here is that you have to check you have to make sure if this island is closed or not so the way i'm doing it is like right by checking if any of the part of the island is on the edge of the 2d grades okay and yeah and space and time complexity so the time complexity of course is like m times n right because we have a four loop here right but you know even though we have a q here but doesn't really matter because each of the i each of the cell will only be in the queue one time so here you can think it's like an n here like a one here so i mean so in total the time comprises the m times n and space since we're not the space is also a oh uh it's also like m times n because you know we have a q here and the worst case scenario is that everything you know everything has a zero okay everything has a zero which means we're gonna insert all the other elements into this q here so the space complexity the worst case scenario is also m times n uh cool i think that's it for this problem thank you so much for watching the videos guys stay tuned see you guys soon yeah bye | Number of Closed Islands | deepest-leaves-sum | Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],\[1,0,0,0,0,1,1,0\],\[1,0,1,0,1,1,1,0\],\[1,0,0,0,0,1,0,1\],\[1,1,1,1,1,1,1,0\]\]
**Output:** 2
**Explanation:**
Islands in gray are closed because they are completely surrounded by water (group of 1s).
**Example 2:**
**Input:** grid = \[\[0,0,1,0,0\],\[0,1,0,1,0\],\[0,1,1,1,0\]\]
**Output:** 1
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1,1,1\],
\[1,0,0,0,0,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,1,0,1,0,1\],
\[1,0,1,1,1,0,1\],
\[1,0,0,0,0,0,1\],
\[1,1,1,1,1,1,1\]\]
**Output:** 2
**Constraints:**
* `1 <= grid.length, grid[0].length <= 100`
* `0 <= grid[i][j] <=1` | Traverse the tree to find the max depth. Traverse the tree again to compute the sum required. | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Medium | null |
1,061 | good morning everyone today is January 14th Saturday morning um I randomly looked up this problem because this is the problem for leave code has a daily problem challenge so this is today's problem um 10 legal problem 1061. this is today's problem challenge you see all the other problems I started in the ascending order except in this one because this is the daily problem little has a monthly challenge you have like until seven hours I think it's UTC time not Pacific Time day 14 I just finished this problem for the first month of this year this is the first problem that I've finished for the lead code daily problem challenge um I think this is a very good refresher and we can introduce a template for solving problems like this let's take a look at the problem first lexical graphically small is the equivalent string it's not a new problem it's a pretty old problem and you know right now we have like more than 2 000 problems this one is only one thousand uh its number is 1061. so let's take a look you're given two strings of the same length as one and S2 and a stream bass string we say S1 I and s2i are equivalent categories by nothing else as long as they are in the same position in the two different strings they are equivalent characters so this is this problem's definition okay not by any other definition for example if S1 is a b c as 2 is CDE then we have a is equivalent to C because they are in the same position in two different strings same as b and d and c and e because they are in the same positions in the two different strings and then equivalent characters follow the usual rules of any equivalence relation reflexivity a is equivalent to a itself symmetry if a is equivalent to B then B is equivalent to a easy to understand the third one is important is transitivity if a equals to b and b equals to b is equivalent to C that means C is equivalent to a is transitive Okay so for example given the equivalency information from S1 equals ABC as 2 equals CDE ACD and aab are equivalent strings of Base strain Eed okay so we're introducing a third parameter in the API that is base string so this is the string that we would like to come up with the lexicographically smallest string with okay written so the problem is asking us to return the lexical graphic response to string of the base string by using the re by using the equivalency information from S1 and S2 so it might be a difficult it might be a bit difficult to understand why we reached at this conclusion we reached a b is the lexicographically smallest let's take a look at one example it will help us understand suppose S1 is Parker as two as Mars base string is this let's forget about base string for a moment let's just figure out the equivalency relationship between S1 and S2 first based on the equivalency information what we have is M and P M P and M they're in the same positions so they are equivalent a and o they are equivalent R okay R and are the third a third position R and R okay via equivalent to itself right and then K and R so R and K they are equivalent so we have R and K they are equivalent so moving on we have e and I so e and i these two are equivalent and then we have the last one is S and R so R occurs again but we have encountered R here so we put s into the same batch the same hash set or three set or whatever it's a union all of these three characters they are equivalent because of transitivity right it transits it's transitive okay So based on the first example we can tell we basically need to find the lexicographically smallest character in the same batch because in one batch every single character they are equivalent so then we find the smallest and the lexical graphic mismanus character in this patch that is basically a representative so we'll use that one to represent the whole batch then we form a string that is lexical graphically smallest based on the base string so then we go through the space stream which is parser so P lexicographically smallest is M so we replace it by m a is still a it's a is lexical graphic smallest character in the alphabet and then r smallest is this batch okay so this one is already sorted like lexicographically so it's k is the representative so we replace r with K right so and then we encounter s is also in this batch so its representative is also K so we replace it with K here and then we encounter Eid e is in this batch itself is the representative of this batch so we keep e here and then we encounter r is in this patch which represents sensitive is K so we formed this lexical graphically smallest string which is m-a-k-e-k smallest string which is m-a-k-e-k smallest string which is m-a-k-e-k so walking through the first example we know exactly what we need to do right so we basically need to find we go through the two equivalent strings we hash out all of the strings as long as they are equivalent based on the three rules they are re flexitivity symmetry transitivity based on these three rules we hash them into different by hashing I don't mean hash map but it just means we sort out all of the equivalency relationships between each character in these two strings and then we can go through the space string one by one we find the representative which is the lexical graphically splawnist character and then we can just return um so I think um the most challenging or the most interesting uh the most media part of this problem is that how do we translate this transitivity rule into actual coding um the problem the first thing that came into my mind is Union find and the only uh related topic here is Union fine so we can introduce a template here to tackle Union fine basically it's similar to almost like a recursive or we can solve it in the iterative way so what I usually do is I introduce a class Union find then in this case um we since the problem is limited to consisting only of lowercase English letters so 26 right so the whole length of this IDs is going to be 26. so the reason we want to have an ID is basically so say let's have some comment here for easy illustration so uh a b c d blah all the way to Z so here and if we have an array we can easily map them to one two three last and one is 25 right so um if we can use an array as the index to find the representative which is lexical graphically smallest character to represent that batch we can easily go through this base string to use the representative to form the lexicographically smallest word smallest string right so that's the that's why we introduced this array of IDs and then we have a Constructor public Union find we want just to initialize this for solve for the interest of this problem is pretty straightforward we'll just initialize this IDs to be the length of 26 because it says only lowercase English letters and then we're going to initialize this array to be pointing to the value of each position is just the index itself so 26 and 90s I equals I so this is its Constructor then we want to have two more methods one is Union the other is fine okay so first we'll have a union method in this case we want to find the representative we basically want to connect two characters because they are equivalent we can put them into the same like group right into the same Union basically in this concept in this context um Char a and charm B so here we want to introduce another method which is basically to iteratively to find the smallest index that can represent this group so we'll use x introduce another one a and Y B and if x is smaller than y so this is the index of um of this character A or B that we can find inside this IDs array if this is the case IDs y will use x as the representative for y otherwise will use IDs X as the or use y as the representative of IDs X okay now we need one more method which is called find or just taking X which is the chart itself so as long as while x minus so here is a one more a little bit tricky thing but also something to remember as well which is um I know how to handle missing Java in other programming languages you can do similar things which is use the character minus this character a which is the base of all of the 26 characters then you get an integer if this one is not equals to this one itself what we will do is that we will keep doing so until we find it IDs x minus a in this case we'll just keep finding the character that has is that we have visited already but has a lower has a smaller character that can represent this batch itself and then we change this one to the IDS and x minus a plus a so we want to convert this one into a character as well so in the very end what we will retain is just the index which is x minus a that is the index that we would like to return so in this way we can keep finding the smallest character in the alphabetical order all right so this is the end this one basically is a template and you can um apply this template you can change modify adjust this template a little bit to fit whatever use case to solve problems that involve Union find algorithm so with this in place we can quickly implement this algorithm which is go through since S1 and S2 they are of equal length C1 S1 Char I uh two next one is so first we will have a union find uh class we will have an instance of this data and this class that we just defined you we can call it Union f e oops I'll just call it UF and then what we will do is we will Union these two c one and C2 and then after we Union all of them we have completely mutated this IDs right when we call Union we basically hash these two into the same equivalence set which is represented by this IDs array okay after we initialize so first step is we initialize this a new instance of this class which caused this Constructor which initialized this is this idea array which has all of the index as its value and after we call Union it's going to call find and construct all of the equivalency in relationship and then afterwards what we'll do is we'll just go through this base string to channel array what we can do we want to have a string Builder to help us facilitate this stream Builder so basically what we can do now is pretty straightforward what we'll do is and of course also we want to convert this because what we get back from calling this is an index so Union uh Union I so here we'll just call oh because my instance is called UF find C that's it this well this will help us find the index the lowest index of this unions of this group's index and then we convert that one into the character which is by doing a sum of a and then convert that into charm in this case we'll just return to string that's it now let's try to run this accept it let me see submit accepted um beats 76 percent um memory bits sixty percent uh anyways um so this is the uh a very uh interesting problem and very um core problem and it basically um so what I would do what I would share with you guys is to apply in this template this is one of my favorite templates you can construct a Class A customized class and you can have an array of IDs in this case for solving legal problems is usually 26 or 52 of a very small number and then you construct it initialize it with the value as with the index as its value and then we always based on the problem requirements in this case we try to find the smallest index as the group representative basically and then you call you iteratively call this ID until you find that this ID is really representing itself basically like a this index is representing itself in this case we exit uh we know we find the smallest group representative um all right I hope this is a pretty long video but I hope I've conveyed my points clearly enough and very worthwhile very immediate problem if you can deeply understand that problem a lot of other Union find Lincoln problems that it can solve um I strongly encourage you guys to really use your use a piece of paper uh like I did use a piece of paper and a pencil to hash out everything why we need to uh for the fine method and for example why do we need to have such a while method to find the lowest one is this like an elegant way could it be more efficient things like this to figure it out um yeah if you guys find this video helpful and please do me a favor subscribe first and then hit the like button that really means a lot to me and helps with the YouTube algorithm so um and I'll see you guys in the next one thank you so much | Lexicographically Smallest Equivalent String | number-of-valid-subarrays | You are given two strings of the same length `s1` and `s2` and a string `baseStr`.
We say `s1[i]` and `s2[i]` are equivalent characters.
* For example, if `s1 = "abc "` and `s2 = "cde "`, then we have `'a' == 'c'`, `'b' == 'd'`, and `'c' == 'e'`.
Equivalent characters follow the usual rules of any equivalence relation:
* **Reflexivity:** `'a' == 'a'`.
* **Symmetry:** `'a' == 'b'` implies `'b' == 'a'`.
* **Transitivity:** `'a' == 'b'` and `'b' == 'c'` implies `'a' == 'c'`.
For example, given the equivalency information from `s1 = "abc "` and `s2 = "cde "`, `"acd "` and `"aab "` are equivalent strings of `baseStr = "eed "`, and `"aab "` is the lexicographically smallest equivalent string of `baseStr`.
Return _the lexicographically smallest equivalent string of_ `baseStr` _by using the equivalency information from_ `s1` _and_ `s2`.
**Example 1:**
**Input:** s1 = "parker ", s2 = "morris ", baseStr = "parser "
**Output:** "makkek "
**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[m,p\], \[a,o\], \[k,r,s\], \[e,i\].
The characters in each group are equivalent and sorted in lexicographical order.
So the answer is "makkek ".
**Example 2:**
**Input:** s1 = "hello ", s2 = "world ", baseStr = "hold "
**Output:** "hdld "
**Explanation:** Based on the equivalency information in s1 and s2, we can group their characters as \[h,w\], \[d,e,o\], \[l,r\].
So only the second letter 'o' in baseStr is changed to 'd', the answer is "hdld ".
**Example 3:**
**Input:** s1 = "leetcode ", s2 = "programs ", baseStr = "sourcecode "
**Output:** "aauaaaaada "
**Explanation:** We group the equivalent characters in s1 and s2 as \[a,o,e,r,s,c\], \[l,p\], \[g,t\] and \[d,m\], thus all letters in baseStr except 'u' and 'd' are transformed to 'a', the answer is "aauaaaaada ".
**Constraints:**
* `1 <= s1.length, s2.length, baseStr <= 1000`
* `s1.length == s2.length`
* `s1`, `s2`, and `baseStr` consist of lowercase English letters. | Given a data structure that answers queries of the type to find the minimum in a range of an array (Range minimum query (RMQ) sparse table) in O(1) time. How can you solve this problem? For each starting index do a binary search with an RMQ to find the ending possible position. | Array,Stack,Monotonic Stack | Hard | 2233 |
527 | word abbreviation so we are given an array of nonempty strings and then we need to generate minimal possible abbreviations and we have some rules so we need to begin with the first character then the number of characters abbreviated followed by the last character and then if there's a conflict we need to abbreviate the word some more until uh we have one unique abbreviation for each word if that's not if we can't then we just want to return the original words then finally uh if the abbreviation doesn't make the word shorter then you want to keep it as the original so uh that's the question so for now I'll get the input then we can work through uh the rules to make them much more clearer so for now I'll just do this and then I'll do this so uh here I'll increment my Visual and then I'll also wrap them so for our inputs yeah so we have our inputs and also our output so we can start so the first rule was we need to begin with the first character and then the number of characters abbreviated which followed by the last character so in this case we have the word like so we begin with the first character is L then we need to follow it by the number of characters in this case the we want to remove I and K so the number of characters is two and then finally you want to add an e so that's the first one so that's the first rule and then the next rule is if we have any conflicts that is if we have more than one words share the same abbreviation a longer prefix is used instead of only the first character until making the map from the word abbreviation become unique so like here for example if you see the word interval and internal so we can just take them so here we have interval so for Interval if we use the first rule we will find its I then six cuz there are six words that we want to remove and then we'll want to have L and then we also have a internal so for internal it will be the same it will be I 6 l so in this case we have a conflict as two words share the same abbreviation so if that's the case then what we want to do is we want to lengthen like or we want to reduce the number of words to remove so that is we want to lengthen this I so you don't want it to only be I but you want to add n to it so if you were to add n now we only remain with five words so instead of having six here we'll have five and then we want to do the same for this one and then we notice that they still have the same conflict so since they have the same conflict we want to now add t to the first part so when we add T now we only remain with four of the characters so here we change to four and then uh the same is true for this when we add T we remain with four so here we change to four so the abbreviation they still are conflict then we want to come to a so when you come to e we want to add e there then here we also want to add E when we add e we only remain with three words that we will remove so here we do three and then here we do three there's still a conflict then we want to come to R so in this case if we add R we check how many words do we have so right now we have like two so if we add R here we remain with two and then here if we add R will also remain with two uh we still see that we have this same abbreviation so that means that there's a conflict then now we want to increment it so here when we increment V so we want to increment V and then also uh down here so when you increment V we notice only remain with one so we can just come and we put one here and then for this one when we increment it we get n and then here so at this point we see that uh we have different abbreviations for the letters so uh this is okay so we can come to the final uh final rule which is if the abbreviation doesn't make the word shorter then keep it as original so in this case uh if you check this one the length is 1 2 3 4 5 6 7 8 this one is 1 2 3 4 5 6 7 8 so it's the same as this so in this case we want the abbreviation not to be have the number but to be original CU it doesn't make it shorter it just makes the abbreviation the same letter of characters and then the same is true for this one so uh in this case we want the oblation to be that uh based on the rules so an interesting another interesting input will have been the one for the intention which will just go through it very quickly so we have intention and also we have uh intrution so we'll just come and put them here and then you can look at them too so for intention we have I and then we have seven characters so we'll have I 7 n and then for intrustion we'll have the same so we'll have I and then we'll have seven so uh at this point you see uh we have the same abbreviations for two letters two strings so it means that there's a conflict and since there's a conflict what we need to do is we need to increment the prefix or increment this left side so we want to add n so when we add n you notice we remain with now six so instead of having seven we have six then for intrustion the same so when we have n and then we have six so now this is okay then we want to continue so since we still have the same abbreviation so we want to uh increment the prefix so the first part so here we want to add a t and then we want to reduce the number of words that now we are going to remove so here we will you see uh if we add the 10 yeah so sorry I think I might have miscounted but if we add the we have 1 2 3 4 five so we have five so I'm just going to change it to five and then here we also want to do the same we want to add the T and then when we add the T now we remain with five items that we want to retain as part of the abbreviation so since the abbreviation is still same what you want to do is want to add the next letter so in this case we add E when you add e we remain with four words that we will remove and then here we want to do the same so we want to add R and then we'll remain with four so at this point our abbreviations are unique and since they're unique we can return them so others were like this one for good so this one for God we have taken according to the first rule we will have begin with the first character which is G then the number of characters that we want to remove which is one and then D and then doing that it breaks the last rule which is the abbreviation uh if it doesn't make it shorter then we stick with it so here it will have been God then uh going to me we can just come and do that so for me here we have me so if you are to do it we will have ADD M then we have e then we add a zero so as you see this breaks the third rule so it means we want to rain the original word then for internet we can just come and do that so it for internet the abbreviation is I and then six and then T so uh because as for now we don't have a conflict we'll just have it as that for internal learning interval we already spoked about them then when you come to intention uh we've just spoken about it and then uh we have the one for face so you can just also look at that so we'll use the first rule so using the first rule we'll have F and then we'll have two and then we'll have e and then finally we have intrustion which we'll have that so uh okay so I noticed we changed this place so interval came after internal so let me just change the space the places and then once I change the places now we can look together so you see uh for like we have L2 e and then for God we have the abbrevation God then internal is internal then me is me then internet is i60 then interval is interval then uh int intention is a for n then face is F2 e then finally we have this one and okay so let me just check the last one also I think it's intention or in so for interraction we have that now that we know uh the rules we want to create some variables that's going to help us uh do this question so the first one will be our abbreviation dictionary uh so this dictionary it will have the type of where we'll have a key so basically our key will be our abbreviation at that point and then for its values we'll want to have a list of the words that we being given so uh this is going to be our dictionary the first dictionary that you want to create which is just basically uh data structure that holds the abbreviation and also a list of words with that abbreviation then uh the next one that you want to do is we want to create also another final dictionary so for our final dictionary what we want it to have as our key will be the word that we are being given and it's abbreviation and then uh the another thing that we want to have is we want to have a Q so a q will help us like when we keep on like uh increasing the prefix so it will keep us it will help us to track this uh which word we need to continuously map so we'll have that and then once we have a queue then uh finally we can have our final variable which will just be result which will be a list that we want to return at the end of the day so uh with all our variables now we can start so the first thing we want to do is we'll want to Loop through our dictionary not through our list of words and uh in their case they call it dict so Loop through list of strings it's called dict then once we Loop so we'll start at the first one which is like then we want to get the abbreviation then once you get the abbreviation we want to add it to our obviation dictionary so we Loop through the list so when we are looping so our second point it's going to be inside the loop so we get abbreviation of current word and then once we get the abbreviation of current word we want to add it to our a brief dictionary so at this point our a brief dictionary should look something like we have L2 as our key and then we have like so this is for the first iteration then for the next iteration uh it should be God and then we have good and then for the third one it should be I6 L and then we'll have internal and then for the next iteration uh it will be me and then it will be me so uh I forgot to put the words inside a list so I'll quickly do that so here it will be this and this CU as you could clearly see here we said that our abbreviation the key will be the abbreviation and then uh the words will be in a list so for me I want to put it inside a list then I want to continue so for internet it will be I 60 and then it will also be inside list then we want to do interval so interval as since we already have I6 L we'll just have it here and then we want to do for intention so intention will be i7n and then I want we do for intention we want to do for our face so for face it will be F2 e and then our want to do for face we also want to do for intrustion which will be uh this one i7 n so we'll add it here so once we get the abbreviation for our B so at the point that our Loop ends this is how our abbreviation day should look like so once we have all these items in our dictionary now we the loop has ended so we want to add we want to check like are some of these items like uh since it's only one word with the abbreviation we just want to put it inside our final dictionary then when you come to good since it's also one we'll want to put it that so that's what you want to do so we're going to Loop through all the items inside our dictionary and then this item so like here we get the value we check if the length is one we add it to our final dictionary but if the length is not one then we want to add it to our queue so that we can continue like abbreviating it some more so that's what you want to do so for our step three as we have said we look through our dictionary so look through our a BRI dictionary and then when we are looping through what we've said we want to do is we want to check for the length so we looping through our division dictionary then we check uh if the length of the value uh is one uh if it is then we want to add it to our final dictionary and then uh if it's not one else what we want to do is we want to add it to our final dictionary no uh else if it's not one then we want to add it to our Q so we add it to Q so when we start the loop our final dictionary at this point will be so we want to come we start with the first one like has a length of one so since it has a length of one we want to have like and then the key L2 e as our first one and then we want to go to the second one which is God so we want to have God and then once we have God then uh we want to have God because the length of its value is one so long as the length of the value is one we want to add it to our final day then when you come to internal the length of this is two so since it's two we want to add it to our Q so at this point our Q uh we should have it should have uh something like I then we had 6 L then we have internal and then once we have that then so this is for the first time then now we get also the one for Interval so we also want to add that so we'll have I6 L and then we want to have our interval then we want to go to the next one so in this case our next one is me but as you can clearly see the length is one so we want to have me and then we have me then the next one is i60 but you see that the length is one so it means we want to have internet and then the abbreviation which is I 6 and T then you want to continue so for this one you see that the length is clearly two so since the length is clearly two we want to add them to our Q so at this point our Q should be i7n uh with tension and then i7n uh with inition so uh once we have uh all of this so this is our Q at this point and then this is our final dictionary at this point so uh we are done with uh this our third step so since we are done with this our third step so now what we want to do is we want to check we want to get the items from the queue then we want to so uh okay so at this point if we don't have an item uh in the queue it means that there's no conflict so since there's no conflict we can just go through our final dictionary and return those things inside there but in our case since we had the conflict we want to keep on like working until the conflict isn't there so probably uh we can create a variable at this point want to create a variable and then uh we can just call it like conflict so for our this conflict we want to instantiate it as true so once we instantiate it as true we want the following step steps to keep on repeating so long as that's true so uh the first step is we want it to do what we want to so we yeah so we want to when whenever we start we want to uh mark it as false so course during this step we hope to uh to kind of fix the conflict issues so we'll just mark it as false and then in case we don't fix it we'll return it to tr true so once we've marked it as false then we want to remove everything we want to clear our abbreviation dictionary so we want to clear everything and then uh once we remove everything from our abbreviation dictionary then uh we now want to start so long as our Q isn't empty so it means we want to L as long as we have items in our que so I'm just going to do that and then uh once we have everything in our queue so what we want to do is if we have an item in our que what we want to do is we want to get the abbreviation then once we get the abbreviation the new abbreviation then we want to add it to our dictionary and then once we add it to our dictionary we want to remove it from our yeah we want to remove it from our queue then we want to add it to our dictionary so that's all we going to do so uh here we going to start here we'll remove the first left item then once we remove it we going to get the next abbreviation so in this case our next abbreviation it will have been I and 5 L as we had previously this discuss on the rules so since this is our next abbreviation we want to now add this one inside our abbreviation dictionary and then so we're going to add it as the key and then the internal as its value so that's what you want to do so we look through then uh here we want to pop so pop uh off an item then once we pop off the item then the next thing want should do is we want to get the next abbreviation so we can just say next abbreviation for it then once we get the next abbreviation for it then sorry I've mistaken my numbering so we have eight then we have n then uh finally we have 10 so we get the next abbreviation then once we get the next abbreviation we want to add the abbreviation so add the next abbreviation we add our next abbreviation to our abbreviation so as key and then uh the value will be uh this word that we are at so uh we can uh go through all this step we can now check this step together so here we say we create a variable is conflict true then uh we mark it as false then we want to remove everything from our abbreviation dictionary then we want to loop as long as we have items in our que so here we have our Q so earlier on our Q had six this so this is we'll just get it quickly and then just paste it so when we pop off we will remove this part so uh this is this part here so this is what we have at this SP so you're going to get its next abbreviation we said that the next abbreviation was i n 5 l so this is our next abbreviation and then uh once we get our next subd deviation which is I in 5 L then what we want to do is we want to add it inside our abbreviation dictionary so at this point our abbreviation dictionary should have i n 5 L and then the value should be interval so uh this is what we'll have so it will do this for this one then once it's finish with this one uh it's going to so here we've already popped off this so sorry no we had already removed it so now we want to pop off this so here we have this then we also want to do the same we get the next subd deviation so the next sub will be I5 L then it will be I think the first one was internal so we'll just do internal and then now this one will be interval so once we do the one for Interval so this is what we'll have here and then uh we'll yeah so we want to so we finished and we've already added to our abbreviation so it's going to come and pop off the next item so this is going to be our next item so this is our next item then it's going to get the abbreviation so the abbreviation is basically I n6n then it's going to add it with the word to our abbreviation so it will be I n6n and then once it's that then uh the value is Our intention and then uh once it does that then uh it's done with this one so again it comes and pops off this one so we'll pop it off again then once we pop it off we get the next iation which is i6n then we want to add the same to our dictionary so here we'll have in so uh with this uh we will uh be done with the so yeah so once at this point now we don't have anything in our queue so we'll finish this so once we finish that then now we want to come to our Step 11 so for our Step 11 uh it will just be uh doing what we had in step three so we'll just have this part but it's okay we'll just come and we'll copy it cuz it's easier so our Step 11 will just be step three so I'll just do that so our 11 will be equals to step three so we look through our obviation dictionary in case any of them has a value of one we want to add it to our final dictionary if that's not the case then what we want to do is uh we want to add it to our queue so here this is not the case so our final dictionary will remain as it is then here for our Q now we have i n 5 L cuz like we are looking through this item so it's going to come to the first one get this part so here it will be I in5 L then here it's also going to be i n 5 L and then here it will be i n 6n which uh it's going to get from our dictionary here and then also this one is going to be i n 6n so it will do this until we'll have no items uh left we will'll have no items with a length of more than that and then at the end of the day uh what will happen is now we will come out of oh yeah so here when we are adding it to the que once we finish adding everything to the queue we want to add another step where we Mark our conflict as true CU we found uh some that share the same abbreviation so once we find that then we want to come out of it so uh that means that at this point now we'll come back to here on step four so once we come up to back to step four then uh what we can now currently do at this point our final dictionary uh will looks like it will be this some is going to come and copy it and then so once it's this way so uh it will have this other one so for internal we know it's internal so it will be internal and then uh for Interval it will be interval and then after interval we have another one so we have internal interval then we have intention and then we also have intrusion but for intention and intrusion we s earlier that the last point will be here where we had int four and then intrustion will be this so I'll just copy this and for in 10 yeah so we'll have something like this so this one is for sorry it's supposed to be the other way around so here we'll have intrusion and then a intention I wish is I in for n so we'll have this and then I yeah this one will be for Interval so uh with this we'll have this so this is our at this point this will be our dictionary and then now we want to uh look through uh the list of strings that you were given earlier so I'll just come and copy it so at this point we just want to do this so you look through this and then when you Loop through this uh now you just add them to our rest variable so you just do rest append so we do like the first one was like on the left side so here on the vs code the first one is like so that's what you want to do so you just come and do final day at like so we just do final D dictionary and then we do at like and then we see it's L2 e so it means here our s will have L2 e and then uh we want to go to the next one uh which is God so for this one is going to be God then the next string is internal so for internal is internal so we do internal then uh we go to the next string which is me so for me the value is me so it will be me then H for internet the value is i60 so it will be i60 then uh we continue so here it will be 60 then after that we have interval so it will be interval then after that uh we have intention so for intention our value was in for n so we'll have this and then uh we had the next one is face and then intrution so for face uh the value for face is okay so we didn't add it but our face was F2 e so it was face and then the value was F2 e so here we'll just have f to e and then our finally we have in for n so uh this is what we want to return as our answer so uh with this we will get the function and then we will uh write the code so I'll just come back here and copy the function declaration and then uh once I copy it I'll make now this one bigger and then I'll save this and then I'll split it to the right and then once I split it now I'll just come here and do that so uh probably the only thing that we want to do is from collections we are going to import a deck so that you can have our queue so I'll just come and do that and then I once you do that we can quickly uh look through everything so as we said uh the first thing we want to do is want to Loop through the list of strings so you can just do for our I indict so uh with this we want to dot so uh forward index so yeah that's what you had oh sorry I forgot so the Step Zero first was having the variables defined so even before that we want to define the variables so we I'll just come and copy them CU I don't want to type them again so I'll just come and do that so here we have abbreviation then we have our final and then we have our q and then we have our rest so this is what you want to have so here we don't want to have this so we'll have remove it for now so here we just want to this one was just supposed to like give us the structure of whatever we are having so we going to have this so we want to start with for our word in dictionary and then so we're looking through the list of strings uh strings which was called dict and then we want to get the abbreviation of the current word so uh we want to Define that function so here we can just come and do yeah can just do abbreviation R is equals to get abbreviation so uh we can Define it as a method of the class so we can just come and do s and then uh here we can just copy it for E so uh we can Define it so it will be def this and then here uh we want to return something so this one was the first part so this one was on rule one where you take the first letter as the prefix then the last letter as the suffix then the two items that you want to remove as the number of items to remove so that's what you want to do so you want to do prefix so we said our prefix should be a word at index zero so it means that we will need to pass in a word here and then uh once we do that then we want to do num remove so these are the number of characters that you will remove uh so basically here it's two we can get this two by also getting the length of the string and then subtracting two from it so it will be length of oneus 2 and then for our suffix it's going to be the last letter on our word so we can just do that word and then we do negative one so this is basically our suffix then here we want to do prefix and then we want to do uh num so we have two ways of doing this the eest ways we can just de to have a prefix number remove so instead of having this as a string we can just do it as a tle to make the work easier so uh that's what we going to do for now so here we can have the remove and then uh finally we can have the suffix so that's going to be our abbreviated one so here we have this so since it's a member of the class it will be self do that and then you don't want to pass in self you want to pass in the word that's coming here when you're are looping so uh we've done the first part uh which is to get the verion of our current word then we've added it to our abbreviation so once this Lo Loops completes we expect it to be this way and then uh that's the first part so uh no we haven't added it sorry so I'm just going to add it quickly so uh to add it we'll just do this and then uh we wanted to add the abbreviation as the key so we can just do this and then our python allows us to kind of check uh inside a dictionary if you have it then uh it's just going to add but if it doesn't you can specify something as default so for in our case we wanted to specify the empty list uh which is in accordance to the value that we provided here in line 15 so uh with that we want to also add uh the word so that uh we can have this so this is this and then at this point uh if we were to run this function up to this point so our abbreviation dictionary on the left here will look like this so here with that we are done with number one and two so you want to come to step three so let step three is just looking through the abbreviation D and then we want to check if the length of the value uh is one if it is we want to add it to the final dictionary so here we check uh here in the dictionary that we had above like what's the length of the value so here the length of this one is one so you add it to our final dictionary so that's what you want to do so we'll just look through so we'll just do four uh we have the key and then the value so we can just do 4 KV in abvd uh do items and then uh once we do that so we check if the length of V so you can just do if Len of V is equals to one so uh in this case uh it is so we want to add so we just come and do final day add the current cuz we want the abbreviation no we want the word first so we'll get V at zero so you see here our like is in the v and then the index is at index zero so that's how you do v0 and then we are going to use the same structure for python where we if we don't have it then uh no actually we don't need to do this structure because for the final one it should always be like one item so since it's one item we will just do the key like that and then we are done with that and then so we've done this part here so that's step four and then now we want to do step five which is add it to the que so if it's not so you're going to do an else then want to do Q do append and then uh we want to look at the structure so uh in our case we appended the abbreviated word and then the word that we have so but you remember where we had like the values that's inter internal we came we did for I6 L internal then we did this so it means we want to look we get the first word then we add it to the que then we look again we get the next so and add it to the Q so that's what you want to do so we going to do for in v and then we want to come and do that so we just want to do Q do append and then we want to append our key and our Val so uh with this uh we are done with step three up to five so once we are done with that now we can continue so we can just come in now go to step four which is creating a variable is conflict so I just come and do that so for our conflict we want to start it as false and then we'll just look so long as no sorry uh we said that we always want to instantiate it with true so sorry about that so here we want to do true and then we want to Loop so long as uh there's a conflict so you can just come and do wi listen conflict then uh always cuz if this step if we run through this Loop we expect to resolve the conflict so here we want to mark it at false but in case we don't resolve it we'll mark the conflict as true as you will see so once we do that then now we want to remove everything from our abbrv so there are so many ways of doing it in Python for now we can just do this and then once we do this then now we want to start so we going to look as long as we have items in the que so you can just do while qu and then uh once we do that you're going to PO off an item so we can just call the item that we pop off we just call it pop L IAL to our Q pop left yeah so once we pop off the item then we want to get the next abbreviation so we can just call here next abbreviation and then uh we've said we're going to define the function so it's going to be get next abbreviation yeah so once we do this then uh okay so let's just go and Define this function and then we can come back so for this function uh it will just be almost like the first one uh the only difference is uh we'll also want to pass in the abbreviated so we want to have this abbreviations and then also we want to pass in the word so this will be the only difference so for now I'll copy this and then uh as I'm doing this I've remembered that we also like when you're getting the abbreviation we don't want to get the abbreviation for letters such as God since God is like three and the abbreviation will have been G and D which is three so we don't want to do that or for me because the abbreviation will be M3 e so we just want to do if the length of the word so you can just come and do if length of word uh is less than four so like if it's three like God we just want to return the word so here we can just do return word and then uh if that's not the case then continue so for this one for getting the next abbreviation we want to have the same thing but here what we want to do is we want to check so if at any point our abbreviation is equals to the word that we want to abbreviate or if at any point like here where you are doing i6 I five like that so if it at any point that number reaches two so this number that you are removing if at any point it reaches two CU if we do 2 minus zero we want to stop and return just the word so we can just do a at V at index one isal to 2 then we want to return our word and then if that's not the case then we want to do that so for our prefix right now what we can do is we can have the prefix that's coming inside our abbreviation so we can just come and do abbreviation that we are coming at uh the first index which is at index zero and then if we do that plus the length of its length this should give us the new so I'm just going to do this with you guys so that you can also be able to see so here we had I6 l so when we did I I6 L we abbreviated it so right now the abbreviation is I6 l so as we've said uh we first check so our abbreviation is a6l it's not equals to internal so since it's not equals to then it will go to the next condition uh is the this one is six is this 6 equals to 2 no it's not equals to 2 so it means line 67 won't run so we'll find the prefix is just what's coming in our abbreviation so in this case our abbreviation at index Z which is I so whatever's coming there is I so it's going to get to the I then we want to add so what's the what's its length so in this case the length is one so get that and also get the word at index one so in this case the word at index one uh for Interval for internal the it's n so it's going to get that so now our new prefix will be i n so that's what we are just doing here and then here the number removed so here we were doing the length one minus 2 right now what you can do is since you know that number six is coming in as the next item we can just get it and then we subtract one sorry so I just come here and get it so it will be a RV at index one and then what we want to do is we want to subtract one CU we've added like when we did when we add n so it means we will only be removing the next five items so that's why we subtract one and then uh the suffix will still be our last letter so uh this will be how we will be getting the next abbreviation so true to that we want to pass that so we've said that when we pop the queue we said that when you're adding items to the queue we can come and check here we had the abbreviation and we also add the word so right now the first item is the abbreviation so we can just come and do pop l at index zero which is the first item then our next item is at index one so uh this is going to be uh give us the next abbreviation so once we get the next abbreviation we want to add the next abbreviation to abbreviation d as the key then the value will be the word so this is what you want to do so you want to come and you want to do abbreviation D sorry yeah at next abev yeah so it's going to be self do abbreviation d uh yeah sorry I was supposed to use get no it's okay sorry I shouldn't be using self yeah so we going to do this uh do get so you're going to get a next abbreviation so if you can find it then that's okay but if you can't find it we want to do this and then we want to add our word which is just basically pop L at one so here we are telling it uh to check inside our dictionary so if we have the next abbreviation which is I n 5 L if that's exist then you just add whatever we have to the value list but if it doesn't then add it to our abbreviation dictionary so uh that's that then uh once it add yes I that's all so here we have this then we have this so here we are done with step seven so it's say pooping an item getting the next obervation adding it the next as K and then value will be the word and then at this point once the loop ends the Q will be empty and then this is what we'll have in our abbreviation so now we are done with our C so we can come out so here we want to repeat step three which was uh basically looking through the abbreviation dictionary so here is the step three so I'm just going to come and copy it and then uh once I copy it I'm just going to indent this and also this and this so uh we've done that then yeah so here we look through abbreviation dictionary then we check if the length of the value is one if it is we add it to the final dictionary uh if it's not then we want to add it to our queue and then the moment we've added it to our que we want to mark that there's a conflict you remember how we said that we hope to resolve the conflict in that call but when it reaches this point uh it means that there's a conflict cuz here we've added it to our que and then since there's a conflict we want to and abbreviate it again so this will happen so we've done that so at this point once we come out of this our Loop so we'll be here at this point what happens is now our final dictionary will look like this and then now we just want to Loop through our list of strings and then once we look through that we want to add them to our rest and then finally you want to return ours so I'm just going to do that so we're going to do for uh so I can just call it item but let me just call it forward in our dict above so we just want to do uh okay so we want to add the abbreviation so we can just come and do abbreviation so uh okay so one thing here we were using the strings because uh we could see them visually but at this point as you guys youve noticed we are using two PS so since we using two PS We want to make sure that we don't have them when you want to add the abbreviation we want to convert them to Strings so to do that we want to look through uh the two PS so we just want to do for I in uh our final dictionary and then the word so here for example our final dictionary we get the word our word is like so we come and we look at like so when you look at like we will see L2 e so the thing is this L is a string the two is a number the e is a string so since that's the case we want to convert everything to a string so I'll just do string at a and then once we do that then we want to use join so we just do join and then uh once we do this yes so we do this so uh this one will give us our abbreviation and we can add it to our rest and then uh once we done that then at the end of the day we just want to return rest and then our we want to test to see uh if it works so we just do s equal to solution and then uh once you do that you want to do print and then you want to do sorry s dot word abbreviation and then we want to get the input which we have basically here and then uh once we have this we want to run and then hopefully if we don't have an error uh it should work so it's complaining that object has no attribute pop left so I just going to check here sorry I was supposed to use a deck I didn't change there sorry about that cuz we imported it I thought that I changed the same so I'm just going to let it run and then now as you can clearly see we have uh our answers which is L2 e then we have good then we have internal me then you have a60 then you have intern then this one then F2 e then inition so uh with that uh I'm just going to uh yeah to cut everything and Trend copying on the other side and see uh if it passes so I'll just remove this and then I'll just copy and then we can run the test and then try and submit so uh so far it's accepted so since uh it's accepted we're just going to try and submit and see yay yeah fast so thank you guys for listening yeah bye | Word Abbreviation | word-abbreviation | Given an array of **distinct** strings `words`, return _the minimal possible **abbreviations** for every word_.
The following are the rules for a string abbreviation:
1. The **initial** abbreviation for each word is: the first character, then the number of characters in between, followed by the last character.
2. If more than one word shares the **same** abbreviation, then perform the following operation:
* **Increase** the prefix (characters in the first part) of each of their abbreviations by `1`.
* For example, say you start with the words `[ "abcdef ", "abndef "]` both initially abbreviated as `"a4f "`. Then, a sequence of operations would be `[ "a4f ", "a4f "]` -> `[ "ab3f ", "ab3f "]` -> `[ "abc2f ", "abn2f "]`.
* This operation is repeated until every abbreviation is **unique**.
3. At the end, if an abbreviation did not make a word shorter, then keep it as the original word.
**Example 1:**
**Input:** words = \["like","god","internal","me","internet","interval","intension","face","intrusion"\]
**Output:** \["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"\]
**Example 2:**
**Input:** words = \["aa","aaa"\]
**Output:** \["aa","aaa"\]
**Constraints:**
* `1 <= words.length <= 400`
* `2 <= words[i].length <= 400`
* `words[i]` consists of lowercase English letters.
* All the strings of `words` are **unique**. | null | Array,String,Greedy,Trie,Sorting | Hard | 408,411 |
1,092 | so welcome back guys today I'm here to solve a deep equation which was I was solving and I just solved by my own with the help of the previous rated question so I am want to explain my strategy what I have used to solve this question you will find many of the solution out there with the different YouTubers but I want to explain my strategy to you so if you want to you can watch this video so it will be simple solution first of all the question is that shortest comma subsequence first of all I will explain you what do you mean by this problem as in this question you have given two substring two string S1 and S2 you have to combine these two string and you have to combine in this way that the string between combined should have the shortest length so that both the string or the string uh subsequence of the bow string should be lie in that long string what do you understand it Let Me Show You by illustrations I was just recording this video but I was not able to record the volume of audio so I'm recording this again no problem at all first of all okay I have a string a b a c a string two wait a minute I have to see with the example c a b okay c a p so what do you mean if I'm combining both the string together as I will just add a concatenate this bootstring a b a c and c a b as I the answer is a b a c and c a b sorry for the or okay so you can see that I can find a b a c and c a b in this string but the question is not satisfied with the solution why because this string can be more strong more small as a quotient volt as you can introduce this string as a b a c and c a b has uh you can reduce by writing this as BAC and c a b you can write c a b a c this can be the answer to because you can find the string a b a c here and you can answer find a c a b here so what you are saying that I have to reduce this whole big string to a small string okay so how you can do this as a b a c and c a b the big this uh you if you're solving the longest common subsequent then only you are able then only you can solve this question if you don't know how to solve the longest common subsequence so it will be a bit difficult but you can easily solve this question okay so what is the intuition for this question if you think normally what I can do if I have to make the string small I will just delete the common elements common characters from both string or a single string and then combined means I will just remove the longest common subsequence is the longest common subsequence means common elements in both the strings so what will be the longest common subsequence I can find this it's a b now I will remove from one of the string I just removed I will just add c a b a c so you can just find it easily okay if I just take my name Yaman and j i n j if I just to combine this boost ring how will I will combine as I will just find common sequence A and A N I will just remove y a m j a i n as I can find y a m a n m n j i n so this will be my answer but you have cleared what you have to think you have to just find this common sequence common logins from a subsequence then you have to delete from one of the air one of the string okay now if you are doing this as uh you have a array strings as well as what uh three uh what I am saying a c b a and S2 as three as a b c a if you are finding only if you're finding only this common sequence and deleting as uh if you delete a c a okay so a c a b so this is the subsequence longest a c a if you delete B if I'm deleting from this and I'm adding this a b c a c b a b so this is the string I would be getting but this will not the right answer so what I am doing I'm getting this string by using my intuition before I was trying to a simple technique but by this technique you can just move ahead and think like that first of all find the longest common subsequence okay as you have used a memo or tabulation method okay as you're using the tabulation method or you have done this question with the helper tabulation method so what you are getting as I'm just keep taking a string as okay this string only I'm taking the small string for the small demonstration then we will just move forward to move forward towards the code as a b c a okay ABC and cab so this is our string and we will just one two three and this is straight end of 0 1 2 3 4. okay so first of all when we are initializing we have to initialize this table as first of all c a b and he sorry can we use a different color a b c a okay so first time initializes now my code will work like that if for Loop enter I equals to 1 and I is smaller than M and M is equals to size of S Plus 1. size of s plus 1 and I plus for Loop hint J One j n and n is size of H2 plus 1 and is size of S2 Plus 1. it's not the size I have just increased because hence I have to make this array or the DP if from for the index as you know I have to just increase the size of this is it's from zero indexing I have to use the three also if I will just initialize the DP with the size of this so what will be the size of this uh string it's three if I will initialize so my index is my leg like B is 1 2 so I will able to use only two but I have to use three so I need to slice with the plus one yeah I hope it's clear as you are doing the DP just now this small these are the basic things which when we are declaring the memo or memos uh tabulation method or the memorization so now what I have to do I will just check my indexes I am starting from 0 1 now check if as one I minus 1 is equal equals to S2 J minus 1. means I will just check that the index is I minus 1 I is 1 I am here but I can't map this both because it's a string and string has the induction from 0 1 2 3 okay so I will just minus 1 and I will move backward okay I have this is minus one I will I am on C and I am on a are these equal no obviously so I will just move to the else condition what's the L condition what the hell condition is DP of I and J is equals to Max of DP of I minus 1 or J and DP of i j minus 1 okay so what is the DP of I minus 1 DBI minus 1 here and this both maximum it's zero now I move ahead are the same C and B I can take the refrigerant are the same no these are not same so we will take 0. and maximum is the maximum is 0 okay uh now I will move ahead cnz yes they are equal so what I will do I will just DP of I will store the answer right here inj plus 1 I think this is not visible to you and I will just move both of my I will just store here and I will just minus because I will just store I will just add the longest uh the previous answer and add one so the previous answer is 0 so I will add 1 here 0 plus 1 now I will just fill up the whole thing as the array maximum is one I will just fill it okay now this match yes this magnesium maximum one yes match Max the two so this two we have added B no match but maximum B match yes to Max 2 be known so the answer is this okay now our the whole table is here now what we have to do at what do you mean by this as I am just making this clean as this will mean dirty okay so what do you understand by this string this table as when you're standing on B ends a means this is a full string which I'm talking about and which these are the strings which are given so we are just finding that what's the longest subsequence in this as his answers to X is correct we have already found that a b c and a b a c a n c a b the longest is a b and this is the string length is 2 okay now good very good I hope this much you have understand this I am not to explain you anything which you don't know already because this only the simple's longest comma subsequence Now the main tax begin here we are standing over here now I am just using the color pen now we are standing over here okay now I will check if this both match if they both match so I will just push the string okay means I mean I am using integers where I equals to m plus 1 means here means m is already defined so I'm just initializing there now n okay this match is clear as I am standing over here this index why I will just use the while loop and I will just reduce see that if it should not equals to 0 and J should not equals to zero I am sending I will show you why I am doing this is my base condition now if I will see that if string ones I minus 1 is equal equals to S2 J minus 1 means this is equals to this so what I will do and else this is not equal else what I will do okay now what do you mean by when you're standing here and what are these are the same answer which we have used here you can see this code here you can see that these are the same word that this is greater which one is greater are being stored the answer yes 2 is greater in the both maximum number is 2 H2 is stored here now as the condition is like that if you are not this as characters are not matching so you will move to one of any one of the column okay either you will move here either you move here let us see let us assume that we are moving towards minus I or this is I and this is J so we are using minus I okay so our else condition is if DP I minus and J is greater DP I J minus 1 so we will move this side as this is the this is greater I minus 1 is greater so move we will move this side okay we are moving this side so we will minus I now what you have to do okay what you have to do you have to just store you have to use you have to print the longest string so I will just take a very well string A and S I'll just take a string A and S now I will just push answer string push back to S1 as I is rated to S1 minus 1 I as it is already reduced so I will just move here now what we will I will just explain you one minute I will just choose just complete the code because it's been a long video I was not expecting that I would take this much time to explain it so now what you can see that if I am standing here means these are not common in my string so I will just add one as I am just leaving this so I will add a here in this answer string okay here and I have just moved here okay now I can see that this is also and this also not matching so I will move to the maximum one and I'm reviewing this one so I will just add here C okay now see I've added now I will see that these are matching I will just move add one string I have just added one string I will move here and I will just move backward here because I am just moving minus 1 and minus 1 in the both because I've just added this as you can see that I have just come from minus 1 i n minus j i okay now where I am I have just added B now again I will check which is the smallest one I will just move here and I will just add here a now I've just write here a now I have just moved riffs to the base condition till now my string is a b a c a b c a but you can see that the string is not completely printed because I am just not emptied J but my index is here at I means I am just trying to say that as I was moving with this Loop my condition this is true or false so this is not completed this is true means I have to just to move through for the next string means that my string is not completed mtds for the second one so I will just so right and while loop here for that J is smaller or greater than 0 so I will write pushback push back has to J minus as I have interested int reduce also and uh for same for I okay so this is the final code I will show you on the vs code okay so you can see that is this is my simple uh subsequence code from here you can see that I've just tried to use the base condition while loop then what I've done I've just pushed the answer when these both are equal then I'm just printed watch debugging now I just was checking that is which one is smaller so I will just push then push again then I will just tell you I have just to use the while loop for the rest over string then I have just revert the string because I will just try them we are traversing from back as this is from the reverse order BAC okay you can understand that okay so this code I will submit it so this is successfully accepted so thank you guys this is was my first video of any explaining and question I know uh I have some difficulty to explain you but I hope I will just improve myself and give you the nice content thank you please like the video and subscribe the channel | 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 |
112 | October lead code challenge the problem that we have in today is path sum this is a fairly easy problem on lead code and I believe the subscribers of coding decoded will be able to solve this question by themselves however if you are new then this video is for you the question says you're given a binary tree and an integer value what do you need to identify whether there exist a path starting from the root to the leaf such that all these nodes that lie in that path sum together to give you the target sum value if that path exists you need to return true if that path doesn't exist you need to return false without further Ado let's quickly walk through the presentation and I'll be explaining the algorithm behind it why the BBD that I usually here you are given a binary tree I have taken the same example and you are given a total value which is 22 in this case what will I do I'll perform the DFS reversal and I'll use recursion for this and I'll keep track of the target sum that I'm looking for as that travs to the child nodes and I'll reduce the target node value by the node value that we have for example here the value is five so the target node that we are looking for gets reduced by five and I make the invocation on the rest of the two sub trees that I have what I'm trying to say let's understand it by the iteration the target value given to you in the question is 22 and the current root value is five so you subtract 5 by 22 what do you get 17 so 17 gets percolated onto the left subtree and the target for this sub tree becomes 17 and the target for the right subtree also become 17 so let's start the iteration and we will exactly do the same steps as I have just talked here 17 minus 4 what does it lead to it leavs leads to 13 so the target for the left sub tree which is this sub tree becomes 13 and since the right sub tree of four is null uh we will not do any invocation over here let's proceed stay ahead and uh the target for this sub tree was 13 the current value is 11 11us 13 what does it give you two so the target for this sub tree becomes two and the target for this sub tree also becomes two is the Target that we are looking for seven is a current node value and what do you see here this is a leaf node uh you subtract uh 2 by 7 you get - 5 the target hasn't by 7 you get - 5 the target hasn't by 7 you get - 5 the target hasn't reduced to 0 as a result of which uh this is not a happy path we will return Falls from over here because this is a leaf node and we haven't found the path that we were looking for let's walk through the right path and let me just change the color of pen here you see the Target that you were looking for is two the current node value is also two these two are equal and this node happens to be the leaf node that means we have successfully identified a happy path we will be returning true from over here true gets returned from over here two gets returned from over here and the final answer that gets returned out turns out to be true so we will be performing or of the result returned from the right sub tree and the or of the result returned from the left sub tree so false minus false or true gives you true as a result of which the final answer that gets percolated to the top is true and this is what we are going to do in the coding section as well you can iterate over the right subt by yourself but to conclude it further let's look at the coding part I have written the code in a very simple manner I check if my root is null I return false otherwise I check if my target sum happens to be equal to my root do Val that means I have found a happy case along with this I should also check whether the current node happens to be the leaf node if that is the case as well I return true otherwise I trade it over the left sub tree and I reduce the Target by Target sub minus root. Val similarly I rate over the right sub Tre I reduce the Target by Target sub minus root. Val exactly same in both these uh iterations just root one in one case we are iterating over the left sub Tre in other case we are iterating for the right s let's try and submit this sub accepted uh with this we have successfully completed today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updates from coding decoded I'll see you tomorrow with another fresh question but till then goodbye | Path Sum | path-sum | Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000` | null | Tree,Depth-First Search,Breadth-First Search,Binary Tree | Easy | 113,124,129,437,666 |
475 | welcome to this new video where we will solve the heater's problem we have a horizontal line and it will have houses for example here the house is 1 3 4 6 8. and these houses have to be heated for that we have heaters at certain positions for example at positions 1 and 5 here and we are given the ability to modify their radius the more we increase the radius of a heater the more it covers houses and the problem says that we need to find the minimum radius that we give to the heaters to cover all the houses for example here they have a radius of zero only house one is covered we increase the radius now houses 1 4 and 6 are covered but 3 and 8 are not we increase the radius again houses 1 3 4 and 6 are covered we increase again now all the houses are covered so the minimum radius is three return three note that you can neither modify positions of heaters nor add new ones and the same radius is applied to all the heaters okay how do we solve this problem we can think of a brute-force solution we can think of a brute-force solution we can think of a brute-force solution that works as we did with the example now we start with a radius of zero and we keep increasing until all houses are covered for that we need two structures a set of uncovered houses and an array that contains the boundaries of the wrench covered by each heater in this example and covered initially contains one three four six eight but we move houses on positions where we have a heater because they are already covered even with a radius of 0 house 1 gets removed and our heaters are in positions 1 and 5 who initialize their range at 1 and 5 respectively because their radius is 0 they cover their position only now first iteration we increase the radius we modify the ranges by decrementing the left boundary and incrementing the right boundary here that one now covers front from 0 to 2 and healer 2 covers from 4 to 6. the new covered positions are 0 2 4 and 6 we'll remove houses that are in these positions the uncovered set isn't empty yet we continue we increment the radius the ranges become one is one to three and three to seven in newly covered positions we can find how three we remove it from uncovered we continue we increment the radius the ranges become minus two to four and two to 8. in newly covered positions we can find house 8 remove it uncovered set is empty now return radius is 3 we need a radius of at least 3 to cover all the houses in code uncovered houses is the difference between the set of houses and the set of heaters remember that we remove houses that are already in positions of heaters then we'll create the area of boundaries of heaters for each heater we put an array of two elements they represent the left and right boundaries at the beginning they are both equal to here the position of the heater now radius starts at zero then while there are still elements in and covered we increment the radius then for each heater we decrement the left boundary and we increment the right boundary we also remove from the set newly covered positions which are the new positions that we've been able to reach after the loop we return the radius for the time complexity we put n as the number of houses ammo the number of heaters and r as the final radius we have and for creating the set of houses and for creating the set of heaters and for calculating the set difference and to amp for creating the ranges array then for the loop at each iteration we're incrementing the radius so the number of iterations is equal to r the final value of radius at each iteration we're traversing the m heaters while doing one operations in total we get t of n m r is equal to two n plus three m plus r times m which gives an o of n plus r times m time complexity we can say that this algorithm is output sensitive its running time depends on the output r in our case and for the space complexity we have n for the set of houses and for the set of heaters and 2m for the ranges array we get m plus 3m which gives an of and plus m space complexity this solution is not the best one because we have cases where it's really slow cases where houses are far from heaters we will need to do a lot of iterations this is why we will see another solution but before please take some seconds to suggest problems that you want me to solve tell me in comments the idea of this second solution is that because all the heaters will have the same radius a house will necessarily start being heated by its closest heater because when we keep increasing the radius its closest heater is the first one that starts covering it what we can do with this information is that for each house we calculate the distance between it and its closest heater and after doing so we take the maximum amount the distances it represents the smallest radius to cover all the houses let's try it with our example house at position 1 its closest heater is the header of position 1. the distance is 0. house at position 3 its closest heater is at position 1. all the one at position five same distance is two how does position four its closest heater is at position five the distance is one house at position six the distance is one house at position eight the distance is three we got all the distances the maximum among them is 3 so 3 is the smallest possible radius to cover all the houses any smaller radius won't be enough to cover the house at position 8. in code we create an array distances then for each house we calculate the distance between it and its closest heater and we add it to the array distances for that we create the variable mendes initialized to infinity therefore each heater mean this becomes the minimum between itself and the distance between the actual house and the actual heater apps means absolute value after the loop we just return the maximum distance which represents the smallest possible radius we can even keep track of the maximum value which is the radius while traversing houses to avoid losing space on storing the distances for the top complexity the outer loop is doing any iterations the number of houses the envelope is doing m iterations the number of heaters and we're doing all one operations inside we get an off and times m time complexity and for the space complexity we get one because we're not using size related variables let's see if we can optimize this solution here we are performing a search on the array of heaters multiple times we're traversing all the heaters we're performing linear search which costs of m but by sorting the heaters we can search for the closest heater to a particular house by using binary search which costs offload m keep going towards that house at each iteration while keeping track of the minimum distance for example we have this sorted array of heaters and we want to find the closest heater to house 16. net is left plus right divided by 2. we'll get 4 the heater at position 9. the distance between 9 and 16 is 7 we got a new smaller distance and because here is of made it smaller than house we drop the whole left part and focus on the right part made this 5 plus 8 divided by 2 which is 6. here at position 13. the distance is 3 we found a new smaller distance here ourselves made it smaller than house we go to the right part made this 7 plus 8 divided by 2 which is 7 hit out of position 17. the distance is 1 we found a new smaller distance heaters of meters greater than house we go to the left part now left exceeded right we finished our switch we found that the smallest distance between the house and the heater is one we return one in code we put left and right extremities of the array at indexes zero and m minus one we initialize min this to infinity then while left is smaller than or equal to right we start by calculating mid index left plus right divided by two after it we check if we replace min dist becomes mean between its actual value and the distance between the house and the heated position mid after it we check if we go to the left or to the right part if heaters of mid is smaller than house we'll go to the right part left becomes mid plus pawn else we'll go to the left part right becomes mid minus one after the loop we return min dist note that i could directly use the python bisect function for binary search but i wanted to show you how to adapt it to this problem to apply binary search the array has to be sorted which is not necessarily the case it's not mentioned in the problem description that the heroes array is sorted so we start by zoning it then we traverse houses while keeping track of the greatest distance between a house and its closest heater return it after the loop it's true that sorting an array costs time but it will give us the ability to search in offload and time only by using binary search instead of ofm with linear search for the time complexity we have of analog m to solve the heaters then for the loop we're traversing n houses while applying binary search on the array of heaters which costs of log m in total we get of m log m plus n times o of log m which is of analog m plus of analog m which gives an of m plus m log m time complexity and for the space complexity it depends on the space complexity of the sorting function we still have a solution to talk about in reality what we can do with binary search is to find between what heaters our house fits between closest ones obviously for example with our last example houses position 16 fits between here at position 13 and here at position 17. and after finding this position we compare between the distance between heaters of iron house and the distance between heroes of i minus 1 and house the smallest value is the minimum distance one in our example and the trick is that to find the closest heaters to the next house we just keep incrementing i until here is of i becomes greater than or equal to the house let me show you an example we have these houses and these heaters we add two heaters on infinity and minus infinity to avoid going out of bounds the first house is three and the first heater is one smaller so we increment i now heroes of is4 greater we stop we found where house at position 3 belongs the distances between house and haters of i and heroes of i minus 1 are 1 and 2. the smallest one is 1 radius becomes 1. next house is at position 12 we increment i and we found the right position distances are 3 and 2 minimum is 2 it replaces radius next house is at position 20 we increment i and we found the right position distances are three and four minimum is three it replaces radius next house is at position 21 will already have the right position of i because the heaters of i is greater than 21. distances are 2 and 5 minimum is 2 is not greater than radius it doesn't replace next house is at position 22 same thing we don't increment i distances are 1 and 6 minimum is 1 it doesn't replace next one is at position 31 we increment i and heroes of i is now greater than house we stop distances are infinity and two minimum is two it doesn't replace radius we finish traversing houses the value of radius is three so we need a minimum radius of three to cover all the houses you can see that we're traversing houses and heaters in a sorted way but the input is not necessarily sorted so we need to sort both arrays before starting in code we sort houses we add infinity and minus infinity to heaters and we sort heaters now we initialize radius to 0 i2 1 to escape minus infinity then for each house we keep incrementing i1 heaters of ice smaller than house after doing so the distances are the distances between house and heroes of i-1 we take the minimum and heroes of i-1 we take the minimum and heroes of i-1 we take the minimum among them it represents the distance between house and its closest heater after it we see if we replace radius becomes mass between its actual value and min dist after the loop we just return the radius for the time complexity we have analog and the sword houses and analog m to sort heaters and for the loops even if we have nested loops the inner loop won't always do the same number of iterations we just know that in total the end loop will do at most and iterations because each heater is traversed once plus any iterations to traverse the houses we get an plus m for the loops in total we have analog n plus m log m plus n plus m it gives a time complexity of o of analog and plus m log m and for the space complexity it depends on the space complexion of the sorting function this solution and the previous one both have a good time complexity but the second one gave better results on lead code we reached the end of this video i hope that you understood all the solutions if you enjoyed like and subscribe to the channel and see you in the next one | Heaters | heaters | Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.
Every house can be warmed, as long as the house is within the heater's warm radius range.
Given the positions of `houses` and `heaters` on a horizontal line, return _the minimum radius standard of heaters so that those heaters could cover all houses._
**Notice** that all the `heaters` follow your radius standard, and the warm radius will the same.
**Example 1:**
**Input:** houses = \[1,2,3\], heaters = \[2\]
**Output:** 1
**Explanation:** The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
**Example 2:**
**Input:** houses = \[1,2,3,4\], heaters = \[1,4\]
**Output:** 1
**Explanation:** The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
**Example 3:**
**Input:** houses = \[1,5\], heaters = \[2\]
**Output:** 3
**Constraints:**
* `1 <= houses.length, heaters.length <= 3 * 104`
* `1 <= houses[i], heaters[i] <= 109` | null | Array,Two Pointers,Binary Search,Sorting | Medium | null |
410 | Hello hello everyone welcome back to my channel today were going to discuss in two problem split air a large sum suji problem value given here which consists of negative teachers and teachers day mam are you can play in 2m non anti quantity just save this The soldiers are given right and teacher and even need to split with her into films after balance hai nahi to izzat do sms2 viewers divided into two saver is dynasty purpose they want at this time the right nor algorithm to minimize the largest respect summer saver is what Is this coming at a price that Germany options available right what can i do cms to give west indies test ke so it time taking rest same2u so let us in possible if u like it play s here into saver is em so sorry bittu divided into To survey research what i can do i 10 sentences for saver and rest where for the second merit ki ukta and but i can do i contact 72 in one saver and five tanning second servants ko aur badha guddu 1972 and five in one saver liye beyhad savere Have More Icon Tips 725 80 In One Savere And Not Only In The Second Savere Hai A Tentative List Can Take All Elements In One Savere Hai Note This Is Not True Because They Have Written That How To Split Deeply *I Am Split Deeply *I Am Split Deeply *I Am Not Attempted Savere Sundhi Subodh Officer They Shouldn't The Possibility This Only And Possibilities Will Divide Daya Settings To Medium Is The Largest Among Themselves To Give One Most Likely In The Morning 770 Be Justin Bieber 500 Shares Twenty-20 Match Maximum Song Sukhi Largest 500 Shares Twenty-20 Match Maximum Song Sukhi Largest Likely In The Morning So Here For So divide f11 avengers elements and the morning so maximum clear 325 a little 1008 will not and share 12853 to here them maximum sunshine and misses maximum 2388 228 and affidavit but is to here 12915 08 2018 for here in directions maximum 15th According to Twitter The Amazing Sort and Share It Well 1954 Sure Joe Hair Oil 728 Yesterday Morning Two Siddha Maximum Largest Maximum Somewhere in the Water Into * in the Water Into * in the Water Into * Minimize This Minimize What is the Minimum Volume Close Vicious Right A Divided Like This is a Hybrid Divided Like This Is the largest sum is minimize which minimize is 828 's settings feature hotspot 's settings feature hotspot 's settings feature hotspot that ₹5 do problem what we do the multiple that ₹5 do problem what we do the multiple that ₹5 do problem what we do the multiple possibilities how they can divide saver year but the thing in undivided true me dance saaf is awaits thum of 98 saver a ko like you how Maximum All Maximum San Gap Mangal Savare This Unmangal Savare Should Be Minimum You all friends are like ok my mother must have come inside problem not just closed side of problems in life in ubuntu leg minimize maximize something and maximize minimum of something to hear what is The inheritance minimize the maximum benefit jasmine maximize light minimize maximize something like that to with this kind of problems of the and you can think of binary search ok so hello how can think of binary search now see how they can do that talibani soch Home Late Very Easy Problem Night Watch You Will Understand How This Problem Networking Site Twitter Easier For You That Not Release You My Best In The Reminder Thinking Diner Research Key To Apply For Your Research Vendors Posted On A Pointed And White Where Reported A Region To leave apply binary search only are very much needed notice for kids learn how will avoid this meaning subscribe weather times also apply - research only when times also apply - research only when times also apply - research only when excited but finally search can also be applied in balance notes2 on this side of problems and chords binary search mode on Answer Finally Search on Answer Right What is the meaning of Apne Partner Research on Cancer What is the Answer Is an Answer is It is Right What is That is It is the year Will not be applied by Researchers who are not born in this area will search on the Answer This Song 25 Minutes Will Be Applied On No A Sudden Demise Tak Inverter Zameen Not Getting Back Sushil Just Hold NCA Five-Year To Find The Samrat View To Five-Year To Find The Samrat View To Five-Year To Find The Samrat View To Find The Minimum Semi Urban God Twitter Minimum Santosh Vyas To Have Song Hu Is the volume minimum yagya-havan inch right in the research work only yagya-havan inch right in the research work only yagya-havan inch right in the research work only beawar inch to the same aravind minimum which is possible for sparing minimum san a for me savere e agree with them maximum song ko maximum san ki offer savere shruti minimum mari what we can only Had One Element Inner Were Not Have Attempted Suicide Volume Minimum Shift Savere So Let's Say Bigg Boss They Riched Her Only One Element 10 Element So Let's Check The Element See What You Think Vidhi Ideal Only One Element Tiffin Savere What Should Be A That Should Be Minimum Element like to have but you think it will give any benefit that foreign tourist only minimum dish minimum suede leather morning day it will give us benefit history to have single element survey will take to get maximum likes 0 that Bigg Boss day 10:00 Is the maximum that Bigg Boss day 10:00 Is the maximum that Bigg Boss day 10:00 Is the maximum anil bind saver and restaurant element with Govind second survey report hai to vansham overall enhanced saver will reduce effect 10 and ine different width maximum element which state in the same days they will increase monday 80s minimum re tu ki patel bhagya ok And what should be maximum society morning mid term of all its elements officer maximum committee taxes for all exams morning so what will be the summit se 10291 more main tujhse bhi choti hoon hai i hope or west nominative and doing so will discuss right with skin Tight Will Be Finding Out You Binary Search And The Answer Is My Research Binary Search On Answer And What Is The Answer Itself Will Be Hai Winner Inch Dada Value No That Understanding Time Informations Handicapped Certificate - Year Man Informations Handicapped Certificate - Year Man Informations Handicapped Certificate - Year Man Whose Log To Log Hua Tha Special 10 Highway Hai 132 To Is Note 4 How Brain Research Works Will Hear A Comment Just Watch Ka Binary Search Video For Your Will Be Able To Understand Why You Search And Footer In The Destruction Of The Video The 15-minute The 15-minute The 15-minute Tweet 1032 Mera Device Abhi Tu Tujhe Mein Fortitude Divided By Two Is Just 2 F 's Rate To Ek Hai 's Rate To Ek Hai 's Rate To Ek Hai Na Dhone 121 Will Take A Droid The Maximum San Ko Tight Can Come From Here For And Savere Okay This Value Which Made At Home Made Come Site Twitter Maximum Song That Can Come From The Ring to divided into to know the year the to check can you check person great can check data that during this time heart research you morning is possible to survey research apossible that this number in this regard there is a system of middle morning Is savere kutbi maximum 21 test maximum everything so f-18 savere and just test maximum everything so f-18 savere and just test maximum everything so f-18 savere and just a 102 savere possible in 10k chowk so let's check seven plus two will be notes15 that 14th stand with 45 going great and does but maximum which can only 10 will Not Take This Train Will Not Understand This Will Observe Every Day That Jab Viman Savere Share Maximum 2114 Savere Sudesh Viman Savere And Dressed With This 1018 Wishes Hai Tu Zara Too Savere Possible To Surgery Possible When Taken To Propose Back To Savere Aisa Possible This Time Officer West 216 A Message To 2021 DR Answer Sheet Also Answer So What Will You Make An Answer Pray And Will 20182 Ki Rihit Swift Mid Week Calculated Come And Meet's Month Wash Which Will Check Weather By Two Morning Possible Absolutely Maximum Clear That Morning 221 And Wherever Possible 203 Sweet Heart Mig-21 Good Dancer 203 Sweet Heart Mig-21 Good Dancer 203 Sweet Heart Mig-21 Good Dancer That 89 And Answer Ko D2h Bird Flu 1021 Also Why They Are Going To And Add This Number Vikas Neetu Minimize December 8 Minutes Minimize System That Space Duty Night But Right Nau Even Thinking And Answer Maa 21 hundred responsible in number which will assist 1021 put CR answer soft video singh arrange will reduce into this that Vinod Gurjar and will reduce rain today to how to reduce french insane hike is high value come to media thus 115 made - reduce french insane hike is high value come to media thus 115 made - reduce french insane hike is high value come to media thus 115 made - one who made this Dos 1522 ok to now high is bunty aur sunao le sakne calculate made the software meet will be 110 plus 2 and to which is 3215 ok no which is the nearest to dawn possible evening morning is maximum is not more than a hai and right sunao Flexible a ki swami ne jaisi year me knowledge check weather zara to morning is possible exams mitti hai to then hair seven plus to be nokia 515 video0 begum grade one teaspoon marriage survey report 80 will start from setting morning will start from 08 2018 anil ko greater Than Fifteen Deal Will Not Be Possible This One Morning And Finally Disturbing Thoughts On Wearing A I To Gai Sewerage To The Waste But The Are Getting Free Survey Research That This Cutting Three Morning Is The Meaning Of This Value Fifteen Is Loop Neetu Hai And Greater Sum Value So That They Can Make Too Savor This Note 3 That They Getting More Savor It Means Diet Which Value Fifteen Visit This Article To Increase It 16 Tweet Have Too Savor Mode Turn That You Ultimately To Increase Drishti Value What Me Too Will Need To Increase Your Value to give low to meet class ninth 120 b id 115 shifting plus 168 ki ukta hai tu aur yeh raw tweet bhi reduce i no veer increase look a poem in anger shri navaleshwar game calculate mid-week shri navaleshwar game calculate mid-week shri navaleshwar game calculate mid-week eviction plus 2 and divide 253 6 Divided into which will begin and hear will check weather were right to serve possible that they do save is possible if the maximum hypnotized saver something is equal to 8 maximum 52.72 notes15 52.72 notes15 52.72 notes15 that and greater on forty plus channel the native should take medicine saver 110 places in Thoughts Spiritual Purification Setting Show Day WhatsApp Images Taken To Be Quite Possible Setting Co DR Answer Sonth Will Update And MP 219 Sensitivity Of Clans Remind You Darkness Lower Value 19th Call Me To Find The Minimum Samrat Diner Minimum Sudharma Viewers Editing So That Tweet Chapter hybrid com ki patti - - - - 10 ok sona bougainvillea absolutely end mid ki sudeshwar bhi 1617 and 21 vich will be 3133 bittu hai and relating something rating points ke this person check weather in observance possible this maximum submit 16th ki flexid this metro chief E 127 plus to 9 0 in the morning early in the morning 110 plus ATM Vikram Greater Suji in the morning to end spirits away there was a nice golden knot too far as possible earth in the morning is possible meaning system value is less accuracy more improved week and have too in the morning is note 3 If in its basis low value need to increase the twin increment low web complete raw one British English 172 ok so in novel ball calculate rich yes you absolutely 272 plus 1782 which will give us 1751 check weather to serve s possible s maximum s most Awaited Bhi 7 That Flexed A Joe Here Once Away With One Main One Are Bhi Dushman 2018 Tanksi Twenty Match 2017 Sauda Tweet And Here S2 And You Will Then Be Meaning 2000 Value Of Review Been Created Nor Man Nor Will Wake Up Sid Plus 1718 Om Namah Shivaay No Vikram Greater Than He Right A Some People Call It Z10 Sponge Will Stop At The Best Of Advance Avinash Available On Like Minimum Some That We Can Get I So Divided Tuesday Just Samosa Different Skin Problem's Just Once Upon A Few Not Getting Any step chest boys pet kapoor dynasty hain to kisi object or doing a photo from being taken as latter function which has given to meaning what they are doing this if taken and are an alarm for alloy from 1000 k and volume maximum element in are So My Dear Maximum Element And Lord Was The Sum Of This Whole Loudest Morning Time Calculator Uniform Fennel But I'm Starting A Smile On Delhi Zinc World Tour 10 Classic Binary Search Lite Commercial And Mid Day Meal Value Of Finding That Left With No One Will Check Weather Sooner or later it's possible to serve it's possible so is a maximum committee member value to life than this function will return of the day phone number of this function will give me the number of all this Harris a possible that is maximum hands free This is a festival of maximum sum this time ok sweet will tell me how many numbers of paris of possible then example for a year when it was laxative 16-10-2016 beautiful preserve s possible not 16-10-2016 beautiful preserve s possible not 16-10-2016 beautiful preserve s possible not sweet will this is possible will give me 3S Is is the account that this is loosening old name meaning dart courier answers to medina answer and reduce half inch but artist greater like prevails coming with the greater the name of that debit means the end values will need to increase your will greater the name of that debit means the end values will need to increase your will witness to media Person who went to meet and also ill not army in this not approved answer find behaving an answer for this is possible function will tell me how most possible with the given them which met that Sushil painting account me ribbon tam to I'm going And Cheating Is The Amazing To Made Just Added That Element In Dasham But It's Coming Grated Ginger Singh Criminal Account Number Of Viruses And Tells Them Will Win Hum Safai Ki Hai To Houses Walking Dead Hydrate Once Upon The Sholay 725 Tenet Uske That Vyaav 725 08 I am already middle you that this 17th ok and after 10 minutes lubricated dark morning time taken it can count sdo and take some valuable time no and how to cure them so 7 the world in the times amazon check weather station this grade it 0.2 ki boat What We Will Do 180 You Might Be Confused Weather In Preventing Account Plus After But I Do Not Want To This What You Can Do You Can E Slide Account Scholar Will Be A Okay Know Love Morning Special See At Least One Survey Will Be At Least Once When Will be the one from whom you are earning i love you can do it i love you can have a near the three nine to 10 otherwise if you want to initiate free mode on the year unit-2 increment watch you will on the year unit-2 increment watch you will on the year unit-2 increment watch you will drive You Can Say You Understand Why They Need To Incremented White 100 To 272 Plus Two Baby Notes Is 9717 Suicide Note 2595 That Is Photo In Which All Soldiers In 1705 Na Resume Support Interest nov20 49 This Is Not Loose Seventeen Meaning For Detail Years Away Evil With And from here morning to starting from this greater than the value which 1772 thanks the festival increment account Vikas 10th wasted and what you have stopped twist French twist to the current element Vikas Yadav and from conservation starting from you on OK 08082080820 Vigyan greater than 600 gan From Near Account Will Increment And I Will Create Sign This To Take Off But That You Are Being Good Preservative But Here Account Dr To 1972 Incremented One Last Time After Coming We Improve Or Year Improvement In 512 Problem Share Also Submitted His Will Not Accepted and write the time, what will be the time, which is happening every time is possible and it's going and so it's time for active in that Android but here with hubrs by loop also visitors every time dividing are * also visitors every time dividing are * also visitors every time dividing are * Half Scientist Flirting Week Morning Going To The Doob Log In Physical Activity And Login On Ok A Specific Mouni Roy Ok No Problem Ko Middle School Please Subscribe My Channel Thank You | Split Array Largest Sum | split-array-largest-sum | Given an integer array `nums` and an integer `k`, split `nums` into `k` non-empty subarrays such that the largest sum of any subarray is **minimized**.
Return _the minimized largest sum of the split_.
A **subarray** is a contiguous part of the array.
**Example 1:**
**Input:** nums = \[7,2,5,10,8\], k = 2
**Output:** 18
**Explanation:** There are four ways to split nums into two subarrays.
The best way is to split it into \[7,2,5\] and \[10,8\], where the largest sum among the two subarrays is only 18.
**Example 2:**
**Input:** nums = \[1,2,3,4,5\], k = 2
**Output:** 9
**Explanation:** There are four ways to split nums into two subarrays.
The best way is to split it into \[1,2,3\] and \[4,5\], where the largest sum among the two subarrays is only 9.
**Constraints:**
* `1 <= nums.length <= 1000`
* `0 <= nums[i] <= 106`
* `1 <= k <= min(50, nums.length)` | null | Array,Binary Search,Dynamic Programming,Greedy | Hard | 1056,1192,2242,2330 |
258 | hey guys welcome back today let's solve the problem add digits so in this problem given an integer num our task is to repeatedly add all of its digits such that the result has only one digit so if you're given an example of two digits 38 what we can do is to take the two digits three and eight and add them together this will result in 11 and once we have 11 we can split the two digits again because our solution requires us to return a single digit number once it split the two digits we'll be having one and the sum of these two digits will be equal to 2 which is the result as you can see in this given example for this problem we have a constraint that we should not be using a loop or a recursion and I'll be showing you the most Optimum solution which will give you a time complexity of all of One how can we approach this problem the first thing that we need to notice that whenever num is 0 if we ever take zero add it to any other zero the solution will always be one so if the given num is equal to zero then our solution will pretty much be equal to zero which is a single digit number the second thing that we need to consider is the divisibility of 9 and by divisibility you will see that whenever we have any given digit that is divisible by 9 say 9 itself 18 27 108 or any other number the sum of all of its digits will always be equal to nine itself will be added to zero to equal 9 itself again if we consider 18 the digits are one and eight if we take the sum of the two digits we'll always have nine which is one plus eight 27 is the same case 2 plus 7 which will always be 9. 108 it's 8 plus 1 plus 0 which will be or this should be in it and the sum of this will be 1 plus 0 Plus 8 which is also equal to nine so what does this tell us so how can we use this to solve part of this given problem we can notice this pattern whenever we take any given value like 108 27 18 or 9 and do a modulation with 9 itself so if we take any given value that is divisible by name or that is a multiple of nine like 108 27 18 9 or any other value and we modulate it with a nine the result will always be a zero so if you have an encounter such a scenario then we clearly know that the sum of the digits as we've proven just above the sum of the left hand side digits will always be equal to nine so this is the second case now what about values that are not divisible by name how do we handle them in our code the case where we have values that are not divisible by nine so again I have three different values like 11 23 and 199. if we modulate with name the remainder will always be equal to the sum of the two digits or the three digits forming the given number so as you can see 11 modulus 9 will give us 2 which is also equal to the sum of the two digits one and one again if we take 23 in this case and modulate it with 9 the result will be 5. if we add the two digits the result is also equal to 5. in the case of 199 as you can see 1 plus 9 will equal to 19 and from 19 here we can take 1 and 9 add them together this will result into a 10. and then for this 10 we can take its individual digits which is 1 and 0 and the result will always be a one that is why we have a one in this spot so the rule in this case is that whatever remainder we have when we take a number and check its modulus with 9 will always be the sum of these digits of the number but it will always be less than nine as you can see any number that is less than 9 is always equal to 2 is always equal to a single digit so with these three cases we can be sure that we can compute any given value to its single digit without using any kind of recursion or Loops in an O of one time complexity let's jump on the code and you can see how we'll do this if you can remember the first condition that we need to check is whether this given number is equals to zero so if we check if the number is equals to zero then we will simply return 0 because that is the default solution the second case that we need to check is whether if we take the number and modulate it with 9 the result is zero in this case it must mean that the sum of the given number that we have is also equal to nine so this is assured otherwise if these two base cases are not executed we can simply return the remainder of taking the number and modulating it with name and we can be sure that one this result will always be less than or equal to name and the result represents the sum of the digits in this number simplified as per this given solution let's run the code and see if it works and as you can see it works and the code is pretty efficient if you enjoyed this session please like And subscribe and I will see you in the next one | Add Digits | add-digits | Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it.
**Example 1:**
**Input:** num = 38
**Output:** 2
**Explanation:** The process is
38 --> 3 + 8 --> 11
11 --> 1 + 1 --> 2
Since 2 has only one digit, return it.
**Example 2:**
**Input:** num = 0
**Output:** 0
**Constraints:**
* `0 <= num <= 231 - 1`
**Follow up:** Could you do it without any loop/recursion in `O(1)` runtime? | A naive implementation of the above process is trivial. Could you come up with other methods? What are all the possible results? How do they occur, periodically or randomly? You may find this Wikipedia article useful. | Math,Simulation,Number Theory | Easy | 202,1082,2076,2264 |
496 | hey what's up guys and they're quite here I do tecnico ting stuff on Twitch in YouTube check the description you get all my information discord is pretty cool if you want to join that and I do all these premium problems on patreon also help me up on github you are given to a raise I don't like hit me up so forget I said that but that was just bothering me sorry this is called next grader element one you're given to a raise and there's no duplicates so they're all unique values in the arrays num1 and num2 where nums one elements are a subset of nums two elements so for one and two are automatically going to be you know the numbers 1 elements are a subset of these elements right so you can see 4 1 & 2 are found in numbers 2 4 can see 4 1 & 2 are found in numbers 2 4 can see 4 1 & 2 are found in numbers 2 4 1 & 2 but you know not in the they don't 1 & 2 but you know not in the they don't 1 & 2 but you know not in the they don't have to be in the same indices it's just a subset of the elements so what we want to do is find the next greater numbers for num ones elements in the corresponding places of num two's elements and what is the next greater element that means the next greater number of a number X in nums 1 is the first greater number 2 it's right in nums 2 so basically what they're saying is if we look through this list we want to find 4 we want to find the next greater element in this list so there is none and it has to be to the right of 4 in this list and there's nothing greater than 4 so we have to put negative 1 if it does not exist negative 1 when we look at 1 in this list in num from nums 1 when we look at 1 and nums to there our next greater elements right and the next greatest one to the right is 3 so we put 3 4 2 we look in the next list there's nothing to the right of 2 so it's negative 1 again there's nothing okay let's go through one more example when we look at 2 in this list the next query is 1 is 3 when we look at 4 in this list there's nothing to the right so we put negative 1 hopefully you understand it now so what are the solutions how do we solve this intuitively I would say that I also say intuitively and not a lot so I should stop saying that so much but um just brute force wise you would think okay well let's loop through this well you're going have to loop through the arrays no matter what but let's loop through this and then let's do a nested loop through this and then just find the next greatest one to the right and then make like an output array that is a solution that's bird force though and it's pretty slow there's a better way to do this and you can use things you can use data structures so what we're gonna use to solve this problem is a stack in the hash map is going to keep track of it's gonna we're gonna loop through this nums to array and we're just gonna build a hash map up with you know the number each number and its next greatest element even if the number doesn't exist so like 3 doesn't exist in nums 1 but we're gonna find whatever that we're gonna say oh we'll put 3 and the next greatest number is 4 in the hash map so we're just going to loop through this array build a hash map and then at the end we'll loop through this array do lookups into the hash map in return we'll be like oh we look in the hash map what's 4 is next greatest element oh there's nothing so it's negative 1 there you go so that's it you're gonna build a hash map we're also gonna use a stack to help us but I'll explain that in a second so let's just start off by initializing our hash map it's gonna be in the integer the current integer and then another integer that represents the next greatest element so we could call this hash map next greatest equal new hash map okay great and then we're gonna have a stack like I said I'll talk about this in a second we'll just call it stack for now new stack and we're gonna be looping through nums to at first to build this hash map look I just said so we're gonna go integer for integer num in nums to we're gonna say okay stack dot push num so we're gonna be pushing these numbers on to a stack as we loop through and we're gonna do a check each time this is how we're putting them in the hash map and I'll explain it right after I write this if the stack is not empty this is the main part of the whole problem this is the only hard part if the stack is not empty and stack peak is less than num we're gonna put the value into the hash map next greatest dot put and we're gonna put stack dot pop so we're gonna pop off the stack and we're gonna put them so let's walk through what this means we're looping through this array and we want to build this hash map with the next greatest elements right we're gonna put the number onto the stack so when the stacks empty we're gonna put a number onto the stack right so we would put one onto the stack so right in this example right here let's just grab this so we can look at the example we're gonna have our stack equal to this right so our stack we're gonna put one on it at first right the stacks not empty so we're looping through the numbers we're looping through all these numbers so let's just put one onto the stack right now the stack isn't empty and we're gonna be looking at three and we're gonna say okay the stacks not empty anymore and is stack dot peak is one less than three yes one is less than three so we found the next greatest element if whatever's in the stack is less than the current number then we found the next greatest element so you could see we would do we would pop this element off so we take the one off and we would do map dot put and we would put that one in the next greatest element into the hashmap then the stack gets pushed on the three value and then we repeat the process where we say okay now we check is 3 less than num okay three is less than in we're on four so 3 is less than four so we say ok 3 is less than four so we found the next greatest to three so we say mapped up put three and then four and we keep doing this and then we put in we you know we popped three off of the stack and then four goes on to the stack etc so that's how it works and here's the only change you have to make this is pretty much like the solution because we build our hash map right so the hash map is going to be built after this point and what we want to do is we want to loop through now we want to loop through nomes one because the hash map is built and we just want to say we want to reconstruct nums one so we have to output this array with all the next greater values so we might as well just modify instead of making a new array let's just modify do right so we just say numbs one is equal to you know next greatest doc gets or default so if the number has a value for numbs one of I so if the current element so when we look at four we're gonna say okay it is four in the hashmap of an escalator element if it doesn't well it defaults to negative one and then after that you just return numbers one array because it'll be reconstructed to have all the next greater elements this is the solution but this isn't the full solution this isn't going to work because we have to make this a while loop so why do we have to make this a while loop because of decreasing elements let's say that the array looks something like this when we want to construct our hash map if it's one three four five or one you know sorry there's no duplicates so we can do eight seven six five and then ten look at this so let's say this is our array if we wanted to construct our hash map we need to make sure that we are not putting the this isn't gonna work we're just going to keep pushing things onto the stack if we make this a while loop this is gonna work because we're gonna be putting things onto the stack in this condition will never trigger because stack dot peak won't be less than num for example when we get to you know eight goes onto the stack and then is stack top peak less than seven no eight isn't less than seven so we keep we put seven on then we put six on then we put five on so it's just a stack with all these values but once we see a ten and we see that stack top peak is less than num now we just keep popping off those stacks and we put into the hash map every single value because you'll notice that all decree if it's a row of decreasing values followed by an increased value it will put the every single one of these indexes the next greater value put into the hash map is going to be 10 so 5s next greatest is town ten seven eight so we need a while loop to pop all of those off to the stat off of the stack and put that next greatest value so that's the whole problem pretty straightforward we could run it make sure it's all good let me know if you guys have any questions about this it's not too difficult to understand but I mean it's a little bit of a trick for an easy problem you know but I don't think it's too difficult so let me know if you guys have any questions I'll be glad to answer them and yeah definitely thank you guys for watching I'm gonna continue going I guess there's a next greatest element too as well and some other ones I do think they throw you off with these two arrays because in some of them I've seen it looks like there's a you know some extra I mean someone just wanna write some all right and that's what we kind of do we just ignore the first array honestly so alright see you guys in the next one | Next Greater Element I | next-greater-element-i | The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array.
You are given two **distinct 0-indexed** integer arrays `nums1` and `nums2`, where `nums1` is a subset of `nums2`.
For each `0 <= i < nums1.length`, find the index `j` such that `nums1[i] == nums2[j]` and determine the **next greater element** of `nums2[j]` in `nums2`. If there is no next greater element, then the answer for this query is `-1`.
Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **next greater element** as described above._
**Example 1:**
**Input:** nums1 = \[4,1,2\], nums2 = \[1,3,4,2\]
**Output:** \[-1,3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = \[1,3,4,2\]. The next greater element is 3.
- 2 is underlined in nums2 = \[1,3,4,2\]. There is no next greater element, so the answer is -1.
**Example 2:**
**Input:** nums1 = \[2,4\], nums2 = \[1,2,3,4\]
**Output:** \[3,-1\]
**Explanation:** The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = \[1,2,3,4\]. The next greater element is 3.
- 4 is underlined in nums2 = \[1,2,3,4\]. There is no next greater element, so the answer is -1.
**Constraints:**
* `1 <= nums1.length <= nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 104`
* All integers in `nums1` and `nums2` are **unique**.
* All the integers of `nums1` also appear in `nums2`.
**Follow up:** Could you find an `O(nums1.length + nums2.length)` solution? | null | Array,Hash Table,Stack,Monotonic Stack | Easy | 503,556,739,2227 |
227 | welcome to the channel this is vaga we are going to solve another reach good question and the question in question is going to be basic calculator and um you're basically given a string you're supposed to evaluate the value in this case 3 plus 2 times 2 is going to be 7 right so how we do this is pretty straightforward is um we would use a stack and um let's just get rid of this we would use a stack and a variable called num and in our first instance we would just push we would start and an operator right we could call it an operator or a sign right we could call it sign and the sign is going to be plus and what we're going to do in that case is if the sign is plus we're just going to add the number in this case we're going to use s as our string so on our stack we're going to add 11 and then after that if the value is negative we just add the number as a plus right you can add a negative so you could say 11 plus and put it in brackets minus 5. and then afterwards we add and what we want to add is uh the next number is going to be uh plus four and then when we get to a multiplication what we want to do is we want to pop it off the number of our stack so in this case we pop the number of our stack and this is going to be um the current number is 4. so we pop it off our stack like so and we multiply it by the number uh the next number uh the number that you're going to use to multiply in that case is going to be 11 times 3 is i'm guessing 12 and after that we add um 12 and after that when we get to division we divide the number we pop the number off and then we divide it and then we add it right so in this case we would remove 12 we do 12 divided by 6 is going to be 2 and then we add that so 2. so afterwards we evaluate this by getting the sum of the stack right this is going to be 6 plus 12 is 18 plus 2 is 20. so the answer is 20. so basically that's what we are supposed to do right so how we would solve this if we put this in code is we would come here and we would create what we want to all the things we want to do and the first one is going to be num after that we're going to have sine and we are going to have stack as our variables and num is going to be zero the sign is going to start off as a positive plus right we're going to start off positive so that we can add the first number right um in this case we want to add the 11 right in this case because the sum is going to be um sort of as 11 so in this case we're going to have 11 and the reason we're including the sign is that you can add the 11 right and afterwards we take we loop through our string and add each character right so that's what we're going to do so now that we can start off uh we can do a loop and we can say for i in our string and we are going to add to the string um a plus like so we put a plus at the end um so that when we are done with quite possibly with the characters we can add the current number of zero to the string right um so that when we are completely done with this the current number will be set to zero and we just want to add it to the stack right so we add a plus here so that it can have the sign can be the plus you will see it when we write out the code right so we could say if um i is digit and we check if i is a digit if it is a number we want to run our code to convert it into uh a number that we can add to it to our stack right and in case it's a number that is greater than nine right so for that we could just say num is going to be num multiplied by 10 plus i and we convert i into an integer right so we just say i and we put into like so right and then okay like so and then else if alif we want to check um alif uh i if it's any of the operators right so we come here and say lfi in um we put uh the various operators that we want to consider and the operators are going to be plus minus multiply and divide right and if it's that and we check if sine if the sine is going to be if we have a plus right if we have a plus and we're going to start off with a plus at the beginning remember so you can add our number and all we need to do is we just need to come to our stack and what we want to do is we want to append and what we want to append is the actual number right so in this case here what that would do it would lead to the first number being appended right if we start off with the same with this string i'm talking about in the strings example right so also our first number whichever way if we start off with a number we will start off if we have a number like we will skip over the space but if we have a number it is going to be added to our stack right and after that we want to check if we have a negative right so we could just come here and just copy this we need to type it all out right and we paste this and what we want is a negative and if it is negative what we want to do is we want to append the number stack dot append and if you can remember we just do negative number right because we do 11 plus minus 5 right so we do that and we come here and we paste and the next thing we want to do is we want to check if we are dealing with a multiplication right if the sign is a multiplication what we want to do is we want to append to our stack but first we want to pop off the last number right we want to say stack dot pop we remove the last number and then we multiply it by the num right by the current number right so in this case we would come here and um the previous number is four right we would remove this four multiply four times three and then append it to the stack right so we just do that and then we come here and we paste this and um after that what we want to do is um we want to do the division and the division is going to be pretty much the same it's just going to be tac and what we're going to append is going to be stack dot pop the last number and we want to multiply it by the number in question right and after that we just want to set our sign is going to be i whatever is the last sign the last character in this case when we come to the end we're going to get a plus and afterwards we're just going to set the number to zero right before we add make a quick correction what we could do here is we could divide and afterwards we need to get the truncation of it so we say math dot shrunk and um what we're going to do is come to the stack here and uh envelope that like that and afterwards all we need to do is just return the sum of the stack like so right and if we run our code it's accepted and if we submit it is also accepted so basically that our time complexity is going to be open our space complexity is going to be open because we create a stack that will uh potentially have as many elements as our array right so it's going to be oven for both of them thank you for watching subscribe to the channel and i'll see you in the next video | 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 |
779 | hey everyone welcome back and let's write some more neat code today so today let's solve the problem Ki symbol in grammar we are given a bunch of rows that I guess are one indexed and to go through it quickly the first row is going to have a single value zero and then the rule is that we build every subsequent row by taking Zer and replacing them with 01 and now since we have a one here we have an additional rule which is we replace zeros with 0 1es but we replace ones with 1 Z and so the next row would look like this where we take this guy and make it 01 this one would be 1 Z this one would also be 1 Zer this one would be 0 1 so that's the idea here so this would be the first row this is the second this is the third and this is the fourth and in this row we want to choose the kith element so n is going to be one parameter in this problem n is going to tell us which row we want to select so for example if n is equal to 4 we are going to choose this row and then in that row we only care about the K element so if K was one this is going to be one index by the way so if K is one we choose the first element if K is two we choose the second if K is three we choose the third etc and we are guaranteed that K is always going to be in bounds if you don't believe me you can read the bottom of the description of this problem but basically they tell us that K is always going to be less than or equal to 2 to the power of n minus1 this isn't a coincidence this is going to be how many elements are going to be in the nth row because we start with one and we double them every single time that's the idea now the first approach you might think of the most brute force would literally be to build every single row and technically that works I'm pretty sure it will get you time limit exceeded though because I believe the time complexity would be roughly 2 the^ of n minus one so pretty roughly 2 the^ of n minus one so pretty roughly 2 the^ of n minus one so pretty inefficient but is there a better approach is there some kind of trick that we can do well the idea actually is just by looking at this picture it kind of looks like a tree doesn't it now let me redraw this exact same thing like this we start with zero the left child is going to be zero the right child is going to be one from this zero same exact thing it's kind of cursive isn't it we have a zero here and then a one here with this one we're going to get a one here and then we're going to get a zero here so the first observation to make is this is kind of like a tree okay with that in mind how is that going to help us don't we still have to Traverse every single element to then like once we get to the kith row choosing the Ki element well maybe the fact that we already know which K value we're looking for can be used to our advantage and in this case it can think about it this way we know we're looking for the nth row let's say we know that the nth row has four elements in it this is the third row and has four elements in it and we want suppose the third element let's say k is equal to 3 we want this target element do we really have to do a bread for search on this tree do we really have to do a depth for search where we go through every single node no because we can do kind of like a binary search or just like a traditional search on a binary tree where the time complexity is actually going to be the height of the tree and the reason that we can do that is because from the root position here we know this is our Target we know that there are four elements in the row that we're looking for and we happen to know that K is in the second half of those elements our Target is in the second half of those elements so from The Roots perspective we have two choices we either go left or we go right with this in mind don't you think we should probably go right no need to go left we can forget that this ever even existed but the hard part or at least this might not be obvious to you how do we do it now when we started with the entire row it was pretty easy to know because we could just take the length of the row divide it by two and then we would know is the K value in the first half or the second half well the easiest way at least in my opinion is to have two pointers one pointer is going to initially be set to this position which is going to be one cuz like I said this is going to be one indexed that's according to this problem and the second value is going to be here in this case it's four but in the general case it's going to be 2 to ^ of nus one which in going to be 2 to ^ of nus one which in going to be 2 to ^ of nus one which in this case let's say is going to be four so that's how we're going to do this with two pointers very simple so here when we decided to go right what we would do kind of like in binary search take this pointer shift it to the right so then it would be here and now that our pointers are here we are at this position by the way and once again we're going to check should we go left or should we go right well this pointer is at Value three this pointer is at Value four K is equal to three so it clearly lies in the left half so here we would choose to go to the left and at this point we would stop we're going to stop once we reach that particular level and we know how many levels to Traverse based on the N parameter so that's kind of the idea of this problem we're sort of doing a augmented binary search or you could think of it as a search on a tree structure with this the time complexity is just going to be the height of the tree which like I said is going to be based on the N input so the time complexity is going to be Big O of n what do you think about the memory complexity since we just have two pointers and we're not really building this tree structure nor are we traversing it with recursion we actually don't need any extra memory is going to be constant so knowing this let's go ahead and code it up one quick thing I want to mention though is when we compute the Midway point we know like we can have a left pointer here a right pointer here uh let's assume that this is one let's assume that this is four when we calculate the Midway point we do so usually by adding these two together and dividing by two if I take 1 + 4 and dividing by two if I take 1 + 4 and dividing by two if I take 1 + 4 and divide that by two and we round down we're going to get two so that kind of tells us that the Midway point is always going to be here and we pretty much are guaranteed that the size of our search space is always going to be even so this is pretty much always going to be the case so when we check if our K value is in the left half or the right half we're going to compare it with mid you'll see what I mean in the code explanation right now so one obvious thing that we need to keep track of is what our current value happens to be we know it's initially going to be zero because that's kind of the root of our tree the first row is a single value with just zero and this is also what we're going to be returning but we know that we have a search space to keep track of as well I'm going to have two pointers called left and right to Define that left is going to be 1 right is going to be 2 to the power of nus1 like I mentioned earlier and then we're going to iterate roughly n times but I'm actually going to iterate in range of n minus one times because we're already at the first row we've already computed the first row and we just need to compute n minus one more rows if n is one this Loop isn't going to execute and we're going to return zero regardless so that works out in that case the reason this is an underscore is because we're actually not going to need this variable at all now it's pretty much just the binary search that I talked about we compute mid it's going to be left plus right divide that guy by two and then we do our comparison like I just mentioned our K variable we need to know is it in the left half or the right half if it's equal to the middle value it's in the left half if it's less than the middle value it's also in the left half so this is the comparison that we do if K is less than or equal to Mid we are in the left half in the other case we're in the right half but what do we do if we're in the left half or rather if our K value is in the left half we should move to the left half so what we do is set our right pointer now equal to Mid if we were in if our K value is in the right half then we'd want to search in the opposite direction so we would set left equal to Mid + 1 so that is kind of the equal to Mid + 1 so that is kind of the equal to Mid + 1 so that is kind of the most important part of the problem but there's one last thing left remember when we have a zero like I have drawn up above or written up above its left child is going to be zero and Its Right child is going to be one when we have a one its left child is going to be one and Its Right child is going to be zero so we could write out a bunch of if statements to get this exactly right but there's actually a bit of a pattern that you might notice if we move to the left half like here is when we're moving to the left side of the search space when we do that the value doesn't change does it zero goes to zero one goes to one so actually there's nothing needed here we don't need to update our current integer when we move to the left but when we move to the right we swap it 0o becomes one 1 becomes zero so that's the pattern so here what we're going to do is Set current equal to zero if current is equal to 1 a shorter way to write this is just if Curr else this is going to be set to one we're basically swapping it so that's all we are doing here so when you look at the solution code this seems like a very trivial problem and it kind of is once you understand that this is sort of like a binary search problem but it's not a trivial problem to solve so don't feel bad if you weren't able to solve it by yourself so let's run this to make sure that it works and as you can see on the left yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out NE code. thanks for watching and I'll see you soon | K-th Symbol in Grammar | max-chunks-to-make-sorted-ii | We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`.
* For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` row is `0110`.
Given two integer `n` and `k`, return the `kth` (**1-indexed**) symbol in the `nth` row of a table of `n` rows.
**Example 1:**
**Input:** n = 1, k = 1
**Output:** 0
**Explanation:** row 1: 0
**Example 2:**
**Input:** n = 2, k = 1
**Output:** 0
**Explanation:**
row 1: 0
row 2: 01
**Example 3:**
**Input:** n = 2, k = 2
**Output:** 1
**Explanation:**
row 1: 0
row 2: 01
**Constraints:**
* `1 <= n <= 30`
* `1 <= k <= 2n - 1` | Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk. | Array,Stack,Greedy,Sorting,Monotonic Stack | Hard | 780 |
315 | Ki gas welcome tu take tu vedita and its video c r going tu solve count of smaller numbers after self so what is given in this problem statement here I have given you a vein and you have to make it how will count aunteric be made what to do here What is the rectangle index one, we have to take the particular index, okay and we have to see how many such elements are there on the right side of it which are smaller than the element at the index, what do we have to do, we have to keep it in the count teddy, okay, what will happen to us with this? Account will be created and now finally what we have to do is to delete it. So let us understand through the example what is the problem. Look at our 5261, in the first example we have given an L. Now you will see that it is five in the index, now to the right of five to five. How many such elements are there which are smaller than Tu, if there are two Tu and Van then what will we do here. We will keep two how many elements are there which are smaller than Tu, there is only one Van, so here we will keep Van. Okay, how many such elements are there on the right which are smaller. So there is only one, okay, if there is no element, otherwise it will be zero, so what will be our output? Okay, so how are we going to solve this problem, here we can solve the problem by doing our sort of thing, okay? Look, first what do I do, let me tell you in brief about our sort, what is my shot, okay, after that we will come to our problem, okay look, what is given here, one is given, now what we have to do is our shot. I have to sort it by doing that, what is the short, you have a sorting algorithm, what can you do by doing that, look, you can sort, okay, so what is this based on, divide and best, what do we do in this, let's keep dividing. Are equal in equal parts i.e. i.e. i.e. divide into half equal parts. For how long do we keep doing this until what we have is changed into a single element, then why do we do it into a single element because we know that a single The element is sorted in itself. The single element is sorted in itself. Okay, so what will we do here, when we will sort, that is, we will divide, then what will we do again, we will start merging it, now how will we merge that too? Let's see what you will do in this, you will divide this here, now how will you divide, people will find its index, the first and last will be zero, what will happen to you 0 1 2 3 4 5 6 Here, if there is six, then you will get zero and six. Okay guys, if you divide both of them by two, you will get three, then the first half will be yours from zero to three, and the next half will be yours, look at four to six, here it is from zero to 3, from four to six. Then what will we do with these two also? Divide them in half. If we divide them in half, then these two are in our hands, then this is also in our hands, divide this is also in our hands, okay? Has the single element been converted into a single element? Now what will we do? We will start merging here. Now how will we merge? What will we do here? We will compare both of them. Which of the two is ours? Here, we are going to do ascending order. What will we do in ascending order? Which is the smaller element? The one that is smaller will come first, the one that is greater than that will come after that, so here 27 will be 38, here will be yours, you will compare 433, what is yours, smaller is three. First 343 then here you will compare these two 9 first 382 then 10 next this then here what we will do is start merging these two then what do we do in this let's compare look here people are here for you Okay guys, first come and see, you will compare which of the two is smaller? 3 is smaller, put three first and then increment k. Okay guys, then come and see, compare which of the two is smaller? 27 is 27, put 27 here. People, then you will increase the pocket by incrementing I, then you will compare these two, then what is your smaller one? What should I do with the stomach? What will I do with the left? What will we do if we keep it here, then this becomes your short, then what will we do with these two? We will sort i, we will take k, then we will compare both, which is smaller, nine, we will keep here, we will increment i, then if we compare these two, we will compare which is smaller among the two, 10, then we will keep 10 here. If we increase the next K, then this is our end. 82 are left here. If we keep 82 here, then this has become short. This has become short. Now what will we do with these two sort-it elements, we will what will we do with these two sort-it elements, we will what will we do with these two sort-it elements, we will sort them again when we We will sort both of them again, then we will start from i here, we will start from here, ok, then we will compare both, which one is yours, if yours is smaller, then three are small, then three will be the first ones, then you will increment i, then compare both of them. What will you do this time, what is your Jeth element, then put nine here, increment K, then you will compare both, increment them, then what is yours, if you compare both, then put it here, increment I, people will be here. Then you will compare both of them, I am smaller, okay, then you will move ahead here, then you will compare both of them, which is smaller among the two, 43 is smaller, 43 is there, people keep I, if you increase, then you are finished, now whatever is left, we will keep it here. Here we will keep it, finally, what will you get, you will get it sorted, from now on, what are we going to do with the concept, we have given it here we will take the first input, five to six one, okay five to six one. Here, what do we do? We will not sort it in ascending order. What will we do? We will sort it in order. Okay, I will explain to you will understand. Okay, look, you have given five, you have given six. Have given van given first sort crore ok short how on the basis of descending order we are going to divide and conquer algodam we are going to do that with our sort what will we do with this we will divide on 1/2 sort what will we do with this we will divide on 1/2 sort what will we do with this we will divide on 1/2 when you divide in half then this is your five You are yours, okay, then what is six, this is yours, one is yours, okay, then we will divide these two in our hands, we will divide this also in our hands, how long will we keep doing this until this five was coming in a single element, right here. Now this is you here, then six here, van here, now what will we do with this? Along with the element, I will also take care of its index, this is zero, van is you, this is three, so here. It will be zero. Okay, taken. Now what will we do, what is yours? So first see if it is smaller, then we are going to do it in descending order. When we get smaller, okay, then what will we do? What will we do by incrementing it here? Van Let's do it, now look, the van is done, now what will you do, people put five here and you will be here, so what will we do here, update it and make it van, we will sort both of them, what will we get, we will get six and van. Got it, now let's see, this is your zero, this is van, this is tu, this is your three, okay, so what will we do, now we will start I from here, we will start GS from here, now we will see whether the element from I to J is smaller or not smaller. So you keep six here, nothing to be done, okay, you have to increment K. Now see how the element of K is smaller. If it is smaller, then increment the count of five, keep it here, you are done, okay you. Now what will we do, which of the two will go, five will come because 5 is greater, so this one will be here, I will be here, now we will compare these two, what is yours, if you are smaller, then here is your index, there is theirs. Let's do this here, let's put this one van here and put you here, now he is left with the van next to this one, see, you have got 21100, see here, I understand the code for you, then through the code, we Neither are we going to see another test case because we have made some changes in the code. The count that we are actually updating here, nor are we updating it one by one, is not the right way. Pass for one or two test cases. Will do it but it won't do it for all, so here what will we do to you when we explain the code then there we are going to show you here ok how are we going to show different faces ok so see here what we will do see this Here, along with the element, I am also taking care of its index. You are also taking care of the right index. So for this, what will we do to that, vector of feet, we will do that, okay, where what will we do, we will take the element and If we keep that also, then what will we do for this? We will do that and we are going to do that for sorting. Okay, so coming to the code part, look at what we did in the court. The account is small. Okay, here we have given NMPS, what will we do? And we will find. Hello, we have found the size and what we have done is to add an extra space here, which will store the element and will store the index, which will be the type itself, so what will we do here, we will take integer OK. So here we have created a foot here, I is yours, then the I index is yours, okay, the index of the element on the index has been updated here, now here we have taken a vector count which will create our account. That account is first given to us here when after calling our sod okay I in short what we have passed which is your vector and tree okay is the count which is going to have your answer now first index Now we have passed the index and the n-1 index Now we have passed the index and the n-1 index Now we have passed the index and the n-1 index. Now what is happening in our short, first of all we are looking at L, if it is gated from R, that is, look at the left if it is L, if it is gated from R, that is, look at the left index of L, what is yours, look, this is the next zero and - 1 What should be this, yours, look, this is the next zero and - 1 What should be this, yours, look, this is the next zero and - 1 What should be this, your right should always be smaller. The index on the left side should always be smaller on the right. Only then we can do this. We will not do this. Okay, what will we do here? We will find the middle element by finding L + R / 2. Let's do this, L + R / 2. Let's do this, L + R / 2. Let's do this, what will we do, we will first divide it into half parts, we are dividing, we will sort it on the right, we will divide the half part first, then how will we do it again, what will we do on this, we will call research which will take I have kept L, taken it and will do it till Mir. Okay, we are doing it till Mir, then what to do in the next one. From Meet + 1 till R means the what to do in the next one. From Meet + 1 till R means the what to do in the next one. From Meet + 1 till R means the index on the right side till there, I have called with you here also, add count is mine. Plus van R and we have called it merge here, what will it do for you, finally sort it, whatever you want short, after merging it, now let's come to our operation which is to be done in this merge, what have we done here. A temporary one is your vector foot int-int here means the vector of foot has been taken, int-int here means the vector of foot has been taken, what will be the size R - L + 1 because what will be the size R - L + 1 because what will be the size R - L + 1 because now look what you are doing here, see what you are doing in this, you are dividing these two. You are dividing, you are dividing these two, you are dividing right, your size is always changing, right size is always changing, so here whatever we will take one of the sizes up to R - L + 1. we will take one of the sizes up to R - L + 1. we will take one of the sizes up to R - L + 1. Okay in which we are going to store after sorting means after merging not so three sorting so in our sod after that what we are doing is margining right so mars we will do and keep one in we are going to keep We have created a vector and a leg in which we are going to keep it short, this is what we are doing right here, which you have sorted, here, so what is this, in the form of a leg, right here, we are going to solve it, so we What we have done here is that we have created a temporary vector here, we are going to perform the operation for how long till i, your less than equals, you will be min and k will be your lesson = r till right, look, if you are your lesson = r till right, look, if you are your lesson = r till right, look, if you are doing the half one, then i who is here. You are giving me how far your eye was going, see here, understand here, your eye was going till its size, then it was going till its size, right, so yes, see, this is till the sweet element, understand here. I am these two if you said these two if you are sorting then I start from here and go till here which is your what is mid which is your we are rich plus which is start K is going till the right, so we have put the condition here, which is the first element, what should we store in the first element, you are storing the elements, okay, after that, what are you doing in the second element, you are storing the index. So what will we do here, we will compare with the first, which is the first element, I think next, which is the first, that is, which element is it less than equals, you arrange first, if yes, then what will we do, which is the greater, which is that, so what will we do? We will store K's in temk++, that, so what will we do? We will store K's in temk++, that, so what will we do? We will store K's in temk++, okay if respect vice, what will we do, update the count errors here, plus R mines, K plus van, now why are we doing this here, let me tell you, okay here I will do one 19785 for this, I will tell you for this, okay let's do 1998 and 45 here, what are we going to do, this is yours, so we will not do anything, simply will not operate, okay, so what will we do, give nine first. Will give and van will give the index of nine is van and its zero is ok then what will we do with this we will merge these two if we will merge these two then what will we do Jitendra ok last is your total we will do r - j+1 i.e. 2 - 2 + 1 So there will be will do r - j+1 i.e. 2 - 2 + 1 So there will be will do r - j+1 i.e. 2 - 2 + 1 So there will be van here. See, by law there should be van here. For this, for the van index pe because index, van index pe because what is eight is smaller than nine, so there should be van here and we also get van. So, we will take van here. Okay, it is done, then what will we do, because if we sort, what will be sorted first, nine will be first, when you increment i, you will compare these two, so what will you do at here? Wait because this smaller one has not got the right index, which is this one, if you have not found it, the smaller one cannot be updated here, further let's leave it as it is, then what will we do, it is finished, whatever is left, we will update it here. Will update it, now it is short, we got 981, now we will do 7 and 5, okay we will do 7 and 5, when we are here, tell us which gate is there in 7.5, what is yours, then how do we count it? Will update, this is your I and this is okay, so what will happen to you today, R will also be your four, so you will do 4 - 4 + 1, now it will become one, that is, do 4 - 4 + 1, now it will become one, that is, do 4 - 4 + 1, now it will become one, that is, in which index will it go, on three index 0 1 2 3 here Pay van ok this van is done now what will we do if we sort both then we will get 75 ok now this came and this came now what will we do ok if we compare with seven then nine is yours what is greater then what we store in yer If you store the nine then it is okay and since what is this, your 7 has already been found, that means 7, what is this, it is smaller than 9, okay, it is smaller, so now tell me, there is only one smaller nine, you have paid here. Now you do seven by increments, you guys do it here, it's okay, you guys do theirs by doing nine, you have got your I stored here, now you go ahead guys, it's okay, you guys even five is smaller than this, isn't 9 to 5 also smaller? Now sometimes you will not be able to compare if you do the same as in increments. If you do as in increments, here you are the only one, but according to the law, your answer should have been three because what is five? It is smaller but we will store the nine. If I am then we will never be able to compare again because our number has already moved forward. So what will we do in this condition. Look, if it is small R then it is sorted. We know this. It is sorted and we sleep in descending order. Let me, whichever number of elements it has, it will be sorted, it will be smaller, so what will we do, R, what will happen to it, four will be then 4 - what will we do 4 - what will we do 4 - what will we do from here, 4 minus what is its index. This is the earth, here we are, if we have to add right then it will become three, what will be our answer, you will get the accurate answer, see, here I had done the increment by doing that, so here what we got is not 3. I got it here, you got it, okay, so what we are doing here is R - j+1 Okay, then we stored it doing here is R - j+1 Okay, then we stored it doing here is R - j+1 Okay, then we stored it in the tempo by doing i plus of k + r a r in the tempo by doing i plus of k + r a r in the tempo by doing i plus of k + r a r because what is yours here is the greater of i. So, if someone from the half is left, then okay, if someone from the left side is left, then we will simply get it done in it and if someone from the right side is left, then what will we do, we will simply store it, then what will we do? Update the add A again. What will we do to the AD? We will repeat it again because after sorting and shortening what we have created, look here, you have sorted it and after shortening, you are doing the same further, so what will we do here? We will need a sorting one, so what will we do, we will update it here to Eric, so this is our solution, let's run it once, submit it, thank you. | Count of Smaller Numbers After Self | count-of-smaller-numbers-after-self | Given an integer array `nums`, return _an integer array_ `counts` _where_ `counts[i]` _is the number of smaller elements to the right of_ `nums[i]`.
**Example 1:**
**Input:** nums = \[5,2,6,1\]
**Output:** \[2,1,1,0\]
**Explanation:**
To the right of 5 there are **2** smaller elements (2 and 1).
To the right of 2 there is only **1** smaller element (1).
To the right of 6 there is **1** smaller element (1).
To the right of 1 there is **0** smaller element.
**Example 2:**
**Input:** nums = \[-1\]
**Output:** \[0\]
**Example 3:**
**Input:** nums = \[-1,-1\]
**Output:** \[0,0\]
**Constraints:**
* `1 <= nums.length <= 105`
* `-104 <= nums[i] <= 104` | null | Array,Binary Search,Divide and Conquer,Binary Indexed Tree,Segment Tree,Merge Sort,Ordered Set | Hard | 327,406,493,1482,2280 |
1,477 | hello today we're gonna be talking about the good problem 1477 fine to non-overlapping subarrays each would non-overlapping subarrays each would non-overlapping subarrays each would target some so I think it's pretty easy conceptually we have to find two non-overlapping subarrays such that the non-overlapping subarrays such that the non-overlapping subarrays such that the target is equivalent to equal to the sum of those two subarrays and if you can't find two subarrays you return negative one so you know in just a brief example let's get a better example so here we can see we have to return the sum of the two sub arrays so the solution here we can see with target of three we have one the solution is this sub array and then either this sub array or this suburb and since that's size one plus size two or answer is three alternatively you know you could look at this and say well this is target three but you know that has a size of three and then you know this is size one so we would have a sum for which is greater than our previous sum of three so let's just go right into the problem so the first thing I'd like to do with any problem is sort of talk about intuition and go over sort of base cases or cases that fail so initially you might think well if I just keep a sliding window and I go through the array maybe I can greedily pick intervals if their shortest so for example let's start with this array and in red on the right you know our target is 15 we would discover that right here we see that we reach our target so maybe we store this you know as a 5 and it's of length 5 and you know maybe we say well let's keep going so we can you know discover another interval here that also sums to 15 and that's size four so lets you know replace this five with the four let's assume that any overlapping interval and if it's shorter is just gonna get replaced right so we discover a four we replace our five it's overlapping because they're using the same three and then when we get to the end we realize there's a 1 in the 14s but that overlaps with our answer from before so you know if they cross this out there's no solution we've only found one interval clearly that's not the right answer because the right answer is if we you know exclude this interval entirely and we keep these two now what's the idea behind this you know sort of in a more abstract sense so if I told you the answer if I told you the shortest two intervals in this range was 7 and 1 could you tell me the answer to this problem I would argue you can because you can immediately see an interval here that satisfies our target of 12 and I just told you the shortest two intervals or seven and one so you would conclude well they have an internal else has one I only have an interval size two so our answer is three all right because you can clearly see that you know this interval doesn't overlap with anything in this sort of region the now the next sort of idea that we will have is how do we formalize this into something that can be written in code right and furthermore what's the actual sort of algorithm right that's more specifically what the question is so let's imagine we initialize our sort of world in a place where there is no solution both intervals just don't exist right and when we first look at the array can we know immediately if the sort of interval satisfies the target oh yeah we can write we can look at the first index and if that satisfies the target oh we've discovered an interval so the question we have now that we've discovered an interval that you know equals our target is okay what came before me and do I want to use this interval at all so you know you would ask given this position what's before me well null and null is okay well an interval size 1 is definitely better than an interval size null but I haven't discovered a second interval yet so basically what you're doing is you're looking at this interval size 1 and you're taking the sort of minimum the two minimum numbers of the set of three you have two numbers here that tell you the best up to that certain point and you have the new interval that you just discovered so in this case it's gonna be you know 1 and null right we've only discovered one interval so let's keep going with the algorithm now what does it do me logically do well since we're kind of done with this interval we can't really use anything with this interval again since we know the target since we know the array is all sort of positive integers moving only one pointer isn't going to help us right so let's just move both of the pointers let's just simplify things whenever you have a window that sums to the target you're done with those you're done with both of these positions of those pointers there's not going to be another window that helps you so we move over by one and we observe that our sum is one let me go okay well that's you know less than our target so we know there's no possible interval that ends on this position so what can we conclude we can clearly that the best point up until this position is literally just the previous one there's nothing we can do here same thing with the next point literally just the previous point we've only discovered one and we'll move the pointer up again oh we go okay now I realize our sum and by the way while we're sort of moving these pointers we can easily compute the next sum in sort of constant time right we don't need to go back and add this interval up starting from this starting from the beginning right we can just as we move this pointer over look at this value and say oh it's a 1 ok add 1 to my son alternatively if you move the left pointer over by 1 say okay well we're removing this element so we're subtracting that right so we're not sort of computing this sum over and over again and going back and forth in the array so we discover an interval here besides 3 what does that mean well that means that we need to ask the question 3 and all non-overlapping the question 3 and all non-overlapping the question 3 and all non-overlapping intervals up to a certain point where are the non overlapping intervals with this position given or sorry not that position the interval so the non overlapping intervals are going to be everything to the left of our left pointer all right everything sort of over here which happens to be right here we've already computed that we already know the answer to that so we have a question of three null and one give me the two smallest numbers from that set let's assume null is infinitely big and by that token in my code I implemented this as actually infinity instead of null but I think nulls little bit easier to explain three and one are the best we can do up to this point which to know some stuff for sore answer right now is four but that's not the only question we need to ask so I sort of didn't ask this question immediately because I didn't want to overwhelm but we also need to ask is what we observe here given this 3 and this non-overlapping intervals better this non-overlapping intervals better this non-overlapping intervals better than everything else we've found up to this point and in this case and actually in this problem example it is always going to be better but you can imagine that we discover some solution maybe here that is not better than the three and one that we discovered previously so we need to be asking the question is our three and one better than the sort of one and null and you know if you initialize these to infinity you know you can just ask is the sum of sort of this less than the sum of this and if it is then we want to stay with the solution we had so let's continue with this example so this interval is done so we need to move our left and our right foot in river by 1 and we realize our sum is greater than 3 so you know it's 7 so we have to move our left pointer if I want and still larger I move our left pointer over my 1 again and it's still larger so let's you know the left whatever I want and let's be smart about the right pointer and say you know if the right pointer ever falls behind just move that up I want so right now you know the this 5 that we've moved our right pointer off of we conclude there's no interval that ends on 5 because we moved our right pointer right so we just look back and we fill in the best answer up to the point not including 5 because there's no interval that ends on 5 and we also observe there's no interval ends on 1 but now that somes too small so we move our right pointer and whenever we move our right pointer we literally just look back let me say just give me the best that you have up to this point and now we realize that there is an interval that sums to three so we asked the same question we asked over here we have this entity three and one and we have all non-overlapping intervals which just non-overlapping intervals which just non-overlapping intervals which just happens to be three and one as well and we asked sorry this is a two of size two and we asked the question give me the three give me the two smallest numbers from these numbers well that's going to be two and one and is two and one better than this guy well yeah it is so we keep the two in the one and as we sort of continue this problem on we can see that you know we shift the left over by one we shift the right over by one we realize this sums too large so maybe the left over by one and we realized we're at the end of the array and the sums still too large so we just record our previous up to that point and then we're done and then algorithm terminates so what's the run time of this algorithm well the run time is gonna be of it right we're only going through this rate once and we do have two pointers so maybe it's on the order of something like 2n but we only go through the algorithm we only go through the array once and as long as we're sort of storing these in a constant time lookup hash table and computing this sum in constant time as we're moving through this array then we're gonna be you know running this algorithm in 11 time so hopefully this was helpful the code is going to be you know in the comments below and I hope to see you in the next video | Find Two Non-overlapping Sub-arrays Each With Target Sum | product-of-the-last-k-numbers | You are given an array of integers `arr` and an integer `target`.
You have to find **two non-overlapping sub-arrays** of `arr` each with a sum equal `target`. There can be multiple answers so you have to find an answer where the sum of the lengths of the two sub-arrays is **minimum**.
Return _the minimum sum of the lengths_ of the two required sub-arrays, or return `-1` if you cannot find such two sub-arrays.
**Example 1:**
**Input:** arr = \[3,2,2,4,3\], target = 3
**Output:** 2
**Explanation:** Only two sub-arrays have sum = 3 (\[3\] and \[3\]). The sum of their lengths is 2.
**Example 2:**
**Input:** arr = \[7,3,4,7\], target = 7
**Output:** 2
**Explanation:** Although we have three non-overlapping sub-arrays of sum = 7 (\[7\], \[3,4\] and \[7\]), but we will choose the first and third sub-arrays as the sum of their lengths is 2.
**Example 3:**
**Input:** arr = \[4,3,2,6,2,3,4\], target = 6
**Output:** -1
**Explanation:** We have only one sub-array of sum = 6.
**Constraints:**
* `1 <= arr.length <= 105`
* `1 <= arr[i] <= 1000`
* `1 <= target <= 108` | Keep all prefix products of numbers in an array, then calculate the product of last K elements in O(1) complexity. When a zero number is added, clean the array of prefix products. | Array,Math,Design,Queue,Data Stream | Medium | null |
1,650 | hello in this video we're going to be going through Lois common ancestor of a binary tree three which is lead code problem 1650 this problem is marked as a medium and it's fairly new and fairly popular but um it is high on the frequency list given two nodes of a binary tree p and Q return their lowest common ancestor LCA each node will have a reference to its parent node the definition for node is below yada according to the definition of LSA and Wikipedia which we know Wikipedia is always right the lowest common ancestor of two nodes p and Q and A tree is the lowest node that has both p and Q as descendants and we also allow a descendant to be a descendant of itself allow me to introduce myself to myself all right root just cuz I figured out how to read these so three 5 1 6 2 08 the null because the six doesn't have a left or right child then we have seven and four and apparently we don't care about the children of the zero and the eight so if p is five and Q is 1 then the parent of these is going to be three so down here we have five and four the parent is going to be five because five is it's in the same branch and five is the parent of itself as well as four all right so how are we going to do this okay so this is a very straightforward problem we're just going to take node p and keep looping through it um assigning it to its parent until it gets to the top and then it's null and then we'll assign it to q and then keep looping and so we'll keep looping through these until they equal each other and I'll show you what I mean here so node P1 is just going to be equal to p and then node P2 is going to be equal to Q all right so while these don't equal each other we're going to do the null culating operator here so P1 is going to be equal to the result of this expression so if P1 equals null then we're going to assign it to Q but if it's not null then we'll just assign it to its parent and then we'll do the same thing with P2 so P2 equals null we'll assign that to P otherwise we'll assign it to P whoops P2 parent and then those will keep going through until they equal each other and then we'll just return P1 we can return P1 or P2 it doesn't matter because they equal each other so let's debug this and see what we get okay for this example I just used example one and so p is going to be five Q is going to be one so we'll just go through here you can see P1 is five P2 is 1 so while P1 is not equal to P2 which is true so P1 is not null so we're going to sign P1 to its parent which is parent is three and then P2 is not null so we're going to ass P2 to the parent which is also three so that's boom easy peasy return P1 which is three and that's all she wrote all right let's try running this see if I did it right looks like I did submit it e faster than 28 and 22 let's try again who we got 65 that time I'll take it now do the time complexity is O of n we're just looping through uh the binary tree so we don't um increase or decrease the time needed based on the inputs is O of one we're not using more space we're just looping through the tree and that is it so let me know if you have questions thanks for watching and we'll see you next time | Lowest Common Ancestor of a Binary Tree III | find-root-of-n-ary-tree | Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_.
Each node will have a reference to its parent node. The definition for `Node` is below:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
}
According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). "
**Example 1:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1
**Output:** 3
**Explanation:** The LCA of nodes 5 and 1 is 3.
**Example 2:**
**Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4
**Output:** 5
**Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition.
**Example 3:**
**Input:** root = \[1,2\], p = 1, q = 2
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[2, 105]`.
* `-109 <= Node.val <= 109`
* All `Node.val` are **unique**.
* `p != q`
* `p` and `q` exist in the tree. | Node with indegree 0 is the root | Hash Table,Bit Manipulation,Tree,Depth-First Search | Medium | 1655 |
1,980 | hey everyone let's talk the today's lad code challenge find unique binary strings so in this problem we are given a string array nums containing n unique binary strings and all of that binary strings are of length n and we have to return any binary string of length n which does not appear in that nums array and you can return any answer so let's have a look on this example here we are given binary strings of length two so for two length how many binary string we can have 0 1 0 and 1 these are the possible options we can have in our nums array and what are the options given to us those are 0 1 and 1 0 and we have to return any binary string from this array which is not present in our given nums so first approach can be like convert converting those element to the base 10 so if we have converted those binary string to base 10 we can just directly iterate over the candidate options so for n = 2 our value will go from 0 to for n = 2 our value will go from 0 to for n = 2 our value will go from 0 to 3 from binary string you can also check 0 1 2 3 so these four are our candidate options and we can compare these value to the values given uh given in the problem so in the problem the in the problem we are given with two binary string which are 0 1 and 1 0 so 0 1 is 1 0 is 2 so we are given 1 and two and we can have 0 1 2 3 in that array so by iterating that array we can get to know which is the element not present in our nums array so we'll iterate over this array 0 1 2 3 0 is not present in that set it means we can return zero as an answer so later on we will convert 0 to base 2 as a binary string so this can be the approach firstly we will add all the values given in nums array to the set converting into base 10 so like this here we have created a set and added one and two in that now we will iterate from the candidate values which is for Nal 2 it would be 0 1 2 3 we will iterate over that and if any value is not present in the set we can use that value as our answer and we can return that by converting that into a binary string but we have to make sure that the binary string is of length two so you will just take a loop uh n number of times and just take modulus with two which is 0o and then divided by two with is 0 so 0 and 0o like this so 0 we have to return the second approach can be check with all the POS ible binary strings of length 2 or maybe n in any example so here in our example we are given with this array so we have to check for all the possible binary strings on Nal 2 so firstly we don't have any we can capture that in a string variable so firstly we will add two and then add one and we will do it recursively till the temporary string length is not equal to n so further we will add 0o and then one then 0o and one which is 1 0 1 okay so here and this or this level n is equal to 2 so we have to back a terminating case so at any index if we get a bind string of length two that is which is not present in our set we will maintain separately that would be our answer and we just have to cancel all the recursive C further okay so here in the code at every point I'm just adding either 0o or one in the answer and if we are able to achieve the answer by adding zero I'll just return the value we don't need to check further okay and if we are not able to get the value we just I'm just returning null so let's try to dyen this code initially we don't have any string and then we added zero and make a further call make a further solution call to this function with index + one so it to this function with index + one so it to this function with index + one so it further made a call and then added zero in that and now the termin terminating case will run if the temp size is equal to n in that case we will check whether it is already present in the set or not if it is not present in the set we will just return it so our call came here and then it came here and at 0 it went into the terminating case and just we return from here and now when it returned to this call it came here and if left is not equal to null it just return the left value then keep on doing so and ultimately it is going to return 0 from this program okay let's try to submit this problem let's try writing the code for this problem here we are going to check all the possibilities for these binary string of length n so firstly let's capture the length num St and we are adding our existing binary search in a set so I'm also taking a set of string in and for the size set equal to new Hash set and then I will just call my S function do we need to pass index no I don't think so we just add empty string okay private void sorry private string so string temp if temp string do length is equal to n it means that is the candidate string and we will check whether that is present in our set or not if that is not present in our set it means that can be our answer and we can return that set do contains temp equal to false in that case we can just directly return temp otherwise we can check for left part we can check by adding zero to our existing string so solution 10 plus Z if we are able to achieve the answer by adding zero if left not equal to n then we will just return left else we will check for the right case solution m + 1 E right not equal to + 1 E right not equal to + 1 E right not equal to n otherwise we are just going to return now let's try to run this code output 0 expected is 0 zero I forgot to add the existing nums in the set so for string s nums set to add s memory limit exceeded okay so maybe it is going to process the elements with length more than n so in that case what we can do is we can add for another parameter which is index string index which is index + one incrementing index which is index + one incrementing index which is index + one incrementing the index at every stage and before going into recursive calls I will just check for the index if index is less than n Only then I'm going to enter in the recursive Poes else it is returning okay let's try to run it again sorry it is index which is iner now let's try to submit this problem okay it is submitted successfully beats 77% of the successfully beats 77% of the successfully beats 77% of the users okay guys I hope you understood the code thank you | Find Unique Binary String | faulty-sensor | Given an array of strings `nums` containing `n` **unique** binary strings each of length `n`, return _a binary string of length_ `n` _that **does not appear** in_ `nums`_. If there are multiple answers, you may return **any** of them_.
**Example 1:**
**Input:** nums = \[ "01 ", "10 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "00 " would also be correct.
**Example 2:**
**Input:** nums = \[ "00 ", "01 "\]
**Output:** "11 "
**Explanation:** "11 " does not appear in nums. "10 " would also be correct.
**Example 3:**
**Input:** nums = \[ "111 ", "011 ", "001 "\]
**Output:** "101 "
**Explanation:** "101 " does not appear in nums. "000 ", "010 ", "100 ", and "110 " would also be correct.
**Constraints:**
* `n == nums.length`
* `1 <= n <= 16`
* `nums[i].length == n`
* `nums[i]` is either `'0'` or `'1'`.
* All the strings of `nums` are **unique**. | Check for a common prefix of the two arrays. After this common prefix, there should be one array similar to the other but shifted by one. If both arrays can be shifted, return -1. | Array,Two Pointers | Easy | null |
377 | in this video we're going to take a look at a legal problem called combination sum four so uh previously i did a legal video called combination sum uh number one number two number three so this is just a follow-up question or so this is just a follow-up question or so this is just a follow-up question or i should say another question that's related to combination sum but this question i find is kind of similar to dp right dynamic programming which follows the uh the distinct ways dynamic programming pattern where we want to find the total distinct ways for the given parameters or the given values right so you can see here given a array of distinct integer values and a target integer value return the number of possible combinations that can add up to this target so you can see the target is guaranteed to fit in a 32-bit integer and here you can see in a 32-bit integer and here you can see in a 32-bit integer and here you can see we have an example of integer array which has distinct values we will not have uh values that are same to each other and you can see here we also have a target of four so we want to know how many combinations can we come up with that has a sum that's equal to four right you can see here we have one plus one uh because you can see here we can use the same element more than once right and you we can also have uh just one plus two or one plus two plus one you can see that this is a different combination is this right even though those values are the same but different combination different order but it still counts right we can also have one plus three uh two plus one two plus two three plus one so we want to know how many combinations can we come up with have it has a sum that's equal to the target right and no the different sequence are counted as different combinations and let's say we have a situation where we have the value right in this case there's only one element and this element is actually bigger than the target sum then there's no way that we can come up with a target sum which is going to return 0 right because there's no combinations because even though if i nine plus nine it still will never reach two to three because nine is all it's always bigger than three right so how can we solve this problem so let's say we have an example like this right so in this case if our current sum is 4 and or i should say the target sum is 4 we want to find total combinations that we can find that has a sum that's equal to 4. so in this case what we can do is we can choose n number of uh well i should say we can go down a number of paths because in this case we can first take the first element or the second element or the third element to be added onto our combination right as long as it satisfy the condition of course so first we're going to do is we're going to add 1 onto our combination so now we have a target now that we have a current sum of 3. we can also add the second element we have a current sum of 2. we add a third element we have a current sum of one and now in this case we can also choose to go down a number of paths right in this case for each and every current sum so if i occur if i have a current sum of three i can choose one added onto our combination so now i have a current sum of two right and then i also can choose to add two onto our combination now i have a current sum of one left to fill right in this case i can also have add three onto our current combination and you can see we have a zero and you can see we have a current sum which is equal to zero that means we found a path that has a sum that's equal to four right because you can see here i add a one here and i also add a three here so one plus three will pretty much give us uh four right so that's why you can see we have zero uh zero sum left to fill so now what we're going to do is we're going to return to its parent say we found one combination and same thing if i go down this path i can choose to um in this case i can choose say i want uh i want to add one in this case if i add one and in this case it will give us zero then we also have a combination so it's we're also going to return back to its parent and say okay well we also have one combination here right and if i try to go down to out of 2 in this case we're going to get a negative value right if we get a negative value we're just going to return 0 because there's no way we can add or find a combination and same thing for 2 if i add one i have one common a current sum of one left if i add a two i have zero combination some left if i add a three i have a negative value so i won't count that right and if i have a one left in this case i can continue i can choose a one in this case i give i get a sum of zero if i get a out of two in this case i will get a negative value right so in this case i won't count that right so what's going to happen is we found a path so what's going to happen is we're going to return back to his parents saying there's one way one combination that has a sum that's equal to 4 and it's also going to return to its parent stack to say well there is one combination for its uh to find a sum that's equal to four or a target and this we also have one path as well because in this case two minus two is zero right so we also have one path or one combination so you can see there's total of two combinations for this element right here right so what's going to happen is this element is going to return back to its parent stack say okay i have two combination sum that has a sum that's equal to four so now for three if i want to find the total combinations uh for if the sum is three then there are one two plus three plus four so there are total four combinations right you can choose one plus one right one plus two uh two plus one right or even a three right so you can see we have a three path or actually four path right because you can see here i can have one plus one or one plus two uh sorry yeah one plus two or two plus one or just plus three right so i have four combinations and then now we have four combinations then we're gonna return back to his pair and say okay for a combination sum for assignments equal four equal three i have four combinations and then you can see here we also have to do the same thing for this path but wait a second we already compute this path already in here we know that two has a total of two combinations in this case we can do one plus one or one plus two so we're going to return back to step pair and say i have two combinations right if i have a current sum one wait a second i also compute that before you can see here if i have a current sum is equal to one i have one combination which is just one so i'm going to return back to this pair and say i have one so four plus two plus one how many combinations do i have if i have a current some four in this case it's going to be seven right so i have seven combinations uh for if i if the current sum is seven or sorry if the current sum is four right uh so what we're going to do here is we're going to do a top down approach with minimization and this will improve time complexity down to a down from exponential to a t times n t is basically target right and the end is number of elements right so for each and every single recursion stack we have to make a number of choices right and for each and every those choices we have to do that t number of times right in this case the height of the tree is t so to do this in code first i create a nums integer array and we're basically going to make this as a global variable so that i can create a helper function and be able to use the nums integer array right and then i also gonna create a cache array and this cache integer array is going to have a size of targets right because what we're trying to do here is we're trying to cache for each and every single targets for each and every single sum that we have left uh we're going to be able to cache that right if we visit that element again we can be able to return the precomputed value so what we're going to do first is we're going to say this.numps is equal to nums and this dot cache is equal to integer with the size of target plus one right because we also have to include the uh the target element itself because in the array is zero based and then we're going to do is we're going to create a helper function right where we're starting we want to figure out what's the total combinations if we have a current if the current sum is equal to target right and this will give us the total combinations unique combinations right or distinct combinations um that we can have right so now we can have create a helper function which takes the current sum and we want to figure out how many combinations that we can have uh with the current sum right so first we're gonna do is we're gonna check to see if the current sum is actually less than zero if it's less than zero that means we can just return zero because there is zero combinations that we can find if the current sum is a negative value right that means like the current sum is bigger than the cur the that means the current combination is bigger than the current sum the target sum so we can just return zero and also if the current sum is equal to zero that means we found a path so we can just return one right so now we're going to do is we're going to iterate for each number every single element in nums we're going to traverse or do a dfs for each and every single path so what we're going to do is we're going to have a integer variable called total which keep track of total combinations that we have seen so far so initially zero right so in this case we're going to say total plus equal to helper at num so in this case we're going to say current sum minus num right in this case this will give us a new current sum and we also have to find the total combinations for this new current sum if we decide to go down this path right and then at the end what we're going to do is we're going to return this is how many total combinations that we can have if the current sum if we have a current sum if this is our current sum right so in this case what we're going to do now is we're going to run our code and let's try with a few more examples and you can see we have a success and now let's try to implement the cash right so if we visit this place before if cash at current sum does not equal to null then we can just return cash at current sum otherwise what we're going to do is we're going to compute it and then we're going to cache it cache at current sum has this number of combinations that has a sum that's e that has a sum is equal to current sum right and now we're just going to run our code and you can see we also have our success and now let's try to submit our code and you can see we have our success so this is how we solve the combination sum number four and now let's take a look at how we can do this using a bottom to up approach so how can we solve this problem using a bottom-up approach bottom-up approach bottom-up approach so to solve this problem in a bottom-up so to solve this problem in a bottom-up so to solve this problem in a bottom-up approach basically let's start with the bottom right let's say if our current sum is one and this is our same example right if our current sum is one how many uh how many combinations can we find in this case we have array of one two and three right so in this case we what we can do is we can have to iterate each and every single elements that we have in our array so if i have one minus one i have a zero if i have a one minus in this case two i have a negative value if i have one minus three i have a negative value as well so if i have a zero then in this case i have a way right i have one combination right if i have a negative value i have zero combination so in this case if i have a zero that means i have one combination if i have a negative value i have a zero combination so in this case one plus zero for if i have a current sum of one then i have one combination right if i have current sum is one i have one combination um and what if i have a current sum two right in this case i can have one minus one right i can also have one minus two sorry two minus one and two minus two and i can also have two minus three which have a negative value right so those are the sum so if i have a current sum of one how many current how many combinations can we find but wait a second we already compute this value right in this case one we know that there's only one combination if i have the current sum of one so we're going to do is we're gonna retrieve that we're going to save the pre-computed value in our cache array pre-computed value in our cache array pre-computed value in our cache array just like how we did in the top-down just like how we did in the top-down just like how we did in the top-down approach right we're going to retrieve that and just say okay for this value if the current sum is 1 then total combinations that we can find is just going to be one because we already compute this value so we're going to return we're going to what we're going to do is we're going to say this is one so one right one combination if i have a zero in this case i have one combination as well right and then if i have a negative value i have zero combination right so again it'll just have zero so one plus zero in this case i have total combinations of two right in this case i can have one plus one which is equal to two is just have uh in this case has a combination of one right if i have just a combination of two in this case i have a sum of two right so now this is how we solve this problem and now let's take a look at how we can do this in code so to do this in code first we're gonna do is we're going to have a cache array that has a size of target plus one right because in this case like i said earlier cache or integer arrays is zero based we want to know each and every single positions total combinations uh that we can have for each and every single element in the cache array right for each and every single cell so what we're going to do is we're going to start at the bottom so for integer i is equal to 0 or yeah in this case equal to one and we're gonna just gonna set first element to be equal to uh one right so we're gonna set this to one because if we have the current sum is equal to zero right then we have one way or one combinations right and then in this case well i is less than target plus one i plus and for each and every single sum that we have basically i is equal to the sum right for each and every single sum what we're going to do is we're going to iterate each and every single element so in this case we have integer num in nums right for each and every single numbers that we have in nums what we're going to do is first we're going to check to see if so we're going to maybe re rename this in this case um current sum is equal to i so maybe we can put this outside so what we're going to do is we're going to first check to see if the current sum minus num is if it's bigger than or equal to 0 that means what we're going to do is we're going to compute the current value right in this case cache at current sum right in this case the current sum uh is equal to the uh the value right plus equal to uh cash at current sum minus num because we know that the current sum minus num is a positive value and we already compute that value before because we're going from the bottom to the top right so we're going to save that um add it on to our current cache at current sum right so at the end we're going to get the total current uh total combinations right for each and every single path and at the end we're going to do is we're going to return cash at target right so this will basically give us total number of combinations if we have this uh if this is our current sum if this is our target cell right so now let's try to run our code and uh now let's try to six submit and you can see we have our success and as you can see here the time complexity uh in this case is going to be m time or n times t right t is the target and uh n is going to be the number of items that we have in nums and the space complexity is also going to be t right where we have uh basically for each and every single sum uh we're going to compute the total number of combinations and to get the current total of combinations right for the current target sum we have to get the sum of all the total combinations for its uh children stack right for or is each and every single path so there you have it and thank you for watching | Combination Sum IV | combination-sum-iv | Given an array of **distinct** integers `nums` and a target integer `target`, return _the number of possible combinations that add up to_ `target`.
The test cases are generated so that the answer can fit in a **32-bit** integer.
**Example 1:**
**Input:** nums = \[1,2,3\], target = 4
**Output:** 7
**Explanation:**
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
**Example 2:**
**Input:** nums = \[9\], target = 3
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 200`
* `1 <= nums[i] <= 1000`
* All the elements of `nums` are **unique**.
* `1 <= target <= 1000`
**Follow up:** What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers? | null | Array,Dynamic Programming | Medium | 39 |
349 | hello guys welcome back to the channel and today we're going to solve this Le code question which is intersection of two arrays this question we basically given two integer arrays nums one and nums two and we need to return the array of their intersection each element in the result must be unique and you may return the result in any order so basically we given two arrays and we need to return the common elements in both the arrays but they should be unique right they should be unique mean there cannot be any duplicates in the result so if You observe carefully in this array and in this two arrays there are two twos which are common but we need to return only a single two right and in these two arrays we see that four and nine are common so we need to return we can also return four and N or we can also return 9 on 9 and four so when we look at the keyword uh unique the first thing that comes to for mind is use a hash set right so a set is used to basically remove all the duplicates and store only the unique elements right so in the first approach we'll use a hash set so let's see how we are going to solve that so initially I'll take a set one I'll take two sets set I'm sorry the set one stores are unique elements of the first array and the set two stores unique element unique elements of the secondary right in the first are what are the unique elements 1 comma 2 right and in the second area what are the unique elements there is only two right so after doing this you know what I'll do is I'll Traverse through the second set or the first set and check if the element is present in the first set or not so uh I will Trav to the second set and I'll check if the same element is in the first set or not if it is in the first set then I will add it to my array so let's suppose this is my resultant array I'll be right here and I'll check if two is present in the set or not it is present right so I will add this to my answer and since this set does not contain any other values that's it suppose if we have three if we also have three here I'll check if three is present in this or not this is not the three this is a bracket uh this three is not present in this right so I will not add this and I cannot also add one suppose what if there is also one I'll check one is present in this or not one is present right so this is the answer so like this we're going to solve this what is the time and space complexity the time complexity will be you know we will be traversing through the whole first will which will be let's say uh the let's say the length of the first array is M and the length of the second AR is n so it will be order of M plus we'll also Traverse the entire secondary right order of n plus and we again Traverse the set two right so the set two in the wor case can be order of n right so this will be our time complexity and what is the space complexity we're using a set for the first shr so at most there can be M elements right and in the second set there can be at most n elements right so this is our space complexity and in the interview the interviewer might ask us to optimize the solution uh what we can do is we can use uh an we can tradeoff between the storage and the time complexity right so in the second approach what we can do is we can sort this can s this array can sort the array and use two pointers approach so uh let's take this example so let's say this is our uh this is our array and we're going to use two poin approach so what I'll do is initially I'll s this two when i s this it will become four 5 and 9 and when I S this it will become 4 comma 8 comma 9 right so what I do is I'll keep a i pointer here and I'll keep a j pointer here so this is my array one right this is my array two so I will use a set in order to store unique elements right unique common elements so what I'll do is uh I'll check if my pointer if my I pointer pointing to the element and the J pointer which is pointing to the element if these two elements are equal or not these two are equal right so it is an intersection so I will add this to my set then I will move I'll move both the pointers at the same time since it is a common element right so I will move both the elements will become I and this will be a right now I'll check if these two elements are equal or not these are not equal right so which pointer am I going to move so if I move this pointer which is pointing to five if I move this pointer it will be pointing to 9 right so when we move our when we move the pointer which is pointing to the highest element there is no way that we're going to match with this right so we'll try to match this since this pointer is pointing to the smallest element if we move the pointer which is pointing to the smallest element then we can get the element which is just greater than this and there may be a probability that it will be easy uh it will be a it will be equal to this pointer right this element right so that's why we'll always try to move the smallest element if you move the pointer which is pointing to the largest element there is no point right these two will never be equal right so that's why I'm going to move this PO this will become G now I'll see that five and8 these two are not equal so which pointer am I going to move if I move my eight it will point to 9 and will never it will never be equal to five right so that's why what I'll do is I'll move my smallest pointer it will be I so I will Point here and I see that again these two are not equal and my J is less than area of J is less than AR of I right I move this point J and 9 are equal so I'll add this two and I'll move both the pointers at the same time so my I will come here and my J will come here right so when one of the indexes goes out of range then it is the end of the uh iteration right then we'll stop and we'll just return the result we'll uh we'll create a new array and store these elements in the array and we'll WR the answer right so that's what we're going to do initially what I do is I'll take a set as so as I have already said I'll Sol the I'll Sol both the arrays th one to and I take two pointers i = 0a j one to and I take two pointers i = 0a j one to and I take two pointers i = 0a j = to0 and while I less than num one = to0 and while I less than num one = to0 and while I less than num one length and J less than to do length if both nums one of I is equal to nums 2 of J what I'll do is I'll add this to my set right set add nums I can also add I'm of J as well but I'll always add the first one uh and else if my nums one of I less than nums of then I'll move my I pointer this is very similar to the thing that we did yesterday right next is problem and at the end I'll create aant array the size of the set and for every element I'll add it to my result again time here oh when we are uh when we are adding both the elements we just need to increment both the pointers forgot to do that yeah try to some with this yeah it's getting accepted guys and let's look at the time and space complex the time complexity for sorting the both the arrays will be order of n log in for the first sh and Order of M log M for the secondary we add this two and the space complexity is order of n or M right depending on the number of unique Elements which you be present in the set so that's it guys for this video thank you | Intersection of Two Arrays | intersection-of-two-arrays | Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must be **unique** and you may return the result in **any order**.
**Example 1:**
**Input:** nums1 = \[1,2,2,1\], nums2 = \[2,2\]
**Output:** \[2\]
**Example 2:**
**Input:** nums1 = \[4,9,5\], nums2 = \[9,4,9,8,4\]
**Output:** \[9,4\]
**Explanation:** \[4,9\] is also accepted.
**Constraints:**
* `1 <= nums1.length, nums2.length <= 1000`
* `0 <= nums1[i], nums2[i] <= 1000` | null | Array,Hash Table,Two Pointers,Binary Search,Sorting | Easy | 350,1149,1392,2190,2282 |
684 | hello everyone so let's talk about a redundant connection so you are giving the um direct graph right and then you are given to the array and which you generate on that request so you want to return the edge that is removable so if you want to remove two or three uh the graphics still connect right if you want to remove one two it's still from there one three so command the problem is you want to remove the edges from the last right so um this is going to be pretty straightforward so uh which is what you're starting from the beginning and then you probably just connect just keep connecting and then we want to just connect two and three right you just have to make sure do you have a connection between what two and three beforehand right so in this uh in this question you can use the union fine so union point is pretty straightforward and if you don't know you can just figure it out right so pause the second just look for the unit fine and if you finish the video then i'll probably just come back to the solution so i'm going to just create a class for unit 1 and then i'm going to have a parent array so for everything don't know for every single note right if i come here one two right so for my one parent is actually equal to two so this is how i connect but by default right you are going to connect u uh you to yourself so which is what i initialize right so union fine and i've been passing on you play the cycle of the note right and then i'm going to just initialize my paragraph and i'm going to okay so the problem is what uh our index doesn't stop from zero right on the cell phone one so i need to give the extra space so i'm going to say i could myself so i'm not actually connect any single note to any single object right so this is so public uh probably uh for this time we use boolean you mean in x in one right i'm gonna i'm going to start i'm going to just pass in two h right one or two right so one into passing to the union so if they are connected together i'm going to return false if i didn't connect i'm so uh so let me just give a little comment so check if they connect or not right so um and then if they didn't comment then and should constantly try and this is going to be pretty much it right so beforehand i need to what i need to know how do i actually find my uh connector beyond so which is parent beyond right so i'm going to say fine since i'm using the in the ring i'm going to return the image so i'm going to pass more fasteners right so i'm going to say well no uh well apparently so you are going to find a parent right and while parenting is not able to know so basically you want to just keep going up right so this is what this is uh basically you by default you're pointing yourself but once you're union you'll connect to others so uh just making sure like if they are another thing if they are all the same with me you are just basically finding your answer right so you will just return very wrong here so i'm going to just keep updating my parent not equal to what able to parents you know so which is what finding your grandparents right then you just keep update your parents uh pointer so uh once i have it i'm to say well i'm use the h root f equal to one x two square it will define what right and then keep traversing so i'm just making sure uh if root x is not equal to u y if they are not the same so which means they are not connecting together right triangular loop x 2 y and i will return true so i'm making sure they connect right so if loop if they are not the same then making sure they come and that will change right over here so if they are already connecting together i'm going to switch and pause all right if you know the logic then come back to the solution so main function union fine i'm gonna put uf instead right and then new union font and then the size is going to be y the age of the edges of that and i'm going to travel from here to the arena so i need to keep calling my union because union is a boolean right so if i'm going to just use a negation right over here i'll talk about it later so if you use the union and i'm talking about zero formal equals one right so what does this mean by in the two input which is age one and two and i'm gonna connect together if they do not have the same pattern right and making sure they have the same parent later on right now return true so at first this is what turns true but you need to get like you need to get the true value so which is false right then you pass me one and three uh one and three later on the root value is not the same so it is still false right because i am gay right so i passing the true over here true negative is false right but when you're passing two and three uh two and three should be one should be fourth already because i already update what i really update one and two one and three um inside my uh theme parent so this is what return the edges i found which is removable right and any other return one to mt already and i hope i don't make a mistake yes i don't all right so let's talk about timing space in your face so for the stage right this is what all of the e represent the age of the length of the age rank so if you have a three then probably you'll have three noises because they will just uh continuously uh increasing by logic for sure like probably you have like one two and 100 million so probably this is actually this is that your wall because you have to traverse you have to initialize from one to one i mean for the problem is that you're just increasing by one union for every single node right so in this case it is all of e right for the time this is prime right this is all of e as well because drivers the land of the edges and you also have a parent in inside a union so kind of space all the same so if you have any question regarding this type of question uh one thing you can do is well search on my channel and type union fine so there are a couple questions i already finished it might not be very clear because due to my improvement right so uh if you have any question leave a comment below subscribe if you want it and leave a like alright see you later bye | Redundant Connection | redundant-connection | In this problem, a tree is an **undirected graph** that is connected and has no cycles.
You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. The graph is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph.
Return _an edge that can be removed so that the resulting graph is a tree of_ `n` _nodes_. If there are multiple answers, return the answer that occurs last in the input.
**Example 1:**
**Input:** edges = \[\[1,2\],\[1,3\],\[2,3\]\]
**Output:** \[2,3\]
**Example 2:**
**Input:** edges = \[\[1,2\],\[2,3\],\[3,4\],\[1,4\],\[1,5\]\]
**Output:** \[1,4\]
**Constraints:**
* `n == edges.length`
* `3 <= n <= 1000`
* `edges[i].length == 2`
* `1 <= ai < bi <= edges.length`
* `ai != bi`
* There are no repeated edges.
* The given graph is connected. | null | Depth-First Search,Breadth-First Search,Union Find,Graph | Medium | 685,721,2246 |
442 | detecting duplicate items in a list is a problem you tend to run into quite often and there are many ways to solve it from direct to optimized this problem has the following list of eight elements have two constraints first no number in the list the little owl indicates a list item can have a value greater than the size of the list itself which here is eight second find all the numbers being repeated twice only the trick in this question as with most of these type of questions is given through the constraints it says that all numbers in the list will be equal to or lesser than the size of the list so if there are eight elements i will only have the numbers 0 1 2 three four five six seven and eight which luckily is all the positional markers of a list so i'm going to make another list with an exact same size and make all the values and all positions equal to zero then i'm going to loop through or go through each item in my list every time i see a number i'm going to find its index the blue boxes and increase that by one i'm keeping count of the number of times a certain number repeats note that 4 is the fourth element in the output list but it will be at index 3 since we start from 0. as i'm moving through this i add a count to its location in the output list and move on when i see 3 i add one to the third location in the output list when i see two i add one to the second location in the output list when i see seven i add one to the seventh location in the output list i see eight i add one to the eighth location in the output list i see two again i add one more to the second location i see three once again i add one more to the third location and finally i see one so i add one to the first location in the end i print out the list the second list i mean and i know which indexes had duplicates and i can do unspeakable things to them here's the code for this i make two lists same size i loop through one then add a one to the value at the second list position when i come across the number of this list position in the first list that was a mouthful so i urge you to solve this by hand and make sure you get the correct sequence of events how about a more advanced way that reduces space or time complexity yes you remembered right we are talking about the algorithmic complexity from way back then we will use the same array and a much smaller list which is initially empty how do we do this by using a minor trick with multiplication and absolute value remember that the absolute value operation gives you a positive number whether you feed it negative or a positive number as i'm moving through this i multiply the location where this number comes by a negative one so four will be the fourth element at list index three or the first position because of the zero effect and we make the value sitting at index 3 a negative number notice this little red flag i put here this is to indicate that this number representing this location for an index has already been seen these flags will prove handy soon enough don't worry this will not mess up anything as we will be using the absolute value operation or the positive value of every number will be gotten because of that so we don't run into any negative indexing problems when i see 3 i go to its list location at index 2 or the third position in the list and multiply that by negative 1 which makes it 2 negative and we put a flag here when i see negative 2 i go to its absolute value list location at index 1 and i multiply that by negative one which makes it three negative and we put a flag here when i see minus seven i go to its absolute value list location at index six and i multiply that by negative one which makes the 3 negative and i put a flag here when i see 8 i go to its absolute value list location and index 7 and multiply that by negative 1 which makes the 1 negative and i put a flag here now i'm seeing that the 2 is repeated i go to its absolute value location at index 1 and before i multiply that by negative 1 an alarm goes off because there's already a flag here which means it was negative before telling me that i will be doing multiplication by negative 1 twice this means that 2 is repeated so i add 2 to my output list and leave the flag untouched ah now again i see 3 repeated i go to its absolute value list location at index 2 and before i multiply that by negative one and alarm goes off because there's already a flag here which means that it was negative before which sets up this alarm telling me that i will be doing multiplication by negative one twice this means that three was repeated twice and so i add three to my output list and i leave the flag untouched finally i get to the last element when i see 1 i go to its absolute value list location and index 0 and multiply that by negative 1 which makes the 4 here negative and i put a flag here after all this have a much smaller list containing the duplicates of 2 and 3 only and the original array or list with some negative flags question how do you think we set the alarms which alert us when a duplicate is detected conditionals here if else of course let's see how this looks like in code we want a condition to be satisfied here which is what we're checking for a flag or a negative number already exists it is a simple check we see if the number at an index that we're looking up is already negative or less than zero if yes that means that we did the multiplication by negative one earlier so this second round is for a duplicate of the same number that gave us this index this might seem a little confusing but once again redo the approach yourself by hand and then compare the answers with the code if you're going for coding interviews this will be a bread and butter coming up with a solution that works we call this brute forcing and then fine tuning it to save either space or time complexity | Find All Duplicates in an Array | find-all-duplicates-in-an-array | Given an integer array `nums` of length `n` where all the integers of `nums` are in the range `[1, n]` and each integer appears **once** or **twice**, return _an array of all the integers that appears **twice**_.
You must write an algorithm that runs in `O(n)` time and uses only constant extra space.
**Example 1:**
**Input:** nums = \[4,3,2,7,8,2,3,1\]
**Output:** \[2,3\]
**Example 2:**
**Input:** nums = \[1,1,2\]
**Output:** \[1\]
**Example 3:**
**Input:** nums = \[1\]
**Output:** \[\]
**Constraints:**
* `n == nums.length`
* `1 <= n <= 105`
* `1 <= nums[i] <= n`
* Each element in `nums` appears **once** or **twice**. | null | Array,Hash Table | Medium | 448 |
413 | hello everyone today we are going to cover arithmetic slices so we are given an input of an integer array and we have to return the number of arithmetic slices in given array so what is arithmetic slice a sequence of number is called arithmetic if it consists of at least three elements and if the difference between any two consecutive element is the same so there must be a sequence inside the given array whose difference should be same and the sequence must be at least three elements now let's see this with an example here is a given example array so now let's start checking the difference between the first element and second element the difference is one and the second element and the third element the difference is one again so one two three forms a sequence that is called arithmetic slice so far the arithmetic slice we found is one so now it is said that the arithmetic slice can be at least of three elements or more than three elements in this case we already found one two three as an as one arithmetic slice and further moving and checking what is the reference so between three and four the difference is one and between four and five again the differences one so now the whole one two three four five can form an arithmetic sequence so that is a second sequence in between if you see one two three four alone forms another sequence so now the sequence total sequence is three the possible sequence from the given array is one two three four five and it can be two three four or three four five or two three four five so we can form six sequence from the given array so let's see how are we going to solve this problem can be solved by you five different approaches and in this video we are going to cover few approaches of them so obviously our first approach is going to be brute force so now in brute force as usual we'll be having two pointers i and j i points at the initial element and j point is the next element and j moves all the way till the end and scan every possible sub array and calculates its consecutive difference and if the difference matches then it gonna count every time we found a summary that matches all the consecutive differences same so this is pretty simple straightforward algorithm we use for every array programs and the time complexity of this is going to be big o of n cube and further if you scrutinize it is going to be big o of n square but we want this algorithm to run in linear time so how do we do it we gonna use dynamic programming so here we are going to arrive at the solution for every sub problem step by step and finally gonna get into our optimal global solution for the given problem so our dynamic programming is going to have a dp array of same size set of given array numbers as i always say each of this cell represents a sub problem so they're gonna make get a solution of each sub problem step by step and gonna arrive at our optimal solution at the end so now let's start filling our array the problem statement says there should be minimum or at least three numbers in a slice so let's fill zeros in first two numbers since we cannot make them alone a slice moving on to our third number five so now we are going to check if the previous two numbers are having the difference and the difference is same so the difference between 1 and 2 3 is going to be 2 and 3 and 5 is going to be 2. so now yes we formed a slice so in this case we found one slice so we are going to update here to one so far the count or the sum is one and now moving on to our third element six so now we are going to ask us a question that whether we can start a new slice from this element or we can append with our previous slice in this case find the difference is again two so you can append this to a new series so far we found one so by adding this one it is going to become completely a second sequence or slice one three five is the first slice we found so by adding six it can be one three 5 6. so we are going to add 1 plus 1 here so far we found 1 and with that one we found one more so we are adding 2 here so now we are going to update our sum to three why because the sequence can be one three five six or three five six so this is this can be one sequence by using six you can form two sequences that is one three five six and three five six that is why we have updated here at this position two so now our sum is gonna become 1 plus 2 3 let's move on to 10 we are going to ask the question again whether we can form a sequence from here starting from here or we can append the number to the existing slice so let's find the difference is 4 which is not matching the previous difference so we cannot append this 10 to the previous sequence so it has to be 0 but later we can check whether we can form the slice or we cannot include this number any in any slice but so far we cannot append it to the previous sequence so it is 0 and sum is still going to be 3 so now let's moving on to 15 the difference is 5 if you check the previous difference and the active difference it differs so you cannot include 6 10 15 so moving on to the next number 20 the difference is 5 again so from 15 the previous difference is 5 and the after difference is also 5 so you can form a minimum sequence with 10 15 and 20. so we found a new sequence so i am going to add one here so as we found new sequence the total sequence or the sum is gonna become four moving to our 25 the difference between 20 and 25 is gonna be five so now checking from 20 the previous difference is 5 and after difference is also 5 so now we can append this 25 to the previous slice then the sequence it can form with 25 is gonna become two that is the previous value plus one in this case we gonna add sum with 2 and the sum becomes 6 and moving on to 28 the difference becomes 3 which is not matching with the previous difference and so we cannot append this with the previous slice so we are going to put 0 here moving on to 29 the difference is 1 it is not matching with the difference between 25 and 28 so again it is going to be 0. so moving on to 30 the difference is 1 again so here you found one more sequence that is from 29 the previous difference is one and after difference is also one so we can form one more sequence or slice 28 29 and 30 so now we found one more sequence so let's update it to one and it adds to the sum and the sum becomes seven as you don't have any more elements left next to 30 and the sequence should have minimum of three elements it stays zero and the final result is going to be seven so this algorithm actually works in big o of n time complexity and big o of n space complexity so let's see how are we going to code it as we saw examples let's directly code as i said i'm going to have an integer rate of size given array and an integer sum so i'm gonna start my array from third element because it should have at least three numbers in a slice since the index starts from zero i'm gonna send it to two we are going to compare if array of i minus 1 minus array of i minus 2 that is from that element and the previous elements difference is equal to from the next element and that element if that is the case we are going to update our tv with one plus value in previous index and we're gonna update our sum every time with the value of dp and finally we'll return sum so let's run so yes this runs fine actually as i said this algorithm is going to work in brick of n linear time complexity and we go off here and space complexity you can modify the same algorithm to have a constant space that is instead of using a dp array i'm just going to use a variable db it is actually going to hold value of the calculation at every stage so simply instead of array i'm going to declare dp at places of db array i'm gonna use just the variable this will also works fine hit submit i forgot to add one condition that if it matches then it is going to update the tp if not we are going to update it to 0 because by default in java the integer ras will be filled with 0 so if we are not updating that vp of i it is going to have 0 and sum is going to add with 0 if not if it is a variable it will be holding the previous value so the test cases fails so in this case we have to update it with 0 if it breaks the chain of consecutive differences so now let's submit yes it is accepted it again works with the same time complexity but we just changed it to constant space so thanks for watching if you do like the explanation hit like and subscribe thank you | Arithmetic Slices | arithmetic-slices | An integer array is called arithmetic if it consists of **at least three elements** and if the difference between any two consecutive elements is the same.
* For example, `[1,3,5,7,9]`, `[7,7,7,7]`, and `[3,-1,-5,-9]` are arithmetic sequences.
Given an integer array `nums`, return _the number of arithmetic **subarrays** of_ `nums`.
A **subarray** is a contiguous subsequence of the array.
**Example 1:**
**Input:** nums = \[1,2,3,4\]
**Output:** 3
**Explanation:** We have 3 arithmetic slices in nums: \[1, 2, 3\], \[2, 3, 4\] and \[1,2,3,4\] itself.
**Example 2:**
**Input:** nums = \[1\]
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 5000`
* `-1000 <= nums[i] <= 1000` | null | Array,Dynamic Programming | Medium | 446,1752 |
1,684 | Hua Hai The Kid Number 101 Title Se Is Account Number Accident Distic And The Problem Description Yagya Ministerial Out In The River Systems And Don't Stop This Problem Virvar Problem Subscribe And Subscribe The Picture And Subscribe To Feed Subscribe Chhindwara To Middle One Playlist Voice Assistant Setting On In Which is the Longest River in Middle Age Subscribe Now to the Subscribe I have subscribed this problem do and tell that police character of birth to order unique love letter to president on this page for all ki taisi colony Kar do ki Vivek Disayla Distributor Test Deposit All put all the best All characters set ki Nagaur ki second of words ki past The individual string of words is on Kar do Ajay ko do Ajay ko ab to aadat si The one variable not Considered 120 During A Balance Merchant Request To Apology Letter Gifts And Checking Point In Different Forms And Avatars Subscribe This Video Not 9th A Consistent Latest Updates Not True Any1 Preventing Ka Answer To Answer Wisdom This Point Of View Account Subscribe Not Attend A Meeting On So one more thing later come Neetu Saturday Nunihal which Bigg Boss gift banister gifting fruit and all the best wishes for these string into a the first method then return pressure yourself now dish notification come and give that his nature irritable loot 202 Aadat Sudhar Top This Problem To Like Positive Pass Turn On The 55572 Printer To The Amazing 2.1 President Mirwaiz More The Amazing 2.1 President Mirwaiz More The Amazing 2.1 President Mirwaiz More Subscribe Thank You | Count the Number of Consistent Strings | find-latest-group-of-size-m | You are given a string `allowed` consisting of **distinct** characters and an array of strings `words`. A string is **consistent** if all characters in the string appear in the string `allowed`.
Return _the number of **consistent** strings in the array_ `words`.
**Example 1:**
**Input:** allowed = "ab ", words = \[ "ad ", "bd ", "aaab ", "baa ", "badab "\]
**Output:** 2
**Explanation:** Strings "aaab " and "baa " are consistent since they only contain characters 'a' and 'b'.
**Example 2:**
**Input:** allowed = "abc ", words = \[ "a ", "b ", "c ", "ab ", "ac ", "bc ", "abc "\]
**Output:** 7
**Explanation:** All strings are consistent.
**Example 3:**
**Input:** allowed = "cad ", words = \[ "cc ", "acd ", "b ", "ba ", "bac ", "bad ", "ac ", "d "\]
**Output:** 4
**Explanation:** Strings "cc ", "acd ", "ac ", and "d " are consistent.
**Constraints:**
* `1 <= words.length <= 104`
* `1 <= allowed.length <= 26`
* `1 <= words[i].length <= 10`
* The characters in `allowed` are **distinct**.
* `words[i]` and `allowed` contain only lowercase English letters. | Since the problem asks for the latest step, can you start the searching from the end of arr? Use a map to store the current “1” groups. At each step (going backwards) you need to split one group and update the map. | Array,Binary Search,Simulation | Medium | null |
212 | Loot hello everyone welcome to my channel today is the last day of miding challenge and problems but search to sleep very famous problem in the interview problem given alms from all must be constructed from subscribe and subscribe to that beer given a list of birds like and Speed and give that subscribe The and Speed and give that subscribe The and Speed and give that subscribe The Channel and subscribe the world will be lit and tried to explain in detail to your show Lakshmi increase font size or fennel birds laugh so much that the show let's pick one word like to veg dishes from dictionary word from dictionary subscribe The Channel and subscribe the Video then subscribe to A Similar ES Look for Being A This Weekend Seervi Chief York City Video [ Seervi Chief York City Video [ Seervi Chief York City Video Subscribe Now We Are Subscribe Now We Are Subscribe Now We Are the subscribe for More videos Study and Nurses and You Will Give Way To That And Start Processing Word Character Director And Look For Director Retired And Old Effective Work And You Will Then Its Existence After Birth And Always Till Twelve Thursday Subscribe To The Page Loot And Similarly Another For You Which Will Go From Pimple 05 2012 Coat Pant And Will Defiantly From Fear And Check Video Subscribe First Character Of Board Of Directors Understand 111 Chair With New Place Ten Old Is Gold And Will Be Difficult David Like Subscribe And Hidden Under A And S The Amazing Not Already End The Bare Difficult For Sale That NDA From This Position Or Length Deposit Language On The Length Of The Running List From A Guy Will Start From 2nd Id Subscribe Scanner For Mother Of All Dictionary Word Problem Implementation In Challenge Problem Solve Thursday To 100MB Family English to a small character morning user of 600 person node was the state champion use the 6 characters of but that try note sadswini report in this explanation powder I will form with what we will do subscribe from roof but nothing is the receiver Thursday subscribe and after That will go down in the 30-day subscribe the world will creative world only cases will result in the reel that encounter set an other is the prohibition of the same is simrely are taking I am so this one try 200 what we can live with considerable Tribes End Will Start From The Body And Look For The Character First Character Subscribe 0 And Call Bhi Dad Check Weather It's Not End Of The World In Your Cities End Of The World Will Update You Are Not No Witch Will Start From Drut The Current Month Witch Will start from Tirunelveli Updates 1359 character idont front will just born in this will call girl try note in the definition in the direction here and before the will mark subscribe kare subscribe and subscribe the Channel subscribe from all over the country in That Young Bullet Bike United States North End Speed Because United States North End Speed Because United States North End Speed Because Minute You Subscribe Mode Of Are Of Midnight Children That Children Which Is New Line Mode Of Sciences String Cheese Word Okay So No Need To Build Right Method And Will Return Subscribe Will Describe The Calling All Cars Will subscribe appointed nodal key and will scan from all the words 100w in words and create account one way current track point to the root of the world in more in all the w and have oh if ever met attract all the character and reduce subscribe share Subscribe 920 Check Children Who Is Not Updated On This Video Channel Bellini Slice The Current Dot Children Of Ideal To New Note In Hindi Will Update Our Current Next David Question You Can Not Familiar With The Dare Devil Children That You In1 Switch Debit The current top updater and current wave in Indian villages in the middle of nowhere in the list of subscribe to that encounter dad be lit the board inter result 2018 youtu.be hai android plus and after that again for intense physical to 10 board of zero Dot NZ Plus absolutely different method like share and subscribe and which excess dry fruit and the result 10th result private type subscribe this Hair that in tie in DJ and within that rose against British rule in the list of strings paints side member Martin Signature for different method to know what will happen first pick character from the board exam today subscribe star channel subscribe 9 that all will change it's there is already children and product children by which 0120 subscribe button hai ka anniversary thing novel chakli root word is not Equal To Know Which Mins Of Wave The 15-minute Bieber And Swift We Will 15-minute Bieber And Swift We Will 15-minute Bieber And Swift We Will Update Blocked Vikas Vihar The Pirates Rubaru Thoughts Children Of - Withdrawal David Results And No To Do Vikram In New Delhi Station Vikas Dushwar Meghwal subscribe in this great content on website board 921 subscribe And subscribe The Amazing side 220f clean board IJ - 1m and roots oil 220f clean board IJ - 1m and roots oil 220f clean board IJ - 1m and roots oil result that similar when check this is loaded on board land minus one which will call the download note members Shapath Call Nikli Not Believe In Myths And Subscribe Our Production And Miss Call Waiting To Face Of Godhead Who Decide Plus One More Interest Result Hai Jai Hind Is College Down SIM LED Light College Is J So 10th Board Of 0 - 110 Is J So 10th Board Of 0 - 110 Is J So 10th Board Of 0 - 110 Exactly Definition Of Board Form Of logic plus one guava result picture volume is all the phone calls and direction call me will be stretched be ours and in impatient tractors pe this is the back track sedan app solutions member jhawar courier hai so let's scum pilot 133 compile and expected result urgent Matter 1658 Solution The Cities Accepted This More Share Like Too Many Problems So You Can Do The Practice Loop Twitter The Amazing So Let's Talk Time Complexity Subscribe Our Dictionary But Number Of Columns Of Power Grid Is So For Every Word Chief Guest Calling In The For Directions on this will v40 power everyone along in the voice of falling for every bird Video plz subscribe to subscribe and subscribe the Channel Please subscribe and subscribe the Channel Ko Main Bechain Se Id Total Length Of The World In More Thank You Like My Solution Please Hit The Like Button and subscribe To My Channel for The Upcoming July Series Jewelers Lootkand Contest Problem Idea Share My Videos A | 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 |
41 | hey everyone today we are going to serve the little question fast missing and positive and you are given unsorted integer array numbers return the smallest missing positive integer you must Implement algorithm that runs in o and a time and I use constant extra space so let's see the example so you are given one to zero output E3 because the number in the range one twos are all in the array so we have to return the like the smallest missing positive integer so that means um we always start our Target is always start from one so um but uh we can find the one in delay so next we find the two so that's why output is 3 in this case and example two um you are given like three four minus one and the output is two because uh so the target one is uh here and then next we need to find the two but we have like three and four so that's why output is 2 in this case before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get a code from GitHub for free so please subscribe my channel hit the like button or leave a comment thank you for your support okay so let me explain with this example three four minus one and so description set we have to solve this question with like a linear time and a constant space but I think I it's good um it's good for you to share your like a multiple idea and to the interviewer in their interview so and then explain why you choose that solution so um that's why uh let me start with like a um like a analog and solution and so to solve this question first of all we have to find the um like a positive number so we don't need a like a negative number so first step is remove the negative numbers so in this case only -1 negative numbers so in this case only -1 negative numbers so in this case only -1 so in the case input array should be 3 4 1 right and then next we will sort this input array with ascending order like a 1 3 4. then finally we will iterate through our sort it is this one and I look for the smallest missing possible positive integer so we can do this by like a keeping track of like a Target value so let's say a Target and as I explain uh earlier so Target always start from one and then compare this target to like each element and if the element is equal to Target we will increase the Target by one and then continue and if the element is greater than Target then we will have found we have found the smallest missing positive integer and then we can return it so in this case um we need to start from one and then um now we find one and the target is one they are same so that's why we increase Target by one so that means two and then move next and then we find three and the three is a greater than two so that means um uh this input array is like a is missing uh two right so that's why we should return two in this case so that is a basic idea to solve this question and uh this question this solution should be a n log n time complexity because we sorted input array here and a space complexity is a o1 or um on some programming language use like a linear time for like a sorting so it depends on the language so that's why in this case space complexity is o1 or on yeah so let's get into the cold okay so let's go first of all remove all non-positive integers remove all non-positive integers remove all non-positive integers so nums equal n for n in numbers and if n is greater than zero so we keep on the positive integers and then after that we sorted positive integers then initialize Target number it always starts from one and then start looping for n in numbers and if n equal Target in that case um we are the plus one to Target cross equal one and the else if n is greater than Target in that case um we are missing the target number so just return Target and then um after that if we reach the end of the list that means the smallest missing positive integer is a length of numbers plus one so just with um Target yeah so let me submit it yeah looks good and the time complexity of this solution should be uh order of analog n because we sorted the input array and the space complexity is a o1 or on um it depends on language because of sorting here yeah next so I'll explain how to solve this equation with linear time and the constant time okay so let me explain with this example so to solve this question with a linear order I use the three Loops in the first loop I remove the value which are less than or equal zero in this case -1 than or equal zero in this case -1 than or equal zero in this case -1 so after I finish the first Loop so I will get 3 4 1. right easy and then in the second loop I use each value as a index number so we uh first of all we find the three so index number is like a three minus one and which is two so look at the index two and then we find one and if this value is greater than zero in the case convert the positive integer to negative integer so which is a minus one in this case and then move next rewind the four minus one and three so look at index three but that is out of bounds so we don't do anything and then move next and now um actually uh index 2 is not one actually minus one so how can we get uh um index number from minus one so it's simple uh combat minus one to like absolute value so in that case uh absolute value is one right so one so absolute value minus one is one uh zero right one minus one zero and look at the index 0 and the three is a uh greater than zero so in that case uh convert three to minus three then finish so in that case four is a step four right and then I finished the second Loop in the third Loop um iterates through from index Terror and then find a fast positive integer which is four so in that case um so in the second Loop we convert the like each value to the index number so that means if we find a first positive number that means we actually missing the that index number so in this case um we have an index number index 0 and the index two and uh we missed the index one so that's why in the suburb we first of all we find a fast positive integer and a combat index number to real number so in that case um four is a index one so convert index one to real numbers or just add plus one so that's why uh in this case um we should return two in this case and let's check so this is a input array and uh of smallest positive number is one and then so we have one and then next uh Target number should be two but as an O2 in this case so that's why we should return two in this case and yeah it looks correct so that is a basic idea to solve this question so without being said let's get into the code okay so let's go first of all remove the value which result will equal zero so numbers equal and n o n in nums and if n is greater than zero so we keep the value uh is uh which are greater than zero so that means remove the value which are some y equals zero so this is a fast loop and in the second Loop convert the each value to index number so for n in nums and then first of all calculate the index number index equal so as I explained earlier I use a absolute value because uh we will find a negative number so as and n minus 1. and the if index number is less than length of input array and the numbers index is greater than zero in that case um convert positive number to negative number and the numbers index multiply equal minus one and then we finish the second Loop in the third Loop we will find a fast positive integer so for I in branch and the lengths of input array and then if numbers I is greater than zero in that case just return index plus one so we convert index number to real number because uh in the second Loop we convert the real number to index number so just a combat um like an opposite way and then if we finish the third group in that case um the smallest positive number should be uh length of input array plus one right episode just return length of input array Plus 1. yeah that's it let me submitted yeah looks good but uh yeah this is our own solution um but uh um I can throw us on the previous one like a login version um I think that's because I think uh um I try many times I hope but definitely uh this is a Time complete this solution is like a on solution we just Loops three loops right this is a fast loop and a second Loop and the third group so yeah time complexity of distortion should be order open and then space complexity is a one because we don't use external data structure just uh use the input array yeah so that's why uh 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 or leave a comment I'll see you in the next question | 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 |
35 | guys today's problem is search insert position and um this is simple search question searching question where we have an integer array it is uh sorted so from um from one to six it is um given in sorted array a sorted manner and we have one target variable and we need to return its position right where can we insert it in this sorted array and we need to write this algorithm in big o of log n runtime complexity so this is simple question of binary search algorithm and binary search is one of the algorithm which you should know by heart and it is very helpful in many cases we'll use binary search algorithm and for the binary search algorithm the question can be asked in multiple ways so this is very helpful algorithm and yeah and whenever we use binary search algorithm the runtime complexity will be b of log n because always we are if you know how we are using binary search algorithm it's like one two three four five six suppose uh this is our array or input so what we are doing is in each iteration we are taking half of this input and searching our element so suppose in the first iteration we have this whole input but in the next iteration we will take maybe right or left half part of this input so in the next step we will have four five six and again in the next step we might have uh five six and in the next step we might find five so this is possible uh and that's why we have big of log n because every time we are uh dividing uh the input in two parts and then searching in it okay let's check the company's facebook apple amazon bloomberg vmware so not lots of company but maybe because they are asking other questions which includes binary search but it is um as far as my experience is uh in many other questions we might see this the same algorithm okay so let's start it uh so in the binary search we always uh divide our input in half so that's why we will have one integer called then we will have left is equal to the starting of the array and we'll have a right which will be the end of all right and we'll do this my left is less than or equal to right so if you have seen my previous video i was explaining two pointer solutions so again this one is two pointer solution we are using left and right two pointers and we'll run this algorithm until uh left and right mids okay so let's initialize mid so for that we need to find the mid element of the array so the idea is suppose this is the input so and the key concept is this input is sorted so if we check whether the mid element here are three and five we can consider both but we'll we can take three here so we can check our target element is greater than three it means uh our target element will be in uh right side of the array or can be in the right side of the array and uh now when we go here we have two elements and let's say the mid element will be the five so we can check with the mid element if it's the target one we can just return it and if it's not the target one we can again divide it uh in two parts okay so that's the gist of the algorithm so first let's find the mid element which is left plus right minus left divide by 2 so it will be uh let's say we have one two three four five six seven eight let's say this is the input then uh let's take odd input i think that would be easier then in that case what will be left is equal to 0 right is equal to 8 because it is starting from zero and length is nine uh nine minus one which will be eight uh and mid element will be uh left uh sorry mid element between b 0 plus 8 minus 0 divided by 2 which will be 4 so our mid element will be 5 because it is zero based array so five will be our mid element and we let's say in this case our target is nine then we know that our target is greater than mid element in that case we will consider 6789 is our input and do this process again so our input will be 6989 our left is equal to five because again it's zero based array and right is equal to eight and mid is equal to five plus eight minus five divided by two which will be five plus 8 minus 5 is 3 and if we divide it by 2 it will be 1.5 but because we are taking it will be 1.5 but because we are taking it will be 1.5 but because we are taking it as integer it will take is 1 and the mid will be 6. uh so our mid will be 6 so our mid will be here 7 and again we know that 9 is greater than 7 then we can do this again taking 89 as our input and that's how we go ahead until we until mid is 9 and we can return its index okay so we found the mid element now if numbers of mid is equal to target then we can return mid uh if our target is less than numbers of mid then we will just change our right index to mid minus one right pointer to mid minus one um and else left is equal to mid one otherwise we will increment our left pointer and at the end outside the while loop will return left let's try running it okay so it not expected a solution or answer yeah okay let's try submitting it okay so this is simple binary search algorithm there are many other algorithms but i think this is the famous one that's it for today's video if you have any questions comments please put it in the comments if you have better solution or better way to do it let me know see you in the next video | 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 |
88 | hey there today we'll solve one of the problem it could merge sorted in so which means that uh two sorted array will be given in the input and the number of elements in the array is also given and the first array will have extra space so that the one will merge it now the second area elements can also be tested inside the same okay so the num one the first array length will be equal to m plus m now to solve that uh there are multiple approaches which you can do uh but i'll uh today i'll be using a two pointer approach um so i'll use declare two pointer uh minus one and pointer p2 uh which will be equal to n minus one and i will declare one index which will be equal to uh m plus and minus one uh the reason of minus one is uh because the array starts with index zero that's why now uh i'll use a while loop to iterate while p two is greater than equal to zero now um the sorted elements needs to be uh inserted inside nums one so i'll have if condition if p1 is greater than equal to zero and nums one p1 equal to if the elements is equal greater than nums to p2 else what will do so in case if it is the higher than in numbers of index minus i'll store nums one p1 minus lines so i'm inserting from the last and uh in other case i'll just use nums to secondary element and the second point so every time this is greater uh from the end uh i'll insert from this array first and otherwise i'll insert from the array two to this index okay and i'm decrementing it so from in to first it will be inserted one by one um so let's see if this solves the problem so success means if this solution is correct um so the as per the problem statement uh we need to insert uh this sorted array uh inside the array num1 that was the requirement uh because uh num1 has the length of m plus n that's why i have added with inside nums one if it would be nums to uh in the requirement then we can insert it inside nums too and these are the conditions which is given uh you can pause the video and go through it there can be a condition like where num n is equal to zero or m is x f equal to zero okay so these conditions also uh is taken care of here so i hope uh this is helpful for the viewers and if you think uh you have any query or you can write in the comment section and yep and if you think the videos are helpful do like the video and subscribe to the channel | Merge Sorted Array | merge-sorted-array | You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively.
**Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**.
The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`.
**Example 1:**
**Input:** nums1 = \[1,2,3,0,0,0\], m = 3, nums2 = \[2,5,6\], n = 3
**Output:** \[1,2,2,3,5,6\]
**Explanation:** The arrays we are merging are \[1,2,3\] and \[2,5,6\].
The result of the merge is \[1,2,2,3,5,6\] with the underlined elements coming from nums1.
**Example 2:**
**Input:** nums1 = \[1\], m = 1, nums2 = \[\], n = 0
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[1\] and \[\].
The result of the merge is \[1\].
**Example 3:**
**Input:** nums1 = \[0\], m = 0, nums2 = \[1\], n = 1
**Output:** \[1\]
**Explanation:** The arrays we are merging are \[\] and \[1\].
The result of the merge is \[1\].
Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
**Constraints:**
* `nums1.length == m + n`
* `nums2.length == n`
* `0 <= m, n <= 200`
* `1 <= m + n <= 200`
* `-109 <= nums1[i], nums2[j] <= 109`
**Follow up:** Can you come up with an algorithm that runs in `O(m + n)` time? | You can easily solve this problem if you simply think about two elements at a time rather than two arrays. We know that each of the individual arrays is sorted. What we don't know is how they will intertwine. Can we take a local decision and arrive at an optimal solution? If you simply consider one element each at a time from the two arrays and make a decision and proceed accordingly, you will arrive at the optimal solution. | Array,Two Pointers,Sorting | Easy | 21,1019,1028 |
1,754 | hey everybody this is larry this is me going over q3 of the weekly contest 227 uh largest merge of two strings so actually this one pretty quickly i spent too much time at the end testing for this one because i wasn't sure um but i think this is uh greedy in a way and how is it greedy um i think for me during the contest the way that i proved to myself is green and i noticed that n is less than three thousand so i have to be um so n squared works but not so much in python i don't know why they do it that way um the only reason why my n square solution works is because in python the strings optimize the string operations are optimized but like if i had to rewrite my own string operations it would be too slow so i think that's actually um that's actually not great um yeah uh cool um yeah so the pro so this problem is going to be um and squares i said the intuition between behind the greedy is just for me during the contest is just try out every case right so this is a good case to kind of highlight it let me put it here for visualization let me also make a little bit bigger here um you know so the tricky part about this one is knowing that here the solution you actually because you know you take the a you don't know which a to take first um and the this prefix that you want to take is the one that gives you the largest lexographically earlier or like the graphically largest string right and that means that you're gonna go okay do i take the first character nope uh can i take the second character no um because they're still the same and then the third cat the three characters a b and d and because this is good then we just want to take this chunk because a b and d is before a b and c right so that's kind of one uh one case the other case that i tested and i did this during the contest it was decreasing right if it's decreasing i don't know b and c say um then you actually don't do the prefix right because d because then you do the greedy of um if they're the same um well i mean i do the same logic but i do one string at one character at a time so then i go okay c is better than b so let's take it from this string it's just a tiebreaker it actually doesn't matter in this case because then now you take the d and you remove the d but then here again because it's lexographically largest you take the second d and then so forth um and then you kind of keep on going that way and um and i think this is also uh for this problem if you have trouble seeing why for lexographically largest greedy works um it's because you know if you look at any given string uh let's say you know you have a um or maybe even do something like you know z sentences that says that right in this case you always want to optimize for the earlier character because in this case even though it doesn't matter what the rest of the characters are right because as long as we have b this is the string will always be larger than this string right so that's kind of the idea and we try to figure out how to be as greedy as possible and in a way that the code works fast enough right so that's basically the idea behind this problem um yeah um cool uh so then after that um basically i built a deck of the two words you could also use a pointer i think it's just i mean it's definitely the same but i like using a deck because it lets me do what i'm about to do but also just um yeah it just makes it a little bit uh clearer so that i don't have to understand it um though with any goes 3000 maybe that was a little bit cutting it close so i don't know we'll see but um but yeah but so i created a deck of the two words and then here this is kind of similar to merge sword uh where okay while they both have string i do comparison and again we use greedy because if the two characters are not the same whatever character you take there's no way to make it bigger by taking the other one right because it's smaller by default um so yeah um okay so yeah um and then after that we look at the entire substring which is what this does um and this is basically the same thing that we talked about earlier where we looked at you know if it's a b c d a b c e we want to be able to take uh the a from here because we know that um if there is a way to get to the e earlier so that's basically what this does is that it does a substring comparison and this is actually o of n even though this is very um you know this line is very short and that you know you might not notice it but this is o n because this the length of the string could be o of n and this is an oven comparison so yeah so that's why this loop is n square um but thankfully because i guess string comparisons in python is fast enough because they optimize it um that's my guess i don't know for sure but in any case that's you know this is n square and we just take the first character from that and we pop it um so that so the reason why we do it this way instead of taking the prefix is so that we handle both cases of increasing and decreasing uh strings and then at way end we just make sure that if there's any characters left we put in the at the end and that's pretty much it so what is the complexity of this uh so it's gonna be dominated by this part again this is o of n this is linear hopefully that's clearer and this is all also oven this is the part that's subtle even if you might have gotten it without noticing so yeah so this is o of n square kind of we're going to call it that or o m uh whoops they do the square if you want to call it that uh roughly speaking and in terms of space the way that i did it's going to be old and plus m because i use dex but this can be improved to o of one and the way that you do an of one is just having two pointers right instead of having a deck um you just keep track of what was the beginning of the string um and then just pop them off as necessary uh but yeah uh cool um that's all i have for this problem let me know what you think and i will yeah you can watch me stop it during the contest next let me make this smaller a little bit for a second so you can screenshot it or whatever so yeah and now you can watch me do this next flexographically enlarges hmm the hot case is trying to figure out which one to go it works what do you say you so okay oops spending too much time hey uh yeah thanks for watching uh hit the like button to subscribe and join me in discord um let me know what you think about this farm and this solution this explanation um and yeah do have a good day and a good weekend stay good stay healthy to good mental health and i will see you next problem bye | Largest Merge Of Two Strings | largest-merge-of-two-strings | You are given two strings `word1` and `word2`. You want to construct a string `merge` in the following way: while either `word1` or `word2` are non-empty, choose **one** of the following options:
* If `word1` is non-empty, append the **first** character in `word1` to `merge` and delete it from `word1`.
* For example, if `word1 = "abc "` and `merge = "dv "`, then after choosing this operation, `word1 = "bc "` and `merge = "dva "`.
* If `word2` is non-empty, append the **first** character in `word2` to `merge` and delete it from `word2`.
* For example, if `word2 = "abc "` and `merge = " "`, then after choosing this operation, `word2 = "bc "` and `merge = "a "`.
Return _the lexicographically **largest**_ `merge` _you can construct_.
A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. For example, `"abcd "` is lexicographically larger than `"abcc "` because the first position they differ is at the fourth character, and `d` is greater than `c`.
**Example 1:**
**Input:** word1 = "cabaa ", word2 = "bcaaa "
**Output:** "cbcabaaaaa "
**Explanation:** One way to get the lexicographically largest merge is:
- Take from word1: merge = "c ", word1 = "abaa ", word2 = "bcaaa "
- Take from word2: merge = "cb ", word1 = "abaa ", word2 = "caaa "
- Take from word2: merge = "cbc ", word1 = "abaa ", word2 = "aaa "
- Take from word1: merge = "cbca ", word1 = "baa ", word2 = "aaa "
- Take from word1: merge = "cbcab ", word1 = "aa ", word2 = "aaa "
- Append the remaining 5 a's from word1 and word2 at the end of merge.
**Example 2:**
**Input:** word1 = "abcabc ", word2 = "abdcaba "
**Output:** "abdcabcabcaba "
**Constraints:**
* `1 <= word1.length, word2.length <= 3000`
* `word1` and `word2` consist only of lowercase English letters. | null | null | Medium | null |
61 | foreign to the right by K places so actually through this problem there are two things that we should know and the both of the two things are pretty much explained by the examples so in the first example we have k equal to 2 so basically we have to rotate the list by to the right by two places and uh we are given one two three four five as a sequence basically that represents our linked list and as you can see there are two rotations happening and the end result will basically be just the two elements at the end of the list because K is equal to two they are moved to the front in the result and the rest of the nodes so basically the nodes that were in front uh in front of the uh during the before the rotation uh will we will be shifted down uh after the K elements from the back of the linked list so in this case we have four and five as the last two elements they will be put into front and then we will have the same sequence of nodes that we had in front before these uh two uh elements so basically you have to rotate the list by K places means to put the last K elements in the front that's what that's basically what it means that's the first thing that we should know and the second thing um is going to be the second example so we have zero one and two um Sr nodes in the link list and we have k equals we have to four important thing here is to know that the length of the list is in this case true and your number of rotations that we will do is the uh is uh four K is equal to four but as you can notice after the third rotation so one two three uh after this two rotation We have basically the same list that we have at the beginning basically the same list as with uh without any rotation and that's basically generally the rule here uh if we have a list of flagged n and we rotated K times where K is equal to n uh or any multiplier of n we will basically arrive at the same destination where we started we will arrive at the same linked list that we had before the rotations so the only uh contribution of K are the elements that are left when we are done dividing K by n so if you for example have in this case four uh the we have total of three rotations before and the only rotation that contributes basically is the last rotation and how do we actually get the uh the number of rotation that contributes we just basically say the module so for model of three is one to get the number of rotations that contribute uh or we basically use just the modular operator now the number of nodes in the list in directly Center rate is 0 to 500 the node values are from minus 100 to 100 and the case from 0 to 10 to uh two times at 10 to the ninth um out here we will have a linear time complexity solution because uh basically we will proceed to solve this problem in three steps the first step would be to actually calculate the length of the list length list to do that we will just reverse the linked list as long as we have valid uh notes as long as we don't have a iterator that's equal to no that's the first thing then we will calculate the number of frustrations and to calculate the number of stations we will just do K module of n to get the number of stations that make actually the contribution that may take effect on the links list and then after that's done we will get basically the number of nodes from the end of the linked list that we have put in the front and how do we actually get to the uh basically to the uh a node before that group of N and nodes so in the first linked list we had one two three four and five so we wanted to take these two nodes and put it in the front we kind of did a similar thing in the removal of the ant nodes from the linked list uh basically we use the fast and slow approach slow pointer approach uh we uh basically move the fast pointer end times and notes and then uh be removed the fast and slow points or simultaneously one note at a time at the end the slow pointer will be pointing just before the group of n nodes because it has to catch up to the fast pointer and it has to catch up to the fast points are in and the differences basically and notes so slow will be pointing to the node T value three so the thing that we have to do is first that we have to break the slinkage here so to do that we can just do slow next is equal to null but before that we will Mark the slow next as our new head because we will return this as the final result so we have our new head which will return this will be the beginning of the rotary table list and we have broke have broken the connection between these two uh the last thing that we have to do we have to put the first group of nodes before the end and notes group of endnotes uh to the back of the linked list so these uh two notes K C because K is equal to two have to be in the front and to do that we know that the if you have a pointer on the let's say tail that points I will be pointing to the last element that's where we have iterated over all the elements so we'll just uh keep our table pointer to point to the last element in the length twice so basically to put the first group of pointer first group of nodes uh to the back of the list we will just do tail next is equal to the Head because initially head will be pointing to this element here it's in the first element in the linked list uh so we can just connect it if the tail is pointing to the last element it can just connect it like this and that in this case if you return the new head we will have 4 5 and then the rest of the notes so we will have linear time complexity and because you are not creating these shots in the addition this actually has a constant space complexity first we will check if you have an empty list basically for now if there is we cannot rotate it so we just return the head as it is next we'll create our dummy node and The Ether will be pointing to the first note in the UFOs which is basically the head and we will clear the list no tail which will basically point to the last element in the link list after we are done with the first reversal and to do the first reversal we will basically use it to calculate the length the total length of the list so we will initialize our list length to zero and we will iterate over the list as long as the iterator is not equal to null basically as long as we have notes in the list and we will link each iteration will increment the length uh and uh before we move data to the next element we will record the last element that we have visited so basically man once the uh the condition in the Bible is not fulfilled anymore the it will be equal to no but the two will be the last well the element it's just basically the last element in the linked list uh then we'll calculate the number of rotation in using the former K module of Link's length to calculate the number of predictions that actually make the effect to the uh that you have that effect uh linked list uh then if the number of rotation is equal to zero we just returned the head as it is there's no uh there are no changes to the linked list otherwise we declare our slow and fast pointer and we make them point to the same node the dummy is pointing to and then we will move uh we'll basically create this um a few notes ahead for the fast pointer by just iterating the number of station times and each time moving the fast pointer to the next uh to the next node next we'll move this fast and slow pointer simultaneously as long as we don't uh basically reach the last element in the linked list then we know that the uh slow pointer is now pointing to the first element of the last n notes in the linked list so that will represent our new head and we declare that new node as our new head then we break the connection between the first and second group by using our slope pointer and then finally and we connect the second group to be now the first group uh by just connecting the last element which is my priority to the initial head uh or the linked list B initial head will be the first element in the first group that's the first element in the whole length plus so we just made the we create that connection and then we just return our own new head | Rotate List | rotate-list | Given the `head` of a linked list, rotate the list to the right by `k` places.
**Example 1:**
**Input:** head = \[1,2,3,4,5\], k = 2
**Output:** \[4,5,1,2,3\]
**Example 2:**
**Input:** head = \[0,1,2\], k = 4
**Output:** \[2,0,1\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 500]`.
* `-100 <= Node.val <= 100`
* `0 <= k <= 2 * 109` | null | Linked List,Two Pointers | Medium | 189,725 |
1,903 | hi everyone so welcome back to our new video today's lead code daily challenges largest odd number in string this is an easy level question okay now let's see the problem description so in this problem we have been given a string which is called num okay and it is representing a large integer and what we need to do is we need to return the largest valued odd integer that is a nonempty substring of num or an empty substring if no odd integer exist now they have told that what a substring is what is a substring basically it is a continuous sequence of characters within a string so if we have let's say and okay so a substring of and will be a n or n d a d cannot be a substring Okay so what it means here is that a substring is a continuous sequence of characters within a string now what we need to do here like we have been given a string right and what we need to do we need to return the largest valued odd integer that means that it can be five it can be 35 it can be 37 it can be 547 anything is possible right now let's see with an example like we have been given here 52 right now we have 52 also now in this the largest odd integer is five right because if it was 55 then we would have written 55 itself but here what we have two at the last index so that means that 52 as a whole is an even number right so we need to return only five here so the output that will be returned here is five now in the second example they have given as 4206 in this four is also even 2 is also even 0 is also even and 6 is also even so they told us that if there is no odd integer then we need to return an empty string so we will just return an empty string now let's see the third example in this example we have 33 5 4 2 7 in this 3 5 and 7 all are odd right 3 5 4 2 7 in this all are odd right now when we if we start from this index okay we see that we have three now when we move on to five we see that it is a value greater than three right now when we move on to four we see that we have an even integer so when we now we move forward right and we see that again we have an even integer but at last we have an odd integer right so what it is what is happening here the number as a whole is an odd integer right the number as a whole is an odd integer so what we have to do we will be returning this entire string now if we start started from the first index then the chances of losing our pointers with the help uh with the uh even and odd integer is very high because like we had here 35 427 right now we started from this we checked that it is 35 right now we came to five we came here then we saw that there is four we and in this even integer um the problem was that uh we don't need this but in order to have the largest integer there is possibility that after this four there was a presence of three then what would have be done so in order to avoid this we know that any odd integer will be ending with a odd number right means here like we have seven it is an odd number right and this entire number is odd because of the seven here right now what we will do therefore we will start iterating from the back and we will see that our number lies between 1 3 5 or 7 or 9 or not if it is one uh it if it is in varying between these numbers then the number from the starting to that Index right will be odd only like here um we had let's take for an example 3 52 okay now we started from this index we see that this is a even number this is an even number so we move forward we see that this is an odd number now since five is an odd number that means whatever number is before that let's say it was four here and two here okay so whatever number are before that it doesn't matter right we just need the last index to see that it is odd or not as soon as we got to know that it is five at this index so what we can say that 2 4 3 5 is an odd number right so what we will do we will take the entire string from 0 to that index whatever index we are on so now we understood that what is happening in this question let's move on to the approach so basically in the approach what we saw we were starting the iteration from the back right or the end of the integer so our integer uh the iteration was starting from nus one and it was continuing till n is I is equals to Z right so I is greater than or equals to Z and I ++ ++ ++ iusus because we are iterating in the opposite one opposite direction now we have the loop now what we need to see if let's say this is num right so what we need to see if num of I is equals equal 1 or num of I is equals 3 or num of I is equals five or num in the same way we will check for seven and N also now we have checked that uh any of the character is equals to these numbers or not right now if we found this then what we have to do we will simply return the number from 0o to whatever the value this string is on like if we have 2 3 4 5 7 okay uh 2 3 4 5 six let's say okay so 0 1 2 3 4 this is on Fourth Index right now uh this is an even number so we will leave it out we will move on to the third index now we see that this is an odd number that means we need this entire string or subring right so what we have to um return we have to return the string from zero to third index so what we will do we will return the value from 0 to I + 1 why we are using value from 0 to I + 1 why we are using value from 0 to I + 1 why we are using here I + 1 because the value here will here I + 1 because the value here will here I + 1 because the value here will be uh ready uh will be returned till I minus one that means it will be returned till I only that's why we are using I + till I only that's why we are using I + till I only that's why we are using I + 1 and if we come out of this Loop and none of this satisfied that means we never found a number which was equals to 1 3 5 or 7 or 9 so simply what we need to do we need to return empty string right so when we didn't find anything out of the loop we will return empty string now let's move on to the code so whatever little doubts are there will be cleared with it so let's move on to the code now here we have a reverse Loop so I will start wrting in a reverse Loop it will start from n minus one and continue till zero and here we have a reverse Loop now what we need to do we need to check if our character at that index is equals 1 or three or five or 7 or 9 now we have these values now what we need to do if we found any of these values then we will return the string from that index to the IAT index so we will take this here I + 1 because uh it will take this here I + 1 because uh it will take this here I + 1 because uh it will take the integer from 0 to I only now if we didn't find anything what we need to do we need to return an empty string so I will be returning an empty string here let's try to run it now okay I didn't Define the length of the string so let's define the length of the string let's try to run it now so the test cases have passed sample test cases let's try to submit it now so this code has been accepted that's it for today guys thank you for watching if you found this video helpful please let me know in the comments also subscribe to the channel and hit the Bell notification so you will be notified every time I post a new video thank you for watching | Largest Odd Number in String | design-most-recently-used-queue | You are given a string `num`, representing a large integer. Return _the **largest-valued odd** integer (as a string) that is a **non-empty substring** of_ `num`_, or an empty string_ `" "` _if no odd integer exists_.
A **substring** is a contiguous sequence of characters within a string.
**Example 1:**
**Input:** num = "52 "
**Output:** "5 "
**Explanation:** The only non-empty substrings are "5 ", "2 ", and "52 ". "5 " is the only odd number.
**Example 2:**
**Input:** num = "4206 "
**Output:** " "
**Explanation:** There are no odd numbers in "4206 ".
**Example 3:**
**Input:** num = "35427 "
**Output:** "35427 "
**Explanation:** "35427 " is already an odd number.
**Constraints:**
* `1 <= num.length <= 105`
* `num` only consists of digits and does not contain any leading zeros. | You can store the data in an array and apply each fetch by moving the ith element to the end of the array (i.e, O(n) per operation). A better way is to use the square root decomposition technique. You can build chunks of size sqrt(n). For each fetch operation, You can search for the chunk which has the ith element and update it (i.e., O(sqrt(n)) per operation), and move this element to an empty chunk at the end. | Array,Hash Table,Stack,Design,Binary Indexed Tree,Ordered Set | Medium | 146 |