video_id
stringlengths
11
11
content
stringlengths
0
123k
datetime
stringlengths
19
19
leetcode_number
int64
1
2k
thumbnail
stringlengths
48
151
title
stringlengths
9
106
XnY8fe0Gs0E
it has been asked by Facebook Tik Tok Amazon lyt Google yendex Snapchat nagaro Amazon lyt Google yendex Snapchat nagaro Adobe Airbnb LinkedIn Microsoft Apple 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 a b c a 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 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 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 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 then this 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 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 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 but but um why why 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 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 it 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 window will only only expand but they can be Cas Okay window will extend extend extend and then expand expand like like as in string string string expand expand expand shing shing string so there are two variations in which only the shrinking will take place like the size will never ever 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 you are new and you want to practice just go and watch this arraying playlist in 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 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 a lot of space but you want to minimize the 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 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 try expanding try expanding 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 J is moving always ahead at every step at every step my J will move j will move at every step that's it no matter what 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 when I have got a correct window size then then then 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 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 and I want just okay minimize the length 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 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 to implement this condition 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 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 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 you can simply decrease its frequency and find if it becomes zero for all the characters of 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 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 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 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 a b c d and e let's say a b c a b c a A and B so I will just keep track of the prefix sum prefix sum will say a equal to 1 here it 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 = 2 Cal 1 now if I ask you what is this specific what is this specific range frequency so you can just subtract this 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 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 n is for this entire length and 26 is for 26 is in the worst possible case so that seems okay that seems okay that for sure work again this approach will for sure work in this problem because it's a easy the the 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 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 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 the 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 the count again in a 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 the T the temp so the 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 that's how you can simply solve it now 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 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 only use this I'll only use this T map 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 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 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 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 I have taken my a this is the existing map so I simply reduce the frequency of a one 1 a taken 1 a taken then I'll simply move on but as you have seen that 1 a is taken 1 a is taken oh 1 a is taken now how will you make sure if all the characters of 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 as soon as my count becomes zero I have taken all the elements of character I I have taken all the characters of T in my window I to J and then I can simply start 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 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 you decrease the frequency but then you also said that okay nums of a when the frequency was decreased but then you you 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 because if you have 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 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 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 when I when I'm about to decrease something when I'm about to decrease a frequency if the 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 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 frequency of b 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 decrease the count as you can see simply decrease the count now when you have decrease the count no matter what 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 more than zero represents 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 C is there frequency was one so simply firstly decrease the count count becomes a zero decrease the frequency of c c frequency will will will become a zero and then J should move ahead but but but ah now do you see one thing do you see one thing it's simple that your count has become a zero 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 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 then try to shrink the window then try to shrink the window so what I will do is I 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 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 it is for sure it is for sure it is for sure because of it was a line inside your string T and thus if something if the after 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 increase the count also now the count becomes one which means 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 while 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 but 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 for sure your window length will be J minus I only and 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 same way here window L is J minus I because your J will for sure move ahead one step but but but as soon as it has moved now it will give a chance to I bro now you will try moving 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 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 then you can actually use the same logic of J Min I +1 just make sure that pointer think that where you are placing your J I usually make sure I usually make sure thatth where is this gone I I 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 move on my specific because of the window which I have moved on shring my I 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 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 B will come in picture okay it will become a one sorry it 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 was was not positive then okay I'll simply keep on going on my a 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 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 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 and thus 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 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 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 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 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 it will become a one it has it has it now again it has become a one which means now okay now it is actually valid now it is actually valid again still it is so far so far it is valid I'll first try to 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 as 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 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 T map is T 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 if 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 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 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 but but 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 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 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 but 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 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 M time 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 J pointer will move one step I can also in wor case move one one step so it is a 2 into n 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 these all five approaches to actually specify that what all you can tell in an
2024-03-20 11:41:02
76
https://i.ytimg.com/vi/X…axresdefault.jpg
76. Minimum Window Substring | 5 Improvizations | Sliding Window
cyIhOdKAoUE
all right let's talk about replace all digits with characters digits with characters so the idea is that you shift how many so the idea is that you shift how many times times after c so for for example fight after c so for for example fight five times after a you get f five times after a you get f and then there's a constraint it's and then there's a constraint it's guaranteed let your shift guaranteed let your shift never exist z so the maximum for a is 25 never exist z so the maximum for a is 25 a plus 25 is 26 right but for this is a plus 25 is 26 right but for this is simple simple a right a plus one is b and then a right a plus one is b and then c and d e and f right basically you are c and d e and f right basically you are taking the previous character plus taking the previous character plus one but the number could be different one but the number could be different like two like two three four right you just have to worry three four right you just have to worry about your tongue your constraint because for for this character you don't have number and then you end up just by itself then we need a stream builder to build now i can just do it like this now i can just do it like this make it easier and no matter what make it easier and no matter what right i have to append a pen see right i have to append a pen see okay so i have i have to check the okay so i have i have to check the character if the character character if the character is less than equal to 9 is less than equal to 9 or n sorry n c square equal to or n sorry n c square equal to 0 which which is which should be 0 which which is which should be one right okay one you can say zero but one right okay one you can say zero but zero doesn't work zero doesn't work the minimum number is one right the minimum number is one right should be one and should be one and we have to make sure i mean choosing we have to make sure i mean choosing case the previous character is quite a case the previous character is quite a good view good view right so index if i'm here right so index if i'm here i have to make sure this is this index i have to make sure this is this index is is valid so let's just say valid so let's just say new character neutral is equal to new character neutral is equal to uh stock chart at i minus one uh stock chart at i minus one but since this is the but since this is the taking the previous character plus the taking the previous character plus the number right 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 you 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 all right let's talk about what happened all right let's talk about what happened so there's a case for zero right so there's a case for zero right and then we have to worry about zero 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
2024-03-25 10:20:40
1,844
https://i.ytimg.com/vi/c…UE/sddefault.jpg
LeetCode 1844 | Replace All Digits with Characters | StringBuilder | Java
7HZmP8r1FBE
hi guys let's talk about a google interview question today the question is interview question today the question is lead code 147 or shuffle the array uh it lead code 147 or shuffle the array uh it goes something like this given that a goes something like this given that a number consisting of two n elements in number consisting of two n elements in the form x 1 x 2 x 3 until x n y 1 y 2 y 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 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 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 3 and so on until x and y n okay so it's a lead code easy problem but it so it's a lead code easy problem but it becomes pretty hard to solve if someone becomes pretty hard to solve if someone asks you to solve it in one space and o asks you to solve it in one space and o in time complexity like it's easy to in time complexity like it's easy to solve in on space but one space is solve in on space but one space is pretty hard and in a google interview pretty hard and in a google interview you will be expected to solve it in o in you will be expected to solve it in o in space basically shuffle this array in space basically shuffle this array in place place so let's look at the input constraints so let's look at the input constraints input constraints are like n is less input constraints are like n is less than equal to 500 and than equal to 500 and length of basically n is the half of the length of basically n is the half of the size of the array because length of size of the array because length of array is 2n and num psi is greater than array is 2n and num psi is greater than equal to one less than equal to thousand equal to one less than equal to thousand okay so basically uh all the numbers in okay so basically uh all the numbers in the array are positive a pretty the array are positive a pretty important constraint which will help you important constraint which will help you develop a solution of open space okay develop a solution of open space okay and here's our test case as well like and here's our test case as well like nums is two five one three four seven n nums is two five one three four seven n is three which is half of the size of is three which is half of the size of array and output is two three five four array and output is two three five four one seven one seven anyways like uh you can solve it in o in anyways like uh you can solve it in o in space by creating a new array and just space by creating a new array and just copying the elements in the order copying the elements in the order specified in that new array very easy specified in that new array very easy but let's see how to do it in one space but let's see how to do it in one space so so like i have taken example here original like i have taken example here original is one two three four five six shuffled is one two three four five six shuffled array will be one four two five three array will be one four two five three six okay six okay and here i am denoting the mapping as and here i am denoting the mapping as well of the numbers from their old well of the numbers from their old position to the current position position to the current position uh basically sorry from the current uh basically sorry from the current position to the new position basically position to the new position basically the position in the original error and the position in the original error and the position the shuffled array okay the position the shuffled array okay like blue color is denoting all the like blue color is denoting all the numbers numbers uh in the first half of the array and uh in the first half of the array and red color is denoting all the numbers in red color is denoting all the numbers in the second half of their basically all the second half of their basically all the numbers whose index current index is the numbers whose index current index is greater than n and blue color current greater than n and blue color current index less than n okay index less than n okay so so this mapping actually helps you to this mapping actually helps you to visualize and uh visualize and uh like the position of the array in the like the position of the array in the original and position of the numbers in original and position of the numbers in the original and shuffled array and it the original and shuffled array and it also helps you determine a formula to also helps you determine a formula to come up with a formula for the uh for come up with a formula for the uh for the new positions of the elements okay the new positions of the elements okay and let's see what that formula is and let's see what that formula is so i have here in violet color i have so i have here in violet color i have written the indices of the written the indices of the like the current indices of the elements like the current indices of the elements in the original array and any n as i in the original array and any n as i said is the half of the size of array said is the half of the size of array so the new positions in the shuffled so the new positions in the shuffled array will be something like this like array will be something like this like if current position is less than a new if current position is less than a new position will be twice of current position will be twice of current position else new position equals twice position else new position equals twice of current position minus n plus one of current position minus n plus one okay and you can also see this formula okay and you can also see this formula is correct like uh for two the current is correct like uh for two the current position is one its new position will be position is one its new position will be uh twice of current position which is uh twice of current position which is two and you can see here in the blue two and you can see here in the blue color two is here which is at index two color two is here which is at index two and similarly for five like its current and similarly for five like its current position is four four is obviously position is four four is obviously greater than n which is 3 okay so its greater than n which is 3 okay so its new position will be twice of 4 minus 3 new position will be twice of 4 minus 3 that is 1 so 2 into 1 plus 1 that is 3 that is 1 so 2 into 1 plus 1 that is 3 and you can see here in the red color and you can see here in the red color that 5's new position is 3 and this that 5's new position is 3 and this formula also holds for the elements at formula also holds for the elements at the first and last position i mean their the first and last position i mean their position remains same in the original position remains same in the original and shuffled array like for one uh its and shuffled array like for one uh its new position will be twice of zero which new position will be twice of zero which is zero only and for six its new is zero only and for six its new position position will be twice of five position position will be twice of five minus three which is two into two 4 plus minus three which is two into two 4 plus 1 5 1 5 okay uh okay uh now what would be our algorithm now what would be our algorithm so algorithm would be something like so algorithm would be something like this that uh what we will try to do is this that uh what we will try to do is go in cycles in go in cycles in for each index like what we will do for each index like what we will do let's take an example for the number two let's take an example for the number two which is at index one which is at index one i determine the new position of two i determine the new position of two using this formula it comes out to be using this formula it comes out to be two only okay i will replace the number two only okay i will replace the number at the index two with at the index two with the number at position index one the number at position index one basically this two so what i would do basically this two so what i would do instead of placing two here i would instead of placing two here i would place minus two here okay and why i'm place minus two here okay and why i'm placing minus two is because i want to placing minus two is because i want to mark that i have actually visited this mark that i have actually visited this element element and and like since i cannot use an extra array like since i cannot use an extra array for marking that i have visited that for marking that i have visited that particular element i will particular element i will mark the visited as by keeping that mark the visited as by keeping that number as a negative number okay and number as a negative number okay and since i already told you in the since i already told you in the constraints we are given that all the constraints we are given that all the numbers are positive so that negative numbers are positive so that negative will not will not basically basically uh uh but you can say basically destroy our but you can say basically destroy our array okay array okay so so so what i would like i have replaced two so what i would like i have replaced two with this and then i would similarly with this and then i would similarly determine the position new position for determine the position new position for the number which was at index 2 and the number which was at index 2 and replaced replaced that number with this particular number that number with this particular number at index 2 and i will keep on doing that at index 2 and i will keep on doing that until i come to a position which was until i come to a position which was already visited okay in case you did not already visited okay in case you did not understand this uh let's actually try to understand this uh let's actually try to simulate this scenario okay so here i am simulate this scenario okay so here i am like my current number is two current like my current number is two current position is one uh which is here i position is one uh which is here i determine the new position which is n is determine the new position which is n is as i told you three new position will be as i told you three new position will be twice of uh twice of one which is two twice of uh twice of one which is two and the new number that is the number at and the new number that is the number at new position is three okay so what i new position is three okay so what i would do i would replace this number so would do i would replace this number so here i am i replace the number at index here i am i replace the number at index two with minus two okay and i then i two with minus two okay and i then i swap current and current number and swap current and current number and current position with new number and new current position with new number and new position so my current number has now position so my current number has now become three current position has become become three current position has become two i determine the new position for two i determine the new position for this which is twice of two which is four this which is twice of two which is four and at index four the number is five and at index four the number is five which is our new number so again i will which is our new number so again i will swap uh basically what i would do is swap uh basically what i would do is that i would replace the number at index that i would replace the number at index 4 with -3 4 with -3 so that's what i have done here i so that's what i have done here i replaced this with minus 3 now replaced this with minus 3 now and swapped new number and current and swapped new number and current number and new position current position number and new position current position current number is 5 current position is current number is 5 current position is 4 4 so new position will now become 3 so new position will now become 3 because like 4 is greater than 3 we'll because like 4 is greater than 3 we'll use this formula so it comes out to be 3 use this formula so it comes out to be 3 the number at index 3 is 4 which is our the number at index 3 is 4 which is our new number so now what i would do is i new number so now what i would do is i would replace the number at index 3 with would replace the number at index 3 with minus 5 so that's what i did i replace minus 5 so that's what i did i replace this number with minus 5 and swap new this number with minus 5 and swap new number current number new position number current number new position current position current position now our current number is 4 current now our current number is 4 current position is 3 we determine the new position is 3 we determine the new position again 3 is not less than n so position again 3 is not less than n so we did use this formula to determine new we did use this formula to determine new position which comes out to be 1 and position which comes out to be 1 and number at current sorry new position is number at current sorry new position is 2 2 so now i would replace the number at 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 that's what i did here i've denoted that's what i did here i've denoted these negative numbers with violet color these negative numbers with violet color and and as now our current number becomes two as now our current number becomes two current position becomes one i determine current position becomes one i determine the new position which comes out to be the new position which comes out to be two okay two okay so i would replace the number at index 2 so i would replace the number at index 2 with minus 2 so i did that with minus 2 so i did that okay and after doing that okay and after doing that what would happen is our current number what would happen is our current number will now become minus 2 and current will now become minus 2 and current position is 2 position is 2 so now since current number has become so now since current number has become minus 2 it means that we have already minus 2 it means that we have already visited this we do not need to you know visited this we do not need to you know go further in our cycle here we can stop go further in our cycle here we can stop this our cycle here this our cycle here and we will keep on doing that for each and we will keep on doing that for each position like this i have only done for position like this i have only done for one like if you remember here we started one like if you remember here we started with the with the number at position one but we will do number at position one but we will do this for each we will repeat do this this for each we will repeat do this cyclic thing for each position like for cyclic thing for each position like for two three four and five okay so this way two three four and five okay so this way you can clearly see that we have you can clearly see that we have basically basically not used any extra space and this will not used any extra space and this will also make sure that we you know also make sure that we you know transform our original error into the transform our original error into the shuffled array now the thing is shuffled array now the thing is like what is its time complexity so the like what is its time complexity so the time complexity is order n and let me time complexity is order n and let me tell you why is that so that is because tell you why is that so that is because this this visited thing like we are replacing visited thing like we are replacing every number with the negative of that every number with the negative of that number so that makes sure that every number so that makes sure that every index will be visited at most twice okay index will be visited at most twice okay once once uh like it would be visited once when we uh like it would be visited once when we encounter encounter basically when we are replacing that basically when we are replacing that number number that particular index and then there that particular index and then there might be a scenario that we might come might be a scenario that we might come back to that index again in our cycle back to that index again in our cycle but but at that moment we'll break out because at that moment we'll break out because you know uh we are using this negative you know uh we are using this negative as a visited flag as a visited flag so this thing make sure that all the so this thing make sure that all the indices are visited at most twice only indices are visited at most twice only so we will at most do like two end so we will at most do like two end traversals traversals and and sorry to win iterations sorry to win iterations so so uh uh and and let me show you one more thing like this let me show you one more thing like this we have done only for the index one then we have done only for the index one then we go to index two so at index two we go to index two so at index two we see that the number is already we see that the number is already negative so we do not do anything here negative so we do not do anything here current number is already negative we go current number is already negative we go to index three again current number is to index three again current number is already negative minus five we go to an already negative minus five we go to an index four current number already index four current number already negative minus three then at five negative minus three then at five like uh last this is the last number so like uh last this is the last number so last number will remain last number will remain at its own position and we finally break at its own position and we finally break out of this loop so out of this loop so you can clearly see that this visited you can clearly see that this visited flag took care of not repeating our flag took care of not repeating our iterations iterations and you can also see that this uh like and you can also see that this uh like after doing this what we will do is that after doing this what we will do is that we iterate over the array once more we we iterate over the array once more we will replace all the numbers with will replace all the numbers with negative numbers with positive negative numbers with positive value of that particular number and uh value of that particular number and uh finally we will get our original finally we will get our original shuffled array basically our expected shuffled array basically our expected shuffled array which is one four two shuffled array which is one four two five three six and if you remember this five three six and if you remember this was the answer as well one four two five was the answer as well one four two five three six so let's look at the code for three six so let's look at the code for it it uh so here is the code which i had uh so here is the code which i had written like this is the api we had to written like this is the api we had to implement and i implement and i what i am going to do is that for each what i am going to do is that for each index i will try to index i will try to you know do that cyclic process you know do that cyclic process so that's why i'm iterating here from i so that's why i'm iterating here from i equal to 0 to length of the array and equal to 0 to length of the array and initialize current number as num psi initialize current number as num psi current position is i and we only current position is i and we only basically basically do you know iterations in this while do you know iterations in this while loop until this current number is loop until this current number is positive until this current number is positive until this current number is greater than zero and greater than zero and we figure out the new position based on we figure out the new position based on current position and this is that current position and this is that particular formula and then what we do particular formula and then what we do is that we would replace the number at is that we would replace the number at new position with the negative of the new position with the negative of the current number and we will then swap the current number and we will then swap the current number and current position with current number and current position with the new number and new position okay and the new number and new position okay and we'll keep on doing that we'll keep on doing that and eventually when uh after this for and eventually when uh after this for loop we iterate over the array again and loop we iterate over the array again and if we see that num size less than zero if we see that num size less than zero we replace it with the positive value of we replace it with the positive value of that uh number and eventually we return that uh number and eventually we return the num array so time complexity o n the num array so time complexity o n space complexity oven we have solved a space complexity oven we have solved a google hard interview question good to google hard interview question good to move to second round thank you guys for move to second round thank you guys for watching please do not forget to like watching please do not forget to like subscribe and comment on this video i'll subscribe and comment on this video i'll see you all next time
2024-03-21 02:57:10
1,470
https://i.ytimg.com/vi/7…axresdefault.jpg
Leetcode Shuffle the Array | O(1) space
FKmt7UvCpMI
hey everyone and welcome to another Elite code problem so today we're going Elite code problem so today we're going to be doing problem number 489 robot to be doing problem number 489 robot room cleaner room cleaner and it's a backtracking problem it's a and it's a backtracking problem it's a hard one it's probably hard one it's probably one of the hardest backtracking problems one of the hardest backtracking problems I've done I've done um even if you know like backtracking um even if you know like backtracking there's a lot of annoying parts of this there's a lot of annoying parts of this problem for sure so I would encourage problem for sure so I would encourage you if you are learning backtracking it you if you are learning backtracking it is on the backtracking explore part I is on the backtracking explore part I would encourage you to try this one for would encourage you to try this one for sure sure um just to test your you know um just to test your you know understanding of backtracking and the understanding of backtracking and the hard thing about this problem is I'll hard thing about this problem is I'll just tell you is so you have this robot just tell you is so you have this robot in a grid and you don't know you're not in a grid and you don't know you're not given access to the grid the only thing given access to the grid the only thing you're given access to is a couple you're given access to is a couple functions for the robot functions for the robot so you're given a move function that so you're given a move function that will return true if the robot can make a will return true if the robot can make a valid move and then you can turn the valid move and then you can turn the robot left and right and it starts off robot left and right and it starts off facing up facing up and so yeah the annoying thing is like and so yeah the annoying thing is like you don't you don't see the grid you you don't you don't see the grid you don't really know where the robot is don't really know where the robot is and it's hard to visualize if what your and it's hard to visualize if what your algorithm is doing is correct also the algorithm is doing is correct also the other annoying thing about this other annoying thing about this backtracking um is like let's say you're backtracking um is like let's say you're in some cell in some cell draw a grid here draw a grid here so let's just draw a simple grid 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 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 and so what you're going to want to do and so what you're going to want to do is you can visualize I mean when you go is you can visualize I mean when you go somewhere your end State needs to be somewhere your end State needs to be your robot needs to turn around right so your robot needs to turn around right so it needs to face this way 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 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 it's 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 so hopefully that makes sense when you so hopefully that makes sense when you have this robot you turn it around have this robot you turn it around so a 180 degree rotation would be left so a 180 degree rotation would be left or right twice then you'd call move then or right twice then you'd call move then it would go here and then you'd turn it would go here and then you'd turn around again and then that would give around again and then that would give you the original state of the robot you the original state of the robot before it entered this so this is this before it entered this so this is this is how you would get out is how you would get out now the other annoying thing for so for now the other annoying thing for so for most backtracking problems well it most backtracking problems well it actually depends but actually depends but let's say you do have some backtracking let's say you do have some backtracking algorithm and let's say you're algorithm and let's say you're backtracking algorithm just backtracking algorithm just so let's say you try the cell in front so let's say you try the cell in front of you of you and then if it doesn't work you just and then if it doesn't work you just keep turning right and you keep turning keep turning right and you keep turning right and you keep turning right well right and you keep turning right well let's see what would happen let's see what would happen so we we can't go here so we're gonna so we we can't go here so we're gonna turn right turn right okay and we're remember when we go into okay and we're remember when we go into a cell we Face the same direction that a cell we Face the same direction that we came in we can't go here we turn we came in we can't go here we turn right right it's going down it's going down okay we can go here okay we can't go okay we can go here okay we can't go down here so we turn right down here so we turn right okay can't go down here okay well now we can't go here we go okay well now we can't go here we go here here so how do you how do we even know and so how do you how do we even know and then we end up here how do we even know then we end up here how do we even know we ended like we don't have we don't we ended like we don't have we don't have a grid remember and in this case it have a grid remember and in this case it worked out but in other cases uh you can worked out but in other cases uh you can try out some other examples but some try out some other examples but some other examples when you do this when you other examples when you do this when you just keep turning right just keep turning right here so in this case you did end up here so in this case you did end up where you started but in a lot of cases where you started but in a lot of cases you'll just run into like a loop you'll just run into like a loop and how do you even know and then you and how do you even know and then you just you just hit maximum recursion just you just hit maximum recursion depth right because you keep looping but depth right because you keep looping but you don't even know that you cleaned you don't even know that you cleaned every room and you can't check that you every room and you can't check that you cleaned every room you don't know how cleaned every room you don't know how big the grid is you're not giving access big the grid is you're not giving access to any of that information all you can to any of that information all you can do is move the robot do is move the robot and so how would we solve that problem and so how would we solve that problem and to solve that problem this is also and to solve that problem this is also kind of really annoying actually what kind of really annoying actually what we're going to do is we're gonna have a we're going to do is we're gonna have a visited set and you may ask well how do visited set and you may ask well how do you have a visited set if you don't even you have a visited set if you don't even have an index of like where you're have an index of like where you're starting starting and so what we actually need to do that and so what we actually need to do that makes this problem difficult is you have makes this problem difficult is you have a visited set a visited set and then you need to figure out what and then you need to figure out what index what at least what relative index index what at least what relative index you're at and so let me show you what you're at and so let me show you what that looks like that looks like so let's say we let's call this index 0 so let's say we let's call this index 0 0 right so we just say inertial index is 0 right so we just say inertial index is zero zero so we put zero zero in here zero zero so we put zero zero in here and now by the way when we Traverse and now by the way when we Traverse we're gonna only Traverse if our we're gonna only Traverse if our if the place we're traversing isn't in if the place we're traversing isn't in our visited set because we don't need to our visited set because we don't need to visit the same room twice also for this visit the same room twice also for this backtracking that makes it different backtracking that makes it different from some other ones like a Sudoku is from some other ones like a Sudoku is even if you like once you're on a path even if you like once you're on a path and you go to a bunch of rooms when you and you go to a bunch of rooms when you backtrack to where you started you never backtrack to where you started you never have to go back to any of those rooms have to go back to any of those rooms again because we of we've already again because we of we've already cleaned them and we've already went as cleaned them and we've already went as far as we could from any of those rooms far as we could from any of those rooms so once we have visited set and we add so once we have visited set and we add items we're never going to remove them items we're never going to remove them in a normal backtracking you normally do in a normal backtracking you normally do remove and you kind of check for a remove and you kind of check for a Final Solution type of thing you know Final Solution type of thing you know like like for end Queens you would go like like for end Queens you would go down all the rows and you have to see is down all the rows and you have to see is there a final solution and you can you there a final solution and you can you keep removing Queens from the set but in keep removing Queens from the set but in this case once you were in a room once this case once you were in a room once you never have to clean it again because you never have to clean it again because as soon as you go into room we can just as soon as you go into room we can just hit clean and then it's clean hit clean and then it's clean so let's say we're here so what we're so let's say we're here so what we're actually going to use is we're going to actually going to use is we're going to use use um to actually use this for a lot of DFS um to actually use this for a lot of DFS so we're actually going to have an array so we're actually going to have an array like this of directions and we're gonna like this of directions and we're gonna so normally when I have this array of so normally when I have this array of rays for different directions I have rays for different directions I have like one zero zero one negative one zero like one zero zero one negative one zero and so on but here the mistake we need and so on but here the mistake we need to not make is to not make is we need to make sure that so we're going we need to make sure that so we're going to be turning right a lot to be turning right a lot and now we need to figure out what are and now we need to figure out what are the values that you need to go up the values that you need to go up and then if you turn right we're gonna and then if you turn right we're gonna try to make sure that the value to the try to make sure that the value to the right of the current one we're at is the right of the current one we're at is the right thing so to go up actually it right thing so to go up actually it would be this would be this we are going up a row we are going up a row now if we're going up now if we're going up and we turn right now what is okay now and we turn right now what is okay now what is this this is column plus one what is this this is column plus one and so this is another tricky thing is and so this is another tricky thing is you have to make sure you arrange these you have to make sure you arrange these in the right order and for this problem in the right order and for this problem so this is going to be 0 1 so this is going to be 0 1 okay now okay now down if we go right so down is one zero down if we go right so down is one zero and then so yeah if you do if you do a and then so yeah if you do if you do a normal like stuff they use for other normal like stuff they use for other functions you're going to get an error functions you're going to get an error so now we were down now we need to go so now we were down now we need to go right or sorry left right so down if we right or sorry left right so down if we turn right from down it's a left turn right from down it's a left and left is actually and left is actually 0 minus one 0 minus one and so this is what it's going to look and so this is what it's going to look like and all we're going to do when we like and all we're going to do when we turn right is we're just going to say turn right is we're just going to say let's just go to the next Direction let's just go to the next Direction let's go to the next Direction and when let's go to the next Direction and when we reach the last one we can simply just 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 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 I might cut out for a second so this I might cut out for a second so this index is going to be negative one zero index is going to be negative one zero now we tried to go up we can't we go now we tried to go up we can't we go right so then what is right going to be right so then what is right going to be well right it's going to be negative 1 1 well right it's going to be negative 1 1 and so on so you're gonna you're gonna and so on so you're gonna you're gonna have these relative indices instead of have these relative indices instead of absolute indices so even though you absolute indices so even though you don't know how big the grid is you have don't know how big the grid is you have to know which way you're facing and to know which way you're facing and where you started and from there you can where you started and from there you can figure out what relative index you're at figure out what relative index you're at and so we're going to keep adding to our and so we're going to keep adding to our visited set until we can't go anymore visited set until we can't go anymore and then we are going to like I said and then we are going to like I said when we're facing some Direction so it's when we're facing some Direction so it's going to look like like this is what a going to look like like this is what a backtracking would look like for just backtracking would look like for just one particular square right so if we one particular square right so if we have a square have a square let's say we came from here let's say we came from here so we came from here we're in the Square so we came from here we're in the Square let's say we can't go anywhere so we try let's say we can't go anywhere so we try to go here can't we turn right to go here can't we turn right try to go here can't try to go here can't 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 try here 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 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 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 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 our initial direction is going to be up which is going to be this 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 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 right after you 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 when we return from a square right so let's say we 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 okay so it actually does work so that's okay so it actually does work so that's another way you can backtrack out is so another way you can backtrack out is so now what I did instead of my original now what I did instead of my original thing is I have something like this thing is I have something like this and so let's say I'm here and so let's say I'm here and now I would be actually and now I would be actually see here so I moved I turned around see here so I moved I turned around twice and then I move yeah okay so so I twice and then I move yeah okay so so I believe that the final state is like believe that the final state is like this of the cell that I backtrack to so this of the cell that I backtrack to so what I need to do is I need to turn it what I need to do is I need to turn it around right then I need to move back around right then I need to move back and then I need to turn it around again and then I need to turn it around again and that would make it the same state and that would make it the same state here here so like I said you can put this code in so like I said you can put this code in multiple different places but basically multiple different places but basically yeah you have to make sure you handle yeah you have to make sure you handle this and turn right to Nursery you know this and turn right to Nursery you know you want to turn right as many times as you want to turn right as many times as you turn left so the the gears on the you turn left so the the gears on the robot you know don't get rusty you don't robot you know don't get rusty you don't want to keep turning right only okay so want to keep turning right only okay so anyway so yeah so you go back and then anyway so yeah so you go back and then this is the initial function call and I this is the initial function call and I just made it pass with one one zero just made it pass with one one zero because and so what I would encourage because and so what I would encourage you to do by the way if you're getting a you to do by the way if you're getting a lot of Errors is lot of Errors is maybe maybe um one thing that helped me is this this um one thing that helped me is this this grid is really big so you can just make grid is really big so you can just make a custom grid and you can you can even a custom grid and you can you can even try something like this you know where try something like this you know where you have a custom grid and this is the you have a custom grid and this is the custom grid I used where every cell custom grid I used where every cell doesn't have anything and then I just doesn't have anything and then I just made all of these ones one meaning it made all of these ones one meaning it doesn't have a uh it doesn't have brick doesn't have a uh it doesn't have brick so it needs to be cleaned and then I so it needs to be cleaned and then I made my starting location this and then made my starting location this and then I would try to draw out the states of I would try to draw out the states of the robot on my grid and then also print the robot on my grid and then also print like the visited set and where it was in like the visited set and where it was in and make sure it matched because that's and make sure it matched because that's how you catch a lot of your areas that's how you catch a lot of your areas that's what saved me a lot of time for sure what saved me a lot of time for sure um so and then you can also do that by um so and then you can also do that by if you don't know in this new lead code if you don't know in this new lead code version what you can actually do is you version what you can actually do is you can go to test case you can add a test can go to test case you can add a test case case and so you can say like if you know what and so you can say like if you know what it looks like so something like this it looks like so something like this you can add that in you can add that in copy that so this would be a three by copy that so this would be a three by three array three array if you wanted to and then you could say if you wanted to and then you could say yeah like start at you know one one and yeah like start at you know one one and maybe print maybe print my visited Saturn row column or whatever my visited Saturn row column or whatever it is when you have errors because like it is when you have errors because like if you think about it there's there's no if you think about it there's there's no really way to test for this what makes really way to test for this what makes it really annoying and difficult is it really annoying and difficult is there's no really way to test your code there's no really way to test your code like when you have a bug it'll just say like when you have a bug it'll just say all the rooms weren't cleaned and you all the rooms weren't cleaned and you don't really know where the robot was or don't really know where the robot was or where it went because you have no access where it went because you have no access to the grid so it's a real pain to try to the grid so it's a real pain to try to debug it unless you actually draw at to debug it unless you actually draw at the grid yourself and try to follow like the grid yourself and try to follow like is the robot facing the right way is it is the robot facing the right way is it going in the right order by checking going in the right order by checking where the visited set is and where the where the visited set is and where the column is and so on and so I do think column is and so on and so I do think this is a great problem for backtracking this is a great problem for backtracking it definitely does get annoying with you it definitely does get annoying with you have to do a lot of israelization and have to do a lot of israelization and figure out what things have to look like figure out what things have to look like with limited information so with limited information so okay so let's do the time in space okay so let's do the time in space complexity and actually the time and complexity and actually the time and space complexity for this prom are space complexity for this prom are pretty good compared to a normal pretty good compared to a normal backtracking algorithm normally they're backtracking algorithm normally they're very inefficient and so here because very inefficient and so here because we're never actually removing from the we're never actually removing from the visited set we're not visiting a set visited set we're not visiting a set we're not visiting a cell more than we're not visiting a cell more than twice twice so we are only visiting cells that so we are only visiting cells that are ones and not uh so let's say zero is are ones and not uh so let's say zero is a brick we're only visiting cells that a brick we're only visiting cells that are one so it'd be something like count are one so it'd be something like count ones mine or just be count ones right so ones mine or just be count ones right so if we have whatever many empty cells we if we have whatever many empty cells we only visit them one time only visit them one time we do have to technically go back we do have to technically go back actually but actually but I think that is not going to add I think that is not going to add complexity so that's fine so what did we do for space so we do so what did we do for space so we do have a have a we do have we do have um um this visited set right this visited set right and so this visited set is going to have and so this visited set is going to have every single every single so this is kind of the same thing it's so this is kind of the same thing it's going to have every single room we going to have every single room we visited but we can only visit rooms with visited but we can only visit rooms with cat ones cat ones so that's just going to be big of count so that's just going to be big of count ones ones and yeah like I said if we clean a room and yeah like I said if we clean a room and we backtrack and we backtrack uh I think that should be constant time uh I think that should be constant time to backtrack back to backtrack back or or yeah it's actually going to be no it's yeah it's actually going to be no it's actually gonna be like Big O of so we so actually gonna be like Big O of so we so we do actually have to visit a room and we do actually have to visit a room and we and we backtrack back so let's say we we and we backtrack back so let's say we we go something like this we go something like this like this is our path and we have to like this is our path and we have to backtrack back how much does that cost backtrack back how much does that cost like like our maximum call stack does get to like our maximum call stack does get to like the number of rooms we visited but we're the number of rooms we visited but we're basically just visiting a room and then basically just visiting a room and then coming back so it's going to be like Big coming back so it's going to be like Big O of 2N instead of n it's not going to O of 2N instead of n it's not going to add any more and then once we did add any more and then once we did visited these rooms and come back we can visited these rooms and come back we can never go into any of any of these rooms never go into any of any of these rooms that we visited ever again because we're that we visited ever again because we're never getting Rhythm and they've visited never getting Rhythm and they've visited um in the visited set that that's what um in the visited set that that's what would make things more expensive and would make things more expensive and that's why most backtracking operations that's why most backtracking operations are more expensive because you have to are more expensive because you have to you have to fill in let's say nine you have to fill in let's say nine different you know problems and then you different you know problems and then you can have repeated work where you're here can have repeated work where you're here you can't once you've visited a room you can't once you've visited a room you're done you're done okay so that's all for this problem and okay so that's all for this problem and if you like the solution app please like if you like the solution app please like And subscribe to the video it helps grow And subscribe to the video it helps grow this Channel and I'll be posting more in this Channel and I'll be posting more in the future so I'll see you in the next the future so I'll see you in the next one
2024-03-22 15:38:25
489
https://i.ytimg.com/vi/F…MI/sddefault.jpg
Robot Room Cleaner
Hz4Fv0pa1vM
cool 62 unique paths will bite it's located on the top left corner over 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 either down or right at any point in either down or right at any point in time well by trying to reach the bottom time well by trying to reach the bottom right corner and the grid how many right corner and the grid how many possible unique paths are there ok it's possible unique paths are there ok it's a little so actually I mean this is a little so actually I mean this is actually a very straight forward I want actually a very straight forward I want to say dynamic pole and well and it's to say dynamic pole and well and it's not straight for in a sense that is you not straight for in a sense that is you know you've come up with it's just very know you've come up with it's just very standard in the sense that it's a very standard in the sense that it's a very possible textbook type album yeah like possible textbook type album yeah like yeah yeah my only concern and that's I'm missing my only concern and that's I'm missing something it's kind of like what happens something it's kind of like what happens if the number gets too big because if the number gets too big because easily with a man and it's a hundred yeah yeah and that's I'm missing yeah yeah and that's I'm missing something like you could definitely over something like you could definitely over for long or and a lot very quickly and for long or and a lot very quickly and actually there's a halving the thing to actually there's a halving the thing to notice here is that it's actually I mean notice here is that it's actually I mean once again this is a straightforward once again this is a straightforward issue unquote dynamic programming issue unquote dynamic programming problem which stems from I mean it's problem which stems from I mean it's very textbook me in a sense once you very textbook me in a sense once you kind of get it down but the other fun kind of get it down but the other fun thing about this poem is that it's thing about this poem is that it's actually related to how you calculate actually related to how you calculate binomials in a sense that just where I binomials in a sense that just where I wish I could draw but you know binomial wish I could draw but you know binomial type things and I could we'll try to type things and I could we'll try to attempt some ASCII or attempt some ASCII or so bear with me for a second but let's so bear with me for a second but let's say you have a tough thing say you have a tough thing oh yeah so the binomial is X and so you oh yeah so the binomial is X and so you have like the top layer and then you have like the top layer and then you have to was a car like 1 plus X 2 man I have to was a car like 1 plus X 2 man I I don't remember my mathematical I don't remember my mathematical formulations to be honest but uh but formulations to be honest but uh but yeah but on the next level yeah but on the next level it's huh it's 1 plus X and then I know it's huh it's 1 plus X and then I know the next level is 1 plus 2x plus x the next level is 1 plus 2x plus x squared oops and and so forth I mean you squared oops and and so forth I mean you know you know their expansion for that know you know their expansion for that kind of worries for me love it and you kind of worries for me love it and you get this so that's kind of like I mean get this so that's kind of like I mean you could keep on drawing this this is you could keep on drawing this this is where is like you learn it in greats where is like you learn it in greats not one of the great schools or maybe not one of the great schools or maybe high school I don't remember anymore and high school I don't remember anymore and that's just like you know and actually that's just like you know and actually tip yeah that's why I messed up so one tip yeah that's why I messed up so one in time and then just and then this in time and then just and then this obviously this corresponds to 1 plus X 2 obviously this corresponds to 1 plus X 2 is 0 this is 1 plus X to the first and is 0 this is 1 plus X to the first and then this is 1 plus X to the second and then this is 1 plus X to the second and so forth right so then that's the kind so forth right so then that's the kind of the pattern here and it it turns out of the pattern here and it it turns out that this thing also is a way to kind of that this thing also is a way to kind of like it's I think they're called like it's I think they're called something like generating functions something like generating functions attire there's like a decade of math ago attire there's like a decade of math ago hey back to a follow him strike him trip hey back to a follow him strike him trip em but yeah but that's the general thing em but yeah but that's the general thing here and that actually and you could and here and that actually and you could and kind of a standard way to explain it is kind of a standard way to explain it is that and you could I forget what that that and you could I forget what that parameters core I just finger was PI parameters core I just finger was PI Gnomeo bread Gnomeo bread scouts tryingo that's what I'm thinking scouts tryingo that's what I'm thinking of way and this is a Pascal triangle of way and this is a Pascal triangle thing where you know you could think thing where you know you could think about it as 1 and then 1 and then 1 2 1 about it as 1 and then 1 and then 1 2 1 go say the same pattern you Center what go say the same pattern you Center what I did before and and where this node is I did before and and where this node is just the sum of the two two entries and just the sum of the two two entries and you know in the world before and so you know in the world before and so forth way dot dot dot forth way dot dot dot so this is Pascal's triangle which so this is Pascal's triangle which relates to this other thing that I guess relates to this other thing that I guess I should have started with the Pascal I should have started with the Pascal triangle by just blank underneath but triangle by just blank underneath but anyway so the fun thing about this is anyway so the fun thing about this is that this is if you kind of tilt the that this is if you kind of tilt the board a little bit or like you look at board a little bit or like you look at it in a diagonal way now now you could it in a diagonal way now now you could see your entries are actually like 1 1 see your entries are actually like 1 1 on the first world 1 in the first column on the first world 1 in the first column and then 2 3 and so forth and then you and then 2 3 and so forth and then you told your head a little bit you could told your head a little bit you could get like the diagnosis so this this maps get like the diagnosis so this this maps to these in the diagonals right I don't to these in the diagonals right I don't even know how George is on ASCII or even know how George is on ASCII or despair but like diagonal for the first despair but like diagonal for the first row and or first first diagonal and so row and or first first diagonal and so forth so those are your things right and forth so those are your things right and also it the fun thing is that this is also it the fun thing is that this is also the number of unique paths because also the number of unique paths because you could look at you should know to be you could look at you should know to be like okay how many ways do I get here like okay how many ways do I get here well just one way to get to this cell well just one way to get to this cell and there's 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 so there's two ways to get here and then how do I get to here how do I get to here well there's two ways to get to this well there's two ways to get to this cell and there's one way to get to this cell and there's one way to get to this cell so that did doing ways to get to cell so that did doing ways to get to this cell and so forth this cell and so forth and anyway so there's all these math and anyway so there's all these math things so anyway there's a very long things so anyway there's a very long explanation hopefully it's kind of explanation hopefully it's kind of interesting to you but it's a long way interesting to you but it's a long way of saying that's how you would solve of saying that's how you would solve this problem in the same way and if we this problem in the same way and if we left a binomial and Pascal's triangle left a binomial and Pascal's triangle and all these other fun stuff but one and all these other fun stuff but one but one more thing that I will leave you but one more thing that I will leave you with with this problem then with with this problem then is actually another kind of interesting is actually another kind of interesting thing is if we sum up the rows of in thing is if we sum up the rows of in Pascal's triangle which is also Pascal's triangle which is also diagonals so this is actually if you sum diagonals so this is actually if you sum it up is two to the zero and if you sum it up is two to the zero and if you sum this up is two to the one and you could this up is two to the one and you could see that easy and then here is two to see that easy and then here is two to the two and two to the third and so the two and two to the third and so forth right and you could kind of make forth right and you could kind of make this proof the other way very quickly this proof the other way very quickly because for each entry in the previous because for each entry in the previous world world you're gonna for you to of those paths you're gonna for you to of those paths there'll be two paths outweigh so you there'll be two paths outweigh so you always double the paths every time where always double the paths every time where so I said so on each row the sum is 2 to so I said so on each row the sum is 2 to the K or whatever so that's kind of one the K or whatever so that's kind of one interesting thing about it and that also interesting thing about it and that also goes back to there's another way to goes back to there's another way to prove this but another way to kind of prove this but another way to kind of visualize it with binomials because visualize it with binomials because we're binomial is another way to think we're binomial is another way to think about it it's like this entry is also about it it's like this entry is also the number of ways to choose one given the number of ways to choose one given three elements choose one element way three elements choose one element way this is given three elements true zero this is given three elements true zero do we animal choose to do a true story do we animal choose to do a true story right right and something so like so that's yeah so and something so like so that's yeah so it's 3 to 0 3 choose 1 3 and then you it's 3 to 0 3 choose 1 3 and then you see somewhere that should be 2 2 2 to see somewhere that should be 2 2 2 to the K because that's literally the the K because that's literally the number of possibilities you can have number of possibilities you can have because that's just you know like the in because that's just you know like the in our counting type thing way anyway so 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 but the reason why I kind of brought but the reason why I kind of brought this up and not just to flex or show off this up and not just to flex or show off or whatever is that it's something that or whatever is that it's something that I think about when I see this form I think about when I see this form because when m and n will be at most 100 because when m and n will be at most 100 what that means is that so like you know what that means is that so like you know just let's say this is 100 I mean I skip just let's say this is 100 I mean I skip ahead a little bit so I gave this entry ahead a little bit so I gave this entry here so yeah I am and I forget I guess here so yeah I am and I forget I guess we should check with you and then like we should check with you and then like in the corner here in the corner here is M plus n right and and the thing here is M plus n right and and the thing here is that as we talked about before so is that as we talked about before so this is a most going to be M Jews oh this is a most going to be M Jews oh sorry sorry M this is M plus and you know what is M this is M plus and you know what is that well I guess I've always MPUs well that well I guess I've always MPUs well that diagonal is ampersand and choose that diagonal is ampersand and choose what know the sum of that one is oh I what know the sum of that one is oh I don't remember don't remember man I'm I'm mixing myself up it's been a man I'm I'm mixing myself up it's been a while but but the point is that this is while but but the point is that this is dominated by like the sum of that dominated by like the sum of that diagonal you will oh yeah oh wait no cuz diagonal you will oh yeah oh wait no cuz okay I'm thinking of this tag so I I was okay I'm thinking of this tag so I I was doing the math with this place where has doing the math with this place where has to be between m and n there's some eggs to be between m and n there's some eggs but if you're doing like diagonal then but if you're doing like diagonal then then M plus N is under on this diagonal then M plus N is under on this diagonal which is yeah so it's M plus and choose which is yeah so it's M plus and choose notice M times n times choose M percent notice M times n times choose M percent I don't know but the point is that this I don't know but the point is that this has a bound of like something like 2 to has a bound of like something like 2 to the M plus N and that was what concerned the M plus N and that was what concerned me when I saw that M plus n will be 100 me when I saw that M plus n will be 100 because you got a really big number is because you got a really big number is my point so and looking up and down my my point so and looking up and down my other daughter about it is to see if other daughter about it is to see if they have any kind of strange to be like they have any kind of strange to be like oh hey but it's ok because you know it's oh hey but it's ok because you know it's between a hundred oh sorry with the between a hundred oh sorry with the answers like the answer will fit in long answers like the answer will fit in long or 64 bit or 32 bit and debate the other or 64 bit or 32 bit and debate the other one too it is usually something that one too it is usually something that they would tell you but anyway so given they would tell you but anyway so given that or set this is that's why this that or set this is that's why this dynamic programming problem is a way dynamic programming problem is a way straight for it dynamic program in this straight for it dynamic program in this sense sense and then it's just about coating it up and then it's just about coating it up so I'm wearing do not yeah okay and so I'm wearing do not yeah okay and there's a easy optimization that I'll 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 center corner to do the one and then I just found checking and now we just I just found checking and now we just have to return no maybe it's off by one have to return no maybe it's off by one out sometimes I walk by one on these out sometimes I walk by one on these things good oh yeah oops 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 watch I Mississippi case ok cool yeah so watch I Mississippi case ok cool yeah so again this is very straightforward but again this is very straightforward but that's how I kind of think about this that's how I kind of think about this problem and it these things are kind of problem and it these things are kind of fun to kind of think about because it fun to kind of think about because it comes up in random places as well oh comes up in random places as well oh yeah the other thing that I would say a yeah the other thing that I would say a very common thing is to refactor this is very common thing is to refactor this is that well this is a dynamic program well that well this is a dynamic program well obviously of M times of M times n and obviously of M times of M times n and with all of em times and space as well with all of em times and space as well but the thing is you actually reduced but the thing is you actually reduced this 200 of min of M or n by noticing this 200 of min of M or n by noticing that if you look at this away you that if you look at this away you actually you know which is this array actually you know which is this array here you essentially pretty much right here you essentially pretty much right so now 2 will always look at you know so now 2 will always look at you know one and this one and so forth and some one and this one and so forth and some domed we will go get the 2 and the 1 and domed we will go get the 2 and the 1 and sum them and so forth and then now like sum them and so forth and then now like we go all the way down and then now for we go all the way down and then now for some of 4 and 5 say well the thing is at 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 under one way so actually in this entire under one way so actually in this entire well let me add some data tots in this well let me add some data tots in this entire world entire world you only care about the results from the you only care about the results from the previous world right so this will only previous world right so this will only calculate itself in this flow so calculate itself in this flow so actually if you kind of take advantage actually if you kind of take advantage of that you could actually just get rid of that you could actually just get rid of all these stuff well not get written of all these stuff well not get written I mean maybe get rid of it but you could I mean maybe get rid of it but you could you don't have to think you don't need you don't have to think you don't need that memory to stay around and that's that memory to stay around and that's you need to look up stuff for whatever you need to look up stuff for whatever reason in the future but but yeah so you reason in the future but but yeah so you notice that then actually you only need notice that then actually you only need to keep track of the last two rows or to keep track of the last two rows or the current world and the previous well the current world and the previous well so you can actually do that in linear so you can actually do that in linear space as well because yeah it's like you space as well because yeah it's like you know when this is done then you just know when this is done then you just keep track of the new one and so forth keep track of the new one and so forth way anyway so that's good how you solve way anyway so that's good how you solve this was I would say for a dynamic this was I would say for a dynamic programming problem this is way fun um programming problem this is way fun um this is a way one of they were more this is a way one of they were more fundamental ones I should definitely get fundamental ones I should definitely get to get familiar with and I heard that to get familiar with and I heard that Google was still asked a lot time before Google was still asked a lot time before grandpa I actually went into Google for grandpa I actually went into Google for a long time but uh but that's what I've a long time but uh but that's what I've heard heard but you know the way interviews I feel but you know the way interviews I feel like people have not been asking dynamic like people have not been asking dynamic programming well so so yeah maybe it's a programming well so so yeah maybe it's a but yeah we've want to go Google I guess but yeah we've want to go Google I guess you should study timing programming oh you should study timing programming oh yeah yeah that's why I have for this one
2024-03-20 10:53:51
62
https://i.ytimg.com/vi_w…xresdefault.webp
62. Unique Paths (Leetcode Medium)
PiPXuZN1O3U
welcome to code map today we are going to discuss daily record challenge find to discuss daily record challenge find the highest altitude the highest altitude now let's discuss the question there is now let's discuss the question there is a biker going on a road trip the road a biker going on a road trip the road trip consists of n plus one points at trip consists of n plus one points at different altitudes the biker status different altitudes the biker status strip at point zero with Attitude equal strip at point zero with Attitude equal to zero to zero you are given an integer array gain of you are given an integer array gain of length n uh where gain I is the net gain length n uh where gain I is the net gain in the altitude between point I I Plus in the altitude between point I I Plus 1. where I is between 0 and M 1. where I is between 0 and M you have to return the highest altitude you have to return the highest altitude of a point of a point let's understand it with a given example 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 now when the backer will be at the point zero so it's its gain will be 0 minus 5 which is which is minus 5 and here also we can which is minus 5 and here also we can say it is -5 say it is -5 now when the biker will be at point one now when the biker will be at point one at point one this gain is 1 so it's so at point one this gain is 1 so it's so its current gain will be minus 5 its current gain will be minus 5 minus 5 plus 1. which is equal to minus minus 5 plus 1. which is equal to minus 4. and here we can see that it is minus 4. and here we can see that it is minus 4. 4. now current we have current gain we we now current we have current gain we we have current gain ah current gain have current gain ah current gain current again as minus 4. now current again as minus 4. now when the marker is when the marker is when the vehicle will reach 0.2 when the vehicle will reach 0.2 0.2 which is 5. 0.2 which is 5. so current again will become minus 4 so current again will become minus 4 minus 4 plus 5. minus 4 plus 5. minus 4 plus 5 which is equal to 1 and minus 4 plus 5 which is equal to 1 and we can see that here it is 1. we can see that here it is 1. now when the biker will move at the now when the biker will move at the point three point three the gain is 0 so 1 plus 0 the gain is 0 so 1 plus 0 equal to 1 so the current gain will be 1 equal to 1 so the current gain will be 1 and here we can see that it is one and here we can see that it is one and when the biker will be at the point 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 will be 1 minus 7 will be 1 minus 7 which is equal to which is equal to -6 -6 and we can see that it is minus 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 which will show the highest highest among all the altitudes and I have taken a current gain which will restore the current gain and I have run and I have run a loop to iterate through the gain array and I have calculated the current gain at every every iteration and I have maximized the current again and my result is in the resultant address variable and I have returned that now we can see that our code has now we can see that our code has successfully passed all the test cases successfully passed all the test cases thank you for watching
2024-03-20 17:48:00
1,732
https://i.ytimg.com/vi/P…axresdefault.jpg
Find the Highest Altitude | leetcode 1732 | Array Coding Questions
OHerBVV3jhs
hello everyone today we are going to calculate money in lit code bank which calculate money in lit code bank which is a problem which is a Del quing of is a problem which is a Del quing of today so uh basically what is happening today so uh basically what is happening is that you have a certain number of day is that you have a certain number of day which is the number of input n and then which is the number of input n and then from that input you are supposed to from that input you are supposed to compute the total amount that has been compute the total amount that has been saved in the bank given that uh the bank saved in the bank given that uh the bank is the money is safe given a process is the money is safe given a process that can be described as follow every that can be described as follow every day you are going to put like $1 day you are going to put like $1 plus what you put yesterday so if today 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 and after tomorrow I'm going to put and after tomorrow I'm going to put three and so on but there's a little three and so on but there's a little trade at the end of the week I'm going trade at the end of the week I'm going to restart that means after 7 I'm not to restart that means after 7 I'm not going to put eight but I'm going to put 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 last first week so this is the first 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'm going to week I'm going to put two instead of instead of one so I'm put two instead of instead of one so I'm not starting back with one I'm starting not starting back with one I'm starting back with with two so um this is how the back with with two so um this is how the thing is actually arranged now the goal thing is actually arranged now the goal is to find out how is to find out how many uh what is the the total amount we many uh what is the the total amount we are going to have at the end of the are going to have at the end of the process that means at the end of the and process that means at the end of the and days so for you to understand better of days so for you to understand better of what we are doing let's say you have what we are doing let's say you have four weeks the first week you are going four weeks the first week you are going to put 1 2 3 4 5 6 7 the second week to put 1 2 3 4 5 6 7 the second week you're going to start back at two that 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 the Siri 2 3 until 8 and so on and at the Siri 2 3 until 8 and so on and at the end of the day you are going to have the end of the day you are going to have the total amount of the the money you the total amount of the the money you need to keep so need to keep so um giv this process how are we going to um giv this process how are we going to solve it so my Approach of solving this solve it so my Approach of solving this will be as follow 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 at 7 we are 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 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 here so I have the number of week uh the here so I have the number of week uh the number of week starting at zero and I number of week starting at zero and I have the days which is starting at one have the days which is starting at one right and then I will say the end of the right and then I will say the end of the end of the process is end of the process is actually the day actually the day where the number of day will be equal to where the number of day will be equal to n and since I'm going to restart the n and since I'm going to restart the number of day after each week I need to number of day after each week I need to compute the total number of day a little compute the total number of day a little bit different here so I need to say week 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 while this is actually less or equal to 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 incrementing my number of days and then incrementing my number of days and then what I'm going to do here is I'm going what I'm going to do here is I'm going to say result plus equal to day plus to say result plus equal to day plus week so what I'm saying is that after week so what I'm saying is that after each operation I need to add the number each operation I need to add the number of the the value of the number of day to of the the value of the number of day to the total sum that means at this step the total sum that means at this step I'm going to say okay my total s will 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 this step it will take the pr Value Plus this step it will take the pr Value Plus two and so on but guess two and so on but guess what actually I'm doing what I'm doing what actually I'm doing what I'm doing here is actually the same thing that I'm here is actually the same thing that I'm doing here just that for each of those doing here just that for each of those value I'm adding + one + one + one why value I'm adding + one + one + one why because because we are on the week two because because we are on the week two we are on the week two so what you can we are on the week two so what you can do is that you can see keep adding the do is that you can see keep adding the number of day day day day but just number of day day day day but just adding the number of week so you can adding the number of week so you can directly handle the fact that we have directly handle the fact that we have different value for different weeks so different value for different weeks so that's what I'm doing here now the that's what I'm doing here now the question is how do I take care of the question is how do I take care of the number of day how do I change the value number of day how do I change the value to make sure that it is actually to make sure that it is actually accurate with the process you're going accurate with the process you're going to say okay if D is actually equal to to say okay if D is actually equal to eight that mean is the beginning of a eight that mean is the beginning of a new week you're going to say okay day we new week you're going to say okay day we take one and week take one and week Plus+ so whenever we are we are Hing the Plus+ so whenever we are we are Hing the end of or whenever we are starting a new end of or whenever we are starting a new we we are saying okay we are going to we we are saying okay we are going to restart the number of day so we are restart the number of day so we are still going to have 1 2 3 6 7 but we are still going to have 1 2 3 6 7 but we are going to increment the number of week so going to increment the number of week so that is why we are titing the number of that is why we are titing the number of day and the number of week here so let day and the number of week here so let us run this and see what it submit so uh we have everything submit so uh we have everything green uh so another approach of solving green uh so another approach of solving this will be uh based on artic formula this will be uh based on artic formula we are going to L the fact that the the we are going to L the fact that the the saving process is been performed using a saving process is been performed using a progression and using that we are going progression and using that we are going to compute the value that has been saved to compute the value that has been saved using mathematical formula so what will using mathematical formula so what will it look like you're going to use this it look like you're going to use this which is saying that if we want to which is saying that if we want to compute the sum of element following an compute the sum of element following an arithmetical formula we can directly use arithmetical formula we can directly use the first element plus the last element the first element plus the last element time the number of element divided by time the number of element divided by two and we are going to have the sum of two and we are going to have the sum of the element so this is what we are going the element so this is what we are going to use to kind of Leverage The the fact to use to kind of Leverage The the fact of using arithmetical formula to have of using arithmetical formula to have this solution so what will it look like this solution so what will it look like this is our things the first thing here this is our things the first thing here is to find out what is the Ser right and is to find out what is the Ser right and then you can see that during full weeks then you can see that during full weeks we have uh like static element like this we have uh like static element like this we have 1 2 3 2 7 now the next week we we have 1 2 3 2 7 now the next week we have again the the same value 1 2 3 till have again the the same value 1 2 3 till 7 till 8 this time but we are going to 7 till 8 this time but we are going to we can transform this into the 1 2 3 we can transform this into the 1 2 3 until 7 plus 1 one one one year and for until 7 plus 1 one one one year and for the third week we can transform it into the third week we can transform it into the same year plus 2 2 2 2 two year the same year plus 2 2 2 2 two year which will always give you like the 28 which will always give you like the 28 for the first week plus Z for the second 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 can be computed with with number of week can be computed with with number of week time 28 which is the static value and time 28 which is the static value and here we have a Ser which is actually 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 * 012 so this is a 012 so this is a series now that you able to figure out series now that you able to figure out this so how do we compute this so let me this so how do we compute this so let me just grab you my solution so uh you have just grab you my solution so uh you have to compute the number of week we need to to compute the number of week we need to have the total number of week and then have the total number of week and then we need to have the remaining days the we need to have the remaining days the remaining days we are going to use it remaining days we are going to use it for for this one all right for for this one all right so um now to compute the the amount save so um now to compute the the amount save in in Full full days we are going to in in Full full days we are going to have total full week which is actually have total full week which is actually the 28 time number of week that is what the 28 time number of week that is what we said because we have 28 28 28 and we said because we have 28 28 28 and then now we are going to compute the then now we are going to compute the remaining year by using the formula we remaining year by using the formula we just we just see here that means the just we just see here that means the first element plus the last element time first element plus the last element time the number of element ided by two the number of element ided by two so in this scenario our first element is so in this scenario our first element is actually zero our our last element is actually zero our our last element is actually the number of we minus one and actually the number of we minus one and the number of element is actually equal the number of element is actually equal to the number of we so that's what we to the number of we so that's what we are going to use here we have our first are going to use here we have our first element which is zero we have our last element which is zero we have our last element which is actually number of we element which is actually number of we minus one we have our number of element minus one we have our number of element which is actually number of we that we which is actually number of we that we going to divide by two so this is the going to divide by two so this is the formula Computing uh this ser and don't formula Computing uh this ser and don't forget that we put seven in Factor here forget that we put seven in Factor here so we just need to reuse this seven here so we just need to reuse this seven here time 7even so this is actually the time 7even so this is actually the formula that will have us to compute the formula that will have us to compute the total number of week The Total Money Sav total number of week The Total Money Sav during full weeks now we also have a during full weeks now we also have a total remaining how do we compete the total remaining how do we compete the total remaining so the total remaining total remaining so the total remaining here we can see that is actually for here we can see that is actually for 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 that is actually the starting pattern of that is actually the starting pattern of saving but depending on the week we are saving but depending on the week we are going to have a certain amount that has going to have a certain amount that has been added so if you have three weeks been added so if you have three weeks that means the four week each value are that means the four week each value are going to be like the normal saving plus going to be like the normal saving plus the number of week here we are on week the number of week here we are on week four the number of full weeks I mean four the number of full weeks I mean here we are on week four we had three here we are on week four we had three full weeks that means here this one is full weeks that means here this one is going to have the normal one plus three going to have the normal one plus three because we had three full weeks and the because we had three full weeks and the same year so this is actually the Ser same year so this is actually the Ser year and for you to have the total value year and for you to have the total value you can just reuse this the first you can just reuse this the first element is one plus the number of week element is one plus the number of week the last element is actually uh the the last element is actually uh the number of full weeks number of full weeks plus the uh the number of week and then plus the uh the number of week and then the and then uh yeah that's the first the and then uh yeah that's the first element that's the last element so how element that's the last element so how how can you solve this you're going to how can you solve this you're going to say the first first element is one plus say the first first element is one plus the number of week the last element is the number of week the last element is uh the remaining days I mean the uh the remaining days I mean the remaining days the remaining days is remaining days the remaining days is here number of remaining days actually here number of remaining days actually the remaining days plus the number of the remaining days plus the number of week and then the number of element is week and then the number of element is actually the remaining day so we have actually the remaining day so we have the first element number of one plus the first element number of one plus number of week last element number of number of week last element number of plus remaining there and the number of plus remaining there and the number of element is remaining there divid by two element is remaining there divid by two this is the formula so this will this is the formula so this will actually give you the value of this and actually give you the value of this and now that you have this you just need to now that you have this you just need to return the the the total full plus the return the the the total full plus the total remaining which is actually this 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
2024-03-20 15:24:43
1,716
https://i.ytimg.com/vi/O…axresdefault.jpg
1716. Calculate Money in Leetcode Bank: Two approaches
XXTYgC8xrMY
Hello and welcome tool again this is Shaur Awasti and today we will talk about a and today we will talk about a medium level problem of lead code which is bit wise and medium level problem of lead code which is bit wise and of number range so basically what is in it, of number range so basically what is in it, in this we are given left and right and in this we are given left and right and what is we have to tell that in what is we have to tell that in What will be the end of all, like suppose five and six and What will be the end of all, like suppose five and six and sane, what will be the answer of all three, sane, what will be the answer of all three, okay, so we cannot do it by putting a normal for loop okay, so we cannot do it by putting a normal for loop because that TL will give us because that TL will give us okay, so if we want to see a little optimized code, okay, so if we want to see a little optimized code, then we have to do this. then we have to do this. then we have to do this. 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 If we keep If we keep If we keep looking at the elements, if we follow the continuous elements, looking at the elements, if we follow the continuous elements, 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 index P means the one which is the highest, LSB is the least significant bit. If we look at it, 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 then one then zero then and so on Zero then one then zero then and so on is fine. Similarly if we is fine. Similarly if we look at the second one here then it follows and 00 and look at the second one here then it follows and 00 and then again 00. By doing like this the meaning of saying then again 00. By doing like this the meaning of saying is that every element is following a pattern is that every element is following a pattern meaning. meaning. meaning. 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 Will not depend Answer: It Will not depend Answer: It Will not depend Answer: It depends only on the first and depends only on the first and last number, why did I say this because the last number, why did I say this because the first is the smallest, so its MSB first is the smallest, so its MSB 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. look at it, it is found right here and look at it, it is found right here and look at it, it is found right here and 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 Now we have Now we have Now we have understood that it depends only on the first understood that it depends only on the first and last number. Why did I say this and last number. Why did I say this because it follows a pattern and if we end each other because it follows a pattern and if we end each other then everything will be canceled then everything will be canceled out? Brother, if we look at this then rows and rows will be canceled out, out? Brother, if we look at this then rows and rows will be canceled out, right? right? right? 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, If he is If he is If he is doing okay, then that zero will become zero, doing okay, then that zero will become zero, so the maximum dependency, we have so the maximum dependency, we have taken the example of our dependency from 2, 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 3 4 Let's assume like this, okay 3 4 Let's assume like this, okay 5, 6 and 7. 5, 6 and 7. 5, 6 and 7. 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 It is It is It is significant that the largest element will be the significant that the largest element will be the highest i.e. no middle highest i.e. no middle element will be found in which father one element will be found in which father one is found ahead or father one is found here ahead 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 found in found in which the most significant bit is found before it. which the most significant bit is found before it. which the most significant bit is found before it. 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 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 As we go, we shifted this As we go, we shifted this As we go, we shifted this element, this element disappeared, this element shifted, this element element, this element disappeared, this element shifted, this element shifted, okay again shifted, okay again this element or element shifted, this element or element shifted, now we have the remaining left and 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 In the while loop we will write while left is not equal to right, what will we do till then we will write while left is not equal to right, what will we do till then we will keep we will keep shifting left to right, ok one by one 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 It will be similar and It will be similar and It will be similar and we will come out of the loop, okay we will come out of the loop, okay and one we will put a counter, one we will put a counter and one we will put a counter, 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, When both are equal, meaning whether you lift left or right, meaning whether you lift left or right, now the two that are left here, when the now the two that are left here, when the right shift is completed and the two that are right shift is completed and the two that are left at the end, will be equal, then either left at the end, will be equal, then either all the zeros will be zero or all the ones will be one and all the zeros will be zero or all the ones will be one and Either all the forests will be one, take one example Either all the forests will be one, take one example and understand the case of one, okay take one more and understand the case of one, okay take one more example let's suppose here 1 1 1 1 0 1 example let's suppose here 1 1 1 1 0 1 0 1 and this 1 1 1 1 10 10 If we see in this then 0 1 and this 1 1 1 1 10 10 If we see in this then right shift this right shift this right shift this 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 Right again it disappeared and one more Right again it disappeared and one more Right again it disappeared and one more zero zero came in the right sides means three zero zero came in the right sides means three zeros are totaled. Again not equal. zeros are totaled. Again not equal. Gaped again one more zero got inserted. Okay so Gaped again one more zero got inserted. Okay so now four zeros have come from here and the next now four zeros have come from here and the next four four four 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 There are four sets of bits in it, There are four sets of bits in it, There are four sets of bits in it, so everything is equal here, so now that it is equal, so everything is equal here, so now that it is equal, in this case, if we in this case, if we look carefully, when it is equal, then the elements that are left on our right look carefully, when it is equal, then the elements that are left on our right side, that is, on the left side, side, that is, on the left side, which we have not shifted yet. which we have not shifted yet. Right, all those are equal, either all va's or Right, all those are equal, either all va's or all ji's are ok, so what to do in this case all ji's are ok, so what to do in this case when these two come, in this case we can take when these two come, in this case we can take any one, take left or right, take it at any one, take left or right, take it at the end, this is what our answer is left. the end, this is what our answer is left. But to bring it back to its position, 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 number of times we are shifting, number of times we are shifting, that is the number of times we are taking the count, after that we will 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 count minus the number of times and the same number of times we have shifted right. we have shifted right. we have shifted right. 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. all the elements which were there returned to their positions and 0 0 00 came here 0 When we come here, now When we come here, now When we come here, now what was the value of left, four times 0, four times one, then four what was the value of left, four times 0, four times one, then four times 0, four times one, back, how times 0, four times one, back, how many counters did we have, brother, here one doti cha many counters did we have, brother, here one doti cha four, we shifted right, so four four, we shifted right, so four times we did this. times we did this. come will come. come will come. Okay, so ultimately this will be our Okay, so ultimately this will be our answer. Okay, so this thing is answer. Okay, so this thing is clear. Once we will code this thing and clear. Once we will code this thing and see, it will be a little better clear to So first of all, we create a counter in this, So first of all, we create a counter in this, So first of all, we create a counter in this, okay, after that we okay, after that we write the while loop, while left is not equal to right write the while loop, while left is not equal to right inside, what will we inside, what will we do, okay inside, till the time our do, okay inside, till the time our left is not equal to right, then in the left left is not equal to right, then in the left Once again we will Once again we will Once again we will update the value of right. Right shift 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 Or right, Or right, Or right, both will be equal to each other, left and right, both will be equal to each other, left and right, then after that keep your left in return then after that keep your left in return or keep right, to bring it back to its position, we will or keep right, to bring it back to its position, we will hit left shift again, hit left shift again, how many number of times count the number of times, how many number of times count the number of times, we will return it we will return it and see. and see. and see. OK, here I have missed the semi colon. OK, all three items are passed. Once 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 See you See you See you in your next video till then in your next video till then bye
2024-03-22 09:40:05
201
https://i.ytimg.com/vi/X…axresdefault.jpg
Leetcode 201. Bitwise AND of Numbers Range || Bit Manipulation || POTD (21Feb2024)
YfCvAgDH6lg
um hello so today we are going to do this problem called check if string is a this problem called check if string is a prefix of array prefix of array so the problem says we get a string s so the problem says we get a string s and then array um of string words and then array um of string words and we want to determine whether s is a and we want to determine whether s is a prefix of strings of orders okay and then we get an array that is a and then we get an array that is a string of words okay so this is array string of words okay so this is array and this is string s and this is string s and then and then i'm going to determine whether s is a i'm going to determine whether s is a prefix of words so [Music] 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 in words in words for some positive k you know larger than 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 s is a concatenation of let's say s is a concatenation of let's say the first case strings in words right the first basically we concatenate right the first basically we concatenate the first k words the first k words 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 so what this would mean here is that we so what this would mean here is that we get get um um so if we say so s can be a here is actually it's just like was zero plus uh plus words uh plus words yeah that's pretty much it's okay is yeah that's pretty much it's okay is equal to yeah i think we should yeah i think we should the problem is whether it's the problem is whether it's concatenating the first concatenating the first thing you can just check right thing you can just check right so here so here it can be made only by the it can be made only by the three last ones but not containing the three last ones but not containing the first one so first one so i think we can just keep checking right i think we can just keep checking right and until we reach the end so and until we reach the end so that would mean something along the line that would mean something along the line of uh in words uh in words right actually we can even do but i think we join join you can just join you can just join actually not in it starts with so actually not in it starts with so python string starts with python string starts with uh yeah i don't think that would work uh yeah i don't think that would work because if because if a portion of it is in one a portion of it is in one one um one one of the array values and one um one one of the array values and not in the not in the not the entire value then we'd have a not the entire value then we'd have a problem so we can do this so we'd have problem so we can do this so we'd have to say for to say for say w in words okay okay how can we name this so how can we name this so yeah let's call it c it's just a yeah let's call it c it's just a concatenation right so here we do c plus concatenation right so here we do c plus w w and then if s and then if s equal to c then return true equal to c then return true otherwise it's returned otherwise it's returned it's a very simple solution here okay so it seems like that one works what if i try one that kind of has what if i try one that kind of has just this right and just this right and this should not work it should be false okay cool so that works okay cool so that works um what if we try something um what if we try something can we do it in a better way can we do it in a better way um yeah i think we can so we can do 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 we can't use any here uh because we want we can't use any here uh because we want to check to check the accumulation maybe we can use scan i the accumulation maybe we can use scan i think think um because cam gives us the um because cam gives us the the last result okay let's see python okay i want this functional uh the functional one 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 which would be x and y and then what we want is to and then we need to press words okay so 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 sounds like i need all the concatenation sounds like i need all the concatenation so i need this so i need this i need this and i need to check equal so i need this and i need to check equal so i need all the concatenation up until i need all the concatenation up until that point that point um so um so how can so we kind of need to so we kind of need to reduce with intermediary results accumulate maybe so ah okay so ah okay so i think this is potentially what we want okay so import 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 okay if we turn it into a list just to okay if we turn it into a list just to see the content see the content it's exactly what we want right it's exactly what we want right and then here we can check if any and then here we can check if any so here any is takes a miracle right so so here any is takes a miracle right so it can take actually this so any it can take actually this so any uh i need to first define s so s is uh i need to first define s so s is let's say this let's say this right and so what i need at this point is to any equal to s 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 this should work so something like this okay so that seems like it works let's try to but i think so that works cool i think but i think so that works cool i think though we can make this i think there is though we can make this i think there is a plus a plus um in python uh python reference um in python uh python reference plus plus operator uh okay so i'm not sorry about that so python pass plus yeah somehow remember but so maybe it's what accumulates even does so maybe it's what accumulates even does by default by default yes yes yes so um actually accumulate does yes so um actually accumulate does concatenation by default both strings concatenation by default both strings because because if i do this and just show it as a list if i do this and just show it as a list then i get the same thing so it's even then i get the same thing so it's even better with just accumulates like this better with just accumulates like this and and we'll check if we find any and actually we just need to check if s is in this we don't even even need to do any so this is a lot simpler and that works so and that works so an even simpler solution is just as an even simpler solution is just as my weight my weight yeah i think this this is good good yeah i think this this is good good enough cool
2024-03-25 13:33:55
1,961
https://i.ytimg.com/vi/Y…D7KBj-VSHgHjt70Q
Leetcode 1961: Check If String Is a Prefix of Array
0TIgjS5b4w0
hey this is josh from leak dev where we try to explain programming questions as try to explain programming questions as simple and concise as we can simple and concise as we can today we'll be talking about the lowest today we'll be talking about the lowest common ancestor of a binary tree common ancestor of a binary tree according to leed code this question has according to leed code this question has been asked quite frequently by facebook been asked quite frequently by facebook amazon microsoft and just from my own amazon microsoft and just from my own personal experience i was actually asked personal experience i was actually asked this question multiple times this question multiple times in screening interviews and actual in screening interviews and actual on-site interviews on-site interviews so being able to know how to work with so being able to know how to work with trees will be a good thing to have in 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 in example two we're given five which is in example two we're given five which is right here right here and four which is right here the first and four which is right here the first common ancestor of them all common ancestor of them all is five itself because according to the is five itself because according to the definition of definition of the lca a node can be a descendant of the lca a node can be a descendant of itself itself so we return five for example too and so we return five for example too and then finally in example three then finally in example three we have a tree we don't have a picture we have a tree we don't have a picture of it but we can imagine of it but we can imagine a tree of one two which probably just a tree of one two which probably just like this three and one right here like this three and one right here and then we would just return the answer and then we would just return the answer one one 1 would be the root node and once again 1 would be the root node and once again a node can be a descendant of itself a node can be a descendant of itself one thing to note is that there are one thing to note is that there are several constraints to this problem several constraints to this problem specifically the important ones to know specifically the important ones to know is that all node values is that all node values 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 is not the same as our q value and that p and q are guaranteed to exist 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 to our two and then we recurse the right to our two and then we recurse the right tree tree and see that it is also one of the value and see that it is also one of the value that we're looking for q that we're looking for q and so we return something back up so and so we return something back up so maybe another true maybe another true in this example and then once we're back in this example and then once we're back at 2 and we finish recursing both at 2 and we finish recursing both its left child and its right child we its left child and its right child we can see both its can see both its childs and see that we have found our childs and see that we have found our answer answer and so we return ideally the problem we and so we return ideally the problem we want the specific node want the specific node but in this example let's say we return but in this example let's say we return true true and then we go back to one we recurse and then we go back to one we recurse it's right child 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 and then once we go back up to our and then once we go back up to our starting node at one starting node at one we we looked at the left node and we see we we looked at the left node and we see that we did find our ancestor so that we did find our ancestor so we returned some value back up and we returned some value back up and that would be how we would solve this that would be how we would solve this algorithm of course we can't just return algorithm of course we can't just return true or false because this problem wants true or false because this problem wants us to return the node that is our us to return the node that is our least common ancestor so we want to 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 one would then go to its right subtree which end would return and then finally back at one we compare and then finally back at one we compare two and null and then return two and null and then return two because it's the only non-no value two because it's the only non-no value and we would have our and we would have our least common ancestor and that's roughly least common ancestor and that's roughly the idea of how this algorithm works the idea of how this algorithm works let's get to the coding section let's get to the coding section in recursion problem i like to find in recursion problem i like to find define a private helper function define a private helper function because usually you need to pass in because usually you need to pass in different nodes in this instance it's different nodes in this instance it's all the same 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 otherwise in our recursive case when we otherwise in our recursive case when we are iterating through our node are iterating through our node we have to go all the way to the left we have to go all the way to the left child and see if child and see if there's a common node and the right there's a common node and the right child to see if that's a common node child to see if that's a common node and if both left and right is a common and if both left and right is a common node that means node that means our current node is the ancestor our current node is the ancestor otherwise we just return 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 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 pass in p and q that brings us to node two 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 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 now we are at line 21. if both the left now we are at line 21. if both the left and the right node is not null that and the right node is not null that means we found the common ancestor and means we found the common ancestor and we can just return our node we can just return our node we return two back up to our we return two back up to our one node so we exit our left recursive one node so we exit our left recursive case case so in this instance let me just erase so in this instance let me just erase everything everything we are at two for our left node we are at two for our left node now we still need to explore our right now we still need to explore our right node so node so we go down there and we enter our we go down there and we enter our recursive case here recursive case here 5 is not null nor is it any of our 5 is not null nor is it any of our descendants so enter a recursive case descendants so enter a recursive case and just to reiterate where we are i'll and just to reiterate where we are i'll use blue to say this is the left and use blue to say this is the left and right value of our word node right value of our word node and i'll use green to say this is the and i'll use green to say this is the left and right value of our five node left and right value of our five node so r5 and we enter a recursive case so r5 and we enter a recursive case we go to left subtree which is null we go to left subtree which is null which is our base case which is our base case and then we turn null back up so that and then we turn null back up so that says null says null and then we do the same with our right and then we do the same with our right subtree which is also null subtree which is also null and because both of our nodes are null and because both of our nodes are null we don't enter our if statement we don't enter our if statement and so we go to our else case and so we go to our else case in this code we said that if left is not in this code we said that if left is not equal and null we return equal and null we return left otherwise we turn right in this left otherwise we turn right in this instance instance because they're both null it doesn't because they're both null it doesn't really matter and we just return no back really matter and we just return no back up up so null goes back up here so null goes back up here and we're back up here and now and we're back up here and now in our one node we have our calculated in our one node we have our calculated node write subtree value which is null node write subtree value which is null and then we follow the same exact logic and then we follow the same exact logic because both of them because both of them are not equal to something we don't are not equal to something we don't return the current node we're at return the current node we're at so instead we check if the left node or so instead we check if the left node or the is null the is null and then we want to check if one of our and then we want to check if one of our nodes is not null and then return that nodes is not null and then return that in this instance our left is not null in in this instance our left is not null in fact it's actually our ancestor fact it's actually our ancestor so we want to return that node back up so we want to return that node back up and so we just return and so we just return two which one will give us the answer to two which one will give us the answer to this question 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 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
2024-03-19 18:13:16
1,650
https://i.ytimg.com/vi_w…xresdefault.webp
Lowest Common Ancestor of a Binary Tree Leet Code Question Explained using Recursion
baRZ4EwtGjs
[Music] hello everyone welcome to coding decoded hello everyone welcome to coding decoded my name isja I'm working at sd5 at Adobe my name isja I'm working at sd5 at Adobe and after a very long time I have come and after a very long time I have come on to creating a new video because uh on to creating a new video because uh all the questions in the month of all the questions in the month of February seems like an easy question and February seems like an easy question and most of them were already solved by me most of them were already solved by me already and for those who were not I already and for those who were not I believe that you guys are capable enough believe that you guys are capable enough to solve those questions because the to solve those questions because the land up an easy category and today since land up an easy category and today since it was a medium question that I haven't it was a medium question that I haven't solved in the past so I thought let's solved in the past so I thought let's create a video and it will give me an create a video and it will give me an opportunity to interact with you so opportunity to interact with you so welcome guys welcome to day 19th of 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 from all top notches in this group and we openly discuss problems that we face 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 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 7A 2A 1112 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 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 add root into the Q what is the root element 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 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 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 40 gets extracted and it's time to build the second element of our answer and what do we see 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 get 7 comma 2 so 7 gets added followed 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 and this element is gone now let's and this element is gone now let's continue the process and since we are continue the process and since we are moving to the next level we will be moving to the next level we will be toggling the value of the left to right toggling the value of the left to right variable so now again it gets set to variable so now again it gets set to true and we are done with the second true and we are done with the second element of our answer which is 0 comma element of our answer which is 0 comma 40 so let's proceed ahead and it's time 40 so let's proceed ahead and it's time to create the third element of for to create the third element of for answer uh the second level has three answer uh the second level has three elements in it 1 1 2 2 and 7 so let's elements in it 1 1 2 2 and 7 so let's pull out the topmost element from it pull out the topmost element from it seven gets seven gets extracted and uh since seven gets extracted and uh since seven gets extracted it doesn't have any children extracted it doesn't have any children so no insertion is made into the Q and so no insertion is made into the Q and let's add seven as part of our answer let's add seven as part of our answer now let's continue the process the next now let's continue the process the next element that we have happens to be two element that we have happens to be two so two gets extracted and does it have so two gets extracted and does it have any children yes it has one child which 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 answered element so in total we have three elements 7 2 1 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 let's set the the left false let's continue the process the false let's continue the process the first element that gets extracted first element that gets extracted happens to be 78 let's create the fourth happens to be 78 let's create the fourth element let's add 78 over element let's add 78 over here and it doesn't have any child so no here and it doesn't have any child so no insertion is made the next element that insertion is made the next element that we have is we have is 34 it also doesn't have any child so 34 it also doesn't have any child so this element would be inserted at the this element would be inserted at the starting point of our answer result why starting point of our answer result why at the starting point because our left at the starting point because our left to right variable happens to be false so to right variable happens to be false so let's write 34 at the let's write 34 at the start with this we have successfully start with this we have successfully iterated over all the elements that are iterated over all the elements that are present in our binary tree and in total present in our binary tree and in total the answer corresponds to 10 040 72112 the answer corresponds to 10 040 72112 3478 and this is what the question 3478 and this is what the question expected us to return so without further expected us to return so without further Ado let's quickly transform this Ado let's quickly transform this algorithm into code and I'll exactly algorithm into code and I'll exactly follow the same steps as I just talked follow the same steps as I just talked here the first thing that I've have done here the first thing that I've have done here is to create a list of list of here is to create a list of list of integers that will help me return the integers that will help me return the answer result in case my root is null I answer result in case my root is null I simply abought the process and return simply abought the process and return the ANS otherwise I go ahead and create the ANS otherwise I go ahead and create a BFS Q I add my root onto it I create a a BFS Q I add my root onto it I create a variable named left to right and variable named left to right and initialize it to true the typical we of initialize it to true the typical we of lighting any BFS reversal Q dot is not Q lighting any BFS reversal Q dot is not Q is not empty I extract the size while is not empty I extract the size while size minus minus is greater than zero I size minus minus is greater than zero I extract the topmost element and here I extract the topmost element and here I have created another subl list that will have created another subl list that will help me create the answer at that help me create the answer at that particular level if my left to right particular level if my left to right happens to be true what do I do I make happens to be true what do I do I make an insertion towards the end of the subl an insertion towards the end of the subl list in case my left to right variable list in case my left to right variable happens to be false I make the insertion happens to be false I make the insertion at the starting point of my subl list at the starting point of my subl list and this is again typical way of writing and this is again typical way of writing the BFS reversal if my head dot left is the BFS reversal if my head dot left is not null I add it into the cube my head not null I add it into the cube my head dot right is not null I add it into the dot right is not null I add it into the cube and once I've done with iterating cube and once I've done with iterating over a particular level in my BFS over a particular level in my BFS reversal I add my sublist on onto the reversal I add my sublist on onto the result and I toggle the value of left to result and I toggle the value of left to right once I'm out of the while loop right once I'm out of the while loop outer while loop I simply return the 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
2024-03-21 10:15:18
103
https://i.ytimg.com/vi/b…axresdefault.jpg
Leetcode 103 Binary Tree Zigzag Level Order Traversal | Amazon Google | SDE Sheet below
Ij7zEqyLfhA
welcome to august leeco challenge today's problem is pascal's triangle two today's problem is pascal's triangle two given the non-negative index k we turn given the non-negative index k we turn the kth index of a pascal's triangle the kth index of a pascal's triangle pascal's triangle is represented nicely pascal's triangle is represented nicely in this graphic where in this graphic where every row has one more cell than its every row has one more cell than its previous row and the numbers within are previous row and the numbers within are going to be the summation of the two going to be the summation of the two cells above it notice how all the cells cells above it notice how all the cells on the borders on the borders are always going to be one so it's only are always going to be one so it's only the ones in the middle that we need to the ones in the middle that we need to calculate calculate so let's think about how we could so let's think about how we could represent this in represent this in a programming language like python and a programming language like python and we'll probably use a list of lists we'll probably use a list of lists if we went straight forward we could if we went straight forward we could think of think of what would we need to do to calculate what would we need to do to calculate the last row the last row here this will be the row three and here this will be the row three and whatever row we want to move forward we whatever row we want to move forward we need to calculate the ones before that need to calculate the ones before that iteratively in order to get the next row iteratively in order to get the next row and the next row and so on and so forth and the next row and so on and so forth so just like the graphic indicates all so just like the graphic indicates all we care about is we care about is the ones in the middle right and we need the ones in the middle right and we need to add up to add up the two on top so if we represent like the two on top so if we represent like this like we can this like we can see that visually but how about what see that visually but how about what would that look like would that look like in uh in a programming language to make in uh in a programming language to make it easier it easier try to instead of making a triangle just try to instead of making a triangle just look at it like look at it like like this um i guess it's still a right like this um i guess it's still a right triangle triangle but you can see all we care about is the but you can see all we care about is the numbers in the middle numbers in the middle right we see that the one right we see that the one row before it we just want to add up the row before it we just want to add up the same index number same index number as well as the index number before it as well as the index number before it here so 2 is going to be here so 2 is going to be the sum of the previous row the sum of the previous row same index as well as the index same index as well as the index minus one here in three we can see that minus one here in three we can see that we need to add up one and two three is we need to add up one and two three is going to be out of two and one going to be out of two and one and everything else at the edges we and everything else at the edges we don't care about those are always going don't care about those are always going to be ones to be ones so our approach then would be to so our approach then would be to go through each row go through each row create a temporary array and create a temporary array and calculate the ones in the middle and calculate the ones in the middle and then add that to our then add that to our output and continue this loop until we output and continue this loop until we are finished and then return the last are finished and then return the last list in that array all right so let's list in that array all right so let's see what that might look like see what that might look like so first things first we want to start so first things first we want to start off with off with i'm going to call it pass this is going i'm going to call it pass this is going to be our pascal's triangle and to be our pascal's triangle and since we know the very top row is going since we know the very top row is going to have just a 1 to have just a 1 we can just begin with that now we want we can just begin with that now we want to do this for to do this for however many rows that we're given so 4i however many rows that we're given so 4i in range of row index in range of row index and we're going to have to do a plus one and we're going to have to do a plus one because because this is 0 indexed and we want to start this is 0 indexed and we want to start at at the second row which is going to be 1 the second row which is going to be 1 here here because we already have row 0 that's because we already have row 0 that's already got a 1. already got a 1. so the first thing we want to do is so the first thing we want to do is start off by initializing our temporary start off by initializing our temporary rate rate and we'll just say make this a list of and we'll just say make this a list of ones for in range of ones for in range of of what i guess it would be of what i guess it would be in range of the the row index that we're on right row index that we're on range of plus or months so plus one range of plus or months so plus one yes all right so after that we now yes all right so after that we now we know that it's going to be like 1 1 we know that it's going to be like 1 1 at this point at this point and we'll say this isn't a very good and we'll say this isn't a very good example because we want to example because we want to save it's like the third second third save it's like the third second third row here row here we only want to care about the one the we only want to care about the one the middle right so what we'll do is since middle right so what we'll do is since the ones at the edges are already ones the ones at the edges are already ones we'll just say for j in range of one we'll just say for j in range of one to the length of our temporary ray minus to the length of our temporary ray minus one so that way we're only going to care one so that way we're only going to care about the ones in the middle about the ones in the middle and at that point we're just going to and at that point we're just going to make make our temporary index array the index our temporary index array the index point equal to point equal to our pascal's triangle whatever the our pascal's triangle whatever the previous row is the last row that we've previous row is the last row that we've added on added on as well as j plus pascals as well as j plus pascals minus one uh j minus one minus one uh j minus one so that's going to equal two on top of so that's going to equal two on top of here here so once we're finished with this since so once we're finished with this since this updates to two this updates to two now we could just add that to our now we could just add that to our pascal's triangle we'll append our pascal's triangle we'll append our pascal strangle with temporary array pascal strangle with temporary array and then just continue the loop after and then just continue the loop after we're finished with that we're finished with that let me just delete that here and we will let me just delete that here and we will return our 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 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 but if you think about it carefully but if you think about it carefully let's just think about that last row let's just think about that last row here one two one we want to get to one here one two one we want to get to one three three one right could we use three three one right could we use this array to get to this array doing this array to get to this array doing the exact same thing that we're doing the exact same thing that we're doing here here well uh the problem is uh first we might well uh the problem is uh first we might want to append a cell right so we'll say want to append a cell right so we'll say that that we add one here at the very end now we we add one here at the very end now we just care about the ones in the middle just care about the ones in the middle so how about we just add up the ones so how about we just add up the ones from before from before and get that three but if we do it left and get that three but if we do it left to right you can see immediately we to right you can see immediately we update this so now this one doesn't work update this so now this one doesn't work because we've because we've changed this we need that too changed this we need that too but what about the other way well but what about the other way well because this one is new because this one is new and that's never going to change you can and that's never going to change you can see that see that here if we just add the previous one here if we just add the previous one we're kind of going we're kind of going uh i guess bottom up uh i guess bottom up we'll add 2 to our 1 here that's 3 but we'll add 2 to our 1 here that's 3 but we'll be keeping this 2 we'll be keeping this 2 and i'd keep bringing the 1 here and now and i'd keep bringing the 1 here and now we've gone to this point we've gone to this point and this is still using the same list we and this is still using the same list we just appended 1 and that's going to just appended 1 and that's going to allow us to only use k extra space allow us to only use k extra space so the algorithm is still the same all so the algorithm is still the same all it is is we're going to get rid of our it is is we're going to get rid of our temporary array that we're creating and temporary array that we're creating and instead use instead use the same list okay so start with the same list okay so start with initializing our output it's not going initializing our output it's not going to be a list of lists it's just going to to be a list of lists it's just going to be a list be a list and we'll still go through this same and we'll still go through this same thing but instead of just creating this thing but instead of just creating this temporary array what we'll do is temporary array what we'll do is append to our output 1 append to our output 1 and the same thing here this would be and the same thing here this would be the same the same except we want to move backwards right except we want to move backwards right so so how will we do that length of how will we do that length of output minus 1 but we want to go minus 2 output minus 1 but we want to go minus 2 because because we don't care about the very last one we don't care about the very last one we're going to go to we're going to go to not negative one we're going to go to not negative one we're going to go to zero and we'll still decrease by 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 of j minus one we don't need to append of j minus one we don't need to append anything anything now all we need to do is return the now all we need to do is return the output at the very end okay it looks like it worked let's go 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
2024-03-21 11:01:54
119
https://i.ytimg.com/vi/I…hA/sddefault.jpg
Leetcode - Pascal's Triangle II (Python)
C2pcj1_NtJY
Hello Hi Everyone Jasmine Chakraborty And Today Will Be Discussing Problem Number 1434 Let Code Find Today Will Be Discussing Problem Number 1434 Let Code Find All Programs In History All Programs In History 109 This Is A Problem Dentist In Bittu 109 This Is A Problem Dentist In Bittu Of Every Day I Am Not Challenge In Its Food Should You Of Every Day I Am Not Challenge In Its Food Should You To Problem Avoid Yesterday I To Problem Avoid Yesterday I Want From You Can Be Want From You Can Be Want From You Can Be List to Play List Soe Hind is the problem giving such things 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 Letter of different water friends Letter of different water friends Letter of different water friends typically used oil generator set you want to typically used oil generator set you want to and from physical representations of a and from physical representations of a lukewarm spring plate in software approach lukewarm spring plate in software approach bring a b c all it's bring a b c all it's an order comes with baby baby an order comes with baby baby force will be included in bsc bca force will be included in bsc bca editor-in-chief RCB Ad SSC Board Result Research RCB Ad SSC Board Result Research RCB Ad SSC Board Result Research Adams Of ABC Okay Something Clear Soe Na How To Adams Of ABC Okay Something Clear Soe Na How To Approach Approach Typical Problem Take Typical Problem Take Care Care Due To Speed ​​And It's Okay Fennel Will Have To Will Will Not Familiar With Lots Of Year Was Giver Giver Giver size the insights and distributes prices size the insights and distributes prices for history for grand set n for history for grand set n alarm of alarm of birth the same size adds patients can not birth the same size adds patients can not be a great and fearless and fear to be be a great and fearless and fear to be considered for window size three layer and considered for window size three layer and facilities and akram have descended facilities and akram have descended from which produced som one shiv from which produced som one shiv from which produced som one shiv 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 computers for of this will be seen in the 11th seen in the 11th that soegi vacancy this to is obscene equal that soegi vacancy this to is obscene equal handed over validation of from itunes handed over validation of from itunes store the answer store the answer has starting date for a number of years 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 And give them but it's there in which And give them but it's there in which And give them but it's there in which year will have year will have battery saver mode on the year open the acid which is singh sentence me 120 gms scene 120 respectively 6 on one so normal that Ravana optimization what we After After After taking any attachment to account for this what we can do it taking any attachment to account for this what we can do it is decrement account is decrement account declared like they never define cid declared like they never define cid comment comment voyager-1 voyager-1 middle aged department 1000 and find every day the moment when middle aged department 1000 and find every day the moment when one sheet one sheet in exam in 2017 this completely hero in exam in 2017 this completely hero sprint with vinod sign up sprint with vinod sign up sprint with vinod sign up 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 Painted Sunth Department And So Vid Painted Sunth Department And So Vid Painted Sunth Department And So Vid 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 Code Year Code Year Code Year Celebration of Celebration of Morality in this Function is Morality in this Function is Hey What So Any Significant and Mrs Hey What So Any Significant and Mrs Pain Person's This Condition Life in First Pain Person's This Condition Life in First Time Bigg Boss This Condition Aa Vriksha Ek Time Bigg Boss This Condition Aa Vriksha Ek Plate Idhar Size Plate Idhar Size Penal Sainik Us After Penal Sainik Us After Death Sentence Death Sentence subscribe The Channel and subscribe subscribe The Channel and subscribe the Channel and in the Channel and in the Channel and in characters page subscribe channel subscribe now to which sliding window is initially e do which sliding window is initially e do not moving til not moving til servi moving servi moving that til size pet checking cba because in this that til size pet checking cba because in this element window size se zoom 12 element window size se zoom 12 benefit for industry don't want for this benefit for industry don't want for this is the time building is the time building is the time building OK Hum Building's Vendor Teller m&m OK Hum Building's Vendor Teller m&m Exercise You OK So M Taking a Character Exercise You OK So M Taking a Character and Thinking in This Present in the House and Thinking in This Present in the House Map and Implement One Developed Is Not Map and Implement One Developed Is Not Present Leaders Were Not Pregnant So I Do Present Leaders Were Not Pregnant So I Do n't Need to Avoid It Simply n't Need to Avoid It Simply Introduce Introduce Gift I Gift I Gift I 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 Responsibly Started Now Desk Does Responsibly Started Now Desk Does It It It not going to later dated check all the from this side start from 30 - 30 - - 121 on that your and share later android Uttar Pradesh Sliding Window Uttar Pradesh Sliding Window 10 in this building Sliding Window 10 in this building Sliding Window And Take And Take You Can and Should Avoid Avoid - Subscribe subscribe Video Use Two Years Boys and Boys Payment But They Don't Need Not a Single Bill Sent But They Don't Need Not a Single Bill Sent Content Science and Technology Department Content Science and Technology Department and the Initial Typing Position Gold Behind and the Initial Typing Position Gold Behind Give New Cars Give New Cars Give New Cars 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 Much of the credit for this is the Much of the credit for this is the Much of the credit for this is the fool solution ok fool solution ok 109 left side this 109 left side this dual sim not interested and want to dual sim not interested and want to avoid you will be amazed and if someone has flowers smack and if someone has flowers smack and sacrifice everything is a row of any harm the sacrifice everything is a row of any harm the middle end middle end middle end 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 is near problem is near problem is near problem Subscribe My Channel Video
2024-03-22 12:19:01
438
https://i.ytimg.com/vi/C…axresdefault.jpg
Find All Anagrams in a String | LeetCode 438 | Sliding Window
3OXWEdlIGl4
hey everyone welcome back to the channel i hope you guys are doing extremely well i hope you guys are doing extremely well so today we will be discussing the so today we will be discussing the zigzag traversal from the frika tree zigzag traversal from the frika tree series now what does this traversal series now what does this traversal means so in the previous means so in the previous traversal that is the level order traversal that is the level order traversal you saw that the traversal was traversal you saw that the traversal was like one like one two three then a four five six now this two three then a four five six now this is zig zag as the name suggests so first is zig zag as the name suggests so first it'll be one it'll be one then you'll go across like this that's then you'll go across like this that's three two three two then you'll go across like this four then you'll go across like this four five six five six so that's the traversal zigzag traversal so that's the traversal zigzag traversal like first like this like first like this then like this then like this then like this then like this so kind of then like this then like this so kind of this this this this this and if there were any other levels this and if there were any other levels it'd be like this then it would have it'd be like this then it would have been like this so that's what a zigzag been like this so that's what a zigzag traversal is all about traversal is all about so we're going to follow the same so we're going to follow the same technique as we did in the level order technique as we did in the level order traversal so initially we will be taking traversal so initially we will be taking a cue data structure so let's take a cue data structure so let's take initially a queue data structure and i'm initially a queue data structure and i'm going to store the root of the tree going to store the root of the tree there's no doubt in that we're going to there's no doubt in that we're going to store the root of the tree in the queue store the root of the tree in the queue data structure data structure also we're going to take a vector of also we're going to take a vector of vector or a list for that reason that's vector or a list for that reason that's the data structure where we will be the data structure where we will be storing the zigzag traversal and we'll storing the zigzag traversal and we'll be returning this as our answer so what be returning this as our answer so what we will do different is we will do different is we are seeing one thing that the first we are seeing one thing that the first traversal is from left to right then traversal is from left to right then it's like this right from right to left it's like this right from right to left then again from left to right then from then again from left to right then from right to left so we're gonna introduce a right to left so we're gonna introduce a flag kind of a variable okay so let's flag kind of a variable okay so let's introduce a flag variable which is gonna introduce a flag variable which is gonna say us if you're moving from left to say us if you're moving from left to right or you're moving from right to right or you're moving from right to left so probably we can keep a flag left so probably we can keep a flag variable uh initially let's assign it to variable uh initially let's assign it to be zero or one you can do it as you wish be zero or one you can do it as you wish so let's start the iteration of the cube so let's start the iteration of the cube so in the iteration of the queue first so in the iteration of the queue first time when i check out the queue there's time when i check out the queue there's only one element so we will take it out only one element so we will take it out okay and now what we will do is if there okay and now what we will do is if there is a left there is so we will insert it is a left there is so we will insert it into the queue if there is a right there into the queue if there is a right there is we will insert that into the queue is we will insert that into the queue once i've done that once i've inserted once i've done that once i've inserted all the bottom notes left and right i all the bottom notes left and right i will take this guy and i'll insert it in will take this guy and i'll insert it in the same order the same order like i took it out that's one the flag like i took it out that's one the flag is zero very important to the flag is is zero very important to the flag is zero so flag zero zero so flag zero says us that the direction is from left says us that the direction is from left to right to right and the value one says us that the and the value one says us that the direction is from right to left in our direction is from right to left in our traversal so we are done with one traversal so we are done with one so once you've inserted one into your so once you've inserted one into your data structure data structure please make sure you turn the flag to be please make sure you turn the flag to be one because you're going to the next one because you're going to the next iteration of the queue right and you'll iteration of the queue right and you'll get the the next level get the the next level notes that's two and three so let's get notes that's two and three so let's get the next level notes to entry the next level notes to entry now now you're gonna check for twos left that's you're gonna check for twos left that's four so kindly insert that into the four so kindly insert that into the queue you're going to check for 2's queue you're going to check for 2's right that's 5 insert that into the right that's 5 insert that into the queue so 2 is done next for 3 is left queue so 2 is done next for 3 is left there is nothing 3 is right there's a 6. there is nothing 3 is right there's a 6. insert it so i can say i've done for 2 insert it so i can say i've done for 2 and 3 so these elements are also done and 3 so these elements are also done now since now since the value of flag the value of flag is one is one what you will do is instead of inserting what you will do is instead of inserting it like two and three it like two and three you will make sure they are inserted in you will make sure they are inserted in the reverse order that's three and two the reverse order that's three and two that's why i said a flag is one it's that's why i said a flag is one it's right to left so flag one told us that right to left so flag one told us that it's right to left now while you while it's right to left now while you while you move to the next level please make you move to the next level please make sure you turn flag back to zero sure you turn flag back to zero so every time you're switching on levels so every time you're switching on levels you turn flag zero one zero one zero one you turn flag zero one zero one zero one right and the next you get something as right and the next you get something as four four five six and it's time to check if they five six and it's time to check if they have left and right four doesn't have a have left and right four doesn't have a left four doesn't have a right five left four doesn't have a right five doesn't have a left five doesn't have a doesn't have a left five doesn't have a right similarly with six doesn't have a right similarly with six doesn't have a left doesn't have a right so can i say left doesn't have a right so can i say the traversal for four five six has been the traversal for four five six has been completed and the flag value is zero and completed and the flag value is zero and if it is zero i will simply take four if it is zero i will simply take four five six and insert it into my data five six and insert it into my data structure without reversing it so i've structure without reversing it so i've inserted that into the data structure inserted that into the data structure now can i say if i look back at the now can i say if i look back at the queue my queue is indeed empty now hence queue my queue is indeed empty now hence we have traversed all the nodes and we have traversed all the nodes and right after the traversal can i say my right after the traversal can i say my data structure is having the zigzag data structure is having the zigzag traversal that i was asked to print and traversal that i was asked to print and i can return this data structure and i can return this data structure and this is going to be my answer so the this is going to be my answer so the difference that i did from the previous difference that i did from the previous question was i just maintained a flag question was i just maintained a flag variable which was like 0 1 0 every time variable which was like 0 1 0 every time i went on to the next level i just i went on to the next level i just converted zero to one one to zero and converted zero to one one to zero and vice versa that is what i did so again vice versa that is what i did so again we're going to discuss the c plus plus we're going to discuss the c plus plus and the java code so you can see the c and the java code so you can see the c plus plus code on the left and the java plus plus code on the left and the java people can definitely follow their code people can definitely follow their code that's on the right them they're mostly that's on the right them they're mostly identical so you can definitely catch up identical so you can definitely catch up so initially we are given the root of so initially we are given the root of the tree the tree and we declare our data structure that's and we declare our data structure that's result and the tree is empty we're going result and the tree is empty we're going to return to return the data structure which will never have the data structure which will never have any uh zigzag traversal right after that any uh zigzag traversal right after that i declare the queue and i initially push i declare the queue and i initially push the route right and we have a flag which the route right and we have a flag which is initially marked as true so basically is initially marked as true so basically over here what i'm done is true means over here what i'm done is true means left to right left to right and the opposite will mean uh right to and the opposite will mean uh right to left that is what i have been doing over left that is what i have been doing over here right after that i travis in the here right after that i travis in the queue so you know uh always we take all queue so you know uh always we take all the notes of that level the notes of that level so let's take all the notes of that so let's take all the notes of that level and what i do is i run a for loop 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 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 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 i can always switch 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 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 please 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 [Music]
2024-03-21 10:13:32
103
https://i.ytimg.com/vi/3…axresdefault.jpg
L19. Zig-Zag or Spiral Traversal in Binary Tree | C++ | Java
GFCZorJUV7w
hello guys my name is Ursula and welcome back to my channel and today we are back to my channel and today we are going to solve a new lead code question going to solve a new lead code question that is determined color of a chessboard that is determined color of a chessboard Square we will be solving this question Square we will be solving this question with the help of python the question with the help of python the question said you are given coordinates a string said you are given coordinates a string that represents the coordinates of a that represents the coordinates of a square of the chessboard below is the square of the chessboard below is the chessboard for your reference return chessboard for your reference return true if the square is white and false if 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 so I will say that e I will say that e C 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 so they are saying the coordinate always so they are saying the coordinate always start with the letter first so we will start with the letter first so we will Target later first so we can use this Target later first so we can use this here because it will always start with a here because it will always start with a letter so if I say that if a letter is e letter so if I say that if a letter is e or a letter is or a letter is these so let's copy this to save our these so let's copy this to save our time time copy and paste it four times or copy and paste it four times or 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 and you will see that mod 2 is equals to and you will see that mod 2 is equals to zero because see these are all zero because see these are all two multiple of 2 2 4 6 8 are all two multiple of 2 2 4 6 8 are all multiple of two so if we can uh use this multiple of two so if we can uh use this for for so we have to use it so we have to use it as an integer because it will not divide as an integer because it will not divide if it's a string so we have to convert if it's a string so we have to convert this only thing here that is our this only thing here that is our coordinate one coordinate one into into integer so that we can see the into into integer so that we can see the modulus of 2 that's its mean even or not modulus of 2 that's its mean even or not if it even then return if it even then return true true else else return 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 coordinates uh is uh is divisible by 2 divisible by 2 means if it's divisible by 2 means if it's divisible by 2 means this value h d f h so B2 D2 F2 S2 means this value h d f h so B2 D2 F2 S2 and so on I will say that return false and so on I will say that return false just the opposite of that just the opposite of that and else and else return return true true so that's that's all in the question so that's that's all in the question hope you have understood it let's run hope you have understood it let's run the code and check the validity of our the code and check the validity of our answer so we have quarter answer here answer so we have quarter answer here thank you guys for watching the video if thank you guys for watching the video if you have any doubt ask in the comment you have any doubt ask in the comment section
2024-03-22 16:20:06
1,812
https://i.ytimg.com/vi/G…axresdefault.jpg
1812. Determine Color of a Chessboard Square with Python | Leetcode with Python #youtube #youtuber
rVuU8iZs4Qk
[Music] hello everyone welcome to kodus camp we hello everyone welcome to kodus camp we are 12th day of october lead code are 12th day of october lead code challenge challenge and the problem we are going to cover in and the problem we are going to cover in this video is this video is guess number higher or lower it is again guess number higher or lower it is again a easy category problems the input given a easy category problems the input given here is an integer value n and we have here is an integer value n and we have to return the number to return the number we picked we picked so so the problem statement has a predefined the problem statement has a predefined api call the method named guess api call the method named guess and this is going to return three and this is going to return three possible values possible values the numbers are going to be from 1 to n the numbers are going to be from 1 to n and and if the number we sent to this method is if the number we sent to this method is exactly matching the same number then it exactly matching the same number then it is going to return 0 is going to return 0 if it is less than the number then it is if it is less than the number then it is going to return minus 1 if it is greater going to return minus 1 if it is greater than the number it is going to return 1. than the number it is going to return 1. so so we have to use minimum number of guess we have to use minimum number of guess calls and guess the number calls and guess the number the system has picked or we picked the system has picked or we picked so let's understand this problem with an so let's understand this problem with an example example so here is the given example the n is so here is the given example the n is equal to 8 which means the numbers are equal to 8 which means the numbers are from 1 to 8 and pick is not actually an from 1 to 8 and pick is not actually an input input the system randomly picks a number and the system randomly picks a number and we have to we have to find exactly which number the system has find exactly which number the system has picked by using the guess call picked by using the guess call so what would guess written is so what would guess written is 0 1 or minus 1 for example if we if the 0 1 or minus 1 for example if we if the system picked the number 5 system picked the number 5 and we have to pass and we have to pass possible numbers to the guess method and possible numbers to the guess method and find which number the system has find which number the system has picked for example if we are passing the picked for example if we are passing the number number seven seven first first the possible outputs will be zero minus the possible outputs will be zero minus one and one so it is definitely not zero one and one so it is definitely not zero because uh the number system picked this because uh the number system picked this five and b cent is seven five and b cent is seven so so if the number is less than the number if the number is less than the number the system has picked then it is gonna the system has picked then it is gonna return minus one so obviously 7 is return minus one so obviously 7 is greater than 5 so it is going to return greater than 5 so it is going to return 1 so which means we can figure out 1 so which means we can figure out 7 is greater than 5 so we have to search 7 is greater than 5 so we have to search for the number which is less than 7 so for the number which is less than 7 so we we we can put our search before 7 and look we can put our search before 7 and look for the numbers for example if we for the numbers for example if we send 3 as the second guess so the guess send 3 as the second guess so the guess method we are passing 3 3 is not 5 so it method we are passing 3 3 is not 5 so it is not going to return 0 but 3 is less is not going to return 0 but 3 is less than 5 so it is going to return minus 1 than 5 so it is going to return minus 1 so in this case we can figure out the so in this case we can figure out the value is after 3 value is after 3 so how are we going to approach this so how are we going to approach this the straight away brute force method the straight away brute force method would be would be calling the guess method calling the guess method from the number 1 from the number 1 to to n that is 8 here and for every method it n that is 8 here and for every method it will be a number return for example will be a number return for example minus 1 minus 1 minus 1 till 4 and guess minus 1 minus 1 minus 1 till 4 and guess of 5 would have 0 and then plus 1 plus 1 of 5 would have 0 and then plus 1 plus 1 plus 1 till plus 1 till 8. 8. so in this case whichever guess is so in this case whichever guess is having 0 that is the number the system having 0 that is the number the system has picked and we should return it this has picked and we should return it this is a straight call and i try to brute is a straight call and i try to brute force method that is going to take force method that is going to take because n time complexity because n time complexity but how do we solve it in a better way but how do we solve it in a better way clearly the input values are from 1 to n clearly the input values are from 1 to n and they are in ascending order and they are in ascending order so this gives us a very clear clue that so this gives us a very clear clue that we can approach this problem using we can approach this problem using binary search binary search so simply we are going to divide the so simply we are going to divide the input by half as usual and gonna find input by half as usual and gonna find the mid so here the mid is going to be 4 the mid so here the mid is going to be 4 and we are going to pass this mid value and we are going to pass this mid value to our guess and based on the result of to our guess and based on the result of our guess method we are going to our guess method we are going to fix our search space fix our search space so let's first so let's first fix the mid to 4 and try sending 4 to fix the mid to 4 and try sending 4 to our guess method so as i said 5 is the our guess method so as i said 5 is the number our program has been picked so we number our program has been picked so we are going to first pass are going to first pass guess of 4 and guess of 4 would actually guess of 4 and guess of 4 would actually return us minus 1 which means our value return us minus 1 which means our value is actually less than the value that the is actually less than the value that the system has picked system has picked so clearly we have to fix our search so clearly we have to fix our search space after 4. so we are going to move space after 4. so we are going to move our our left value to 5 left value to 5 because 4 is not our value we are because 4 is not our value we are searching for searching for and right value stays the same so now and right value stays the same so now our search space is our search space is between 5 and eight now again it's time between 5 and eight now again it's time to fix the mid value and to fix the mid value and pass it on to the guess method so here pass it on to the guess method so here the mid value is going to be six we are the mid value is going to be six we are going to pass going to pass guess of six guess of six so this is going to return one because 6 so this is going to return one because 6 is clearly greater than 5 which means is clearly greater than 5 which means our search space must be before 6 so we our search space must be before 6 so we are going to move our right pointer are going to move our right pointer towards before 6. towards before 6. now our left pointer and right pointer now our left pointer and right pointer point at the same number five point at the same number five which means we have reached the point which means we have reached the point where our guess is going to be zero so where our guess is going to be zero so for confirmation let us send our guess for confirmation let us send our guess back with five and that returns zero back with five and that returns zero which confirms phi is going to be a which confirms phi is going to be a number number so 5 is going to be an output so 5 is going to be an output so the previous solution is much easier so the previous solution is much easier than this this algorithm is going to than this this algorithm is going to work and big o of log in time complexity work and big o of log in time complexity because because of the binary search rule and we go of of the binary search rule and we go of one space complexity one space complexity so hope you're understanding the so hope you're understanding the solution let's get back to the code solution let's get back to the code so as i said let's fix our limits left so as i said let's fix our limits left and right to one and yeah so every time we are going to call our so every time we are going to call our guess method and store the result in the guess method and store the result in the integer variables since we don't have to integer variables since we don't have to call it again and again 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 so yes based on the result if the result so yes based on the result if the result is less than zero which is minus one is less than zero which is minus one then we are going to fix our search then we are going to fix our search space before the minute if not we fix space before the minute if not we fix our uh left bound to after the bit if our uh left bound to after the bit if not we did not find the number at all not we did not find the number at all then we are going to return -1 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
2024-03-24 11:39:43
374
https://i.ytimg.com/vi/r…axresdefault.jpg
Guess Number Higher or Lower | LeetCode 374 | Coder Camp
RRQVDqp5RSE
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem maximize score let's solve the problem maximize score after n operations this one is pretty after n operations this one is pretty hard but it's not as crazy as you might hard but it's not as crazy as you might think and if you're not super familiar think and if you're not super familiar with bit masks this is an opportunity to with bit masks this is an opportunity to learn a bit about them no pun intended learn a bit about them no pun intended but we are given an array of positive but we are given an array of positive integers and the fact that they're integers and the fact that they're positive integers is only significant positive integers is only significant because we are going to be running the because we are going to be running the gcd operation the greatest common gcd operation the greatest common divider aka the greatest common factor divider aka the greatest common factor if you don't remember what that is if you don't remember what that is consider two numbers six and nine what's consider two numbers six and nine what's the greatest factor between them I think the greatest factor between them I think it is three because we can take six it is three because we can take six divided by three and it equals two we divided by three and it equals two we can take nine and divide it by three and can take nine and divide it by three and it equals three so we get an integer in it equals three so we get an integer in both cases and we can't really get a both cases and we can't really get a larger integer that will divide them and larger integer that will divide them and in this case they say the size of the in this case they say the size of the array is actually two times n that's array is actually two times n that's significant because we're told that significant because we're told that we're going to be doing n operations we're going to be doing n operations where we are going to be choosing two where we are going to be choosing two elements from the array and basically elements from the array and basically removing them to calculate a score removing them to calculate a score therefore we can only do about n therefore we can only do about n operations until we run out of elements operations until we run out of elements from the array because it's of length from the array because it's of length two times n so suppose we have an array two times n so suppose we have an array that looks kind of like this how many that looks kind of like this how many operations would we do in this case operations would we do in this case three of course because let's say we're three of course because let's say we're going to be removing two each time and going to be removing two each time and we do that again and then we do that we do that again and then we do that again and then we're out of elements but again and then we're out of elements but what we're going to be doing every time what we're going to be doing every time we remove two elements is calculating we remove two elements is calculating the gcd between them and I'm just going the gcd between them and I'm just going to tell you right now that we're not to tell you right now that we're not going to get super into that this is a going to get super into that this is a math function and in the scope of this math function and in the scope of this problem we're just allowed to call problem we're just allowed to call math.gcd because I think this problem is math.gcd because I think this problem is hard enough and in a real interview hard enough and in a real interview hopefully your interviewer would tell hopefully your interviewer would tell you that or you could just ask them but you that or you could just ask them but given those two numbers that we removed given those two numbers that we removed we would call gcd on them one and two we would call gcd on them one and two find the greatest common divider which I find the greatest common divider which I believe in this case is one and as we'd believe in this case is one and as we'd make these n Opera operations we're make these n Opera operations we're going to keep track of how many going to keep track of how many operations we've made so if this is our operations we've made so if this is our first operation we're going to take the first operation we're going to take the score or rather the gcd of the two score or rather the gcd of the two numbers and multiply it by one because numbers and multiply it by one because this is our first operation so so far this is our first operation so so far our score would be equal to one suppose our score would be equal to one suppose we take two more elements three and four we take two more elements three and four calculate the gcd between them three and calculate the gcd between them three and four I believe it is also one in this four I believe it is also one in this case but this time we would take one and case but this time we would take one and multiply it by two because this is the multiply it by two because this is the second time we are doing that operation second time we are doing that operation and then we would take this two and add and then we would take this two and add it to the score which would get us to a it to the score which would get us to a total of three so far and then at the total of three so far and then at the end we would do that again and pretty end we would do that again and pretty much repeat that operation but the much repeat that operation but the complicated thing here is that we have complicated thing here is that we have flexibility on how we want to calculate flexibility on how we want to calculate these gcds so we don't have to do it the these gcds so we don't have to do it the way I showed we actually have choices we way I showed we actually have choices we could start with one and six we could could start with one and six we could start with one and four we could start start with one and four we could start with three and four it doesn't matter we with three and four it doesn't matter we have a lot of flexibility but we want to have a lot of flexibility but we want to find the way that maximizes the score so find the way that maximizes the score so we want to find the max score we could we want to find the max score we could possibly get doing it this way which is possibly get doing it this way which is definitely not going to be easy I mean definitely not going to be easy I mean right off the bat you might think okay right off the bat you might think okay let's just try like The Brute Force way let's just try like The Brute Force way trying every single combination but you trying every single combination but you might think is there room for might think is there room for optimization here like is there some optimization here like is there some kind of math pattern behind it could we kind of math pattern behind it could we maybe sort the array or maybe numbers maybe sort the array or maybe numbers that are close together going to have a that are close together going to have a greatest common divider that's larger greatest common divider that's larger because that's probably what we want to because that's probably what we want to maximize to maximize the score well once maximize to maximize the score well once you start going down that train of you start going down that train of thinking you kind of realize that even thinking you kind of realize that even if there is a solution like that you if there is a solution like that you must need like a math dissertation to must need like a math dissertation to figure it out so probably there isn't figure it out so probably there isn't going to be some kind of crazy math going to be some kind of crazy math solution and again if there is you solution and again if there is you probably just wouldn't be able to figure probably just wouldn't be able to figure it out so then you might go back to the it out so then you might go back to the brute force and think if you can somehow brute force and think if you can somehow try to optimize this but before we even try to optimize this but before we even optimize it let's just understand stand optimize it let's just understand stand how we could even solve this in a Brute how we could even solve this in a Brute Force way because it's not trivial Force way because it's not trivial that's for sure okay so starting at the that's for sure okay so starting at the root of our decision tree because we are root of our decision tree because we are going to solve this recursively let's going to solve this recursively let's try to enumerate all possibilities how try to enumerate all possibilities how would that be like what's our first would that be like what's our first choice well we can choose any pair of choice well we can choose any pair of values we could choose these two values values we could choose these two values we could choose this and this we could we could choose this and this we could choose one and four etc etc how do we choose one and four etc etc how do we even enumerate those well we're going to even enumerate those well we're going to need a couple nested for Loops right and need a couple nested for Loops right and doing that we realize that at the first doing that we realize that at the first layer of our decision tree we have about layer of our decision tree we have about N squared choices that is not going to N squared choices that is not going to be very efficient right and when I'm be very efficient right and when I'm saying n in this case let's say n is saying n in this case let's say n is actually the length of the array even actually the length of the array even though in the context of this problem it though in the context of this problem it means something else but I think it's means something else but I think it's more simple to just think about it in more simple to just think about it in terms of n so we have N squared choices terms of n so we have N squared choices how many choices are we going to have how many choices are we going to have well if we remove two elements on each well if we remove two elements on each choice and the length of our array is n choice and the length of our array is n the height of the tree is probably going the height of the tree is probably going to be n divided by two so overall here to be n divided by two so overall here the time complexity is going to be N the time complexity is going to be N squared to the power of n divided by 2 squared to the power of n divided by 2 which I think would be n to the power of which I think would be n to the power of 2 times n because I think this 2 times n because I think this multiplies with this well I guess the multiplies with this well I guess the divided by 2 cancels out the 2 here so divided by 2 cancels out the 2 here so this would actually just be roughly n to this would actually just be roughly n to the power of n but clearly that's not the power of n but clearly that's not super efficient that's even a lot worse super efficient that's even a lot worse than 2 to the power of n so this is not than 2 to the power of n so this is not very efficient but there is something we very efficient but there is something we can do to speed this up and the idea is can do to speed this up and the idea is caching yes this is a dynamic caching yes this is a dynamic programming problem but it's not a programming problem but it's not a traditional one we're gonna need a bit traditional one we're gonna need a bit mask but first let me tell you why we mask but first let me tell you why we can use a bit mask in the first place can use a bit mask in the first place there is a constraint on this problem there is a constraint on this problem which is not shown here but it tells us which is not shown here but it tells us that the length of this array is at most that the length of this array is at most going to be 14. that's not a very large going to be 14. that's not a very large number at all now it's not not enough to number at all now it's not not enough to pass on leak code if you have a solution pass on leak code if you have a solution that's n to the power of n that's going that's n to the power of n that's going to be a pretty big number but using this to be a pretty big number but using this we can apply caching notice something we can apply caching notice something about our decision tree here well about our decision tree here well instead of drawing out that entire tree instead of drawing out that entire tree I'm actually just going to show you on I'm actually just going to show you on the arrays it'll be a lot simpler trust the arrays it'll be a lot simpler trust me let's say for one of the branches me let's say for one of the branches over here we chose one and two as our over here we chose one and two as our first choice and then maybe on our first choice and then maybe on our second choice we chose three and four second choice we chose three and four that's one possibility let's say on that's one possibility let's say on another possibility though we chose one another possibility though we chose one and three then on the second choice we and three then on the second choice we chose two and four so even though we chose two and four so even though we made different decisions in our tree we made different decisions in our tree we ended up at the same sub problem now the ended up at the same sub problem now the way we calculated the score when we took way we calculated the score when we took these elements and we took these these elements and we took these elements definitely could be different elements definitely could be different I'm not saying the score is the same I'm I'm not saying the score is the same I'm saying after we make those choices the saying after we make those choices the sub problem is the same so when we have sub problem is the same so when we have to solve this sub problem why should we to solve this sub problem why should we ever have to solve it again that's the ever have to solve it again that's the idea that we can apply caching to idea that we can apply caching to because we see there's repeated work because we see there's repeated work going on now how do we even Define this going on now how do we even Define this sub problem we can't just keep track of sub problem we can't just keep track of it in a single integer can we because it in a single integer can we because here clearly we have an array so what here clearly we have an array so what should we do maybe we should use an should we do maybe we should use an array as the key of our cache and what array as the key of our cache and what that array would represent is for each that array would represent is for each element have we already used it or is it element have we already used it or is it available to us so in this case we have available to us so in this case we have six positions and we say for the first six positions and we say for the first four they've already been used and for four they've already been used and for the second two and for the last two they the second two and for the last two they are still available to us so that's kind are still available to us so that's kind of the information we need and yes you of the information we need and yes you actually can use an array if you want to actually can use an array if you want to or maybe you could convert that array or maybe you could convert that array into some kind of a string if you want into some kind of a string if you want to that's like delimited by commas but to that's like delimited by commas but the most common approach here is to use the most common approach here is to use a bit mask because actually we can a bit mask because actually we can represent all of this information in a represent all of this information in a single integer and we can do it in an single integer and we can do it in an integer that's 32-bit because the integer that's 32-bit because the constraint here is that the max size of constraint here is that the max size of the array is going to be 14. so we only the array is going to be 14. so we only need 14 bits 32 bits should be plenty need 14 bits 32 bits should be plenty for us so instead of using the array to for us so instead of using the array to Mark whether our value has been used or Mark whether our value has been used or not we're going to have an integer that not we're going to have an integer that might look like this well it'll have might look like this well it'll have more bits but we just care about the more bits but we just care about the first six of them and when we use an first six of them and when we use an integer like for example when we use integer like for example when we use these four we would take these and turn these four we would take these and turn them into ones like this and this would them into ones like this and this would evaluate to some integer I don't know evaluate to some integer I don't know what it is off the top of my head but it what it is off the top of my head but it can be used as the key for our cache in can be used as the key for our cache in my case I'm going to use a hash map but my case I'm going to use a hash map but you could also use a array a you could also use a array a one-dimensional array now lastly what one-dimensional array now lastly what are the parameters that we're going to are the parameters that we're going to keep track of as we make our recursive keep track of as we make our recursive calls because remember not only do we calls because remember not only do we have to keep track of which elements have to keep track of which elements we've already used we have to keep track we've already used we have to keep track of what operation and we are currently of what operation and we are currently on because that plays into the on because that plays into the calculation we have to remember take calculation we have to remember take that operation number and then multiply that operation number and then multiply it by the gcd that we end up calculating it by the gcd that we end up calculating each time so at that point you might each time so at that point you might think as we go down this decision tree think as we go down this decision tree we're keeping track of our bit mask but we're keeping track of our bit mask but we're also keeping track of the we're also keeping track of the operation number which at first might be operation number which at first might be one then on the second level might be one then on the second level might be two two etc etc should we also use this as a key etc etc should we also use this as a key in our hashmap well think about it for a in our hashmap well think about it for a second and I'll tell you right now the second and I'll tell you right now the answer is no because actually this answer is no because actually this operation number represents redundant operation number represents redundant information we don't need to use that as information we don't need to use that as a key in our cache I mean technically a key in our cache I mean technically you could if you want to I'm pretty sure you could if you want to I'm pretty sure your solution would pass the same as your solution would pass the same as mine but it's redundant information let mine but it's redundant information let me tell you why going back to the me tell you why going back to the example maybe on one branch I choose example maybe on one branch I choose these two elements first on another these two elements first on another Branch I choose one and three then for Branch I choose one and three then for the second decision Maybe I choose three the second decision Maybe I choose three and four on one branch on the other and four on one branch on the other Branch I choose two and four we ended up Branch I choose two and four we ended up at the same sub problem this is what our at the same sub problem this is what our bit masks would look like they would be bit masks would look like they would be identical and not only that the identical and not only that the operation number would also be identical operation number would also be identical operation would be two here and it would operation would be two here and it would be 2 over here because we have to choose be 2 over here because we have to choose two elements at a time if the sub two elements at a time if the sub problems are the exact same therefore we problems are the exact same therefore we must have made the same number of must have made the same number of operations here as we did over here so operations here as we did over here so the operation number is redundant the operation number is redundant information we are going to keep track information we are going to keep track of it for the calculation but we don't of it for the calculation but we don't need to use it as a key in our cache need to use it as a key in our cache okay so knowing all of that what are the okay so knowing all of that what are the total number of possibilities that our total number of possibilities that our key value could be well let's say this key value could be well let's say this array is of size n and for each value we array is of size n and for each value we could either include it or not include could either include it or not include it so we get roughly 2 to the power of n it so we get roughly 2 to the power of n possible values that our bit mask could possible values that our bit mask could be so this is the number of sub problems be so this is the number of sub problems and remember each time we make a choice and remember each time we make a choice we're making N squared choices on each we're making N squared choices on each level of the tree so we take that and we level of the tree so we take that and we multiply this by N squared and that's multiply this by N squared and that's how we get the overall Big O time how we get the overall Big O time complexity well technically we also have complexity well technically we also have to compute the gcd which I believe is to compute the gcd which I believe is going to be log of the max number in the going to be log of the max number in the array so max of nums let's say but I array so max of nums let's say but I think this has already deep enough for think this has already deep enough for the Big O time complexity I would be the Big O time complexity I would be surprised if you ever had to know things surprised if you ever had to know things this in depth in a real interview so this in depth in a real interview so overall we would take this term and overall we would take this term and multiply it by this logarithm term but I multiply it by this logarithm term but I think that's enough so now let's think that's enough so now let's actually code this up so I usually start actually code this up so I usually start these DP problems with my depth first these DP problems with my depth first search and we know we're gonna have two search and we know we're gonna have two parameters one is going to be the mask parameters one is going to be the mask which is going to tell us which numbers which is going to tell us which numbers are available and the second is going to are available and the second is going to be the operation number I'm going to be the operation number I'm going to call it op for short and the main base call it op for short and the main base case believe it or not in this case is case believe it or not in this case is just going to be if this mask has just going to be if this mask has already been computed meaning this is in already been computed meaning this is in our DP cache well let me just call it our DP cache well let me just call it the cache because that's a bit more the cache because that's a bit more descriptive and I'm going to create that descriptive and I'm going to create that cache up above in my case I'm going to cache up above in my case I'm going to create a hashmap because it makes things create a hashmap because it makes things more simple you don't have to know off more simple you don't have to know off the top of your head how many possible the top of your head how many possible values we are actually going to be using values we are actually going to be using as the key but like I said it's going to as the key but like I said it's going to be roughly 2 to the power of the length be roughly 2 to the power of the length of nums so if you wanted to create an of nums so if you wanted to create an array instead of a hashmap that would be array instead of a hashmap that would be the size of your array maybe a plus one the size of your array maybe a plus one to that but I'll keep things simple and to that but I'll keep things simple and use a hash map and if we have computed use a hash map and if we have computed this subproblem before let's just go this subproblem before let's just go ahead and return the result that we ahead and return the result that we ended up storing if not then we actually ended up storing if not then we actually have to calculate it and we do that by have to calculate it and we do that by enumerating all possible choices with a enumerating all possible choices with a couple nested for Loops so for I in couple nested for Loops so for I in range length of nums and for J in range range length of nums and for J in range length of nums but remember there's a length of nums but remember there's a bit of a bug here we don't want to have bit of a bug here we don't want to have to necessarily count the duplicate pairs to necessarily count the duplicate pairs so we should start our second pointer so we should start our second pointer right after her the first pointer at I right after her the first pointer at I plus one and now's the part where we plus one and now's the part where we want to do our recursive call right but want to do our recursive call right but we can only do the recursive call for we can only do the recursive call for numbers that have not already been numbers that have not already been chosen how do we know if the number at chosen how do we know if the number at index I has already been used how do we index I has already been used how do we know if the number at index I and the know if the number at index I and the number at index J have both not been number at index J have both not been used before well that's what our bit used before well that's what our bit mask is for if the ith bit is one then mask is for if the ith bit is one then that value has already been used before that value has already been used before how do we figure that out well basically how do we figure that out well basically we take one shift it to the left by I we take one shift it to the left by I and we take this value and we bit wise and we take this value and we bit wise and it with the mask value so for and it with the mask value so for example if our mask looked something example if our mask looked something like this zero zero zero and we wanted like this zero zero zero and we wanted to know if maybe this value had already to know if maybe this value had already been used before we would take our one been used before we would take our one digit which is over here shift it to the digit which is over here shift it to the left left by two so like to put it in left left by two so like to put it in this position and then we would and this position and then we would and these together bit wise and them these together bit wise and them together and we would get a one if both together and we would get a one if both of them are one and we would get a zero of them are one and we would get a zero if this is a zero so it works pretty if this is a zero so it works pretty much like you would expect it to so much like you would expect it to so let's check if this has been used and let's check if this has been used and let's also check if the other one has let's also check if the other one has been used so one shifted to the left by been used so one shifted to the left by J bit wise or it or bitwise and it with J bit wise or it or bitwise and it with the mask and if either of those have the mask and if either of those have been used before then we can't use both been used before then we can't use both of them so therefore we're just going to of them so therefore we're just going to continue to the next iteration of the continue to the next iteration of the loop okay but if they haven't been used loop okay but if they haven't been used before what should we do we probably before what should we do we probably want to make our recursive call and we want to make our recursive call and we probably want to pass in the new mask probably want to pass in the new mask after we have marked both of them as after we have marked both of them as being used so let's actually create a being used so let's actually create a new mask after we have marked each of new mask after we have marked each of those positions which we can do like those positions which we can do like this mask logic or with one shifted to this mask logic or with one shifted to the left left by I and then bitwise or the left left by I and then bitwise or that with one shifted to the left by J that with one shifted to the left by J the difference between the bitwise and the difference between the bitwise and and the bitwise or is that and is and the bitwise or is that and is basically us reading the value when we basically us reading the value when we bit wise or we're pretty much bit wise or we're pretty much overwriting the value at that location overwriting the value at that location now that we have the new mask we can now that we have the new mask we can pass that in as a parameter and for the pass that in as a parameter and for the second parameter we probably want to second parameter we probably want to pass in the current operation number pass in the current operation number plus one but what exactly are we going plus one but what exactly are we going to do with this recursive call what were to do with this recursive call what were we trying to do in the first place we trying to do in the first place remember we were trying to calculate the remember we were trying to calculate the score of the two values that we just score of the two values that we just chose how do we calculate the score of chose how do we calculate the score of them well that's the part where we just them well that's the part where we just use math.gcd and python because this use math.gcd and python because this problem is hard enough and we don't want problem is hard enough and we don't want to get super into the math so we're just to get super into the math so we're just going to call gcd on the two numbers going to call gcd on the two numbers that we are currently choosing and we that we are currently choosing and we say that's our score but remember we say that's our score but remember we actually want to multiply this by the actually want to multiply this by the operation number as well it's easy to operation number as well it's easy to forget so try not to and then using that forget so try not to and then using that score we want to take that and add it score we want to take that and add it with the return value of our DFS over with the return value of our DFS over here but this is just one possibility we here but this is just one possibility we are enumerating all the possibilities are enumerating all the possibilities and trying to determine the maximum so and trying to determine the maximum so what we're going to say here is the cash what we're going to say here is the cash for this mask value is going to be the for this mask value is going to be the max of itself cash with mask as the key max of itself cash with mask as the key and whatever value we ended up and whatever value we ended up calculating here let me clean this up a calculating here let me clean this up a tiny bit so this is the recursive step tiny bit so this is the recursive step where we try to find the maximum there's where we try to find the maximum there's a tiny bug here though what happens if a tiny bug here though what happens if we try to access this value if we we try to access this value if we haven't already inserted mask as a key haven't already inserted mask as a key well we're going to get an exception well we're going to get an exception throne and an easy way to fix that would throne and an easy way to fix that would be before we even start the loop Just be before we even start the loop Just Say Cash mask is equal to zero just Say Cash mask is equal to zero just initialize it to some value like zero initialize it to some value like zero but in even simpler way at least in but in even simpler way at least in Python would be just to make this a Python would be just to make this a dictionary carry this hash map a default dictionary carry this hash map a default dict like this collections.default dict dict like this collections.default dict where the default value is going to be where the default value is going to be an integer so this will basically do an integer so this will basically do what I talked about previously this will what I talked about previously this will evaluate to zero if the key hasn't evaluate to zero if the key hasn't already been inserted yet now after this already been inserted yet now after this Loop has terminated we will have the max Loop has terminated we will have the max stored so let's go ahead and return it stored so let's go ahead and return it out here and finally now that we've out here and finally now that we've wrapped up the DFS let's go ahead and wrapped up the DFS let's go ahead and actually call the DFS and return the actually call the DFS and return the return value our mask initially we don't return value our mask initially we don't even need to create a variable for this even need to create a variable for this remember it's just an integer we can remember it's just an integer we can just pass in zero like this now for the just pass in zero like this now for the operation number we're not starting at operation number we're not starting at zero we're starting at one and then zero we're starting at one and then incrementing it each time that we call incrementing it each time that we call the DFS so this is the entire code the DFS so this is the entire code Remember the Time complexity was roughly Remember the Time complexity was roughly N squared for the for loops and the N squared for the for loops and the number of times we're going to be number of times we're going to be solving the sub problem and caching it solving the sub problem and caching it is going to be 2 to the power of n and is going to be 2 to the power of n and to actually calculate the gcd each time to actually calculate the gcd each time in the nested for Loops is going to be in the nested for Loops is going to be log M where let's say m is the max log M where let's say m is the max integer in our number array now let's integer in our number array now let's run this to make sure that it works now run this to make sure that it works now as you can see yes it does and it's as you can see yes it does and it's pretty efficient if you found this pretty efficient if you found this helpful please like And subscribe if helpful please like And subscribe if you're preparing for coding interviews 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 free resources to help you prepare free resources to help you prepare thanks for watching and I'll see you thanks for watching and I'll see you soon
2024-03-22 14:55:47
1,799
https://i.ytimg.com/vi/R…axresdefault.jpg
Maximize Score after N Operations - Leetcode 1799 - Python
jpuDyt-ruFc
A high-rise So friend, today we will make a playlist of binary search and this video of binary search is going to be and this video of binary search is going to be made. Okay, the question is medium. The question on the made. Okay, the question is medium. The question on the list is number-34. The list is number-34. The question is how to find the first question is how to find the first and last position of element in state. and last position of element in state. and last position of element in state. 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 Take and last position which Take and last position which Take and last position which index number is four then this is to be returned index number is four then this is to be returned first position and last pollution first position and last pollution and given target is ok the end of this answer is 384 and given target is ok the end of this answer is 384 its answer is 314 ok its answer is 314 ok so this is not told to you in the interview so this is not told to you in the interview that brother that brother that brother 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 Let is given in the question Let is given in the question Let is given in the question that you have to solve these in one place, it that you have to solve these in one place, it is okay because in the off end, it is is okay because in the off end, it is very difficult to solve it, you will search the sample very difficult to solve it, you will search the sample attractive, first attractive, first find the index where at is there, then you will search for edit, then you will find the index where at is there, then you will search for edit, then you will find the last one. find the last one. find the last one. 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. What was the What was the What was the binary system? Our left was the binary system? Our left was the mode index, right was the most index, mode index, right was the most index, okay and we used to find out the 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, okay, okay, after that we used to check 3 things, the after that we used to check 3 things, the face that face that our our our okay, that means my net is bigger than the target, so I have to okay, that means my net is bigger than the target, so I have to look on the left side, if the target look on the left side, if the target is there, is there, then then what will I do, I will make the AR smaller, if I what will I do, I will make the AR smaller, if I look at the fat, then Arjun to look at the fat, then Arjun to look at the fat, then Arjun to 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 So that means we will do it by heart, that So that means we will do it by heart, that So that means we will do it by heart, that means we have got the difficult visible means we have got the difficult visible target, okay, if it does not target, okay, if it does not happen, then as our Hey Easy Medical Tourism happen, then as our Hey Easy Medical Tourism target has been reached, then we would have returned target has been reached, then we would have returned that we have got the index, it is made that we have got the index, it is made here only. here only. here only. 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 0202 210 [Music] Show More Yes Brother, It's okay and here it is and here it is, we have taken out l plus and minus l bittu and If the target is If the target is If the target is good then it's ok then madam what will 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 my Me Too turned out to be this is my mail my Me Too turned out to be this is my mail ok no this is my melt so I ok no this is my melt so I got the target It was a tiger tattoo only but got the target It was a tiger tattoo only but this is my answer this is my answer this is my answer 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, Is there any more Is there any more Is there any more two on the right side two on the right side because I want the left most target, I want because I want the left most target, I want brightness and target. Okay, so how will we brightness and target. Okay, so how will we fold it, how can we do it, fold it, how can we do it, so look at that simple, I will take an example from it. so look at that simple, I will take an example from it. Okay, To Tu Tu Tu Tu To Tu Tu Tu Tu To Tu Tu Tu Tu Nirodh Nirodh 1234 1234 521 What had I taken out, mine had come out, 521 What had I taken out, mine had come out, this is my oil, this is mine coming, it is okay this is my oil, this is mine coming, it is okay and and that I had taken out the mid, that was that I had taken out the mid, that was my target, two had I taken out the my target, two had I taken out the mud, what had I taken out, you had taken out the mud, what had I taken out, you had taken out the remedy in the beginning. remedy in the beginning. remedy in the beginning. 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 So the answer to that is the matter but for So the answer to that is the matter but for So the answer to that is the matter but for now I feel that this is my now I feel that this is my answer so I will break the net use in the left most part and take it to answer so I will break the net use in the left most part and take it to mean you are my index, mean you are my index, hey, I have left the tools and taken it okay but hey, I have left the tools and taken it okay but I will not return the balance. I will not return the balance. I will not return the balance. 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 Alarm, I agreed, I went 190 by 20, Alarm, I agreed, I went 190 by 20, 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 So it is a simple condition, then I will make it So it is a simple condition, then I will make it So it is a simple condition, then I will make it eligible to make plus one, then eligible to make plus one, then aloe vera has come here, aloe vera has come here, you have it, then you have come to my R here, do you have it, then you have come to my R here, do n't n't look like this, if it has come to the alarm, then I look like this, if it has come to the alarm, then I grow it twice in the morning. grow it twice in the morning. What are you looking at me now? Hey, how are you looking? [Music] [Music] 0210 45 And everything is fine now that my oil was here, RB was here and remember what I had assumed in the beginning What came out in the beginning was two What came out in the beginning was two What came out in the beginning was two index number two was for me I index number two was for me I write the target in the settings again so that 2222 Okay write the target in the settings again so that 2222 Okay now I will go out again as usual now I will go out again as usual medical 2l plus this is what one plus and minus medical 2l plus this is what one plus and minus link one minus one by two is that link one minus one by two is that link one minus one by two is that 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, My answer would be, My answer would be, My answer would be, which is one, left most, maybe you, I am my left most, I will update it and you, I am my left most, I will update it and stopped it, but again I stopped it, but again I said the same thing, maybe there are two more on the left side, so 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 did not return but went to the left and I did not return but went to the left and okay, so let's check, 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 The condition is that by doing The condition is that by doing The condition is that by doing binary search everywhere, left is always binary search everywhere, left is always smaller than right, so if you take us now then smaller than right, so if you take us now then look in the final, we will have got our look in the final, we will have got our answer, I have found the leftmost one, answer, I have found the leftmost one, I am the leftmost, two fonts and different is The thing is character, The thing is character, The thing is character, our answer is similar, you think yourself, if you have to our answer is similar, you think yourself, if you have to take out the right most, take out the right most, okay, I am coming again in the same line, okay, I am coming again in the same line, if you have to take out the right most, 202 [Music] 2102 three, four, five, aloe vera is here and Figured out Figured out Figured out that the media will be released Zero Plus File Manager that the media will be released Zero Plus File Manager Fight for Justice Two So what would I like to ask for now Fight for Justice Two So what would I like to ask for now that this is my mail, we have this 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 my index number is two, even if what I have got is got is got is 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 and now my hey, something has happened and now my hey, something has happened that the body is Is zero two two two two two Is zero two two two two two Is zero two two two two two 02 02 12345 now aloe vera is here and here is 12345 now aloe vera is here and here is done okay I take out again done okay I take out again medical two three plus five hard work in the 2nd medical two three plus five hard work in the 2nd three plus two back to 10 three plus one is three plus two back to 10 three plus one is equal to two 4 means my media equal to two 4 means my media equal to two 4 means my media 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, But But But now my time middle which has come is also now my time middle which has come is also equal to the target so I will equal to the target so I will update the brightness tight Mohsin Rezai which one is update the brightness tight Mohsin Rezai which one is for come but I will not characterize again for come but I will not characterize again I will say again that maybe I will say again that maybe right I can also right I can also right I can also 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, 202 two two two 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 - 58225 so my This five is okay, now This five is okay, now This five is okay, now I have added green chilli to one. Okay, I made it so I have added green chilli to one. Okay, I made it so my target is equal to the target, my target is equal to the target, my target is equal to the target, my two got my target is equal to the target, my two got broken in the tiger, so again I will do the same thing, 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 I will hit the update on the right most which is the same as that of the mate. that of the mate. that of the mate. 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 But now But now But now I will free you from the right. What will happen to you? I 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 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 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 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 break and look at me. The answer must have come right most. right most. right most. 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 If we If we If we do this with code, then it will be do this with code, then it will be cleared from the court, okay, let cleared from the court, okay, let me ask the question once again, me ask the question once again, you will be named interior, you will be named interior, which is spotted, in non-tickory border, which is spotted, in non-tickory border, okay, you have to find the target, target okay, you have to find the target, target first. first. first. and if you don't get that target 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, okay, and I will return the one who came, I will take out the left most, right now. Look, Look, Look, I I write find left exactly and fine left most key and find right most, both will be very similar. most, both will be very similar. You can write such a function and I You can write such a function and I can tweet its explanation to the one can tweet its explanation to the one which removes both left and right but which removes both left and right but written separately. written separately. written separately. 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 okay, a letter, and the norm, and Target end is fine then - writes end terrible 20822 end minus one is fine and my 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 l Plus and minus album to meet nickel l Plus and minus album to meet nickel l Plus and minus album to meet nickel donkey come donkey come that my name is the same madam if it that my name is the same madam if it comes equal to the target then what I said comes equal to the target then what I said that I will accept that this is my leftmost that I will accept that this is my leftmost answer who is equal to made answer who is equal to made means means that that that 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 if it is bigger than the mit then I free the left right hand and I am I free the left right hand and I am plus. plus. plus. 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 I can write from ' I can write from ' I can write from ' And find the right And find the right 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 And change the name of the variable And change the name of the variable And change the name of the variable then it is right most ok from now on Ambani then it is right most ok from now on Ambani suggest people to artica suggest people to artica enter medical 2l plus and minus album to enter medical 2l plus and minus album to ok now if this is what I have got then it is ok now if this is what I have got then it is equal to my target ok equal to my target ok assuming you assuming you assuming you okay, okay, it's okay, okay, it's possible, my answer possible, my answer is okay, but what I said was that I is okay, but what I said was that I will still check from the height that my will still check from the height that my right was present and if it is not my target, 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, You You You should go to the bar, should go to the bar, okay, all the exams have been cleared, let's 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
2024-03-20 08:45:54
34
https://i.ytimg.com/vi/j…axresdefault.jpg
Find First & Last Position Of Element In Sorted Array-(LinkedIn, Amazon):Live Coding 🧑🏻‍💻👩🏻‍💻
jUdhe0EPEHA
welcome to january's leeco challenge today's problem is boats to save people today's problem is boats to save people classic problem the eighth person has classic problem the eighth person has weight people eye and each boat can weight people eye and each boat can carry a max carry a max weight of limit now each boat carries at weight of limit now each boat carries at most most two people at the same time provide the two people at the same time provide the sum of the weight of those two people sum of the weight of those two people is at most limit return the minimum is at most limit return the minimum number of boats to carry number of boats to carry every given person now it is guaranteed every given person now it is guaranteed that each person can be carried by a that each person can be carried by a boat so that's good we don't need to boat so that's good we don't need to worry about worry about a person being bigger than the limits a person being bigger than the limits here here now the very first approach you might now the very first approach you might think is to do something recursively think is to do something recursively maybe we can do like backtracking maybe we can do like backtracking we would take like a combination of two we would take like a combination of two people and pop those off the list people and pop those off the list and continue that recursion and then and continue that recursion and then backtrack by adding those two people backtrack by adding those two people back onto the list back onto the list but that's gonna i'm not even sure if but that's gonna i'm not even sure if that would work but either way that's that would work but either way that's gonna be gonna be a exponential time complexity it's just a exponential time complexity it's just gonna take too long so gonna take too long so let's not go with that let's think about let's not go with that let's think about this a little bit more intuitively and this a little bit more intuitively and see if there's a better solution see if there's a better solution so let's just say we had this example so let's just say we had this example here here if we wanted to figure out how how to if we wanted to figure out how how to minimize the number of boats what do we minimize the number of boats what do we want to do want to do well we know that we could carry at well we know that we could carry at least one heavy person right least one heavy person right the heaviest person we could put onto the heaviest person we could put onto the boat at least once now the question the boat at least once now the question then is then is since it's a maximum of two people on since it's a maximum of two people on each boat can we fit another person each boat can we fit another person and what we could do is just get the and what we could do is just get the lightest person lightest person uh we could sort this list by uh we could sort this list by ascending order have two pointers and ascending order have two pointers and check to see check to see can we put both these people on the boat can we put both these people on the boat and if we can and if we can then we could increment our start then we could increment our start pointer and decrement our end pointer pointer and decrement our end pointer if we can't if we can't fit both these if we can't if we can't fit both these people then we know that people then we know that the only person we can put on is that the only person we can put on is that heavy person we can like for instance heavy person we can like for instance here here we could only put on the person three we could only put on the person three with a limit of three and then we just with a limit of three and then we just decrement that decrement that end pointer and keep our star pointer at end pointer and keep our star pointer at the beginning there the beginning there now how do we know that this is going to now how do we know that this is going to minimize number of boats minimize number of boats um well it's i mean there's a um well it's i mean there's a mathematical reason behind it but mathematical reason behind it but if you just think about it intuitively if you just think about it intuitively like if we have the heaviest person like if we have the heaviest person who do we want to put on with him like who do we want to put on with him like obviously we want to put on the lightest obviously we want to put on the lightest person there person there um because the next heaviest person um because the next heaviest person uh we wouldn't want to try to put the uh we wouldn't want to try to put the you know nice person with you know nice person with that person as well um otherwise if we that person as well um otherwise if we can't put that heavy person then we can't put that heavy person then we could only put on could only put on um or we can't put on two people then we um or we can't put on two people then we can only put on that heavy person right can only put on that heavy person right so that's going to be our approach what so that's going to be our approach what we'll do is have two pointers we'll do is have two pointers and we are going to sort our list and we are going to sort our list and then we'll do a um a while loop and then we'll do a um a while loop and check to see if we can fit both and check to see if we can fit both check check to see if we can fit both if we can't to see if we can fit both if we can't then we'd only put in one okay so let's then we'd only put in one okay so let's um start this approach here first thing um start this approach here first thing we'll do is initialize two pointers we'll do is initialize two pointers called start and end this will be zero called start and end this will be zero this will be the length of people this will be the length of people and we have minus one because of the and we have minus one because of the zero index now we want to also zero index now we want to also sort our list to make sure that we sort our list to make sure that we are doing this correctly now while start are doing this correctly now while start is less than or equal to end is less than or equal to end what do we want to do we want to first what do we want to do we want to first check to see if we can put on both check to see if we can put on both people right so if people right so if people start plus people end people start plus people end if it's less than or equal to limit then if it's less than or equal to limit then we are going to we are going to increase our star pointer and decrease increase our star pointer and decrease our end pointer our end pointer otherwise what do we want to do we only otherwise what do we want to do we only decrease our end pointer and we could decrease our end pointer and we could just just make it look like this because that make it look like this because that would be the same thing and also make would be the same thing and also make sure that we increase our boats sure that we increase our boats uh to one and i should initialize that uh to one and i should initialize that up here up here starting with zero once that's finished 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 and accept it so time complexity wise is and accept it so time complexity wise is mostly here mostly here this is going to be n log n otherwise this is going to be n log n otherwise everything else is just everything else is just n because it's two pointers and i don't n because it's two pointers and i don't think we use any extra memory and it's think we use any extra memory and it's really just a sort that might really just a sort that might that takes the bulk of the time that takes the bulk of the time complexity complexity all right so that's it um you know this all right so that's it um you know this is actually is actually a harder problem than looked uh but a harder problem than looked uh but once you know the solution i think it's once you know the solution i think it's pretty easy to implement pretty easy to implement uh one of the other things i think about uh one of the other things i think about is what if we had is what if we had um more people allowed on the boat like um more people allowed on the boat like three people or four people three people or four people how would that algorithm work and my how would that algorithm work and my guess is it would be something similar guess is it would be something similar but but with a double while loop um with a double while loop um possibly a queue involved anyway thanks possibly a queue involved anyway thanks for watching my channel for watching my channel and remember do not trust me i know and remember do not trust me i know nothing
2024-03-22 17:33:43
881
https://i.ytimg.com/vi/j…HA/sddefault.jpg
Leetcode - Boats to Save People (Python)
v-Fo4-9yE4A
hey everyone in this video we are going to solve the three sum closest problem to solve the three sum closest problem in lead code it is similar to the in lead code it is similar to the threesome problem which we threesome problem which we solved previously the only difference is solved previously the only difference is instead of instead of checking if the sum is equal to zero we checking if the sum is equal to zero we have to check if it is if the sum of have to check if it is if the sum of those three numbers is closest to a those three numbers is closest to a target number so we are given a num target number so we are given a num sorry and a Target and we have to sorry and a Target and we have to calculate the sum of any three numbers calculate the sum of any three numbers from this array whose sum when add from this array whose sum when add together together the results closest to the target number the results closest to the target number and we have to return that closest sum and we have to return that closest sum so this is the question let's see how we so this is the question let's see how we can do it can do it so we'll use the same approach we used so we'll use the same approach we used while solving the threesome problem so while solving the threesome problem so we'll run uh first initially we'll sort we'll run uh first initially we'll sort this array so after sorting this array this array so after sorting this array this array will become this array will become -1 1 2 and 4. -1 1 2 and 4. now after this uh we'll start a for loop 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 4 and we'll also use two more pointers 4 and we'll also use two more pointers left pointer and right pointer left pointer and right pointer and then we'll run a while loop and then we'll run a while loop so and that while loop will run so and that while loop will run while our left pointer is less than the while our left pointer is less than the right pointer right pointer so if you try on this so if we start so if you try on this so if we start from here our Loop will start from here from here our Loop will start from here so I will be here uh start of the for so I will be here uh start of the for Loop then our left pointer will be this Loop then our left pointer will be this one just next to it and the right one just next to it and the right pointer will be the end of the array the pointer will be the end of the array the last element of the array here last element of the array here now the difference between the previous now the difference between the previous threesome problem and this one is threesome problem and this one is instead of calculating that if adding instead of calculating that if adding these three number so these three number so the three numbers we have are nums at I the three numbers we have are nums at I plus num set plus num set l l plus numset are plus numset are adding three numbers in previous problem adding three numbers in previous problem three some problem we have to check if three some problem we have to check if adding them result zero but in this adding them result zero but in this problem we have to check the closest sum problem we have to check the closest sum and the thing about closes sum is let's and the thing about closes sum is let's say if we have a target of 0 and we have say if we have a target of 0 and we have two options we have minus 1 and we have two options we have minus 1 and we have two two in this case minus 1 is the closest sum in this case minus 1 is the closest sum we could have got so we could have got so how do we get that so to get that we how do we get that so to get that we have to get the absolute difference so have to get the absolute difference so absolute difference will mean absolute difference will mean irrespective of the sign whether it is a irrespective of the sign whether it is a negative number or positive number so we negative number or positive number so we have to check if the absolute difference have to check if the absolute difference of this one if it is result if it is less than some if it is result if it is less than some temporary variable which we'll be using temporary variable which we'll be using let's call it result let's call it result then we'll replace then we'll replace so if this condition is true so if this condition is true then we'll replace the result with then we'll replace the result with our our this song this song and initially result will be and initially result will be the math Dot the math Dot max value max value which is the maximum value a number can which is the maximum value a number can have in JavaScript so initially it will have in JavaScript so initially it will be greater than irrespective of what be greater than irrespective of what value we get what irrespective of the value we get what irrespective of the temporary sum we get here temporary sum we get here so if you try run this so if you try run this we'll start from here so in initially it we'll start from here so in initially it will be minus 1 plus the value at left will be minus 1 plus the value at left pointer which is 1 and then the value at pointer which is 1 and then the value at right pointer which is 4 it will result right pointer which is 4 it will result 4 and 4 is less than our math dot max 4 and 4 is less than our math dot max value so instead of math dot max value value so instead of math dot max value result will store now 4. result will store now 4. since uh since uh the value we got 4 is greater than the the value we got 4 is greater than the target will move the right pointer target will move the right pointer backward so right pointer will come here backward so right pointer will come here now we'll we'll again calculate the now we'll we'll again calculate the temporary sum it will be minus 1 temporary sum it will be minus 1 plus 1 plus 2 and it will be equals to plus 1 plus 2 and it will be equals to 2. 2. Which is less than 4 so again our Which is less than 4 so again our sum is less than result so we'll replace sum is less than result so we'll replace result with result with our new temporary sum which is 2 3. now our new temporary sum which is 2 3. now 2 is greater than Target so we'll move 2 is greater than Target so we'll move left pointer one step forward but now left pointer one step forward but now our while loop will break because left our while loop will break because left pointer is now no longer less than the pointer is now no longer less than the right pointer right pointer so this condition so this condition in this iteration we have for in the in this iteration we have for in the first iteration of the for Loop we have first iteration of the for Loop we have find that uh the closest sum we got is find that uh the closest sum we got is two now if we move forward I will come two now if we move forward I will come here and then n again L will come here here and then n again L will come here and R will come here now you notice uh and R will come here now you notice uh all these three are positive number so all these three are positive number so adding them will always result a sum adding them will always result a sum which is greater than 2. so there is no which is greater than 2. so there is no need to drag around this solution need to drag around this solution but if you want you can try it yourself but if you want you can try it yourself and uh so at the end our output will be and uh so at the end our output will be this 2. this 2. the time complexity for this one will be the time complexity for this one will be same as the previous reason problem of n same as the previous reason problem of n square and space complexity will also be square and space complexity will also be same o of n since I'm sorting or same o of n since I'm sorting or algorithms like merge sort use some algorithms like merge sort use some extra space so this is the extra space so this is the drawing explanation let's see how we can drawing explanation let's see how we can do it in code okay so first let's just do it in code okay so first let's just sort our array so nums dot sort and we sort our array so nums dot sort and we want to sort it in ascending order so want to sort it in ascending order so inside the Callback function inside the Callback function we'll write next let's declare out some of our next let's declare out some of our variables in diff and it will be initially equal to number Dot it is the maximum possible value of it is the maximum possible value of number can have in JavaScript next number can have in JavaScript next temporary variable result which will be temporary variable result which will be returning as an output returning as an output so we'll start a for Loop we'll start so we'll start a for Loop we'll start from 0 we'll let I equals to 0 and I is from 0 we'll let I equals to 0 and I is less than num start length next let's declare our left and right next let's declare our left and right pointer so let left equals to I plus 1 pointer so let left equals to I plus 1 and write equals to and write equals to nums dot length nums dot length minus 1. next inside the while loop we'll check we'll run the while loop and then we'll calculate the temporary and then we'll calculate the temporary sum so temp sum will be equals to num sum so temp sum will be equals to num set I set I plus num set plus num set left left plus num set plus num set right right now we need to check if the absolute now we need to check if the absolute difference between this let's call it difference between this let's call it temp sum temp sum so if the absolute difference between so if the absolute difference between between this temp sum between this temp sum and Target is less than a previous minimum this is the case will stored in the this is the case will stored in the result the new temporary sum and we'll also update the minimum math dot abs math dot abs boot temp minus boot temp minus Target but this is not the case we have three possible condition if temp sum is equal equal to Target if this is the case then that means we just return the target we otherwise we have two more options if otherwise we have two more options if a temporary sum that we calculated a temporary sum that we calculated is less than the target is less than the target and as we have already sorted the array and as we have already sorted the array we need to move the left pointer one we need to move the left pointer one step forward step forward else that means if the temperature else that means if the temperature addition is greater than the target addition is greater than the target we need to we need to move the Left Right pointer one step move the Left Right pointer one step backward and at the end after the for Loop we'll just return the so if we run this and we got one more error so in this instead of just absolute we will have math dot absolute one more difference so temp sum minus one more difference so temp sum minus Target 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
2024-03-19 15:42:24
16
https://i.ytimg.com/vi/v…axresdefault.jpg
3Sum Closest - Leetcode 16 - JavaScript
zKFvjSL6SFQ
hello everyone let's look at letter combinations of a phone number letter combinations of a phone number the problem statement is we are giving a the problem statement is we are giving a string containing digits from two to string containing digits from two to none inclusive none inclusive return all possible letter combinations return all possible letter combinations now the number could represent now the number could represent written answer in any order a mapping of written answer in any order a mapping of a digit to letters a digit to letters look looks like below the question is look looks like below the question is really straightforward really straightforward for example 1 input digit is 2 3 so the for example 1 input digit is 2 3 so the output is output is adaf b d b e b f adaf b d b e b f c d c e c f c d c e c f in general when we see a problem asking in general when we see a problem asking us for all combinations us for all combinations we potentially need to use a back we potentially need to use a back tracing solution tracing solution we pretty much build a tree for all we pretty much build a tree for all possible combinations possible combinations and travels all the path we do it and travels all the path we do it using recursion before we even look at using recursion before we even look at the solution the solution let's look at the input digit string if let's look at the input digit string if the string the string the lens is 2 like 2 3 we can simply the lens is 2 like 2 3 we can simply have 2 have 2 for loops if we know the input digit for loops if we know the input digit length is 3 length is 3 then we can have 3 for loops but then we can have 3 for loops but if the input digit length is not if the input digit length is not predetermined we basically need to use predetermined we basically need to use recursion recursion because we don't know how many loops because we don't know how many loops we're going to need we're going to need but for this particular solution the but for this particular solution the recursive function is really easy to recursive function is really easy to understand 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 now we can look our backtrack recursive what kind of parameters we can pass in i what kind of parameters we can pass in i guess guess we definitely need to pass in index with we definitely need to pass in index with i 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 if this is not the case what we can do if this is not the case what we can do we can first get the letter we can first get the letter from the map inside the for loop we call our inside the for loop we call our backtrack in the for loop we call itself again by in the for loop we call itself again by passing current string concatenate a new passing current string concatenate a new latter latter and then we move the index the recursive and then we move the index the recursive method will keep calling itself method will keep calling itself until it reaches the termination until it reaches the termination condition that's the index condition that's the index move to the move to the last and then move to the move to the last and then we'll push the result into output we'll push the result into output in the end we can simply run the in the end we can simply run the backtrack method by passing an empty backtrack method by passing an empty string 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 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 i guess for time that should be the same i guess for time that should be the same because because to generate this amount of combination to generate this amount of combination we need this we need this same amount of time same amount of time for this problem if we do not want to for this problem if we do not want to use recursion use recursion we can use a queue to track all the we can use a queue to track all the combinations combinations we can have a for loop to loop through we can have a for loop to loop through the input digits the input digits and in the input which first ship that and in the input which first ship that item item out of the queue and then we concatenate out of the queue and then we concatenate it with the it with the next digits characters and then push next digits characters and then push them all in the queue them all in the queue let us look at an example here say the let us look at an example here say the input digits is 2 3 input digits is 2 3 so initially the q is empty so when we so initially the q is empty so when we shift out we shift out nothing so that's shift out we shift out nothing so that's an empty string and then we concatenate an empty string and then we concatenate with with all the letters for dg2 that's abc and all the letters for dg2 that's abc and then we push them in then we push them in then we have a b c in our queue then we have a b c in our queue and then we move on the photo moves to and then we move on the photo moves to the second digit the second digit that's three and then in the first we that's three and then in the first we shift a out so we shift it out and then shift a out so we shift it out and then a will concatenate with d e f so we have a will concatenate with d e f so we have a d a e a f then a d a e a f then we push these three in the q and then we push these three in the q and then we shift b out we shift b out and then concatenate with d f again we and then concatenate with d f again we have have b d b e and b f b d b e and b f and then we shift c out and then we shift c out concurrently with d f we have concurrently with d f we have c d c e c f and then c d c e c f and then we have done all the iteration so we we have done all the iteration so we have all the combination have all the combination let's have a look at the code base let's have a look at the code base we can change it into q we can remove all these things and finally initially the initial value for the initially the initial value for the queue is an empty string queue is an empty string and then that's how our for loop and then we have another for loop based so this current represents the value so this current represents the value that's shift out of the queue and then that's shift out of the queue and then with this current with this current we will concatenate with the we will concatenate with the corresponding 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 uh so for the map digit we get all those 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 it looks good for the time complexity it looks good for the time complexity and space capacity and space capacity they should still remain the same this they should still remain the same this is because is because although these two solutions looks although these two solutions looks different different but behind the scene we are still doing but behind the scene we are still doing brute force brute force to a certain extent but in different to a certain extent but in different ways ways when we need to find all combinations we when we need to find all combinations we literally literally need to iterate all different input need to iterate all different input digits and then loop through digits and then loop through all letters behind those digits so the all letters behind those digits so the complexity should remain the same here complexity should remain the same here if you have any questions please leave a if you have any questions please leave a comment below comment below thank you for watching
2024-03-19 16:00:03
17
https://i.ytimg.com/vi/z…axresdefault.jpg
LeetCode 17 Letter Combinations of a Phone Number in javascript
fTkkeDvqeIo
and welcome back to the cracking Fang YouTube channel today we're solving lead YouTube channel today we're solving lead code problem code problem 1,186 maximum subarray sum with one 1,186 maximum subarray sum with one deletion given an array of integers deletion given an array of integers return the maximum sum for a non-empty return the maximum sum for a non-empty subarray with at most one element subarray with at most one element deletion so in other words you want to deletion so in other words you want to choose a subarray and optionally delete choose a subarray and optionally delete one element from it so that there is at one element from it so that there is at least one element left and the sum of least one element left and the sum of the remaining elements is uh the maximum the remaining elements is uh the maximum possible note that the subarray needs to possible note that the subarray needs to be non-empty after deleting one element be non-empty after deleting one element all right pretty straightforward we have all right pretty straightforward we have already solved on this channel the already solved on this channel the maximum subarray problem so hopefully maximum subarray problem so hopefully this one isn't too much of an this one isn't too much of an extension now let's look at uh an extension now let's look at uh an example here so we have this input 1 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 the subarray what would we get or sorry the subarray what would we get or sorry the entire array well minus one one plus the entire array well minus one one plus -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 going to be two so obviously adding all the elements uh doesn't work we need to the elements uh doesn't work we need to get rid of one uh and in this case get rid of one uh and in this case obviously we want to just delete the obviously we want to just delete the negative one uh which is minus 2 in this negative one uh which is minus 2 in this case and you know the sum would just be case and you know the sum would just be four so we use our one deletion on the four so we use our one deletion on the negative cool but what happens if negative cool but what happens if there's actually two negatives we can there's actually two negatives we can only delete one of them and in this case 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 they're actually the same value uh they're actually the same value obviously you'd want to take the smaller obviously you'd want to take the smaller one um if you have a choice but one um if you have a choice but sometimes you don't so what do we want sometimes you don't so what do we want to do here well we don't want to sum to do here well we don't want to sum anything cuz we don't want to really sum anything cuz we don't want to really sum one of these minuses remember that we one of these minuses remember that we can take any subarray here which as long can take any subarray here which as long as it's as it's nonempty we also don't need to delete an nonempty we also don't need to delete an element we can just say I'm going to element we can just say I'm going to take three and that's it so we just take take three and that's it so we just take three uh because that's the maximum three uh because that's the maximum value so we have a choice we don't have value so we have a choice we don't have to delete something if we don't want to to delete something if we don't want to for example if all of them are um you for example if all of them are um you know right we're we only optionally have know right we're we only optionally have to do one so if they're all positive you to do one so if they're all positive you would just sum uh the subarray so the would just sum uh the subarray so the way that we want to approach this is way that we want to approach this is very similar to how we solved the very similar to how we solved the maximum subarray problem where we maximum subarray problem where we essentially just keep track of the sum essentially just keep track of the sum and at certain conditions we want to and at certain conditions we want to actually ask ourselves does it make actually ask ourselves does it make sense to add uh more variables to our sense to add uh more variables to our sum or do we actually just want to start sum or do we actually just want to start over now I don't want to get too much over now I don't want to get too much into the explanation because we're into the explanation because we're actually going to do this in the code actually going to do this in the code editor this one's a really fast problem editor this one's a really fast problem no need to kind of go through examples no need to kind of go through examples line by line it's just a waste of time line by line it's just a waste of time let's do it in the code editor it's let's do it in the code editor it's about 15 lines of code and I will walk about 15 lines of code and I will walk you through it as we go through so I you through it as we go through so I will see you momentarily in the code will see you momentarily in the code editor in 3 2 1 we are in the code editor in 3 2 1 we are in the code editor let's type this up so we're going editor let's type this up so we're going to want a few variable here and I'm to want a few variable here and I'm going to Define them and explain to you going to Define them and explain to you what they are so we're going to say the what they are so we're going to say the sum with a Skip and this one's pretty sum with a Skip and this one's pretty straightforward right this is the sum of straightforward right this is the sum of our current subarray that we're our current subarray that we're considering um assuming that we've considering um assuming that we've skipped one element so pretty pretty skipped one element so pretty pretty straightforward uh then we're going to straightforward uh then we're going to have a sum except we haven't skipped have a sum except we haven't skipped anything this would just be the direct anything this would just be the direct sum of whatever the current subarray sum of whatever the current subarray we're considering is um all the elements we're considering is um all the elements added together we haven't taken anything added together we haven't taken anything so we're going to say sum no Skip and so we're going to say sum no Skip and we're also going to need to return a we're also going to need to return a result here so all of this is just going result here so all of this is just going to equal to the first element in the to equal to the first element in the array remember that uh you need to have array remember that uh you need to have at least one element in your subarray so at least one element in your subarray so we're just going to set it equal to the we're just going to set it equal to the first element and then we'll process the first element and then we'll process the rest of the elements from there so the rest of the elements from there so the next thing we want to do is we want to next thing we want to do is we want to Loop through our elements so for Num in Loop through our elements so for Num in Array of oops uh one uh forward so Array of oops uh one uh forward so obviously we've just processed the obviously we've just processed the zeroth index there's no reason to zeroth index there's no reason to process it again so we're going to start process it again so we're going to start our iteration at the first index and our iteration at the first index and what we want to do now is we want to ask what we want to do now is we want to ask ourselves is our ourselves is our sum uh with skip is it less than zero sum uh with skip is it less than zero now the reason that we want to ask now the reason that we want to ask ourselves this is because if your ourselves this is because if your numbers are already significantly below numbers are already significantly below zero it doesn't really make sense to add zero it doesn't really make sense to add numbers to try to bring it above zero so numbers to try to bring it above zero so 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 you know Min you know Min -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 100 then we add the 40 and you know whatever is left in the array but then whatever is left in the array but then we'd be at minus 60 and actually we can we'd be at minus 60 and actually we can just say I don't need the rest of this just say I don't need the rest of this array it's already gone negative I can't array it's already gone negative I can't do anything with it so I'm just going to do anything with it so I'm just going to consider the 40 onwards so what we can consider the 40 onwards so what we can do is we're going to say do is we're going to say if um if our sum with skip so if we've if um if our sum with skip so if we've already used our Skip and we're below already used our Skip and we're below zero then we've taken too many negatives zero then we've taken too many negatives that we really shouldn't we should just that we really shouldn't we should just consider the first positive that we get consider the first positive that we get and that will be where we want to start and that will be where we want to start so we're just going to reset our skip uh so we're just going to reset our skip uh sorry not our skip our um sum with skip sorry not our skip our um sum with skip we're just going to reset it to zero cuz we're just going to reset it to zero cuz you know we don't need the number right you know we don't need the number right so now what we want to do is there's two so now what we want to do is there's two cases right the number can either be cases right the number can either be greater than or equal to zero or it can greater than or equal to zero or it can be less than zero so if the number that be less than zero so if the number that we're currently processing is a positive we're currently processing is a positive so greater than or equal to zero then we so greater than or equal to zero then we want to take it there's no reason to want to take it there's no reason to skip it adding it will only increase our skip it adding it will only increase our sum so so there's no reason to skip it sum so so there's no reason to skip it ideally we only skip negatives or if ideally we only skip negatives or if there's only positives then actually we there's only positives then actually we wouldn't want to skip anything at all wouldn't want to skip anything at all because there's no reason to so if it's because there's no reason to so if it's positive then we always take it so we're positive then we always take it so we're going to say the scum with skip we're going to say the scum with skip we're we're not going to skip it we're just we're not going to skip it we're just going to take the number um so we're going to take the number um so we're going to add the current number to the going to add the current number to the sum with the sum with the skip otherwise we need to make a skip otherwise we need to make a decision do we want to take this number decision do we want to take this number uh take the hit of taking this number so uh take the hit of taking this number so for example maybe the number is minus for example maybe the number is minus one and that's not really going to one and that's not really going to affect our sum too much so we can take affect our sum too much so we can take the hit or we want to compare well let's the hit or we want to compare well let's just see what we're going to do so we're just see what we're going to do so we're going to say that the sum uh with skip going to say that the sum uh with skip is either going to be the maximum of su is either going to be the maximum of su the current sum with the current sum with skip if we just take the hit and add the skip if we just take the hit and add the number to our sum or remember that sum number to our sum or remember that sum no skip represents the sum of our no skip represents the sum of our subarray up until our current Point subarray up until our current Point assuming we haven't skipped anything if assuming we haven't skipped anything if that value is actually bigger than um that value is actually bigger than um you know us taking the hit on the number you know us taking the hit on the number then that will become our new um sum then that will become our new um sum with skip right so we just want to set with skip right so we just want to set it to the other one and we're going to it to the other one and we're going to ignore this current number maybe the ignore this current number maybe the 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 it would mess up our sum so we actually want to take the maximum of taking the want to take the maximum of taking the hit with the num in the case that it's hit with the num in the case that it's negative well actually in this case it negative well actually in this case it is negative because we're in this El is negative because we're in this El block um or you know we're just going to block um or you know we're just going to skip it so in which case the sum with skip it so in which case the sum with the skip obviously we've now just taken the skip obviously we've now just taken a skip um in that case so that's why we a skip um in that case so that's why we have to do the sum with the no skip now have to do the sum with the no skip now what we want to do is actually similar what we want to do is actually similar uh to what we did up here with the sum uh to what we did up here with the sum with skip we actually want to check with skip we actually want to check whether or not um if sum no skip is less whether or not um if sum no skip is less than zero um then we just want to reset than zero um then we just want to reset it as well cuz again it may just be it as well cuz again it may just be easier to start our sum from the current easier to start our sum from the current number uh than it would be number uh than it would be to um just try to add more to it so to um just try to add more to it so we're going to say sum no skip uh is we're going to say sum no skip uh is going to equal to zero and now you might going to equal to zero and now you might be asking yourself why didn't we do this be asking yourself why didn't we do this earlier up here you know why have you earlier up here you know why have you left it after you processed the current left it after you processed the current number and the reason for that is number and the reason for that is actually this statement here now you see actually this statement here now you see that we use some no skip here if in fact that we use some no skip here if in fact we actually overd the value of sum no we actually overd the value of sum no Skip and set it to zero then when we try Skip and set it to zero then when we try to use it in this function uh in this to use it in this function uh in this else block here it would be pointing to else block here it would be pointing to zero if we overrided which is not zero if we overrided which is not correct because we want to hold the old correct because we want to hold the old sum no skip now we could get around this sum no skip now we could get around this by Def uh declaring a variable like sum by Def uh declaring a variable like sum no skip temporary but that's just a no skip temporary but that's just a waste there's no nothing obligating us waste there's no nothing obligating us to do it earlier so we just do it to do it earlier so we just do it afterwards so we have access to this um afterwards so we have access to this um sum no skip so if in case you're sum no skip so if in case you're wondering why we do it down here and not wondering why we do it down here and not up here with the other one that's why up here with the other one that's why because the order actually will matter because the order actually will matter here otherwise um we need to add the here otherwise um we need to add the number to our sum no skip uh sum no skip number to our sum no skip uh sum no skip because obviously we don't skip any because obviously we don't skip any numbers with this sum we just add numbers with this sum we just add everything to it and now now that we everything to it and now now that we have all of our variables updated we can have all of our variables updated we can actually take a actually take a um a maximum uh to see uh if we have a um a maximum uh to see uh if we have a new uh best answer so we're going to new uh best answer so we're going to take the maximum whatever our current take the maximum whatever our current result is uh whatever sum no skip is result is uh whatever sum no skip is sorry some no skip I can't really see my sorry some no skip I can't really see my keyboard uh and then sum with skip so keyboard uh and then sum with skip so those are our three variables and we those are our three variables and we want to take the maximum of them at each want to take the maximum of them at each iteration through the loop to figure out iteration through the loop to figure out which one we want to use and the last which one we want to use and the last thing once the loop ends we simply thing once the loop ends we simply return res and we are good to go so let return res and we are good to go so let me run this make sure I didn't make any me run this make sure I didn't make any stupid syntax mistakes as sometimes I do stupid syntax mistakes as sometimes I do at these live recordings and it looks at these live recordings and it looks like accepted perfect so time and space like accepted perfect so time and space complexity this one is really easy complexity this one is really easy obviously all we're doing is we are obviously all we're doing is we are passing through our array here uh from passing through our array here uh from left to right processing all of the left to right processing all of the elements all of our checks here are elements all of our checks here are going to be constant time checks you going to be constant time checks you know we we're just comparing against know we we're just comparing against zero we're doing an addition uh we have zero we're doing an addition uh we have an if else block nothing here um is an if else block nothing here um is anything but constant uh time so our anything but constant uh time so our time complexity is going to be Big O of time complexity is going to be Big O of n uh we have n elements we perform um n uh we have n elements we perform um you know Big O of one operation for each you know Big O of one operation for each n element that's Big O of n uh for the n element that's Big O of n uh for the space complexity um we don't have any space complexity um we don't have any extra variables here we have um just extra variables here we have um just these three which are just holding these three which are just holding numbers um because of this we don't numbers um because of this we don't declare any extra data structures so we declare any extra data structures so we can consider our uh space complexity to can consider our uh space complexity to be Big O of one okay so that is how you be Big O of one okay so that is how you solve maximum subarray sum with one solve maximum subarray sum with one deletion like I said it's really similar deletion like I said it's really similar to the previous iteration of this to the previous iteration of this problem just maximum subarray sum where problem just maximum subarray sum where you're not allowed to delete an element you're not allowed to delete an element this one is quite good practice for this one is quite good practice for kadan's algorithm sometimes you will get 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 if you get the the standard version so if you get the the standard version so it's good to know how to do it and again it's good to know how to do it and again look at how simple this code is it's look at how simple this code is it's like less than 20 lines right once you like less than 20 lines right once you get rid of this stuff here so nothing get rid of this stuff here so nothing too complicated hopefully you enjoyed too complicated hopefully you enjoyed the video hopefully you found it um the video hopefully you found it um helpful if you did why not leave a like helpful if you did why not leave a like and a comment on uh the channel it and a comment on uh the channel it really helps me out uh to grow hopefully 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 if you want to join a Discord Community if you want to join a Discord Community where we talk about all things interview where we talk about all things interview prep you can ask for referrals you can prep you can ask for referrals you can ask me random questions um then I will ask me random questions um then I will leave a link in the description below if leave a link in the description below if that sounds interesting for you that sounds interesting for you otherwise I'm going to stop rambling otherwise I'm going to stop rambling thank you so much watching and I will thank you so much watching and I will see you in the next one goodbye
2024-03-25 18:19:09
1,186
https://i.ytimg.com/vi/f…axresdefault.jpg
MAXIMUM SUBARRAY SUM WITH ONE DELETION | LEETCODE 1186 | PYTHON
FSHl8X4WOvc
hey guys welcome back to our channel so this channel every data science is all this channel every data science is all about trying to learn the different about trying to learn the different concepts involve data science by concepts involve data science by practicing a lot of questions in this practicing a lot of questions in this video i am going to solve this question video i am going to solve this question elite code regarding users that actively elite code regarding users that actively request confirmation message messages request confirmation message messages and try to walk you through how we can and try to walk you through how we can develop solutions to such problems the develop solutions to such problems the difficulty level of this question is difficulty level of this question is easy okay let's jump right in we are easy okay let's jump right in we are given a table called signups with two given a table called signups with two different columns user id and timestamp different columns user id and timestamp user id is the primary key for this user id is the primary key for this table each row contains information table each row contains information about the sign up time for the user with about the sign up time for the user with the id user id the id user id we are also given a second table called we are also given a second table called confirmations with three different confirmations with three different columns columns user id timestamp and action the user id timestamp and action the combined column user id and timestamp is combined column user id and timestamp is the primary key for this table user id the primary key for this table user id is a foreign key with a reference to the is a foreign key with a reference to the signups table okay signups table okay action is an enum of the type confirmed action is an enum of the type confirmed or time out each row of this table or time out each row of this table indicates that the user with the id user indicates that the user with the id user id requested a confirmation message at id requested a confirmation message at this particular time stamp this particular time stamp and that confirmation message was either and that confirmation message was either confirmed or expired without confirming confirmed or expired without confirming that is timer that is timer we are asked to write a sql query to we are asked to write a sql query to find the ids of the users that requested find the ids of the users that requested a confirmation message twice within a 24 a confirmation message twice within a 24 hour window hour window two messages exactly 24 hours apart are two messages exactly 24 hours apart are considered to be within the window the considered to be within the window the action does not affect the answer only action does not affect the answer only the request time the order of the result the request time the order of the result does not matter okay does not matter okay let's go through this example right so let's go through this example right so basically we have the signups table and basically we have the signups table and then we have the confirmations table and then we have the confirmations table and now we need to report the user ids where now we need to report the user ids where a confirmation was requested a confirmation was requested irrespective of the action right so it irrespective of the action right so it was confirmed or timed out does not was confirmed or timed out does not matter irrespective of the action matter irrespective of the action within the 24 hour period we need to within the 24 hour period we need to return the users which requested a return the users which requested a confirmation message twice confirmation message twice right right so here if you look at it right so user so here if you look at it right so user right let's let's go through this right let's let's go through this example right so user id 3 you have okay example right so user id 3 you have okay so the first one was on 6th of january so the first one was on 6th of january 2021 at 3 30 and 46 seconds 2021 at 3 30 and 46 seconds and the next request was and the next request was about seven minutes or six seven minutes about seven minutes or six seven minutes later right so obviously this is within later right so obviously this is within the 24 hour period like two requests the 24 hour period like two requests within 24 hour period so within 24 hour period so this should be in the output for seven this should be in the output for seven if you look at it closely it is 20 after if you look at it closely it is 20 after so 12th of june 2021 11 57 and 29 so 12th of june 2021 11 57 and 29 seconds and then the next seconds and then the next request was on 13th of june 2021 11 57 request was on 13th of june 2021 11 57 and 30 seconds right so that is 24 hours and 30 seconds right so that is 24 hours one seconds later right so this is not one seconds later right so this is not in the 24 hour period right so seven in the 24 hour period right so seven shouldn't be included similarly for 2 shouldn't be included similarly for 2 this is exactly 24 hour apart and the this is exactly 24 hour apart and the question says that the 24 hour apart question says that the 24 hour apart exactly exactly is considered to be within window right is considered to be within window right so again 2 is also going to be in the so again 2 is also going to be in the output and similarly for 6 right so two output and similarly for 6 right so two three and six should be in the output three and six should be in the output right and that is what we have so right and that is what we have so basically if you look this question is basically if you look this question is very simple all we have to do is for very simple all we have to do is for each of the users we can try to you know each of the users we can try to you know arrange the timestamps in ascending arrange the timestamps in ascending order and then try to find out when the order and then try to find out when the next request was and based on that we next request was and based on that we can see whether the next request was can see whether the next request was within the 24 hour period or after the within the 24 hour period or after the 24 hour period or exactly at the 24 hour 24 hour period or exactly at the 24 hour period right so let's start developing period right so let's start developing this query it will be more clear right this query it will be more clear right so so from from this table this table called confirmations called confirmations by the way did you notice that you don't by the way did you notice that you don't even need this signups table to solve even need this signups table to solve this question right because all you do this question right because all you do need to do is uh you know get that 24 need to do is uh you know get that 24 hour hour period period for different user ids right and you can for different user ids right and you can do that using this confirmations table do that using this confirmations table only like you don't need this signups only like you don't need this signups table so yeah so from this confirmations table so yeah so from this confirmations table let's return all the three columns table let's return all the three columns and make a fourth column which will be and make a fourth column which will be basically the next request time right basically the next request time right next request time so to do this firstly next request time so to do this firstly for each user right so partition by user for each user right so partition by user id then order by timestamp right id then order by timestamp right so let's since we are using a window so let's since we are using a window function we need to write the over function we need to write the over clause over clause over partition partition by by user user id id order order by by time stamp time stamp in increasing manner right and once you in increasing manner right and once you arrange them right then you basically arrange them right then you basically find the next one right so how do you find the next one right so how do you find the next one you use the window find the next one you use the window function lead and for which column you function lead and for which column you want to find what to find the next value want to find what to find the next value you need timestamp right so timestamp you need timestamp right so timestamp and let's aliase this as and let's aliase this as next request request time time right let's aliase this as so that is right let's aliase this as so that is easy to understand let's this is not yet easy to understand let's this is not yet complete but let me just you know go complete but let me just you know go ahead and run this to see what happens ahead and run this to see what happens so here we have the four columns right so here we have the four columns right three three from this table confirmations and the from this table confirmations and the four that we just created like next four that we just created like next confirmation request time so user id confirmation request time so user id timestamp action next confirmation timestamp action next confirmation request time so for this one right so request time so for this one right so for user id to 22nd of january 2021 for user id to 22nd of january 2021 right so for user id 22nd of january uh right so for user id 22nd of january uh 2021 right you have this and then uh 2021 right you have this and then uh this is the next one right so the next this is the next one right so the next request is 23rd of january 2021 this request is 23rd of january 2021 this much right for much right for now again for this the next one was this now again for this the next one was this one right for this obviously there is no one right for this obviously there is no third third login uh there is no third confirmation login uh there is no third confirmation request right so that is why you have request right so that is why you have null and similarly for all other user null and similarly for all other user ids right so once we have this then what ids right so once we have this then what we can do let's store this in a common we can do let's store this in a common table expression right table expression right now now from this common table expression from this common table expression what do we need to do is we need to keep what do we need to do is we need to keep only those rows or basically we need to only those rows or basically we need to only keep those users right only keep those users right where the next confirmation request time where the next confirmation request time is between is between the timestamp and when you add 24 hours the timestamp and when you add 24 hours to that timestamp it should be between to that timestamp it should be between that right because that is what question that right because that is what question is asking you right is asking you right that that user that's requested confirmation user that's requested confirmation message twice within a 24 hour window so message twice within a 24 hour window so if i write where if i write where next confirmation request time right next confirmation request time right then next confirmation request time then next confirmation request time is between right so it is between is between right so it is between the time stamp the time stamp right between the timestamp right between the timestamp and and you need to add 24 hours to that time you need to add 24 hours to that time step right so how you can do that you step right so how you can do that you can use the date add function right so can use the date add function right so date add then which column do you want date add then which column do you want to add the hours to so timestamp to add the hours to so timestamp and then and then you need to write interval you need to write interval then 24 then 24 then hour then hour right okay so basically what is this right okay so basically what is this going to do so here you imagine the going to do so here you imagine the fourth column right fourth column you fourth column right fourth column you have next confirmation request time have next confirmation request time right so for this one it is going to right so for this one it is going to have this value here right for this one have this value here right for this one it is going to have null similarly for it is going to have null similarly for all now when i am saying from this all now when i am saying from this common table expression only keep those common table expression only keep those rows where next confirmation request rows where next confirmation request time is between this value and adding 24 time is between this value and adding 24 hours to this value right so obviously hours to this value right so obviously this next confirmation request time if this next confirmation request time if it is between this timestamp column and it is between this timestamp column and the 24 hours addition to this then you the 24 hours addition to this then you are going to keep that row otherwise you are going to keep that row otherwise you are going to ignore right so are going to ignore right so once we have this then all we need to do once we have this then all we need to do is because in the output you need to is because in the output you need to return the user id right so you need to return the user id right so you need to return return user user id id okay there is still one thing remaining okay there is still one thing remaining in this right but let me just go ahead in this right but let me just go ahead and run this right and run this right so this is accepted our output is same so this is accepted our output is same as expected output right but can you as expected output right but can you think of a test case that even though think of a test case that even though this is green and accepted but there is this is green and accepted but there is still some one thing that might lead to still some one thing that might lead to a problem and i can show you that if i a problem and i can show you that if i try to go and submit this right this is try to go and submit this right this is going to throw us an error why this is going to throw us an error why this is throwing you an error can you think of throwing you an error can you think of the reason so here if you see right the reason so here if you see right the only difference that we have right the only difference that we have right so the output that we are getting is so the output that we are getting is this and the expected output is this one this and the expected output is this one right so if you see everything is same right so if you see everything is same except we have 35 twice right and that except we have 35 twice right and that is the test case that we didn't you know is the test case that we didn't you know took care of that it might be possible took care of that it might be possible that one user that one user can have two multiple logins on can have two multiple logins on different dates but within those 24 hour different dates but within those 24 hour period right so maybe period right so maybe i am a user i logged in today and then i i am a user i logged in today and then i logged in after let's say six hours logged in after let's say six hours today as well then tomorrow i logged in today as well then tomorrow i logged in and then after let's say and then after let's say 15 hours i logged in again right so 15 hours i logged in again right so based on the query that we have written based on the query that we have written both of those rows are going to come both of those rows are going to come right and when you are returning the right and when you are returning the user id the user id is going to be user id the user id is going to be returned from both of those cases right returned from both of those cases right and and in the output you don't need repetition in the output you don't need repetition right so basically what you need to do right so basically what you need to do is you just need to return distinct user is you just need to return distinct user id right id right so so return return distinct distinct user id right user id right now let's go ahead and run this so this now let's go ahead and run this so this is accepted again like it was accepted is accepted again like it was accepted before as well but now let's go ahead before as well but now let's go ahead and submit it to see what happens and submit it to see what happens so yeah this is accepted now right this so yeah this is accepted now right this is successful so now we took care of the is successful so now we took care of the that test case so yeah this is how i do that test case so yeah this is how i do it let me know if there is a better way it let me know if there is a better way or a more efficient way you can think of or a more efficient way you can think of to solve this problem to solve this problem this question was very simple all you this question was very simple all you had to do was firstly you don't even had to do was firstly you don't even need one of the tables that is given in need one of the tables that is given in the question and secondly all you had to the question and secondly all you had to do was like you know find out the next do was like you know find out the next confirmation request time and then make confirmation request time and then make sure that that next confirmation request sure that that next confirmation request time is between the timestamp and when time is between the timestamp and when you add 24 hours to that particular time you add 24 hours to that particular time stamp because that is what the question stamp because that is what the question is asking uh requested a confirmation is asking uh requested a confirmation message twice within a 24 hour window message twice within a 24 hour window and even if it is exactly 24 and even if it is exactly 24 hours apart they are still counted as a hours apart they are still counted as a window according to the question so you window according to the question so you do that and remember to add distinct do that and remember to add distinct because if you don't then we discussed because if you don't then we discussed about a test case where you might have about a test case where you might have duplicate duplicate values in your output and you don't want values in your output and you don't want that right so let me know that right so let me know in the comment section if you can think in the comment section if you can think of a better way to solve this question of a better way to solve this question let the solution be in the comment let the solution be in the comment section below and until then i will see section below and until then i will see you guys in the next video
2024-03-25 13:32:36
1,939
https://i.ytimg.com/vi/F…axresdefault.jpg
LeetCode 1939 "Users That Actively Request Confirmation Messages" Interview SQL Question Explanation
z21tnf3Hj_0
[Music] hey guys welcome back to another video hey guys welcome back to another video and today we're going to be solving the and today we're going to be solving the leakout question carpooling leakout question carpooling all right so in this question we're all right so in this question we're driving a vehicle that has capacity driving a vehicle that has capacity empty seats initially available for empty seats initially available for passengers passengers the vehicle only drives east and it the vehicle only drives east and it cannot turn around and drive the other cannot turn around and drive the other direction direction so in other words it drives in only one so in other words it drives in only one direction given a list of trips direction given a list of trips so a certain instance of trips of trip so a certain instance of trips of trip has has the number of passengers in it the start the number of passengers in it the start location and the end location location and the end location so it contains the information about the so it contains the information about the ite trip the number of passengers that ite trip the number of passengers that must be picked up the location to pick must be picked up the location to pick them up and drop them off them up and drop them off the locations are given as the number of the locations are given as the number of kilometers kilometers due east from your vehicle's initial due east from your vehicle's initial position position which ensure if and only if it is which ensure if and only if it is possible to pick up possible to pick up and drop off all the passengers for all and drop off all the passengers for all the given trips the given trips okay so by the ending of this we want to okay so by the ending of this we want to be able to accommodate all the be able to accommodate all the passengers without leaving any of them passengers without leaving any of them off off and drop off all of them for all the and drop off all of them for all the given trips given trips okay so that being said let's take a okay so that being said let's take a quick look at this over here so let's quick look at this over here so let's just take a look at this example over just take a look at this example over here which actually outputs true here which actually outputs true so what does capacity mean so capacity so what does capacity mean so capacity is going to be how much is going to be how much how many people our car can hold so we how many people our car can hold so we can hold a maximum of 11 people can hold a maximum of 11 people and over here we have three different and over here we have three different trips so instead of just uh going over trips so instead of just uh going over it let's just draw it out and kind of it let's just draw it out and kind of visualize it visualize it okay so over here we kind of have like a okay so over here we kind of have like a number line number line to represent each of the directions so to represent each of the directions so this is the same example three two seven this is the same example three two seven three seven nine and eight three and three seven nine and eight three and nine and just so you remember the first nine and just so you remember the first value is the number of people value is the number of people the second value is the start location the second value is the start location and the third value is the end location and the third value is the end location so what i'm going to do is let's just uh so what i'm going to do is let's just uh let's just draw out let's just draw out each of these trips so in the beginning each of these trips so in the beginning over here we have one trip over here we have one trip starting off at uh the second location starting off at uh the second location so let's just say two kilometers so let's just say two kilometers and it goes all the way up to seven and it goes all the way up to seven kilometers and how many people are kilometers and how many people are transporting over here the answer to transporting over here the answer to that is three okay so we have that that is three okay so we have that and then after this we have one more and then after this we have one more trip starting at seven kilometers going trip starting at seven kilometers going all the way up to nine kilometers all the way up to nine kilometers with again three people and we have one with again three people and we have one more trip more trip starting at three kilometers so let's starting at three kilometers so let's just do that over here and it goes just do that over here and it goes all the way up to nine kilometers and all the way up to nine kilometers and that has that has eight people so the question that we eight people so the question that we want to ask over here want to ask over here is can we accommodate all of these is can we accommodate all of these people people inside of our car so let's just go by inside of our car so let's just go by this step by step so we have zero this step by step so we have zero passengers here then zero over here passengers here then zero over here but once we reach the value two let's but once we reach the value two let's just use the color red just use the color red over here we get three passengers so over here we get three passengers so let's just add let's just add plus three so now we have a total of plus three so now we have a total of three passengers three passengers so at the next uh spot we actually end so at the next uh spot we actually end up up picking up eight more passengers so over picking up eight more passengers so over here we do here we do plus eight we're picking up eight more plus eight we're picking up eight more passengers so passengers so in the beginning we had three now plus in the beginning we had three now plus eight giving us a value of 11. eight giving us a value of 11. and that makes sense our capacity can and that makes sense our capacity can hold hold up to 11 people but if this number does up to 11 people but if this number does increase at any point that means that increase at any point that means that we're not going to be able to facilitate we're not going to be able to facilitate everyone okay so now we keep going and everyone okay so now we keep going and the number of the number of passengers stays the same until we reach passengers stays the same until we reach the number seven the number seven so what happens at the number seven is so what happens at the number seven is that first we're actually dropping off that first we're actually dropping off three of the original passengers who three of the original passengers who started off from over here started off from over here so we're gonna do minus three since so we're gonna do minus three since we're dropping three of them off we're dropping three of them off but we're also picking up three new but we're also picking up three new passengers from that instance passengers from that instance so we're doing minus three and we're so we're doing minus three and we're also adding three and that's just gonna also adding three and that's just gonna cancel off cancel off and we're still gonna have 11 of people and we're still gonna have 11 of people remaining remaining and at the very ending which is the and at the very ending which is the ninth kilometer ninth kilometer we end up dropping all of these eight we end up dropping all of these eight people so minus eight people so minus eight and we also drop out all of these three and we also drop out all of these three people so people so minus three over here so 11 minus eight minus three over here so 11 minus eight minus three ends up giving us a value of minus three ends up giving us a value of zero zero and that means that we are done all the and that means that we are done all the passengers were dropped off and everyone passengers were dropped off and everyone was was picked up so that's all that we're doing picked up so that's all that we're doing and now let's see how we can actually do and now let's see how we can actually do this in code this in code so over here we're going to start off by so over here we're going to start off by creating a list so let's just call this creating a list so let's just call this list list l and it's going to be an empty list and l and it's going to be an empty list and the purpose of our list over here is the purpose of our list over here is going to be to going to be to add the number of people who are going add the number of people who are going to get on at a certain stop to get on at a certain stop and the number of people who are going and the number of people who are going to get off at a certain stock to get off at a certain stock so let's first add that over here so how so let's first add that over here so how do we exactly add this so do we exactly add this so we're going to iterate through our car we're going to iterate through our car our trips list over here our trips list over here so again the format of it is first we so again the format of it is first we get the number of people get the number of people then we get the start point and then we then we get the start point and then we get the end point get the end point so for that in trips so now we have so for that in trips so now we have this information for each of our trips this information for each of our trips so now what we're going to do is we're so now what we're going to do is we're going to go to our going to go to our list and we're going to append the list and we're going to append the values so over here we're going to have values so over here we're going to have two conditions two conditions so what if we're actually starting so so what if we're actually starting so over here we're currently starting right over here we're currently starting right and when we're starting we're going to and when we're starting we're going to have more people so the number of people have more people so the number of people coming in coming in is going to increase so in this case is going to increase so in this case what's going to happen what's going to happen is people is going to be positive and is people is going to be positive and what that represents what that represents is the fact that more people are is the fact that more people are entering into the car entering into the car so in that case the capacity decreases so in that case the capacity decreases okay so that's what hap that's what's okay so that's what hap that's what's happening happening when we're reaching the starting point when we're reaching the starting point and on the other hand when we're and on the other hand when we're reaching the end point reaching the end point so we have end point and in that case so we have end point and in that case what's happening what's happening is people are getting off the car so is people are getting off the car so when they're getting off we have less when they're getting off we have less people inside of the car people inside of the car so we're decreasing the number of people so we're decreasing the number of people in the car so we're going to have in the car so we're going to have negative people over here so that just negative people over here so that just shows that the people got off shows that the people got off okay so now at the ending of this we okay so now at the ending of this we have our list have our list uh and it's ready to go so over here uh and it's ready to go so over here what we're gonna do is i'm gonna print what we're gonna do is i'm gonna print out the list and then i'm gonna sort it out the list and then i'm gonna sort it and then print it out and then print it out just to show you why we might need to just to show you why we might need to sort our list sort our list and we're using the same example as and we're using the same example as example four over here example four over here okay so this over here is the non-sorted okay so this over here is the non-sorted version of version of it so what's happening over here is so it so what's happening over here is so we have two comma three which is the we have two comma three which is the starting point starting point and seven comma negative three is the and seven comma negative three is the ending point for that trip but what ending point for that trip but what we're going to do is we want to go we're going to do is we want to go day by day so if you look out if you day by day so if you look out if you look at our sorted list over here which look at our sorted list over here which is this one over here is this one over here so we first go to day two then we go to so we first go to day two then we go to a day three a day three then we go to day seven then day seven then we go to day seven then day seven again then day nine and so on and so again then day nine and so on and so forth but we're going in an forth but we're going in an ordered fashion okay so that's gonna be ordered fashion okay so that's gonna be really important and really important and that's the reason why we're sorting it that's the reason why we're sorting it okay so over here we're gonna okay so over here we're gonna sort out our list and now we're gonna sort out our list and now we're gonna perform the last step perform the last step which is going to be to add or decrease which is going to be to add or decrease the number of people the number of people at each instance in order to see whether at each instance in order to see whether we might have we might have an overflow of people so over here we're an overflow of people so over here we're going to go into a for loop and we're going to go into a for loop and we're going to be iterating through our list going to be iterating through our list l so over here we don't actually care l so over here we don't actually care about the start or end positions about the start or end positions so i'm just going to do underscore and so i'm just going to do underscore and we just care about the people and the we just care about the people and the reason we added them here is well to reason we added them here is well to sort them in the right order so now that sort them in the right order so now that we have this we're going to iterate we have this we're going to iterate through it for through it for our list l and over here we're going to our list l and over here we're going to decrease our capacity decrease our capacity each time so capacity minus equal to each time so capacity minus equal to number of people number of people so when we're adding people the capacity so when we're adding people the capacity in the car is going to decrease in that in the car is going to decrease in that case we're just going to case we're just going to subtract it okay but then when we're subtract it okay but then when we're dropping off someone then in dropping off someone then in that case so you're subtracting a that case so you're subtracting a negative number which is going to add negative number which is going to add so our capacity is going to increase so our capacity is going to increase when we're dropping off people so that's when we're dropping off people so that's what it's going to do what it's going to do and over here we're going to have an if and over here we're going to have an if condition so we're gonna check condition so we're gonna check if our capacity is less than zero if our capacity is less than zero and if it is less than zero that means and if it is less than zero that means that there are too many people that there are too many people in our car and in that case we're just in our car and in that case we're just going to end up returning false and going to end up returning false and we're done with the question we're done with the question right we can never accommodate more right we can never accommodate more people than the capacity people than the capacity so that's the condition for when it's so that's the condition for when it's going to be false but if we do going to be false but if we do pass everything and we're done with our pass everything and we're done with our for loop at the outside of this we're for loop at the outside of this we're going to end up returning true going to end up returning true that means that we picked up everyone that means that we picked up everyone and we dropped everyone and we dropped everyone so let's submit this and as you can see so let's submit this and as you can see our submission did get accepted our submission did get accepted and finally thanks a lot for watching and finally thanks a lot for watching guys do let me know if you have any guys do let me know if you have any questions questions and don't forget to like and subscribe and don't forget to like and subscribe if the video helped you thank you
2024-03-25 17:21:34
1,094
https://i.ytimg.com/vi_w…xresdefault.webp
Car Pooling | Leet code 1094 | Theory explained + Python code
MnbTKT4-KLc
hey so welcome back this is another daily problem so today it's called daily problem so today it's called delete and earn and it's a medium level delete and earn and it's a medium level dynamic programming problem and so dynamic programming problem and so essentially you're just given a array essentially you're just given a array called nums here and you're playing a called nums here and you're playing a game where you want to get the maximum game where you want to get the maximum number of points and the way this game number of points and the way this game works and I'm kind of assuming you works and I'm kind of assuming you already read some of this already read some of this but basically you get to choose any but basically you get to choose any number in here so let's say we choose number in here so let's say we choose three and basically if you choose that three and basically if you choose that number you get to add up the total uh number you get to add up the total uh number of points that you can get by number of points that you can get by choosing that number which is choosing that number which is essentially the value of that number essentially the value of that number which is three in this case multiplied which is three in this case multiplied by the number of times it occurs which by the number of times it occurs which is three and so you get nine points is three and so you get nine points but the catch here or the constraint is but the catch here or the constraint is that if you choose the number three or that if you choose the number three or any arbitrary number let's just call it any arbitrary number let's just call it n then you can't use the number that's n n then you can't use the number that's n minus 1 or n plus one minus 1 or n plus one and so in this case you would have to and so in this case you would have to basically eliminate two because that's n basically eliminate two because that's n minus 1 here and you're gonna have to minus 1 here and you're gonna have to eliminate 4 which is n Plus 1. all right eliminate 4 which is n Plus 1. all right and so you get a total value or a total and so you get a total value or a total sum of nine let's say if you go a sum of nine let's say if you go a different route well that would be okay different route well that would be okay let's say you choose two first and so let's say you choose two first and so that would eliminate one but there's no that would eliminate one but there's no ones here and that would eliminate three ones here and that would eliminate three so then you'd get four points so then you'd get four points but you can also choose this four here but you can also choose this four here and so you could add four extra points and so you could add four extra points there which gives you eight there which gives you eight but well we saw before that we were able but well we saw before that we were able to get nine points by choosing three and to get nine points by choosing three and so because well nine is greater than so because well nine is greater than eight that would be the output all right eight that would be the output all right and so that's basically how the and so that's basically how the algorithm works or what we're trying to algorithm works or what we're trying to accomplish but essentially I'm going to accomplish but essentially I'm going to show you uh time and space complexity show you uh time and space complexity solution of O of the maximum solution of O of the maximum numbers so what that really means is numbers so what that really means is basically the time complexities kind of basically the time complexities kind of going from like oh going from like oh or zero one two three all the way to or zero one two three all the way to basically whatever number is the largest basically whatever number is the largest number in this particular array nums number in this particular array nums array and so in this case uh we'll have array and so in this case uh we'll have like a time space complexity of like 0 like a time space complexity of like 0 of 4 where 4 is the maximum number in of 4 where 4 is the maximum number in here here and so that might not make much sense and so that might not make much sense now I think it's very intuitive as you now I think it's very intuitive as you see like the Forum that we're creating see like the Forum that we're creating and the DP array in the lookup table and and the DP array in the lookup table and so what we're going to do is we want to so what we're going to do is we want to have a quick lookup of what is the total have a quick lookup of what is the total number of points you're going to get if number of points you're going to get if you choose some number you choose some number so we'll have basically a lookup of so we'll have basically a lookup of basically the index 3 will represent or basically the index 3 will represent or return the value nine so that just means return the value nine so that just means okay okay if we choose the number three we'll get if we choose the number three we'll get nine points nine points all right and so to do that it's uh all right and so to do that it's uh pretty simple where you just have let's pretty simple where you just have let's call it like num lookup maybe and so call it like num lookup maybe and so it's initially zero it's initially zero and we're just going to get basically and we're just going to get basically the length of the numbers or sorry the the length of the numbers or sorry the maximum number in here maximum number in here and just add one to it and so that way and just add one to it and so that way we can have the kind of lookup table of we can have the kind of lookup table of saying okay the number the value 4 will saying okay the number the value 4 will then map to well four because there's then map to well four because there's only one here only one here and so basically to populate this with and so basically to populate this with actual values other than zero we'll just actual values other than zero we'll just iterate through all the numbers in our iterate through all the numbers in our nums array and just say okay the num nums array and just say okay the num look up at this particular number is look up at this particular number is well we want to add this number to it well we want to add this number to it and that basically just creates it and that basically just creates it and so from here we also want to have and so from here we also want to have our DP array and so what we're going to our DP array and so what we're going to want to do is this array at the end of want to do is this array at the end of it is going to return our answer it is going to return our answer so this is another common pattern where so this is another common pattern where you kind of want to propagate forward at you kind of want to propagate forward at every step the maximum number of points every step the maximum number of points or the solution and so at every single or the solution and so at every single step or every index as we move forward step or every index as we move forward it's going to have it's going to have the answer at that point in time and so the answer at that point in time and so at every step it just says okay at this at every step it just says okay at this particular number this would be the particular number this would be the maximum number points that we could get maximum number points that we could get and so basically what that looks like is and so basically what that looks like is then okay let's just iterate through a then okay let's just iterate through a particular range and we're going to go particular range and we're going to go from 2 to the length of our num look up from 2 to the length of our num look up array array here here and so the way this works and the reason and so the way this works and the reason why we're starting at 2 here is why we're starting at 2 here is initially this DP array will also be initially this DP array will also be just a bunch of zeros just a bunch of zeros multiply by the length of our num lookup multiply by the length of our num lookup because they're going to have the the because they're going to have the the same lengths basically as this same lengths basically as this and so and so initially the initially the DP array that we have here add index one DP array that we have here add index one is going to directly map to the num is going to directly map to the num lookup at the same index at 1 here and lookup at the same index at 1 here and so this just means okay at one we would so this just means okay at one we would be able to get this many points if we be able to get this many points if we only considered one and so beyond that only considered one and so beyond that point we're basically going to have two point we're basically going to have two pointers that's saying okay pointers that's saying okay um if we choose the current number that um if we choose the current number that we're at we're at and we include everything that's two and we include everything that's two steps behind it what's the number of steps behind it what's the number of points that we can get but we also want points that we can get but we also want to consider what number points that we to consider what number points that we can get if we look at one set behind it can get if we look at one set behind it and I'll quickly write this out and and I'll quickly write this out and explain this further but I think it'll explain this further but I think it'll make more sense in a second make more sense in a second and so basically the DP array at the and so basically the DP array at the index n index n will be equal to the maximum of the two will be equal to the maximum of the two possible choices that we can make which possible choices that we can make which is essentially how however many points is essentially how however many points we can get at the current index we can get at the current index plus what we could get basically two plus what we could get basically two steps behind it because we can't steps behind it because we can't consider one step behind it consider one step behind it but let's also compare this to basically but let's also compare this to basically the number of points we can get one step the number of points we can get one step behind this point behind this point let's go ahead and run that oh it looks let's go ahead and run that oh it looks like there's something wrong here like there's something wrong here so let me just think for a second so let me just think for a second so we're going from two to the end so we're going from two to the end and well I know that we also want to hmm particular point this goes to the left end oh sorry about that we want to consider oh sorry about that we want to consider the one one step behind it the one one step behind it there we go okay so essentially what's there we go okay so essentially what's going on here is what we're doing is the going on here is what we're doing is the DP array what it does is it represents DP array what it does is it represents at every point in time what's the at every point in time what's the maximum number of points that we can get maximum number of points that we can get and so the very end of this will hold and so the very end of this will hold that answer that answer but at every step what we want to do is but at every step what we want to do is consider okay we can either include this consider okay we can either include this particular number that we're at particular number that we're at and everything that we've propagated so and everything that we've propagated so far two steps behind it far two steps behind it or we could choose to just get what's or we could choose to just get what's one step behind it and so that way you one step behind it and so that way you can kind of can kind of um um not consider what is one number ahead by not consider what is one number ahead by always just looking back always just looking back one and two steps behind it one and two steps behind it and so it's kind of a it's a lazy way of and so it's kind of a it's a lazy way of doing it doing it um and so this is what's kind of adding um and so this is what's kind of adding the numbers here because initially it's the numbers here because initially it's just zero and the first answer is filled just zero and the first answer is filled but this is what holds the actual number but this is what holds the actual number lookup of how much values that we're lookup of how much values that we're getting but we're constantly just kind getting but we're constantly just kind of storing in this minimization or this of storing in this minimization or this caching that we're doing caching that we're doing um at every single step and this is just um at every single step and this is just the two branches that we can go down the two branches that we can go down okay so I hope I explained that quite okay so I hope I explained that quite well well um it's not very intuitive I find this um it's not very intuitive I find this solution much much better than the solution much much better than the alternative so yeah once again it's just alternative so yeah once again it's just o of the maximum number in this array o of the maximum number in this array and that's kind of the time and space and that's kind of the time and space complexity but let's go ahead and just complexity but let's go ahead and just run this oh now let's go ahead and run run this oh now let's go ahead and run it and success so yeah pretty performant it and success so yeah pretty performant solution but I hope that helped and good solution but I hope that helped and good luck with the rest your algorithms luck with the rest your algorithms thanks for watching
2024-03-21 12:06:38
740
https://i.ytimg.com/vi/M…axresdefault.jpg
740. Delete And Earn - LeetCode Python Solution
uCCJx6HSjd8
the question is resistible characters to make old strings equal you are given an make old strings equal you are given an array of things worth zero in text in array of things worth zero in text in one operation with two distinct indices one operation with two distinct indices I and J where sub I is a known MD string I and J where sub I is a known MD string and move any character from WhatsApp I and move any character from WhatsApp I to any position in WhatsApp J return to any position in WhatsApp J return true if you can make any string in words true if you can make any string in words equal using any number of operation and equal using any number of operation and force otherwise so take the first force otherwise so take the first example the first example this array is example the first example this array is given to you so you have to make all given to you so you have to make all these things equal right shown ABC aapc these things equal right shown ABC aapc PC right you can take this a or this aim PC right you can take this a or this aim okay okay and you can just move this a to this and you can just move this a to this string and you can make this thing also string and you can make this thing also ABC right so that's why it will give you ABC right so that's why it will give you true okay true okay but in the second example they have only but in the second example they have only a b and a right but it will give you a a b and a right but it will give you a false y so because you cannot make these false y so because you cannot make these two strings equal okay two strings equal okay so that's what it will give you false I so that's what it will give you false I think this is clear to you okay now let think this is clear to you okay now let me take an example okay like you have a me take an example okay like you have a string history string history okay okay RR equals to 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 2 means what the length of the array right now if we have another string only r a m okay so now 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 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 give you give you true I think this concept is clear to true I think this concept is clear to you because I will use this concept to you because I will use this concept to solve this problem okay solve this problem okay so basically Iris of this problem in an so basically Iris of this problem in an easy way the thing is I will take an easy way the thing is I will take an integer array okay uh let me take in 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 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 in is so then so then you can do the thing is like count of you can do the thing is like count of C minus of a C minus of a plus plus okay and then plus plus okay and then we only need to do we only need to do one thing the strappers are thing okay 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 false okay otherwise you just return false okay otherwise you just return true right so basically this first fold true right so basically this first fold we can actually in this folder let me we can actually in this folder let me take take advancing like a advancing like a B A okay so basically B A okay so basically this is Count this count have total uh this is Count this count have total uh 26 in indexes from 0 to 1 25 right so 26 in indexes from 0 to 1 25 right so the thing is right at first we have a the thing is right at first we have a okay basically this will be oh yes okay okay basically this will be oh yes okay so basically at first we have a right so so basically at first we have a right so a minus a will be what 0 so in the zero a minus a will be what 0 so in the zero interest positive will increment by one interest positive will increment by one okay now your second is p minus H then okay now your second is p minus H then it will give you what one okay index it will give you what one okay index position one it will increment by one position one it will increment by one okay and then your next character is a okay and then your next character is a again right you need to increment Again again right you need to increment Again by one okay in in part in this position by one okay in in part in this position a minus a is what zero okay interpreter a minus a is what zero okay interpreter than zero increment by one again now it than zero increment by one again now it will become two so now you can easily will become two so now you can easily understand that thing in this way you understand that thing in this way you can easily count a number of the can easily count a number of the occurrences of a occurrences of a and number of currency of B basically and number of currency of B basically ten into a number two occurrence of a is ten into a number two occurrence of a is two and about the occurrency of B is 1 two and about the occurrency of B is 1 right right so that's why I am telling you you can so that's why I am telling you you can do the same thing using hash map also do the same thing using hash map also okay so now at the end I just traversing okay so now at the end I just traversing this count array okay and I just taking this count array okay and I just taking the occurrences of each character is the occurrences of each character is divisible by the oh not the count length divisible by the oh not the count length actually actually it will be words sorry actually actually it will be words sorry for that so yeah I just um 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
2024-03-25 12:11:44
1,897
https://i.ytimg.com/vi/u…axresdefault.jpg
1897. Redistribute Characters to Make All Strings Equal || In JAVA || Easy Way #leetcode
I7T8TZzoDPk
[Music] hello everybody today we'll be taking a hello everybody today we'll be taking a look at odd even linked list on the code look at odd even linked list on the code it is problem number 328 so let's take a it is problem number 328 so let's take a look look given the head of a singly linked list given the head of a singly linked list group all the nodes with odd indices group all the nodes with odd indices together together followed by the nodes with even indices followed by the nodes with even indices and return the reordered list and return the reordered list the first node is considered odd and the the first node is considered odd and the second node is even second node is even and so on so this is important because and so on so this is important because it's the ranking of the list that's odd it's the ranking of the list that's odd and even and even not so much the values at that node not so much the values at that node so another thing that we should note so another thing that we should note here it should be solved in all of one here it should be solved in all of one space space and all of in time so let's take a look and all of in time so let's take a look at an example here at an example here in example one we have one two three in example one we have one two three four five four five one three and five are odd indices so one three and five are odd indices so they should be grouped at the first they should be grouped at the first and two and four are the even indices so and two and four are the even indices so they should be grouped last they should be grouped last so over here it's just by by the example so over here it's just by by the example the odd indices are odd and the even the odd indices are odd and the even indices are even indices are even but really we do not care about the but really we do not care about the value at that node it's just about value at that node it's just about whether it's odd or even in its ranking whether it's odd or even in its ranking so let's try to visualize this to get a so let's try to visualize this to get a better idea of what our solution will better idea of what our solution will look like look like so if we take a look at here at the so if we take a look at here at the linked list from example one linked list from example one we see that the odd indices are colored we see that the odd indices are colored in blue and the even indices are colored in blue and the even indices are colored in orange in orange and what our solution will pretty much and what our solution will pretty much look like if we imagine it is look like if we imagine it is one will point to three one will point to three and then three will point to five and and then three will point to five and then we can imagine then we can imagine two pointing to four and now we have two pointing to four and now we have all our odd indices grouped in one list all our odd indices grouped in one list and all are even and this is grouped in and all are even and this is grouped in one list one list and then what we want to do is pretty and then what we want to do is pretty much connect this last indicee much connect this last indicee from the odd to the even and now this from the odd to the even and now this little little i guess circle ish shape we have here i guess circle ish shape we have here would be what our final link list looks would be what our final link list looks like like so now let's take what we just described so now let's take what we just described and break that down by step by step and break that down by step by step so we described grouping all the odd so we described grouping all the odd indices in one list indices in one list and all the even indices in one list and and all the even indices in one list and then finally we're going to attach the then finally we're going to attach the two lists together two lists together if we want to imagine us grouping the if we want to imagine us grouping the indices together indices together we should have a head for our odd we should have a head for our odd indices indices so let's make a new head and so let's make a new head and this is going to be odd this is going to be odd and now let's just copy this and now let's just copy this and now this is going to be and now this is going to be our even head our even head and then let's give this a separate and then let's give this a separate color so now these are the heads of the color so now these are the heads of the two new lists two new lists we are going to create we are going to we are going to create we are going to create this in all of one additional create this in all of one additional space because we are just going to space because we are just going to attach attach the elements from this list onto here the elements from this list onto here and that way we're not using more space and that way we're not using more space by creating new nodes by creating new nodes so what we would also probably need is so what we would also probably need is we want to imagine we have two other we want to imagine we have two other pointers pointers and these pointers are going to be and these pointers are going to be references to the last references to the last node in each of these lists so we can node in each of these lists so we can imagine them as odd tail pointer imagine them as odd tail pointer and the even tail pointer right now we and the even tail pointer right now we have a pointer to even have a pointer to even and let's call that even tail and we and let's call that even tail and we have a pointer to odd have a pointer to odd and then we just have our regular and then we just have our regular pointer here that points to the node pointer here that points to the node let's just call it ahead and then we're let's just call it ahead and then we're going to have another variable going to have another variable let's call it odd and if it's odd we let's call it odd and if it's odd we know we are looking know we are looking at an odd indices so we should add to at an odd indices so we should add to the odd tail if it's not odd the odd tail if it's not odd then by default we know it's even and we then by default we know it's even and we are looking at an even indice are looking at an even indice and we should add it to the even tail so and we should add it to the even tail so now we are at the first indices now we are at the first indices odd is true that means we should be 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 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 now let's do the same for even head now let's do the same for even head make a new reference node and point even make a new reference node and point even tail tail to the last node in our even linked list to the last node in our even linked list then let's set up our lin variable odd then let's set up our lin variable odd equals true equals true now this is going to be toggled on and now this is going to be toggled on and off in each indices off in each indices for odd and if this is going to be on so for odd and if this is going to be on so we know we should be pointing at the odd we know we should be pointing at the odd head head for even indices it's going to be off for even indices it's going to be off meaning we're going to be pointing at meaning we're going to be pointing at the even head and then let's iterate the even head and then let's iterate over our list node head while it does over our list node head while it does not equal null so while there's still not equal null so while there's still information here let's information here let's iterate over it and then we're going to iterate over it and then we're going to say if odd meaning if we're at an odd say if odd meaning if we're at an odd index index what we want to do is all tail dot next what we want to do is all tail dot next equals head equals head so we're at the last node in the odd so we're at the last node in the odd linked list we want the next node to be linked list we want the next node to be the current node we're looking at and the current node we're looking at and then we want to move our odd tail then we want to move our odd tail position forward like we did in our position forward like we did in our visualization example to the now visualization example to the now last node in our odd linked list last node in our odd linked list which in this case here if we're still which in this case here if we're still following example one should be now following example one should be now one instead of the reference node head one instead of the reference node head else we know we're going to be at an else we know we're going to be at an even index by default even index by default so we know this should go to the even so we know this should go to the even linked list so the same logic here 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 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 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 and voila there we go it has passed all and voila there we go it has passed all the tests and it's 100 the tests and it's 100 faster than all java solutions so faster than all java solutions so hopefully you guys enjoyed that and hopefully you guys enjoyed that and found the educational if you did please found the educational if you did please consider liking and subscribing consider liking and subscribing and see you guys next
2024-03-24 10:35:15
328
https://i.ytimg.com/vi/I…pY831CUtllVWXVnw
LeetCode 328: Odd Even Linked List in Java
nsnpeb_0Hfw
welcome to october's lee code challenge today's problem is remove duplicate today's problem is remove duplicate letters letters given a string remove duplicate letters given a string remove duplicate letters so that every letter appears so that every letter appears once and only once you must make sure once and only once you must make sure your result your result is the smallest in lexicographical order is the smallest in lexicographical order among all possible results say we're among all possible results say we're given the string given the string bc abc our bc abc our smallest lexicographical order with all smallest lexicographical order with all the characters being the characters being unique or appearing just once would be unique or appearing just once would be abc abc so the order of the string matters you so the order of the string matters you can imagine if it was b can imagine if it was b c a c b the answer would be a c b c a c b the answer would be a c b not b a b c because the order here is not b a b c because the order here is what we have to take what we have to take now they give you a hint to try using a now they give you a hint to try using a greedy method greedy method and that's going to be big because one and that's going to be big because one of the first temptations we might have of the first temptations we might have is to do some sort of recursion and find is to do some sort of recursion and find every possible every possible permutation but that's really permutation but that's really inefficient instead inefficient instead let's try building up our string using a let's try building up our string using a stack stack and what we'll do is keep track of and what we'll do is keep track of the greatest index number for each the greatest index number for each unique character unique character so say that we had this example here so say that we had this example here we're going to build up we're going to build up our string starting at the first our string starting at the first character and we'll say okay b character and we'll say okay b okay whatever now c when we check c okay whatever now c when we check c let's let's check to see the previous letter and ask check to see the previous letter and ask ourselves ourselves can that letter be added at a later time can that letter be added at a later time and would that be better so basically and would that be better so basically just check to see if just check to see if b is greater than c which it isn't b is greater than c which it isn't but if it was then check to c can be but if it was then check to c can be be added later is this index number um be added later is this index number um you know current index number is less you know current index number is less than the than the max index number for that unique max index number for that unique character and if it is then we should character and if it is then we should just pop it off of our stack and add it just pop it off of our stack and add it later later so that's what happens when we add a so that's what happens when we add a right we add a right we add a we see that c is greater than a and we we see that c is greater than a and we also see that c also see that c can be added later so we should we can be added later so we should we should pop that off should pop that off and add that later same with b b is and add that later same with b b is greater than a greater than a and we could also add that later so pop and we could also add that later so pop that off that off and now we move on to the next one we and now we move on to the next one we see all right b well a see all right b well a is less than b so that ends that and is less than b so that ends that and then c then c well b is and smaller than c so this well b is and smaller than c so this would be the smallest would be the smallest lexicographical order right so we lexicographical order right so we have to have a couple things a couple have to have a couple things a couple data structures to keep track of here data structures to keep track of here we need to keep track of the greatest we need to keep track of the greatest index number for each character index number for each character so we'll have some sort of dictionary to so we'll have some sort of dictionary to keep track of that keep track of that and we'll build up our stack as well as and we'll build up our stack as well as have some sort of set to keep track of have some sort of set to keep track of whether we've seen this character or not whether we've seen this character or not so let's start with initializing a so let's start with initializing a dictionary to call it lookup dictionary to call it lookup and this is going to contain the max and this is going to contain the max index number for each character index number for each character so for i in range of the length of so for i in range of the length of string string we will just we will just for the character make that value the for the character make that value the index number index number and this will get us the greatest index and this will get us the greatest index number right number right next let's initialize our stack this next let's initialize our stack this will be a list will be a list as well as a set i'm going to call this as well as a set i'm going to call this scene scene and this will uh just keep track of and this will uh just keep track of whether we've seen this character or whether we've seen this character or really whether this character is still really whether this character is still in the stack or not because if it is in the stack or not because if it is then we could just continue so now we'll then we could just continue so now we'll have a loop have a loop say four iron range length of s first thing we want to check to see is 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 if character i is in scene if character i is in scene then we'll just continue otherwise we'll then we'll just continue otherwise we'll have this while loop have this while loop and we'll check first while there's a and we'll check first while there's a stack and stack and the previous item on this stack is the previous item on this stack is greater greater than the current character that we're than the current character that we're about to add and about to add and we can add this character later we can add this character later so say if the i is well i should say so say if the i is well i should say more more for my lookup the max index number for my lookup the max index number if it's greater than our current index if it's greater than our current index number then we know number then we know we should pop it off of our stack we should pop it off of our stack because we can add it later and it's because we can add it later and it's going to be going to be in smaller lexicographical order so we in smaller lexicographical order so we should just pop that off and we should should just pop that off and we should remove it from our stack as well remove it from our stack as well to get back to negative one and i think to get back to negative one and i think i need to do i need to do pop it off my set first before popping pop it off my set first before popping it off the stack to do that it off the stack to do that all right so once that's finished once all right so once that's finished once we realize that we realize that we can't we shouldn't pop off any of our we can't we shouldn't pop off any of our previous letters we'll add previous letters we'll add this current character to our stack this current character to our stack and we'll also add this current 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 and that would be it so our example here and that would be it so our example here this should return abc this should return abc does not um does not um see what did i do wrong here 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 and that gets accepted so this is greedy 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 easy to understand way to do it so thanks for watching my channel and remember do not trust me
2024-03-24 10:22:16
316
https://i.ytimg.com/vi/n…fw/sddefault.jpg
Leetcode - Remove Duplicate Letters (Python)
U1q16AFcjKs
minimum window substring is a sliding window problem asked at facebook amazon window problem asked at facebook amazon microsoft lyft google linkedin apple microsoft lyft google linkedin apple bloomberg bloomberg this problem is definitely hard so get this problem is definitely hard so get your thinking cap on and let's get into your thinking cap on and let's get into it for this problem we are given two it for this problem we are given two strings and we need to return strings and we need to return the minimum window in string s that will the minimum window in string s that will contain contain all characters in string t confused all characters in string t confused let's look at an example let's look at an example the string abc has three unique the string abc has three unique characters we need to find the smallest characters we need to find the smallest sub string sub string in s that contains all of those in s that contains all of those characters characters looking at string s we can see that a looking at string s we can see that a b and c are in this substring in this b and c are in this substring in this substring as you can see we actually substring as you can see we actually have two b's here instead of just one have two b's here instead of just one but that is totally fine we just need at but that is totally fine we just need at least one the characters a b least one the characters a b and c are also in this substring and and c are also in this substring and this substring there are other this substring there are other substrings that satisfy this requirement substrings that satisfy this requirement but remember we are looking for the but remember we are looking for the smallest substring so let's just ignore smallest substring so let's just ignore the others the others looking at these smaller sub strings b a looking at these smaller sub strings b a n c would be the minimum window n c would be the minimum window substring substring since it has a length of four which is since it has a length of four which is the smallest now that we understand what the smallest now that we understand what the problem is asking us to do let's the problem is asking us to do let's jump into the approach to solve this jump into the approach to solve this problem problem which is a sliding window algorithm a which is a sliding window algorithm a sliding window algorithm sounds sliding window algorithm sounds complicated but really all it is complicated but really all it is is a window or section that is formed is a window or section that is formed over parts of your data over parts of your data and in our case our data is just a and in our case our data is just a string we move this window in string we move this window in increments over our data to perform some increments over our data to perform some sort of computation and in our case sort of computation and in our case that would be finding the minimum window that would be finding the minimum window substring going back to the example we substring going back to the example we looked at previously looked at previously let's do a step-by-step walkthrough of let's do a step-by-step walkthrough of the algorithm the algorithm the first thing we need to do is create the first thing we need to do is create a map to generate a count of all a map to generate a count of all characters in string t characters in string t this is so that as we iterate through this is so that as we iterate through string s string s we will know how many characters we have we will know how many characters we have seen in seen in t this will make more sense as we go t this will make more sense as we go through the problem so don't worry so through the problem so don't worry so far far we have a having a count of 1 b having a we have a having a count of 1 b having a count of 1 count of 1 and c having a count of 1. now get ready and c having a count of 1. now get ready i said this problem was going to be hard i said this problem was going to be hard we need a couple different variables we need a couple different variables that are going to be used we're going to that are going to be used we're going to have to have an i have to have an i and j pointer both pointing at index and j pointer both pointing at index 0 in string s another variable called 0 in string s another variable called count is going to be initialized to the count is going to be initialized to the number of number of unique characters we have in string t unique characters we have in string t which we can easily get from our map so which we can easily get from our map so our count our count is going to be initialized to three now is going to be initialized to three now we are going to initialize we are going to initialize a left and right variable which will be a left and right variable which will be used to keep track used to keep track of the minimum substring positions we of the minimum substring positions we come across come across as we are iterating through string s so as we are iterating through string s so our left our left pointer will start at 0 and our right pointer will start at 0 and our right pointer will start at 12 pointer will start at 12 which is the last index in string s which is the last index in string s technically in the beginning our left technically in the beginning our left and right pointers can be initialized to and right pointers can be initialized to anything so anything so don't pay too much attention to the don't pay too much attention to the values right now now we need a variable values right now now we need a variable min length to keep track of the min length to keep track of the difference difference between the right and left pointer this between the right and left pointer this value is the length of the substring value is the length of the substring technically we don't need this variable technically we don't need this variable but is really just for convenience but is really just for convenience so our min length is going to be so our min length is going to be initialized to 13 initialized to 13 this is initialized to 13 because if this is initialized to 13 because if there is a substring there is a substring in s it will be guaranteed in s it will be guaranteed to be lower than the length of s finally to be lower than the length of s finally we need a boolean variable called we need a boolean variable called found to determine if we have found a found to determine if we have found a substring in substring in s the reason we need this is because if s the reason we need this is because if we do not we do not find a substring in s we must return find a substring in s we must return an empty string all right now that we an empty string all right now that we have all of these variables initialized have all of these variables initialized we can get into the details of the we can get into the details of the sliding window algorithm sliding window algorithm our j pointer is currently looking at our j pointer is currently looking at character a character a we check if character a is in our map we check if character a is in our map and in this case it is that means we and in this case it is that means we need to decrease need to decrease the value of character a down to zero the value of character a down to zero now we need to check if character a is now we need to check if character a is at zero or not and in this case it is at zero or not and in this case it is that means we can decrease our count that means we can decrease our count variable so our count is now variable so our count is now two the reason we decrease the count is two the reason we decrease the count is because our sub string because our sub string so far is character a and we have so far is character a and we have satisfied the amount of satisfied the amount of a's we need in this substring which was a's we need in this substring which was just one just one now we need to find one b and one now we need to find one b and one c to find a successful minimum window c to find a successful minimum window substring we're going to continue to substring we're going to continue to move our j move our j pointer forward until we have satisfied pointer forward until we have satisfied finding all of these unique characters finding all of these unique characters in string s in string s so our j pointer is going to move so our j pointer is going to move forward and if our count forward and if our count variable is greater than zero that means variable is greater than zero that means we have we have not found a minimum window substring yet not found a minimum window substring yet and that we should continue on and that we should continue on so our j pointer is currently looking at so our j pointer is currently looking at character d character d d is not in the map so we ignore it and d is not in the map so we ignore it and move forward move forward j is looking at character o o is not in j is looking at character o o is not in the map the map ignore it move forward j is now at ignore it move forward j is now at character b character b and that is in our map that means we and that is in our map that means we need to decrement the value of b need to decrement the value of b which would be zero and since b is at which would be zero and since b is at zero zero we can now decrease our count down to 1. we can now decrease our count down to 1. this is saying that we need just one this is saying that we need just one more character to be found more character to be found character c in order to find a minimum character c in order to find a minimum window substring window substring so far from index 0 to where so far from index 0 to where our j pointer currently is you can see our j pointer currently is you can see that we have an that we have an a and a b inside of this substring a and a b inside of this substring now we're just trying to look for the c now we're just trying to look for the c character our j pointer is going to move character our j pointer is going to move forward again forward again and check if our count is greater than and check if our count is greater than zero in this case it is so we continue zero in this case it is so we continue on on our j pointer is now looking at our j pointer is now looking at character e that is not in the map so we character e that is not in the map so we ignore it and move forward ignore it and move forward j pointer is now looking at character c j pointer is now looking at character c that that is in our map so we're going to decrease is in our map so we're going to decrease the value down to zero since c is the value down to zero since c is equal to zero that means we decrease our equal to zero that means we decrease our count count down to zero as well our j pointer is down to zero as well our j pointer is going to move forward going to move forward and now we check if our count is greater and now we check if our count is greater than zero which it is not what this than zero which it is not what this means is that we found a minimum means is that we found a minimum substring substring but now our i pointer needs to be moved but now our i pointer needs to be moved forward forward until our count is greater than zero until our count is greater than zero again this is the most confusing part of again this is the most confusing part of the algorithm the algorithm the reason why we have to do this is the reason why we have to do this is because there might be because there might be extra useless characters in the prefix extra useless characters in the prefix of our substring that we don't need of our substring that we don't need our eye pointer is at character a that our eye pointer is at character a that is in our map so we're going to do the is in our map so we're going to do the opposite of what we did in the previous opposite of what we did in the previous steps steps we're now going to increase the value in we're now going to increase the value in a to 1. a to 1. since our count is not 0 we now increase since our count is not 0 we now increase our count to 1 as well our count to 1 as well now we check if j minus i now we check if j minus i is less than our current minimum length is less than our current minimum length j minus i j minus i is the length of our substring which is is the length of our substring which is why we are comparing it to why we are comparing it to the current minimum length j minus i is the current minimum length j minus i is less than our min length in this case less than our min length in this case so now we save our i and j positions so now we save our i and j positions with the left and right variables so with the left and right variables so left left becomes 1 right becomes 6 becomes 1 right becomes 6 and then our min length is j minus i and then our min length is j minus i which is 5. since we found a substring which is 5. since we found a substring we now we now set found equal to true meaning our set found equal to true meaning our final result final result will not be an empty string and now it's will not be an empty string and now it's really just performing the same steps really just performing the same steps so our j pointer is looking at character so our j pointer is looking at character o o that is not in the map we ignore it move that is not in the map we ignore it move forward j forward j pointer is looking at character d not in pointer is looking at character d not in the map ignore it move forward the map ignore it move forward j pointer is that character e not in the j pointer is that character e not in the map ignore it move forward map ignore it move forward j pointer is at character b that is in j pointer is at character b that is in the map the map so we're going to decrease the value b so we're going to decrease the value b is now equal to negative one that value is now equal to negative one that value is not is not zero so we don't do anything to our zero so we don't do anything to our count we move our j count we move our j pointer forward and check our count our pointer forward and check our count our count is greater than zero count is greater than zero so we continue our search for an a so we continue our search for an a character character j pointer is at character a which is in j pointer is at character a which is in our map our map so that means we decrease the value down so that means we decrease the value down to zero to zero and since it is at zero we also decrease and since it is at zero we also decrease our count to zero our count to zero we move our j pointer forward again and we move our j pointer forward again and check if our count is greater than zero check if our count is greater than zero it is not which means we found another it is not which means we found another minimum window substring minimum window substring now we're going to move our i pointer now we're going to move our i pointer forward to get rid of the useless forward to get rid of the useless characters characters so right now it's currently looking at so right now it's currently looking at character d character d and that is not in the map so we move and that is not in the map so we move forward forward now our i pointer is looking at now our i pointer is looking at character o that's not in the map so we character o that's not in the map so we move forward move forward our i pointer is now at character b that our i pointer is now at character b that is in the map is in the map so that means we increase this value to so that means we increase this value to zero zero since b's value is not greater than zero since b's value is not greater than zero we do nothing to our count and move we do nothing to our count and move forward our i pointer is at character e forward our i pointer is at character e that is not in the map so we move that is not in the map so we move forward forward now it's looking at character c which is now it's looking at character c which is in the map in the map so we're going to increase the value to so we're going to increase the value to one one we move our eye pointer forward and we move our eye pointer forward and since the value is greater than zero since the value is greater than zero we can now increase our count to one now we can now increase our count to one now we're going to check the length of the we're going to check the length of the substring substring again so we do that by doing j minus i again so we do that by doing j minus i which equals 11 minus six which equals which equals 11 minus six which equals five five if we compare this number to our current if we compare this number to our current minimum length minimum length five is not less than five so we five is not less than five so we continue on continue on without setting the left and right without setting the left and right pointer our j pointer is looking at pointer our j pointer is looking at character character n that is not in the map so we're going n that is not in the map so we're going to ignore it and move forward to ignore it and move forward our j pointer is at character c and that our j pointer is at character c and that is in the map so we decrease is in the map so we decrease the value to zero and since c's value the value to zero and since c's value is at zero we decrease our count to zero is at zero we decrease our count to zero we move j forward again we move j forward again and check if the count is greater than and check if the count is greater than zero it isn't zero it isn't so now we can see what letters we can so now we can see what letters we can shave off by moving shave off by moving our i pointer forward right now the our i pointer forward right now the substring we have substring we have so far is d e b so far is d e b a n c and that is valid but technically a n c and that is valid but technically we don't need the o d e part since none we don't need the o d e part since none of those characters are in of those characters are in a b or c our i pointer will go to o a b or c our i pointer will go to o d and e and all of those characters are d and e and all of those characters are not in the map so we're just going to not in the map so we're just going to move forward move forward and now our i pointer is looking at and now our i pointer is looking at character b character b and that is in the map so we're going to and that is in the map so we're going to increase the value to 1. increase the value to 1. we move our i pointer forward again and we move our i pointer forward again and since since the value of b is greater than zero the value of b is greater than zero that means we can increase our count to that means we can increase our count to one one now we're going to check the length of now we're going to check the length of our sub string by doing j minus our sub string by doing j minus i which would be 13 minus 10 which i which would be 13 minus 10 which equals equals three three is less than our current three three is less than our current minimum length of five minimum length of five so our new left and right values are so our new left and right values are going to get set going to get set our left will be equal to 10 our right our left will be equal to 10 our right will be equal to 13 will be equal to 13 and then our new min length would be and then our new min length would be three and now we are done since our j three and now we are done since our j pointer is not looking pointer is not looking at an index any longer we just need to at an index any longer we just need to compute the substring compute the substring between our left and right pointers keep between our left and right pointers keep in mind though that our left and right in mind though that our left and right pointers pointers are one step ahead so we take all are one step ahead so we take all characters characters inclusive between left minus one inclusive between left minus one and right minus one which would be b a and right minus one which would be b a and c and c all right so let's implement the code all right so let's implement the code for this solution we are given for this solution we are given two strings s and t and then we need to two strings s and t and then we need to return a string return a string which will be the minimum window which will be the minimum window substring the first thing we can do substring the first thing we can do is just have various base cases if our is just have various base cases if our string s or string t is null or empty string s or string t is null or empty we know that we can just return an empty we know that we can just return an empty string and now we're going to get a mapping of now we're going to initialize all of the now we're going to initialize all of the variables that we talked about variables that we talked about and now this is where the actual sliding and now this is where the actual sliding window part comes window part comes we are going to move our j pointer we are going to move our j pointer forward forward until it hits the very end of string until it hits the very end of string s so we can say while s so we can say while j is less than s dot length j is less than s dot length and then we can grab that character so and then we can grab that character so we can say we can say char and char equals char and char equals s dot char at j s dot char at j plus plus every time that we extract a plus plus every time that we extract a character from the string character from the string we are automatically going to move our j we are automatically going to move our j pointer forward pointer forward right after and now we're going to check right after and now we're going to check if this character if this character is present in the map or not so if is present in the map or not so if our map contains the key our map contains the key and char what this means is and char what this means is we are going to decrease the value of we are going to decrease the value of this this character inside the map so we'll say character inside the map so we'll say map map dot put and char dot put and char map dot get and char map dot get and char minus one and then if our map minus one and then if our map dot get and char if this value is equal dot get and char if this value is equal to zero at this point to zero at this point that means we have satisfied the that means we have satisfied the requirement requirement to have all of these characters in the to have all of these characters in the substring substring and we can say count minus equal and we can say count minus equal by one when we come out of this if check by one when we come out of this if check this is where we check if our this is where we check if our count is greater than zero or not so if count is greater than zero or not so if count count is greater than zero then we are just is greater than zero then we are just going to going to continue if this if statement is continue if this if statement is satisfied that means we have satisfied that means we have not successfully found a minimum window not successfully found a minimum window substring yet substring yet if we make it out of this if statement if we make it out of this if statement however this is where we are going to however this is where we are going to shave off any of that extra unnecessary shave off any of that extra unnecessary characters in the prefix of the characters in the prefix of the substring substring so we can say while our count so we can say while our count is equal to zero then we're going to is equal to zero then we're going to extract the start character now extract the start character now and we can say s dot char at and we can say s dot char at i plus plus and once again every time i plus plus and once again every time we extract a character from our eye we extract a character from our eye pointer pointer we're going to move it forward right we're going to move it forward right after and now in this step we're going after and now in this step we're going to do to do exactly the opposite of what we did exactly the opposite of what we did on lines 18 to 20. so what we can do we on lines 18 to 20. so what we can do we can actually just can actually just copy this section and let's put it down copy this section and let's put it down here here and let's fix the indentation and let's fix the indentation and instead of n char we'll put and instead of n char we'll put start char in all of these sections start char in all of these sections and then instead of decreasing we're and then instead of decreasing we're going to be going to be increasing and right here as well plus increasing and right here as well plus equal to 1 and then the only other equal to 1 and then the only other difference difference is instead of saying if it's equal to 0 is instead of saying if it's equal to 0 we want to say if it's we want to say if it's greater than zero finally when we make greater than zero finally when we make it outside of this it outside of this while loop that means we have while loop that means we have successfully shaved off successfully shaved off all of the unnecessary characters in all of the unnecessary characters in the start of our string and now we just the start of our string and now we just need to compute need to compute the length of our substring so we can the length of our substring so we can say if say if j minus i if that is j minus i if that is less than our current min less than our current min then what that means is we set our left then what that means is we set our left pointer to i pointer to i our right pointer to j and then our min our right pointer to j and then our min variable is going to just be j minus i variable is going to just be j minus i and remember the min variable is really and remember the min variable is really just for convenience just for convenience and then we also can say found is now and then we also can say found is now equal equal to true and then when we come out of to true and then when we come out of this while loop this is where we this while loop this is where we have either found a substring or we have either found a substring or we didn't didn't and so we can determine whether we and so we can determine whether we return an empty string or not return an empty string or not using that found boolean variable using that found boolean variable so we can say return if it's so we can say return if it's not found then we just return an empty not found then we just return an empty string string however if we did find a substring this however if we did find a substring this is where we need to actually compute the is where we need to actually compute the substring of string substring of string s using our left and right pointers so s using our left and right pointers so we can say we can say s dot sub string of left s dot sub string of left minus one and right and so this is minus one and right and so this is pretty much the equivalent pretty much the equivalent of saying left minus one right minus one of saying left minus one right minus one inclusive so let's make sure the inclusive so let's make sure the solution works solution works i put a capital s instead of a lowercase i put a capital s instead of a lowercase s s so let's submit that one more time so let's submit that one more time the time complexity of our solution is the time complexity of our solution is going to be big o of going to be big o of 2 times n plus m so n 2 times n plus m so n is the length of string s and m is the is the length of string s and m is the length of string t length of string t we must iterate over string t in order we must iterate over string t in order to create the map of counts to create the map of counts in the worst case our i and j pointer in the worst case our i and j pointer could potentially touch every single could potentially touch every single character in character in s so this could technically be written s so this could technically be written as n plus n plus m but since we drop as n plus n plus m but since we drop constants it just becomes big o of n constants it just becomes big o of n plus plus m our space complexity is going to be m our space complexity is going to be big o of n where big o of n where n is the length of string t the only n is the length of string t the only memory we initialize memory we initialize is the map and this will be the size of is the map and this will be the size of string t string t check out my other sliding window check out my other sliding window algorithm tutorial here algorithm tutorial here to see how to solve one of the most to see how to solve one of the most popular sliding window problems popular sliding window problems on leak code like and subscribe for more on leak code like and subscribe for more content and check out my patreon for content and check out my patreon for discord access and resume reviews discord access and resume reviews that is all i have for you and i will that is all i have for you and i will see you later
2024-03-20 11:42:19
76
https://i.ytimg.com/vi/U…axresdefault.jpg
Minimum Window Substring | Sliding Window | LeetCode
AUIfTelAGVc
welcome to leak codes blind crate 75 where I'll be solving the top 75 leak where I'll be solving the top 75 leak code questions this question is called code questions this question is called combination some and it's a pretty combination some and it's a pretty standard problem that you will probably standard problem that you will probably see in your coding journey here's the see in your coding journey here's the problem given a set of candidate numbers problem given a set of candidate numbers with out duplicates and a target number with out duplicates and a target number find all the unique combinations in find all the unique combinations in candidates that equal or sum up to the candidates that equal or sum up to the target if we're given a list like this target if we're given a list like this we'll say our solution set is going to we'll say our solution set is going to be 7 and 2 to 3 because those are all be 7 and 2 to 3 because those are all the unique combinations that we can find the unique combinations that we can find to create the number 7 now this could be to create the number 7 now this could be solved in a couple of ways we could solved in a couple of ways we could write something recursively and use write something recursively and use memoization to save on space but this is memoization to save on space but this is simple enough that I think you can simple enough that I think you can immediately go to the DP solution or the immediately go to the DP solution or the dynamic programming solution so let's go dynamic programming solution so let's go to the whiteboard and get our intuition to the whiteboard and get our intuition here's a representation of my DP RA and here's a representation of my DP RA and up on the top is going to be the total up on the top is going to be the total count for all the numbers from 0 to 2 count for all the numbers from 0 to 2 the number that we're trying to figure the number that we're trying to figure out as well as our integers that we can out as well as our integers that we can use for the combinations now remember use for the combinations now remember that we can use each number as many that we can use each number as many times as we want times as we want as long as it's going to equal the as long as it's going to equal the number that we're trying to figure out number that we're trying to figure out so what I'm going to do is build up so what I'm going to do is build up lists inside of this array to find all lists inside of this array to find all the combinations possible and just build the combinations possible and just build this up as I move along this DP RA so this up as I move along this DP RA so starting with 0 we know that there's no starting with 0 we know that there's no combination whatever number we're given combination whatever number we're given to make 0 so these are just going to be to make 0 so these are just going to be empty lists now let's start with 1 as empty lists now let's start with 1 as long as the number that we start with is long as the number that we start with is less than or equal to the number that less than or equal to the number that we're calculating for just add the we're calculating for just add the current number to this list as well as current number to this list as well as the 1 minus the current number from the the 1 minus the current number from the list before so here they're going to be list before so here they're going to be empty we know we want to add 1 because empty we know we want to add 1 because this is going to be the possible this is going to be the possible combination and we'll add whatever's combination and we'll add whatever's inside here as well too inside here as well too this list in the same way we can see this list in the same way we can see that one is less than or equal to two so that one is less than or equal to two so we want to add one and add whatever we want to add one and add whatever we've calculated from before because we've calculated from before because whatever combination does that we have whatever combination does that we have for tackling one is going to be added for tackling one is going to be added here right so just have one one like here right so just have one one like this and that's just going to continue 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 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 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 1 & 2 right so it'd be 2 2 1 1 like this as well as 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 1 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 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 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 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 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 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 okay so I know the list is not a list 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 of course so let's try that one more 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
2024-03-20 09:07:12
39
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode - Combination Sum (Python)
lMa36OOKy7Y
hey guys persistent programmer here and welcome to my channel so if you're new welcome to my channel so if you're new here we solve a lot of problems on this here we solve a lot of problems on this channel and today we're gonna be looking channel and today we're gonna be looking at the reverse string problem so this is at the reverse string problem so this is a really interesting problem when you a really interesting problem when you use the two pointer solution to solve it use the two pointer solution to solve it and that's exactly what we will be doing and that's exactly what we will be doing today so I hope this video helps you today so I hope this video helps you understand the question and let's go understand the question and let's go ahead and get started ahead and get started so this is a very simple problem to so this is a very simple problem to understand we're given a string and we understand we're given a string and we just need to reverse the input so if just need to reverse the input so if we're given hello we need to return oleh we're given hello we need to return oleh so just reverse the strings but the key so just reverse the strings but the key in the question is we need to do this in in the question is we need to do this in place so this means that we cannot place so this means that we cannot create any auxilary array to do this create any auxilary array to do this transformation okay so with this in mind transformation okay so with this in mind let's look at the solution okay so to let's look at the solution okay so to solve this problem what i'm gonna do is solve this problem what i'm gonna do is i will initialize two pointers so i will i will initialize two pointers so i will start my pointer here so this will be my start my pointer here so this will be my left pointer and I will have a pointer left pointer and I will have a pointer at the end of the list here at the O and at the end of the list here at the O and I'm going to swap these two positions so I'm going to swap these two positions so what do I mean when I say swap right so what do I mean when I say swap right so if I were to do this for this first if I were to do this for this first iteration what this would look like iteration what this would look like would be Oh II l l h so what I did is I would be Oh II l l h so what I did is I swapped the oh and the H here okay so swapped the oh and the H here okay so you can see that yeah there's just what you can see that yeah there's just what the first two positions but we haven't the first two positions but we haven't swapped the rest of the list right so swapped the rest of the list right so how do we swap all the items in the how do we swap all the items in the string so what we do is we just move our string so what we do is we just move our pointer so we move this right pointer pointer so we move this right pointer over here to this next position and over here to this next position and remove this left pointer forward so at remove this left pointer forward so at each step we're going to move our left each step we're going to move our left pointer forward and our right pointer pointer forward and our right pointer backwards and then what we do is we have backwards and then what we do is we have the same positions here so these don't the same positions here so these don't change and this will transform to now L change and this will transform to now L L and then II so now we switch the L and L and then II so now we switch the L and the e right and this will remain this the e right and this will remain this the same and you can see that we've the same and you can see that we've already solved the problem because this already solved the problem because this is the output so at each point what we is the output so at each point what we need to do is we just need to do is we just to move our pointers and go through in a to move our pointers and go through in a while loop and solve this problem so the while loop and solve this problem so the time complexity for this is o FN because time complexity for this is o FN because we will iterate over the entire array we will iterate over the entire array and the space complexity is o of 1 which and the space complexity is o of 1 which is what the question asks us to do and is what the question asks us to do and at each step we will just literally swap at each step we will just literally swap the two positions were at this the the two positions were at this the strings the elements at those places and strings the elements at those places and who will just advance our pointers and who will just advance our pointers and that's that's it that's all we got to do that's that's it that's all we got to do okay awesome so let's look at the code okay awesome so let's look at the code awesome so I'm back of the code and the awesome so I'm back of the code and the first thing I'm gonna do is define my first thing I'm gonna do is define my left and right pointers so I will say left and right pointers so I will say let left equals zero and this is going let left equals zero and this is going to start at the first index here which to start at the first index here which is the zero index and our right index is is the zero index and our right index is going to start at the end here so that going to start at the end here so that index is flat right it was s toddlin index is flat right it was s toddlin minus 1 okay so we're doing minus 1 minus 1 okay so we're doing minus 1 because we're starting at 0 so this because we're starting at 0 so this index actually points to this last spot index actually points to this last spot in the list that's why we're doing the in the list that's why we're doing the minus 1 ok awesome now we need to write minus 1 ok awesome now we need to write our while loop so we'll say a while left our while loop so we'll say a while left is less than right and we want it to is less than right and we want it to check this condition because if left is check this condition because if left is equal to right that means we're pointing equal to right that means we're pointing at the same item that means like we have at the same item that means like we have finished doing all the swaps we possibly finished doing all the swaps we possibly can right so that's why this is our can right so that's why this is our while condition and what we're gonna do while condition and what we're gonna do is create a temporary variable called is create a temporary variable called and we are going to put the left value and we are going to put the left value in here for it to hold it right so this in here for it to hold it right so this is how we'll do our swap so we will say is how we'll do our swap so we will say let hold equals adds at the index of let hold equals adds at the index of left so in the first iteration the hold left so in the first iteration the hold will be holding this H okay and then will be holding this H okay and then what we're gonna say is S at the index what we're gonna say is S at the index left equals S at the index right and left equals S at the index right and what this is going to do is it will what this is going to do is it will actually say is oh so it will just take actually say is oh so it will just take this last element and just put it here this last element and just put it here so currently if I point this it will so currently if I point this it will just look like oh e ll oh now we need to just look like oh e ll oh now we need to now transfer this H that we put in the now transfer this H that we put in the hold back here right so that's our last hold back here right so that's our last step so what we want to say is step so what we want to say is yes at the index right which is the last yes at the index right which is the last index currently is going to be equal to index currently is going to be equal to whatever we put in that variable to hold whatever we put in that variable to hold so we'll say hold okay so we'll say hold okay and then what we need to do is advance and then what we need to do is advance our pointer so then they move forward so our pointer so then they move forward so the left pointer so remember left the left pointer so remember left pointer will go this way so we're going pointer will go this way so we're going to add to it so we'll say left plus plus to add to it so we'll say left plus plus and the right pointer is going to move 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 right - - all right that looks good right - - all right that looks good let me run code okay awesome so let's let me run code okay awesome so let's submit okay also it works
2024-03-24 11:03:58
344
https://i.ytimg.com/vi_w…xresdefault.webp
Reverse String JavaScript Leetcode 344 | Easy Leetcode Question | Two Pointer Solution
CMTlE0W01Pk
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 date playlist is the name of very important question Similar string group ok if you had to write BF 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 He told that to a friend, He told that to a friend, He told that to a friend, when should they say that they are similar? Two strings when should they say that they are similar? Two strings 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 This is definitely a graph question, This is definitely a graph question, This is definitely a graph question, okay here it is saying that together these 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 remember rates and rates were similar and rates and art are similar that is why these three are grouped together. and art are similar that is why these three are grouped together. and art are similar that is why these three are grouped together. 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 This star This star This star was not similar to anyone else, that is why it has been included in a different group, 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 it is okay, now what is the matter with you, I have given you a string, let me given you a string, let me tell you how many such groups will be formed in total. tell you how many such groups will be formed in total. Look here, two groups have been formed. Look here, two groups have been formed. Look here, two groups have been formed. 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 Okay, so here I will look at the stars and rates. rates. These will come in this group, These will come in this group, in separate groups of this, total two groups. in separate groups of this, total two groups. Okay, so now pay attention to the question here, Okay, so now pay attention to the question here, what time is it in this form, you what time is it in this form, you connect group by similarity, what does it mean connect group by similarity, what does it mean that these two groups are not two, these two groups are that these two groups are not two, these two groups are formed, formed, this is a connect group, all this is a connect group, all three are connected, there is three are connected, there is one or the other. one or the other. one or the other. is okay then a definite question is going to come from here so you can visualize it like this if it and these eight are groups then it is okay you can see that the It is see how many strings we had in total. There were 1 2 3 4 4 strings and which ones were 012 similar and this third one 012 similar and this third one was not similar. was not similar. was not similar. 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 then 3 marks will be made then 3 marks will be made then 3 marks will be made 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 So we have to make So we have to make So we have to make adjustments to make the graph, so adjustments to make the graph, so we have to tell that zero which is we have to tell that zero which is connected to one is fine and one which is connected to one is fine and one which is connected to you is right, here it was zero one second one, connected to you is right, here it was zero one second one, how will you do that, okay so first how will you do that, okay so first how will you do that, okay so first 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 Saw Saw Saw that both of them are similar. How are they similar? They will that both of them are similar. How are they similar? They will check that either there should be check that either there should be zero difference between the two, there should be a difference of characters zero difference between the two, there should be a difference of characters or there should be a maximum of only or there should be a maximum of only two character difference by replying or both should be similar and If both the If both the If both the strings are there then strings are there then if I get I and G that both are if I get I and G that both are similar then what will I do, I is what is similar then what will I do, I is what is zero, I put one in it that I is zero, I put one in it that I is zero one is connected zero one is connected similarly, after this I similarly, after this I saw that these two are not similar saw that these two are not similar because multiple. because multiple. because multiple. 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 If they were If they were If they were similar then one becomes one, if it is not connected to you science or indirect graph then zero seven, science or indirect graph then zero seven, if you have made it then you will have to make zero from one too, 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 okay, you will have to make one from one, you were from one, you will have to make one from you, okay make one from you, okay make one from you, okay 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 There are as many notes as there are, starting from zero, one to There are as many notes as there are, starting from zero, one to There are as many notes as there are, starting from zero, one to three, everyone will be uninvested. three, everyone will be uninvested. I start GG from one, but for I start GG from one, but for example, I started DFS from zero, example, I started DFS from zero, then then if I hit 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 First we will First we will First we will make a graph, after that we will solve 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 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 okay after that the first step was to make the graph. so what will we do, it will connect to I. Okay, so we have made this string our graph, now we just have to when were when were string and s1 string and s2 string and s1 string and s2 right 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 and if the difference is only at two places or there is and if the difference is only at two places or there is highlighted first. highlighted first. highlighted first. how many times we have done DFS? Now let's 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 which is our graph. last time if it is not visited then expand it on but this is not the website then they bill tomorrow DFS tu pass which d test cases ing DFS now we don't have to do anything ing DFS now we don't have to do anything from BFS to create this which from BFS to create this which from BFS to create this which why okay, on whom DFS is done yesterday, on some note, it must have been done tomorrow, okay okay [music] great, let's see after submitting butt debt bill be in d difference separate video because debt bill be a little
2024-03-22 15:13:31
839
https://i.ytimg.com/vi/C…axresdefault.jpg
Similar String Groups | Leetcode - 839 | DFS & BFS | AMAZON | Explanation ➕ Live Coding
sFv6T_wLS4k
come to my channel so in this video i'm going to cover two things the first going to cover two things the first thing thing is we should cover uh the solution to is we should cover uh the solution to this problem and then we are going to do this problem and then we are going to do some coding work some coding work and the second one i'm going to cover and the second one i'm going to cover the general procedure to follow in the the general procedure to follow in the coding interview briefly coding interview briefly so before we start the real content for so before we start the real content for today i would really appreciate that if today i would really appreciate that if you can help subscribe this channel you can help subscribe this channel because it can help me to grow so because it can help me to grow so thanks in other ones let's restart this thanks in other ones let's restart this problem problem remember in the real coding interview remember in the real coding interview the first step is always trying to the first step is always trying to understand the problem understand the problem so don't jump into the coding part too so don't jump into the coding part too quickly try to fully understand the quickly try to fully understand the problem first and uh problem first and uh if there's anything unclear please bring if there's anything unclear please bring out the question to the interviewer out the question to the interviewer and at the same time think about some and at the same time think about some ash cases so let's say ash cases so let's say sorry remove subfolders from the file sorry remove subfolders from the file system system so give a list of others return sorry so give a list of others return sorry remove remove all subfolders in those folders and all subfolders in those folders and return in any other the return in any other the folders after removing okay so if a folders after removing okay so if a folder is located within another folder folder is located within another folder j it is called a subfolder of it j it is called a subfolder of it so the format of the pass is one or so the format of the pass is one or more concatenated string of the forms more concatenated string of the forms forward slash followed by one or more forward slash followed by one or more lowercase english letters for example lowercase english letters for example slash lead code and slash record slash lead code and slash record problems problems are valid passes well an empty string are valid passes well an empty string and follow slash are not okay and follow slash are not okay so let's see we have this something like so let's see we have this something like this this finally after removing all the finally after removing all the subfolders we have slash a and slash subfolders we have slash a and slash cd slash um okay so that's because a b cd slash um okay so that's because a b slash a b is subfolder of slash a slash slash a b is subfolder of slash a slash cd cd is a subfolder of cd so similarly for is a subfolder of cd so similarly for example two three example two three okay so let's see some constraints it okay so let's see some constraints it says that the further the lens is says that the further the lens is between one two for the four times four between one two for the four times four to the power of four to the power of four which is 40k okay so for this lenses which is 40k okay so for this lenses between between uh so each father uh uh so each father uh the lens for each of the father the lens the lens for each of the father the lens of the string is between of the string is between two to 100 and it only contains two to 100 and it only contains lowercase lowercase letters and forward slash always starts letters and forward slash always starts with with character slash so each father name is character slash so each father name is unique unique so it says that we don't have unique so it says that we don't have unique we have we don't have the root uh so we we have we don't have the root uh so we will not never have the root will not never have the root uh directory as the as a folder because uh directory as the as a folder because it says that just one for slash is not it says that just one for slash is not valid valid and now so um the each father the lens and now so um the each father the lens of each father is going to be of each father is going to be larger than two which means the root larger than two which means the root father is not 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 oh we can try to see if oh we can try to see if if one father if one father is any sub-father is any sub-father of the previous fathers so 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 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 so when 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 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 suppose 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 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 the next thing the next solution i can the next thing the next solution i can think about is think about is we could use prefix tree which is we could use prefix tree which is try we could use try to solve this try we could use try to solve this problem problem so first of all we build a try by going so first of all we build a try by going by going through everything by going through everything and then after we build a try we we go and then after we build a try we we go over each of them over each of them uh again so let's say when we when we go uh again so let's say when we when we go over over cd we see that in the prefix tree cd we see that in the prefix tree there is already a pass from c to d and there is already a pass from c to d and uh cd is just a child of that uh cd is just a child of that father so we are just going to ignore father so we are just going to ignore this one this one so this uh regarding this one the so this uh regarding this one the runtime is going to be runtime is going to be n times m n times m uh essentially we need to uh essentially we need to go over each of the thing to go over each of the thing to build the tree build a try and then we build the tree build a try and then we go over again go over again to see if uh if the if to see if uh if the if if the corresponding folder has if the corresponding folder has a ha the corresponding harder a ha the corresponding harder has a parent father that is included in has a parent father that is included in the in the tree the in the tree so overall i think um it depends so overall i think um it depends so it depends if the login is so it depends if the login is larger than m then i would larger than m then i would say yeah if logan is 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 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 so in this one uh tri is going to have so in this one uh tri is going to have the children so the children let's the children so the children let's define it define it as a map from the character as a map from the character to the trinomial let's say we define a to the trinomial let's say we define a trinomial trinomial to triangle okay so this is 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 let's give it a constructor let's say let's give it a constructor let's say the has new hashmap and his father sat as boss or you could say um have another 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 so for the dir first of all we are going so for the dir first of all we are going to to uh split it so string uh split it so string like i would say let's say it is a chunk like i would say let's say it is a chunk is going to be exploit where's i think it's just slash forward slash i think it's just slash forward slash and then you're going to say okay and then you're going to say okay ghost reach a bit um ghost reach a bit um well we shouldn't define it here well we shouldn't define it here actually actually let's define another thing which is a let's define another thing which is a try so for the try we will have a public so for the try we will have a public let's say we have a tri node let's say we have a tri node as a route and then we have the root and as a route and then we have the root and then we will have the then we will have the uh constructor uh constructor so try no okay so here no okay so here let's define a helper function let's say 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 and then we need to go through each of 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 node is equal to root at the very beginning if the no doubt children key chunk key chunk then we are just going to say okay note then we are just going to say okay note is equal to node.children is equal to node.children dot get chunk dot get chunk otherwise if it doesn't contain the otherwise if it doesn't contain the chunk chunk what we are going to do is we are going what we are going to do is we are going to say okay node.children the trunk into it this is of course a the trunk into it this is of course a new 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 yeah so after that uh yeah so after that uh i think you're going what we're going to i think you're going what we're going to do is we're going to have no the dot do is we're going to have no the dot is father as is father as true so let's say suppose it is 80 first true so let's say suppose it is 80 first it goes to suppose it's slash a then at it goes to suppose it's slash a then at the very beginning it doesn't have the a the very beginning it doesn't have the a so we are going to put so we are going to put uh the the a and the corresponding uh the the a and the corresponding new node into the children of the root new node into the children of the root and then we go to the corresponding and then we go to the corresponding child and then we will uh child and then we will uh after after that we are going to set the after after that we are going to set the corresponding trinode as true okay so corresponding trinode as true okay so that's pretty much about the insert that's pretty much about the insert and we we also need to define another and we we also need to define another helper function uh let's say uh the helper function is 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 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 so again we are going to split it into so again we are going to split it into the trunks yeah so one thing i need to think yeah so one thing i need to think okay so it says that the each father is okay so it says that the each father is going to be unique so we don't need to going to be unique so we don't need to worry about the worry about the the duplication stuff the duplication stuff so um for the chunks let's say we have the chunks let's say we have the try here so you're going to have to try try here so you're going to have to try no known as equal to the roots here no known as equal to the roots here at first if the so let's see note should be equal to node.children.uh gets the chunk so let's see if so let's say if we so let's see if so let's say if we already have the slash already have the slash listed there are only two things slash a listed there are only two things slash a and slash a b 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 and then we going to be and then we going to be so if we go into be so if we go into be um we shouldn't so we should um we shouldn't so we should check first i would say so if no check first i would say so if no dots is father then we are going to return sure otherwise we are going to return so let's say we have slash n slash a b so let's say we have slash n slash a b and we form the tree at the very and we form the tree at the very beginning so when we tell whether a b beginning so when we tell whether a b slash a b is a subfolder so first of all slash a b is a subfolder so first of all it is a root it is a root and we see okay root of course is not a and we see okay root of course is not a folder so we are going to we are not folder so we are going to we are not going to touch this one going to touch this one then we go to the corresponding then we go to the corresponding subfolder which subfolder which is slash a slash a is slash a slash a a it is a subfolder so you're going to a it is a subfolder so you're going to return true here return true here well but let's say if you only have well but let's say if you only have slash a b slash a b here we only have slash av for the try here we only have slash av for the try then slash a is not a something then slash a is not a something it's not the the it's not it's not the the it's not slash a is not within the try so you're slash a is not within the try so you're not going to touch this one not going to touch this one and then if it is slash a b and then we and then if it is slash a b and then we go to the b go to the b okay yeah so what i would just want to okay yeah so what i would just want to want to want to see is we don't want to say we don't see is we don't want to say we don't want to have want to have introduce some fast positive so let's introduce some fast positive so let's say we only have we have say we only have we have the slash a slash b we want to make sure the slash a slash b we want to make sure that that when we touch slash a slash b again when we touch slash a slash b again it is not going to return so it's a it is not going to return so it's a further as true further as true all right so having said that i think all right so having said that i think it's okay so it's okay so next thing for us to do is to uh next thing for us to do is to uh use the define class to use the define class to to really uh solve this problem so we to really uh solve this problem so we are going to say okay let's try are going to say okay let's try uh try is when you uh try is when you try and then try and then go through everything string go through everything string oh yeah let's say oh yeah let's say they change this as fathers so try not to insert and then we have to define a list of the and then we have to define a list of the string here let's say our yes new linked 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 okay so it is not character so it is 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
2024-03-19 11:58:57
1,233
https://i.ytimg.com/vi_w…xresdefault.webp
Facebook Coding Interview Question | Leetcode 1233 | Remove Sub-Folders from the Filesystem
hd2Jl2cWxgA
[Music] hi hi i'm ali today i want to talk about i'm ali today i want to talk about another another important interview question this important interview question this question is called question is called lru cache and it's a bit different lru cache and it's a bit different from other problems that we have solved from other problems that we have solved till now in this problem we have to till now in this problem we have to design design a data structure and then implement it a data structure and then implement it this is among one of the most popular this is among one of the most popular interview questions interview questions in lots of great software companies in lots of great software companies and it has been asked by companies like and it has been asked by companies like amazon google microsoft bloomberg amazon google microsoft bloomberg and apple so in order to solve this and apple so in order to solve this problem problem let's first read it carefully and let's first read it carefully and understand it understand it so the problem says design a data so the problem says design a data structure that follows the constraints structure that follows the constraints of of a least recently used cache a least recently used cache and here are the information about the and here are the information about the lru cache class lru cache class so as you can see this class contains a so as you can see this class contains a constructor constructor which takes the capacity as an input which takes the capacity as an input and it initializes the lru cache with and it initializes the lru cache with positive size of capacity positive size of capacity and in the get method it takes and in the get method it takes the key as an input and it returns the the key as an input and it returns the value of the key value of the key if the key exists if the key exists and otherwise it returned -1 so and otherwise it returned -1 so that means that it takes the key and if that means that it takes the key and if the key the key is not already in the cache it returns is not already in the cache it returns -1 and if it is in the cache -1 and if it is in the cache so it returns the value of that key so it returns the value of that key and also the method put and also the method put takes two parameters the key and the takes two parameters the key and the value value it updates the value of the key if the it updates the value of the key if the key exists key exists so if we have that key it updates the so if we have that key it updates the value of that value of that and otherwise it adds the key value per and otherwise it adds the key value per to the cache to the cache so if we don't have that key in the so if we don't have that key in the cache already cache already we should add the key value per we should add the key value per to the cache and if the number of keys to the cache and if the number of keys exceeds the capacity from this operation exceeds the capacity from this operation evict evict the least recently used key the least recently used key so that means that for example so that means that for example consider that our cache our cache consider that our cache our cache capacity is capacity is free and we already have free and we already have three inputs in our cache so if this three inputs in our cache so if this function is called we have to remove function is called we have to remove one of those entries from our cache one of those entries from our cache and that would be the least and that would be the least recently used entry of the cache recently used entry of the cache on the follow-up section it asked us to on the follow-up section it asked us to implement the get implement the get and put method in o1 and put method in o1 when you are reading the question try to when you are reading the question try to paraphrase the question for yourself paraphrase the question for yourself and also check the keywords of the and also check the keywords of the question question for example in this example those for example in this example those keywords keywords are o1 time complexity key value per are o1 time complexity key value per and lru which is our eviction policy and lru which is our eviction policy don't forget to double check the don't forget to double check the discussion points discussion points with the interviewer this shows that you with the interviewer this shows that you are understanding the problem well are understanding the problem well and you have a full grasp on the problem and you have a full grasp on the problem before i explain the solution of this before i explain the solution of this problem problem and write the code let's go and write the code let's go through the example that the question through the example that the question gave us in order to gave us in order to understand this problem better and understand this problem better and deeper so as you can see deeper so as you can see we are given two arrays the first array we are given two arrays the first array contains contains the methods of the lru cache class the methods of the lru cache class and the second array contains the and the second array contains the parameter parameter parameters of those methods for example parameters of those methods for example two is two is the capacity which is the parameter of the capacity which is the parameter of the the lru cache constructor and one one is the lru cache constructor and one one is the key value that we should key value that we should put into our cache and one here put into our cache and one here is the key that we have to is the key that we have to return the value of that based on the return the value of that based on the definition of the definition of the get function solve the problem based on the inputs so solve the problem based on the inputs so as you can see the size of this cache is as you can see the size of this cache is two two or the capacity is two so this would be or the capacity is two so this would be my cache of size two oops ah my cache of size two oops ah let's let's race it and let's let's race it and draw it again draw it again so it is 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 and the first item that we should put and the first item that we should put into this into this cache is one one but do not forget we cache is one one but do not forget we have to have to write the output that i mean write the output that i mean the number that we return the number that we return so that would be my output array and the first method hillary cache does not return anything and the second method is put with the and the second method is put with the values one one values one one so we have to add the key1 and value one so we have to add the key1 and value one into our cache and into our cache and also as it doesn't return anything also as it doesn't return anything the output would be again null the output would be again null the next method is put with q and value the next method is put with q and value 2 2 so we have to add 2 2 into so we have to add 2 2 into our cache and again as it doesn't return our cache and again as it doesn't return anything anything our output is null our output is null the next method that is called is get the next method that is called is get and and the parameter is one so based on the the parameter is one so based on the definition definition that means that we have to return the that means that we have to return the value value of the key which is here one of the key which is here one so we have to return 1 here so we have to return 1 here and the output would also be 1. the next method is put with a 3 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 recently used entry is 2-2 because the 1 1 entry has just been called with the get method so we have to remove the 2 2 entry from the cache and then put 3 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 oops i missed to write the output of the oops i missed to write the output of the previous call which was put so previous call which was put so the output of put is null and the output the output of put is null and the output of of get with the key of two is minus one get with the key of two is minus one the next method that is called is put the next method that is called is put with key value for but as you can see with key value for but as you can see our cache is full so we have to remove our cache is full so we have to remove an item an item but and we should use the least recently but and we should use the least recently used used policy to remove the appropriate 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 just has been called with the put method just has been called with the put method so so we have to delete the one one we have to delete the one one from the cache and we put four from the cache and we put four four instead of that and as four instead of that and as it's put and it doesn't return anything it's put and it doesn't return anything so the so the output is null again then we have get output is null again then we have get one one and we just removed the and we just removed the get one from the cache get one from the cache so the output will be so the output will be minus one based on the definition minus one based on the definition then we have get three so we have to then we have get three so we have to return return the value of this key which is three so the value of this key which is three so the output the output will be three and then we have get four will be three and then we have get four so we have to return the value of the so we have to return the value of the key four 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 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 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 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 i just write single ll to save some time so let's see how that works consider that these are our key values and so and so how can we design uh the suitable how can we design uh the suitable cache lre cache with using cache lre cache with using these two data structures so i want to these two data structures so i want to put all of the keys put all of the keys which are the first elements in a set which are the first elements in a set or a list so this would be or a list so this would be the items in the list which are 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 and the these are my values and these and the these are my values and these are my keys are my keys and i have a direct reference and i have a direct reference from my keys to from my keys to the values that are in the linked list the values that are in the linked list and that would be 10 and that would be 10 11 and 12. 11 and 12. so in this way i have a direct reference so in this way i have a direct reference and don't forget that this is the and don't forget that this is the structure structure of the uh single of the uh single linked list here is linked list here is the value and here is the the value and here is the address to the next node address to the next node actually here the value section is actually here the value section is divided into divided into key and value because the data is in key and value because the data is in key value format so maybe key value format so maybe uh i should say uh i should say that this is the structure that we use that this is the structure that we use so we have key value so we have key value and the address to the next node and the address to the next node so this is our value section so this is our value section which is divided into key and value yeah which is divided into key and value yeah so as you can see here i just built so as you can see here i just built a map right a map a map right a map of integer a list of integer a list of integer to a linked list of integer to a linked list which is here a single linked list which is here a single linked list so this is the map that we were talking 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 so let's see let's consider that so let's see let's consider that here is the function that is just called here is the function that is just called get 8. so what should we return get 8. so what should we return we should return the value of this key we should return the value of this key which is 11. which is 11. okay but because we are using the okay but because we are using the lru policy lru policy so after this method is called so after this method is called we have to update our linked list we have to update our linked list so because this node now is the most so because this node now is the most recently used node and we have to move recently used node and we have to move this node at the beginning this node at the beginning of the list of the linked list right but of the list of the linked list right but the problem is that because of this the problem is that because of this format that the single linked list has format that the single linked list has we cannot uh change the next pointer we cannot uh change the next pointer on the on this node we cannot change it on the on this node we cannot change it to to 12 so it means that we we have 12 so it means that we we have removed this node from here and put it removed this node from here and put it at the beginning at the beginning so what do we need now is to have a so what do we need now is to have a reference to the reference to the previous node so that that brings us previous node so that that brings us to the double linked list so let me to the double linked list so let me change the color change the color and show you how it works and show you how it works so i want to use here the double linked so i want to use here the double linked list list instead of single linked list because instead of single linked list because double linked list double linked list format is that here we also have format is that here we also have an address to the previous node so that an address to the previous node so that means that this node means that this node has access to the previous node and also has access to the previous node and also this node has access to the previous this node has access to the previous node node so when get 8 is called so when get 8 is called and i want to transfer this node at the and i want to transfer this node at the beginning beginning i can simply change the i can simply change the next note next address of this note next note next address of this note because now because now i can go to the previous note from this i can go to the previous note from this note so note so i go here and i just change i go here and i just change the next address to the the next address to the 12 instead of 11. so in this case 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 and as you can see we now can get the and as you can see we now can get the uh get the value from the cache uh get the value from the cache in one and we also can put that with one in one and we also can put that with one with the double with this double linked with the double with this double linked list because whenever list because whenever i want to put something for example i 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 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 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 and on the next part i will explain the and on the next part i will explain the code of this code of this data structure so you can data structure so you can understand this problem easier understand this problem easier and better now that we understood the and better now that we understood the problem problem and the suitable data structure that we and the suitable data structure that we want to design want to design let's uh look at the code to understand let's uh look at the code to understand how should we implement how should we implement this data structure but this data structure but before i explain the code i should say before i explain the code i should say something about something about the code we assumed that we have a the code we assumed that we have a pseudo head and tail so pseudo head and tail so we are doing this because we do not want we are doing this because we do not want to to check for the null when we want to check for the null when we want to update the update the linked list and that also helps us linked list and that also helps us to write a cleaner code to write a cleaner code and also pay attention that the linked and also pay attention that the linked list that list that we have here is from most recently used we have here is from most recently used elements to list recently used elements elements to list recently used elements so that means that so that means that the elements that are at the beginning the elements that are at the beginning of the list are those that of the list are those that have recently used and those that are have recently used and those that are at the end of the linked list are those at the end of the linked list are those that that have been least recently used so keep in have been least recently used so keep in mind these mind these uh two points because uh uh two points because uh we need them when we want to analyze the we need them when we want to analyze the code now let's see the code code now let's see the code so we have a class called lru cache so we have a class called lru cache which is the which is the cache class and in this class we have cache class and in this class we have just defined just defined 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 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 we do 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 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 so the next note would be this 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 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 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 class called previous and next and in previous we keep the node.previous 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 previous note next node would be next so previous note next node would be next so that means that means as i told you this node should point to as i told you this node should point to this node this node and also the next node should and also the next node should refer or point to the previous node refer or point to the previous node instead of this origin instead of this origin so we do that by this code and this is so we do that by this code and this is the visual format of this code and so as you can see this method is also so as you can see this method is also void void and it takes again a node as the and it takes again a node as the parameter and what do we want here is to parameter and what do we want here is to move a node to the head but move a node to the head but remember that as we have pseudo remember that as we have pseudo uh head and tail here we actually uh head and tail here we actually add it to the node after our pseudo head add it to the node after our pseudo head and this will use in cases that we and this will use in cases that we update the linked list for example if we update the linked list for example if we call a node call a node for example we just call get method for example we just call get method any node is called so that would be our any node is called so that would be our most recent node and we want to move it most recent node and we want to move it to the head to the head to the head of the linked list because to the head of the linked list because remember remember our order is from most recently used to our order is from most recently used to list recently used so let's see what do list recently used so let's see what do we we do in this function so i've just called do in this function so i've just called remove node that we explained here remove node that we explained here an add node but let's show you the an add node but let's show you the visual format again 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 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 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 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 get that given key in the method from the cache so we call 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 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 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 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 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 so ah 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 so based on this graph uh our so based on this graph uh our run time beats about 95 percent 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
2024-03-21 12:52:40
146
https://i.ytimg.com/vi/h…axresdefault.jpg
LRU Cache (LeetCode 146 - Medium)
U0utLw_vWGM
hello guys welcome to algorithms made easy my name is rajat and today we will easy my name is rajat and today we will be discussing the question maximum be discussing the question maximum points you can obtain from cards points you can obtain from cards in this question we are given several in this question we are given several cards arranged in a row and cards arranged in a row and each card has an associated number of each card has an associated number of points the points are given in the points the points are given in the integer array integer array in one step we can take one card from in one step we can take one card from the beginning the beginning or from the end of the row and you have or from the end of the row and you have to take exactly k to take exactly k cards your score is the sum of the cards your score is the sum of the points of the cards you have taken points of the cards you have taken so we need to return the maximum score so we need to return the maximum score that we can obtain that we can obtain in the first example we can see that the in the first example we can see that the k is equals to 3 k is equals to 3 so we can take three cards from the end so we can take three cards from the end and hence the output will be maximum 12 and hence the output will be maximum 12 and similarly in the rest of the and similarly in the rest of the examples so now let's first try to examples so now let's first try to understand what this question is about understand what this question is about and how we can solve it so suppose this and how we can solve it so suppose this is the input error given to us is the input error given to us and the k is equals to 3 that means we and the k is equals to 3 that means we need to select need to select exactly three cards from this array exactly three cards from this array starting from either from the beginning starting from either from the beginning or from the end in order to make the or from the end in order to make the maximum sum maximum sum so as we know that in this case the so as we know that in this case the maximum sum is maximum sum is if we take the cards starting from the if we take the cards starting from the end end that will make the sum is equals to 12 that will make the sum is equals to 12 which is the maximum that we can make by which is the maximum that we can make by picking up three cards with the given picking up three cards with the given conditions conditions now let's change one of the values that now let's change one of the values that is the value at zeroth index becomes 10. is the value at zeroth index becomes 10. now in this case what will be the answer now in this case what will be the answer in this case we need to pick one card in this case we need to pick one card from the beginning from the beginning and two cards from the end in order to and two cards from the end in order to make a maximum sum of 17 make a maximum sum of 17 with these two examples you must be with these two examples you must be clear with what the question is about clear with what the question is about and how we need to proceed further and how we need to proceed further now let's take the two examples that we now let's take the two examples that we discussed side by side and find out what discussed side by side and find out what are the similarities between are the similarities between the two examples the length of the two the two examples the length of the two array are the same array are the same the k is the same for them but not the the k is the same for them but not the result result as the one value at the start of this as the one value at the start of this array has been changed to a much higher array has been changed to a much higher value which changes the result the value which changes the result the number of cards number of cards picked from the two arrays are the same picked from the two arrays are the same which is equals to which is equals to k which is three and so are the number k which is three and so are the number of cards of cards which are not pegged from this array so which are not pegged from this array so here the main intuition is here the main intuition is what we can use of these unused or what we can use of these unused or unpacked cards unpacked cards that we can get the result of the pegged that we can get the result of the pegged cards cards so the number of non-pegged cards so the number of non-pegged cards in these two arrays are equals to 4 in these two arrays are equals to 4 which can be found out by 7 minus 3 is 4 which can be found out by 7 minus 3 is 4 where 7 is the total length of the array where 7 is the total length of the array 3 is the 3 is the k so n minus k is 4 in this case k so n minus k is 4 in this case now we can find out the total sum of the now we can find out the total sum of the array at the top array at the top is equal to 31 and if we find out the is equal to 31 and if we find out the maximum point maximum point that we can get from this array it will that we can get from this array it will be equal to 31 be equal to 31 minus 14 which is 17 where 14 minus 14 which is 17 where 14 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 31 being the sum of the total number of cards when we apply the same logic cards when we apply the same logic on the below array as well we get the on the below array as well we get the same result same result that is the total sum is 22 max point that is the total sum is 22 max point will be 12 which is 22 minus 10 will be 12 which is 22 minus 10 10 being the sum of the unpicked cards 10 being the sum of the unpicked cards and by the condition given with the and by the condition given with the problem we can see that problem we can see that these unpicked cards will be in a these unpicked cards will be in a contiguous sequence contiguous sequence so we need to find a contiguous sub so we need to find a contiguous sub array in this array which gives us array in this array which gives us a minimum sum this sub array should be a minimum sum this sub array should be of length of length n minus k we can subtract that value n minus k we can subtract that value from the total sum from the total sum and get the maximum sum that we can get and get the maximum sum that we can get by picking up by picking up exactly k cards so now it's time to code exactly k cards so now it's time to code this particular approach this particular approach so as discussed we need to find out the so as discussed we need to find out the sum of sum of this whole array so we will have a sum this whole array so we will have a sum variable variable so let's first find out that so we have so let's first find out that so we have the sum with us the sum with us now we need to find out the result so we now we need to find out the result so we will have this will have this answer variable which will initially be answer variable which will initially be 0 0 and then we need the sum of and then we need the sum of the window n minus k so we will name the window n minus k so we will name that that variable as window and we will have that variable as window and we will have that as as 0 initially so we'll declare a variable 0 initially so we'll declare a variable n which will be the length of the card n which will be the length of the card points array so now in the example points array so now in the example as we know that the window will be of as we know that the window will be of length 4. length 4. we will first find out from the 0th we will first find out from the 0th index n minus k minus 1 that is index n minus k minus 1 that is in this case length of 3 which we will in this case length of 3 which we will store in a temporary sum store in a temporary sum so we'll code this wherein we'll start so we'll code this wherein we'll start from the 0th index till from the 0th index till n minus k minus 1 incrementing this n minus k minus 1 incrementing this sum of window so once we have this sum of window so once we have this temporary sum which in this case will be temporary sum which in this case will be initially 50 initially 50 we need to make this window equals to n we need to make this window equals to n minus k length that is 4 minus k length that is 4 so we will add one more value this will so we will add one more value this will be in a be in a next loop we will add this value make next loop we will add this value make this value as 19 this value as 19 the temporary sum and now we need to the temporary sum and now we need to find out find out what will be the sum of the remaining what will be the sum of the remaining values values and we will take that into the answer and we will take that into the answer which is equals to the maximum of which is equals to the maximum of the answer and the total sum minus sum the answer and the total sum minus sum of n minus k of n minus k window which comes out to be 12 in this window which comes out to be 12 in this case case once we have find out this max value we once we have find out this max value we need to again need to again shorten up this window so that we can shorten up this window so that we can at the next iteration add one more value at the next iteration add one more value so we will shorten up by so we will shorten up by removing the starting index value from removing the starting index value from this this temporary sum making it now 9 and then temporary sum making it now 9 and then we again add the value find out the we again add the value find out the answer which is the maximum answer which is the maximum which now becomes 17 and again remove which now becomes 17 and again remove the value from the start so now let's the value from the start so now let's write that write that so we now we will start off from the so we now we will start off from the index from where we left index from where we left that is n minus k minus 1 that is n minus k minus 1 going till the last index we need to going till the last index we need to add the value in this window to make it add the value in this window to make it equal to length equal to length n minus k now we'll find out the maximum n minus k now we'll find out the maximum which will be max of the answer which will be max of the answer and total sum minus the window and now and total sum minus the window and now we need to shorten up this we need to shorten up this window by subtracting the value at the window by subtracting the value at the start index of this window start index of this window and that will be i minus n minus k minus and that will be i minus n minus k minus 1 1 at the end we just need to return the at the end we just need to return the answer now there can be condition where answer now there can be condition where n n and k are both equal in that case we and k are both equal in that case we need not to perform any logic and we can need not to perform any logic and we can directly return sum directly return sum in that case so if n is equals to k in that case so if n is equals to k we can return sum directly as we are we can return sum directly as we are picking up all the cards picking up all the cards present in this array this completes the present in this array this completes the coding part coding part now let's try to run this code for all now let's try to run this code for all the sample test cases the sample test cases so it runs successfully let's submit so it runs successfully let's submit this this so it got submitted successfully the so it got submitted successfully the time complexity is often time complexity is often well the space complexity is all fun do well the space complexity is all fun do let us know your thoughts in the let us know your thoughts in the comments below thanks for watching this comments below thanks for watching this video see in the next one
2024-03-21 01:20:12
1,423
https://i.ytimg.com/vi/U…axresdefault.jpg
Maximum Points You Can Obtain from Cards | Live Coding with Explanation | Leetcode - 1423
a6ug649-vkU
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 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 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 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 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 right so what will be our process 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 the complexity of this algorithm is Big O of n because we are just scanning that array once it 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
2024-03-21 11:24:57
125
https://i.ytimg.com/vi_w…xresdefault.webp
Valid Palindrome | LeetCode 125 | Python
dy_GA7sG22g
hey everyone today we are going to solve theal question power all four okay I theal question power all four okay I think we can solve this question with think we can solve this question with bitwise operation like this so this is a bitwise operation like this so this is a one time but in real interviews I've one time but in real interviews I've never seen someone who solved the never seen someone who solved the question with bitwise operations so I'll question with bitwise operations so I'll show you another way instead of bitwise show you another way instead of bitwise operation I think each programming operation I think each programming language has like a mass log function so language has like a mass log function so we use it so for example python has mass we use it so for example python has mass log and this number should be n and this log and this number should be n and this question is power four so that's why I question is power four so that's why I put four here so this function put four here so this function calculates a logarithm of n to the base 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 we will get the answer with like a float we will get the answer with like a float so 15 and four is so 15 and four is 1.93 95344 1.93 95344 something and uh simply if the decimal something and uh simply if the decimal part is part is zero so we can return through right zero so we can return through right right if not like a 1.53 right if not like a 1.53 44 um we should return false right and 44 um we should return false right and to check the decimal part so we can so to check the decimal part so we can so in Python we have is integer function so in Python we have is integer function so we can use we can use that yeah so that is a basic idea to that yeah so that is a basic idea to solve this question so with that being solve this question so with that being said let's get into the code okay so said let's get into the code okay so let's write the code coding is very easy let's write the code coding is very easy so first of all if n is less than or so first of all if n is less than or equal zero equal zero in that case we can immediately return in that case we can immediately return false false false and then return Mass do log and false and then return Mass do log and put n here and put n here and four 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
2024-03-24 10:59:04
342
https://i.ytimg.com/vi_w…xresdefault.webp
Power of Four - LeetCode #342 | Give me 3 minutes Python, JavaScript, Java, C++
UbE4-ONpJcc
hello everyone welcome back again to Li Kui Kui today we're here with a very interesting today we're here with a very interesting problem called de visa game problem called de visa game this problem is very famous in companies this problem is very famous in companies such as Google and Microsoft so we will such as Google and Microsoft so we will be going through a series of solution be going through a series of solution solving this problem initially we will solving this problem initially we will start with a simple naive recursive start with a simple naive recursive problem then we will try to convert that problem then we will try to convert that into our dynamic programming problem into our dynamic programming problem which will be solving the problem in Big which will be solving the problem in Big O of n square so from exponential we O of n square so from exponential we will be going to Big O of n square using will be going to Big O of n square using dynamic programming and then using dynamic programming and then using dynamic programming we will try to dynamic programming we will try to optimize this from n Square to n raised optimize this from n Square to n raised to the power 3 by 2 and then finally we to the power 3 by 2 and then finally we will move on to the trick part which is will move on to the trick part which is Big O of 1 solution to the problem so Big O of 1 solution to the problem so please watch the complete video and let please watch the complete video and let us type into the problem it is given us type into the problem it is given that there are 2 players Alice and Bob that there are 2 players Alice and Bob which are playing a game so they're which are playing a game so they're given a number and initially and that given a number and initially and that number could be replaced by another number could be replaced by another number X which could be greater than 0 number X which could be greater than 0 and smaller than n at the same time it and smaller than n at the same time it should divide n completely so we can should divide n completely so we can replace the number n with another number replace the number n with another number that is n minus X so each player take that is n minus X so each player take turns alternately and then else in turns alternately and then else in studying the game first first it is studying the game first first it is Ellis studying the game she is going to Ellis studying the game she is going to play optimally and then the turn will be play optimally and then the turn will be passed on to Papa now Bob will make the passed on to Papa now Bob will make the same move and he will also play same move and he will also play optimally this way we have to tell that optimally this way we have to tell that well whether Ellis can win the game or well whether Ellis can win the game or not let's try to implement this using not let's try to implement this using recursion as we don't know anything recursion as we don't know anything about mathematics yet so we will move on about mathematics yet so we will move on to that but now we are solving this to that but now we are solving this using dynamic programming for that we using dynamic programming for that we need a recursive solution now it is also need a recursive solution now it is also given that if a player cannot make a given that if a player cannot make a move then that player loses the game move then that player loses the game what do you mean by a player cannot make what do you mean by a player cannot make a move so making a move means choosing a a move so making a move means choosing a number X that is greater than 0 and number X that is greater than 0 and smaller than N and that divides n smaller than N and that divides n completely so there is always the completely so there is always the possibility of choosing one because one possibility of choosing one because one divides any number but if n is given to divides any number but if n is given to be 1 that means that we cannot choose be 1 that means that we cannot choose one one so the number should be greater than so the number should be greater than zero and it should be smaller than one zero and it should be smaller than one so that means that means there is no so that means that means there is no such number which we can choose so if such number which we can choose so if the number is one that means that we are the number is one that means that we are stuck and we will lose the game in all stuck and we will lose the game in all the other cases we have possibility of the other cases we have possibility of choosing certain numbers we are going to choosing certain numbers we are going to choose them each so we will see that if choose them each so we will see that if we choose I is equals to one then I we we choose I is equals to one then I we will choose from one to N and I plus will choose from one to N and I plus plus now if we choose I is equals to one plus now if we choose I is equals to one and it leads the current player to win and it leads the current player to win so if this is the case and it is leading so if this is the case and it is leading us to win then we are going to choose us to win then we are going to choose this if it is not leading us to n then this if it is not leading us to n then we will go for another possibility and we will go for another possibility and try with that so this is what we mean by try with that so this is what we mean by playing optimally we will go to each of playing optimally we will go to each of the possibility that we have in our hand the possibility that we have in our hand and we will go forward with that and we will go forward with that possibility we will lead us to win the possibility we will lead us to win the game eventually so a player X winning game eventually so a player X winning the game means that the player Y should the game means that the player Y should lose the game let me explain that so if lose the game let me explain that so if we can choose this particular I we can we can choose this particular I we can only choose this when it is dividing the only choose this when it is dividing the given number n so if we can choose this given number n so if we can choose this and if the next player next player is and if the next player next player is going to get this n minus I as the going to get this n minus I as the number which is on board now if the next 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 so let's not wait for that I know that so let's not wait for that I know that it is going to give us T le what I will 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 see we got T le now what I'm taking one see we got T le now what I'm taking one zero one is because the N is given to be zero one is because the N is given to be thousand there's repetition in this thousand there's repetition in this problem so if you want to see repetition problem so if you want to see repetition let us take an example to prove that as let us take an example to prove that as well let's say the number is eight the well let's say the number is eight the number is eight so one is a possibility number is eight so one is a possibility that we can choose then two then four that we can choose then two then four and then eight is not an option and then eight is not an option so these are the three possibilities so these are the three possibilities this will give then the okay this was this will give then the okay this was the player one playing the game now the the player one playing the game now the player two will play the game and he player two will play the game and he will get he will get seven because 8 will get he will get seven because 8 minus 1 is 7 then he will get 6 and then minus 1 is 7 then he will get 6 and then he will get 4 know this now second he will get 4 know this now second player was 7 he can choose I think he player was 7 he can choose I think he can only choose one so he will give it 6 can only choose one so he will give it 6 ok no another option now 6 we will be 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 then another option 6 minus 2 is 4 then then another option 6 minus 2 is 4 then another option is 3 now this 4 I don't another option is 3 now this 4 I don't think we have to go further because you think we have to go further because you already see repetition for over here already see repetition for over here four over here six over here and 6 over four over here six over here and 6 over here so once we calculated 6 using this here so once we calculated 6 using this one why should we go and calculate 6 one why should we go and calculate 6 using the same steps here so that will using the same steps here so that will be a waste of time be a waste of time that's why we are they are cashing these that's why we are they are cashing these we are using dynamic programming for we are using dynamic programming for this so I am going to initialize my DP this so I am going to initialize my DP array with minus 1 memset DP minus 1 array with minus 1 memset DP minus 1 sighs of TP if DP of I is not calculated sighs of TP if DP of I is not calculated it should be DP of n if it is calculated it should be DP of n if it is calculated then we have to return DP of n we won't then we have to return DP of n we won't be calculating this again if it is not be calculating this again if it is not calculated we are going to calculate 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 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 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 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 icicles t 1 is smaller than equals to M icicles t 1 is smaller than equals to M it is giving us true or something that it is giving us true or something that is false okay I got this because we should not choose 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 let me try this forward three there's let me try this forward three there's some difficulty in balancing the 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 very 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 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 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 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 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 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 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
2024-03-25 15:07:56
1,025
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 1025. Divisor Game
feeMamxD9Vw
hello hi everyone loot do it president pimi numbers elements of porn of oo numbers elements of porn of oo loot it it is the garden and number aadhaar loot it it is the garden and number aadhaar number of dangers lu 2012 novel in two two two two two two two two and objective sarat2 bane 550 two two two two and objective sarat2 bane 550 two two two two To to to to a significant boiled only then at once first class 10th explain this question to you with the help of that you understand it in a good way that you understand it in a good way in Sapna wa hai who in Sapna wa hai who is the battle in which is the number base is the battle in which is the number base number of lemon juice lemon juice number of lemon juice lemon juice number of lemon juice lemon juice 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 third goal Kunthu half-half flowers flower third goal Kunthu half-half flowers flower show show a week a week a week off the number and I am the answer hai net speed hai andar ke us bad news in hindi question 12345 all disawar news room aa and lu lu lu lu 12345 all disawar news room aa and lu lu lu lu Also the Also the Also the answer is not getting back side answer is not getting back side New Delhi white poll is in ours New Delhi white poll is in ours so let's make of functions forget bullets in which 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 Of Of Of flowers operator pimples pe karna hai flowers operator pimples pe karna hai 20 sec is the biggest vid oo Bluetooth settings pe remedy hai 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 is equal to left side is equal to left side Jhaloo He Got A Satisfied And I Will Give The Jhaloo He Got A Satisfied And I Will Give The Results Admit Th Results Admit Th And Anshu Boys Withdrawal Pipe With U And Anshu Boys Withdrawal Pipe With U 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 Also a Also a i will return - 110 test ranking mein i will return - 110 test ranking mein that file is pimple complete a new this minute that file is pimple complete a new this minute live video ko live video ko kahan ho yaar checking available pimple away 8.1 kahan ho yaar checking available pimple away 8.1 urgent a urgent a that this period already blue blue that addison volume come will do made - 1the pizza 1212 Bread Paneer Vidyalaya Result Was Interactive Way Was Interactive Way That Reddy Submitted To Loot Aishwarya Logic That Reddy Submitted To Loot Aishwarya Logic For This Program Will Destroy All
2024-03-21 10:21:29
1,482
https://i.ytimg.com/vi/f…axresdefault.jpg
Miniumum Number Of Days To Make m Bouquets || Leetcode 1482
zesp0cWYs4w
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 If it is on this one, then you If it is on this one, then you If it is on this one, then you simply make a different one. If there is no 132 pattern, simply make a different one. If there is no 132 pattern, then simply print it in the office. There is then simply print it in the office. There is no requirement. no requirement. Okay, so let's see what 132 pattern Okay, so let's see what 132 pattern is in reality. So this is the is in reality. So this is the age for the basic. Three indexing on the face. age for the basic. Three indexing on the face. age for the basic. Three indexing on the face. 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 It It It should be okay, this industry value should be large, I am not talking about robbers, only these not talking about robbers, only these three are speaking in comparison and that is the three are speaking in comparison and that is the value of K, it should apply between small and large, value of K, it should apply between small and large, it cannot be input, it cannot be input, like on some media. like on some media. 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. This will be on the next minute of the day on the planet. Okay, so let's see some examples Okay, so let's see some examples like if the rectangle index like if the rectangle index like if the rectangle index 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 This is boiled 132 buttons. This is boiled 132 buttons. This is boiled 132 buttons. Let's take one more complex. Today's Let's take one more complex. Today's value is one. If the value is nine then the value is one. If the value is nine then the value of velvet can be this. value of velvet can be this. Here it ranges from two to one art. Here it ranges from two to one art. If only you get it. If only you get it. You got 132 pattern, okay print 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, if Rishi had given you some number like this, free wave and then exam, the first number three is here That and the District Magistrate and Lee That and the District Magistrate and Lee That and the District Magistrate and Lee and then you apply here. and then you apply here. In this case, if you want 132 pattern, then I think In this case, if you want 132 pattern, then I think here, keep this in mind, here and on the here, keep this in mind, here and on the day of tax, here this guy is the smallest, day of tax, here this guy is the smallest, this guy is bar just and who this guy is bar just and who this guy is bar just and who is the element that you get a lot of likes between them so this time you got 108 so let's do the again he got a sketch on this again he got a sketch on this that if you had got the number - 152 hero Let's see smallest - 1023 Let's see smallest - 1023 Let's see smallest - 1023 likes here largest value is likes here largest value is likes here so worker is two and likes here so worker is two and zero is okay on this one if I zero is okay on this one if I wanted the alarm value of IJ smallest here you wanted the alarm value of IJ smallest here you can say digestive here and which is can say digestive here and which is can say digestive here and which is should be rally, this is also correct and 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 Just take it here, see bring it here, Just take it here, see bring it here, 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, 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 There is There is There is no laxity in the middle, it is okay if no laxity in the middle, it is okay if you take them instead and you take them instead and take them for higher cholesterol index, after this you take them for higher cholesterol index, after this you should have liked it here, tight should have liked it here, tight here, if you had liked it at this point, then here, if you had liked it at this point, then it is between these two. it is between these two. it is between these two. 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 But I would have But I would have But I would have liked in this case, I would have got liked in this case, I would have got Pragyaan for the one, but I will not get the ticket, I have to Pragyaan for the one, but I will not get the ticket, I have to see the confirmation, Taylor Swift elements see the confirmation, Taylor Swift elements 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 point is so much, let's meet in the pollution point is so much, let's meet in the pollution piece. piece. piece. 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 For For For complete, add it here and edit the complete here to complete, add it here and edit the complete here to point to a valid number. point to a valid number. Now every time you can go and check that the numbers Now every time you can go and check that the numbers of I Labs name of fennel are this lace Ghanshyam of I Labs name of fennel are this lace Ghanshyam fennel fennel that if this is the desired condition, bread role that if this is the desired condition, bread role play somewhere. play somewhere. play somewhere. 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 From the start again till the end, the From the start again till the end, the From the start again till the end, the entire pending will be kept, so as for entire pending will be kept, so as for all the values, K is going to complete the journey all the values, K is going to complete the journey and K itself is and K itself is this closed loop of end travel, that this closed loop of end travel, that too will be done by Android and whatever has come. too will be done by Android and whatever has come. too will be done by Android and whatever has come. 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 How can you solve Mains paper? How can you solve Mains paper? How can you solve Mains paper? Look, you Look, you kept this here, you kept this here, your 1st year ahead, did kept this here, you kept this here, your 1st year ahead, did any element not match with you any element not match with you on the sequence, meaning the elements that came on the sequence, meaning the elements that came are 3D and this camphor in oil is fine in between. are 3D and this camphor in oil is fine in between. No one is lining up the element in me, right No one is lining up the element in me, right now you did not get the crop this time, 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 one for four, you did not get any for the seven, it is late, now it is 80. late, now it is 80. late, now it is 80. no element available, even for 80 there is no proper value of velvet here, what are you going to do next time, after what are you going to do next time, after checking all your things, after this you checking all your things, after this you will come one step ahead and ignorance is a force which will come one step ahead and ignorance is a force which will come one step ahead and ignorance is a force which 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 It is It is It is okay 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 this oil, the villagers kept it on the value of their Jab ab aayi and here they did their stomach full, and here they did their stomach full, take the poem clear smallest meaning here here here 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 For here tiriya goes right For here tiriya goes right For here tiriya goes right that you move once ahead here later that you move once ahead here later post here there would be another number that would have been checked for your stomach 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 by bittu and after that one who see now at 8:00 the 8:00 the value is your basically value is your basically only this one was checked first on these three, then what can we do? Instead of only this one was checked first on these three, then what can we do? Instead of these three, if only one child is used, these three, if only one child is used, then it would be sufficient, that is, we have to find a number then it would be sufficient, that is, we have to find a number which is less than 8. which is less than 8. which is less than 8. 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 Then here we have to point out by keeping the minimum, the Then here we have to point out by keeping the minimum, the Then here we have to point out by keeping the minimum, the value of K is an event value of K is an event scientist, so this solution depends scientist, so this solution depends on on what you are keeping and whether you are keeping it completely straight, what you are keeping and whether you are keeping it completely straight, whatever is the minimum to take pride, you will whatever is the minimum to take pride, you will get it on one. get it on one. get it on one. 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, You have to be reminded on the day of the range, You have to be reminded on the day of the range, You have to be reminded on the day of the range, subscribe this, this quarter inch, this condition subscribe this, this quarter inch, this condition and minimum balance should be bigger and the win should become smaller than the element, it is okay than the element, it is okay that this is the work of fitting the element on the range, that this is the work of fitting the element on the range, it should be done by the use of trees and it should be done by the use of trees and What the data structure basically What the data structure basically does is now he has some elements so this does is now he has some elements so this time if I had given him add pipe 738 all the time if I had given him add pipe 738 all the elements if I ask him elements if I ask him man give me just the highest value from the pipe man give me just the highest value from the pipe that is just values ​​bigger than five his that is just values ​​bigger than five his that is just values ​​bigger than five his 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 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, You will be working for the guy, You will be working for the guy, You will be working for the guy, Swami. For the value, assume that you Swami. For the value, assume that you got the minimum of this range. got the minimum of this range. This is the minimum value from the pilot. This is the minimum value from the pilot. If five, If five, when would this be such a big value and that is the when would this be such a big value and that is the current value train. 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, Ko Ko Ko Minimum Devi is small closed, now what will you do Minimum Devi is small closed, now what will you do if you get it free from your side, if you get it free from your side, if it is small then the minimum set up will be smaller and 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 no requirement to check with Pisces, after this if and Reddy post 210 or Reddy post 210 or any negative value, whatever is any negative value, whatever is smaller than this one, here you have to 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. no requirement to check with a small earth element now, you have to check off first. Properties of T and then ignore this model. Properties of T and then ignore this model. Okay, if Okay, if I ignore this model, then it is possible I ignore this model, then it is possible that if I make this person a husband, then it is that if I make this person a husband, then it is possible that after this you will get a value of mine possible that after this you will get a value of mine and it is not smaller than three. and it is not smaller than three. and it is not smaller than three. 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, if there are some more valley sleepers here and if there are some more valley sleepers here and if there are some more valley sleepers here and 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 it Is it Is it correct or do you have cancer, what did you do, correct or do you have cancer, what did you do, skipped the minimum and only skipped the minimum and only Greater Valley, all the ones on increasing order, Greater Valley, all the ones on increasing order, checked it, steel, if this guy himself 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, okay, it has become bigger, what now? okay, it has become bigger, what now? okay, it has become bigger, what now? 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 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, Also chat Also chat Also chat its village to check here ok its village to check here ok this could have been a solution this could have been a solution what could be another solution 100 what could be another solution 100 to solve this problem keep your j&k hydration at the station but see here what will happen with it see here what will happen with it see here what will happen with it 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 At that At that At that time, time, if the minimum of this range is five, it will be if the minimum of this range is five, it will be from here to from here to this range, the minimum pipe will be this, this will this range, the minimum pipe will be this, this will also be small and three two will be something like this, also be small and three two will be something like this, right, this one is closed, this is still this guy, right, this one is closed, this is still this guy, this is still this is still this is still 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 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 How do we implement this, How do we implement this, How do we implement this, then it should be found basically in three ways, then it should be found basically in three ways, as I had seen earlier, the first is that as I had seen earlier, the first is that you should tell the minimum, okay, we know how to you should tell the minimum, okay, we know how to calculate the prefix minimum and make the calculate the prefix minimum and make the call. The second thing we did was call. The second thing we did was that the alteration that should be done is that the alteration that should be done is that the alteration that should be done is last thing that should be done on this website was just to check Yo 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 Extra Extra 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 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 whole inch will be reduced from here, it is going to be of this category, fiber sheet is the category, fiber sheet is the comparison, this time also there are five minimums. comparison, this time also there are five minimums. comparison, this time also there are five minimums. 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 should have come here and this should be here then go start from here, it is tight but for chatting on minimum minimum greater element, we are required to work from here Let's see, Let's see, Let's see, now it has turned around, there now it has turned around, there is no one in the surgical strike, so is no one in the surgical strike, so now it will not happen at any time, now 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 that it will come here, this time it is Jatin, he is this So far the minimum is send three tracks, there is a So far the minimum is send three tracks, there is a sequence in it, the stomach is exactly sequence in it, the stomach is exactly number two, so check with this guy here that if it is number two, so check with this guy here that if it is greater than the minimum so far, greater than the minimum so far, then it is not greater, if it is smile, it then it is not greater, if it is smile, it is water, so I don't want it. is water, so I don't want it. is water, so I don't want it. 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 Now this guy from Nine Now this guy from Nine Now this guy from Nine who is there has handled himself with the minimum, seeing that who is there has handled himself with the minimum, seeing that this guy is Ismail, this guy is Ismail, so there is no requirement for him, so there is no requirement for him, I also know what he did and added it I also know what he did and added it and removed it with strike. Again now and removed it with strike. Again now in this tag. in this tag. in this tag. 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, She was She was She was subscribing to this channel but subscribing to this channel but not doing anything. Okay, so what will she not doing anything. Okay, so what will she do from here? Before leaving, do from here? Before leaving, put yourself on this track. What is put yourself on this track. What is behind her? Now, how will she do? This is so The minimum is five so he The minimum is five so he The minimum is five so he needs a valley bigger than five, he is so stupid and even more 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 ballooning, he is small, the force is required from the Greater Valley school, this school, this raid will forgive him and throw him out from here, the raid will forgive him and throw him out from here, the next value for the Greater Valley is not what it was. next value for the Greater Valley is not what it was. This was a This was a requirement for me to check with this, is it the same in the track or did I 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 add it, has it increased from there, he saw, yes friend, he is bigger than you, saw, yes friend, he is bigger than you, okay, are you okay, are you smaller than me? 90 is also smaller, so we have 132 patterns here. smaller than me? 90 is also smaller, so we have 132 patterns here. Got the induction that is the minimum Got the induction that is the minimum index in here has a here show this current index in here has a here show this current list and that's my steps Got list and that's my steps Got these three loops which meh that is a valid 132 these three loops which meh that is a valid 132 pattern sect so make it an incident pattern sect so make it an incident if I in terms of algorithm if I in terms of algorithm if I in terms of algorithm 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, 120 This philosophy should be there, what do we do, all the elements which are smaller than my minimum, commit all the elements which are smaller than my minimum, commit sin, so long as the sin, so long as the tractor behind is small, it is tractor behind is small, it is tractor behind is small, it is 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 So 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 If it is such a If it is such a If it is such a small gift, we do small gift, we do not have to put aside our work. If it is not weak, then before going to 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 put the current element in the add track. Turn off the numbers. Okay, basically three pegs. numbers. Okay, basically three pegs. numbers. Okay, basically three pegs. done and this minimum one has to be created. Jhal hua hai kuch na jhal, 9th, first account element will be received, here 9th, first account element will be received, here I have taken one and then you are asking them to receive it, Jhal Got the element understood, now I have to Got the element understood, now I have to Got the element understood, now I have to create a minimum, it will have prefix neem create a minimum, it will have prefix neem store, then main and the size will also be N on it, store, then main and the size will also be N on it, this 90 phone number will become a shop gang and will jhal jhal hua tha, hua tha, jhal Now a pack that Ajay's hydration egg will start from minus one that this is basically three mustards here, 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 So far, the minimum is the So far, the minimum is the So far, the minimum is the minimum, like minimum, like remove that element from here, remove that element from here, Lakshmi has been removed Lakshmi has been removed that now if practice remains an element that now if practice remains an element and that element is increased by redaction, then the and that element is increased by redaction, then the tax element is small, less ban tax element is small, less ban phone numbers are off, phone numbers are off, this is mine. this is mine. that you will get the pension, others will start that you will get the pension, others will start and stop their work, and stop their work, if the answer is not found then the current elements if the answer is not found then the current elements pack will go away, okay then your algorithm. okay then your algorithm. okay then your algorithm. run the compilation of Jhal. Every line number is 21 compilation of Jhal. Every line number is 21 9th not found symbol Okay, it is ready. Take it absolutely, my dear friend. If you have learned something from this video Don't forget Don't forget Don't forget and if you have some other solution then and if you have some other solution then do tell it in comment. Thanks for do tell it in comment. Thanks for watching, see you Ajay in the next video.
2024-03-22 14:45:41
456
https://i.ytimg.com/vi/z…axresdefault.jpg
132 Pattern | Leetcode 456
nPvjcQBplH4
this question asks you to implement a queue using stacks so let's make sure we queue using stacks so let's make sure we understand the fundamentals before we understand the fundamentals before we start solving this start solving this a stack a stack follows the lethal structure which is follows the lethal structure which is last in first out so if i have a stack last in first out so if i have a stack it will look something like this it will look something like this and if i'm going to add values let's say and if i'm going to add values let's say i'm going to add a i'm going to add a b b and then c and then if i want to pop and then c and then if i want to pop values i'll be popping them c b a values i'll be popping them c b a because it's last in because it's last in last in first out last in first out this is for a stack this is for a stack but if i'm implementing a q but if i'm implementing a q if i add a if i add a b b c c then if i'm going to pop the values or then if i'm going to pop the values or if i'm going to remove values then i if i'm going to remove values then i will be removing a first will be removing a first then i'm going to be removing b first then i'm going to be removing b first and then i'm going to finally be and then i'm going to finally be removing c first while in a stack it removing c first while in a stack it will be the opposite this will go first will be the opposite this will go first this will go second and this this will go second and this will go third will go third so the question gives us the option of so the question gives us the option of implementing a queue using only two implementing a queue using only two stacks stacks so we can take the hint that by using 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 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 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 add it to my second stack add it to my second stack so it goes so it goes this way so now i have a here then i this way so now i have a here then i would add b would add b and then i would add a back and then i would add a back so if i would to call the pop function so if i would to call the pop function now a will be popped now a will be popped since it follows the logic of a stack since it follows the logic of a stack so in a queue the first value that's so in a queue the first value that's been added in should be the first value been added in should be the first value out and since the stack can only add or out and since the stack can only add or remove values from the end i will use remove values from the end i will use the second stack to pop out all the the second stack to pop out all the current values in s1 and then append the current values in s1 and then append the newest value then add back all the newest value then add back all the values from s2 to s1 values from s2 to s1 perhaps this will be clear as i write perhaps this will be clear as i write the code so if i'm pushing here it will the code so if i'm pushing here it will orbit arbitrary mean i'm going to append orbit arbitrary mean i'm going to append s1 s1 i'm going to append x to s1 i'm going to append x to s1 but if 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 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
2024-03-22 11:16:58
232
https://i.ytimg.com/vi/n…H4/sddefault.jpg
Leetcode 232. Implement Queue using Stacks - Python
eoyO8hOkPNs
[Music] [Music] Okay, some variations have been Okay, some variations have been asked in Google like Path Sam asked in Google like Path Sam Tu whatever is okay, this has been asked to the company Tu whatever is okay, this has been asked to the company till now till now 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, 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 returned. It returned. It should be live from the root to the leaf, but it is okay. should be live from the root to the leaf, but it is okay. I want everything, okay, so here there are I want everything, okay, so here there are many things from routes to live, okay, 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 20 + 20 + 20 + 22 is equal to the correct targets. The 22 is equal to the correct targets. The second one 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, It comes from this that you It comes from this that you It comes from this that you can only travel from route to leave, neither do 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, so that we can keep track of our SAM, what is our SAM, right now what is our SAM, right now like here like here like here value was zero in the beginning, now I am on five, I am on the route, Sam's value, please do it, I what notes are there in the route's zero plus five, are there values, that too, what notes are there in the route's zero plus five, are there values, that too, so I so I so I keep adding to it whatever notes I have keep adding to it whatever notes I have got, I have also got five, got, I have also got five, okay and now my Sam is five, so let okay and now my Sam is five, so let me go to the left side me go to the left side of five because I have written in this order. of five because I have written in this order. Okay, I came on four, so four Okay, I came on four, so four is not my leaf product, so what happened to me here, it is 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 give a team to four, now I have give a team to four, now I have covered fever four in myself. covered fever four in myself. Now let me move ahead, I have got 11 so let's Now let me move ahead, I have got 11 so let's add 11 here first okay and Sam 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 Let's go Let's go 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? 54112 is 54112 is 54112 is correct, that is my answer too, so let's correct, that is my answer too, so let's add it. add it. 54112 is right, we will go 54112 is right, we will go reverse from here, so reverse from here, so we will remove it, so you are from here, okay and back to 13 + 136. 13 + 136. 13 + 136. equal to the target? It is equal to the target, so that means it will not be our answer. This path is so I will not store it, so I will so I will not store it, so I will remove it first. Back track remove it first. Back track is going back, going back from recension. is going back, going back from recension. is going back, going back from recension. left hand right move has also been explored. 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, I will store 584 and 5. I will store 584 and 5. I will store 584 and 5. Okay, so this is mine, I have stored it in the answer. Okay, so this is mine, I have stored it in the answer. Okay, now we will back track from here 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, because there is nothing further in the five leaf note. We do not have anything else. So, when we do the black track, then when we do the black track, then Will go Will go Will go from the team and if we track back then go back like this 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 Left side of the four Finished go to the right side of the hole Go to the right Got the Got the van here Ok so added the van here van here Ok so added the van here Sam in the temp What happened to my 18 What and van Sam in the temp What happened to my 18 What and van Sam in the temp What happened to my 18 What and van 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. 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 Ok Ok Ok and we will keep adding to the tempo, if it 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 do this then let's see the question once. Ok, then let's see the question once. Ok, what is there in this is that you will be given the root what is there in this is that you will be given the root of the binary and a target What I told you about the meaning of root tulip path is What I told you about the meaning of root tulip path is that it is a paisa leaf which starts that it is a paisa leaf which starts from the root and ends at the leaf note. Okay, so 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 What was said that I will What was said that I will 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. return it, the 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 OK, now it is not like that, so remember what we say So all the answers. So all the answers. 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
2024-03-21 10:46:28
113
https://i.ytimg.com/vi/e…axresdefault.jpg
Path Sum II | Bloomberg | LinkedIn | Amazon | Bloomberg | Quora | Leetcode 113
kpcWs4WUdhA
hello guys today we are moving through the question max point on a line from the question max point on a line from lead code lead code in the given problem we have given an in the given problem we have given an array consisting of end point for each array consisting of end point for each point is represented by the point is represented by the intercept on the x axis and y axis as x intercept on the x axis and y axis as x and y and y and we have to return maximum number of and we have to return maximum number of point on any particular line if we match point on any particular line if we match each of the point through every other of each of the point through every other of them them so okay so okay um let us move on the first example this um let us move on the first example this is pretty much simple there are only is pretty much simple there are only three point if we match each point with three point if we match each point with every other of them then they form a every other of them then they form a single line so required answer in this single line so required answer in this case is three case is three but in the second case if we match but in the second case if we match all the points to each other of them all the points to each other of them then there are two then there are two big cases big cases let's suppose first cases is our let's suppose first cases is our required answer which consists of four required answer which consists of four points points but in these cases and this one two and but in these cases and this one two and three total number of point is three if three total number of point is three if we form this type of line we form this type of line so required answer is maximum of d2 so required answer is maximum of d2 which is equal to 4 which is equal to 4 so our answer is 4 let us move through so our answer is 4 let us move through algorithm algorithm total number of points maybe lies from 1 total number of points maybe lies from 1 to 300 so i think n square should be to 300 so i think n square should be working fine working fine simply we can do what is we can 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 points dot size and try to iterate over to love i equal to zero to y less than and i plus plus and in each loop we an ordered map 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 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 equal to once i zero okay once i zero and this means x coordinate are same and once j j 1 equal to equal to points i 1 one okay one okay then in this case we find a duplicate then in this case we find a duplicate so we maintain another variable naming so we maintain another variable naming duplicate duplicate so duplicate plus plus so duplicate plus plus total number of duplicate total number of duplicate maybe at least maybe at least maybe not it is you that it is at least maybe not it is you that it is at least one one and duplicate equal to one and duplicate equal to one in each step if we find the required in each step if we find the required condition then condition then increment our duplicate by one else we increment our duplicate by one else we do what do what let's suppose end let's suppose end x x equal to equal to difference between these two 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 so for simplification um we take gcd of these two into gcd of x comma y and we store these two in a variable and we and we divide both of them by their gcd divide both of them by their gcd x y equal to g c t and y y equal to g c x y equal to g c t and y y equal to g c d because you take our map of string types so we should do here something m1 of two string two string x okay plus this plus y y uh and we increment the count okay uh and we increment the count okay so after execution of this second for so after execution of this second for loop loop we maintain our answer let's suppose in we maintain our answer let's suppose in any case there are only duplicate any case there are only duplicate version in our array no so our map version in our array no so our map becomes empty so we can handle this becomes empty so we can handle this using answer equal to maximum of using answer equal to maximum of maximum of answer comma maximum of answer comma duplicate else we can do something for auto 18 our m1 answer equal to maximum of answer comma plus plus we can do we can add total number of we can do we can add total number of duplicate duplicate okay okay and finally we can return our answer and finally we can return our answer return our answer let me check uh if there any mistake present okay we have to initialize our answer by okay i 0 1 1 okay okay okay else we can do something like this m1 of plus plus yeah i think fine let's run the code fine let's run the code i don't think there should be any i don't think there should be any mistake but mistake but maybe maybe oh compilation error oh compilation error we have 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
2024-03-21 13:03:48
149
https://i.ytimg.com/vi_w…xresdefault.webp
Max Points on a Line | Leetcode #149 \ Code Explorer
vSSTRKiKo5c
hey everyone welcome back to my channel before we get started don't forget to before we get started don't forget to click the Subscribe button if you want click the Subscribe button if you want more videos about coding interview so in more videos about coding interview so in this video we'll be solving the problem this video we'll be solving the problem lead called odd ever linked list so lead called odd ever linked list so let's get started so the problem is that let's get started so the problem is that they give us a singular linked list and they give us a singular linked list and they ask us to group all the odd nodes they ask us to group all the odd nodes together followed by the even nodes so together followed by the even nodes so the tricky part in this question is that the tricky part in this question is that we are not talking about the value of we are not talking about the value of the notes but we are talking about the the notes but we are talking about the node numbers for example the first note node numbers for example the first note is considered odd and the second one is is considered odd and the second one is considered even and so on and also we considered even and so on and also we must solve this problem with a constant must solve this problem with a constant space complexity of off one and a linear space complexity of off one and a linear time complexity so let's say we have time complexity so let's say we have this input singly linked list so as we this input singly linked list so as we know from the details of the question know from the details of the question the odd numbers start at the first node the odd numbers start at the first node therefore we will point a variable therefore we will point a variable called odd at the head of the linked called odd at the head of the linked list which is the first note also as we list which is the first note also as we know that the second node are even node know that the second node are even node will Point another variable called even will Point another variable called even to the next node after the first one to the next node after the first one furthermore since we know that the furthermore since we know that the second node will be the start of the second node will be the start of the even linked list we'll set another even linked list we'll set another variable called even list that also variable called even list that also point to the second node in the linked point to the second node in the linked list and which will be the head of the list and which will be the head of the evil linked lists at the end of the loop evil linked lists at the end of the loop so the principle of this algorithm is to so the principle of this algorithm is to be able to rearrange the linked list by be able to rearrange the linked list by grouping the old nodes in the first half grouping the old nodes in the first half of the linked list and the even nodes in of the linked list and the even nodes in the second half of the linked list after the second half of the linked list after that we're gonna Loop over the linked that we're gonna Loop over the linked list by using the even pointer so at the list by using the even pointer so at the first iteration we're gonna set the next first iteration we're gonna set the next pointer of the odd node to be pointed at pointer of the odd node to be pointed at the node after the even node which is in the node after the even node which is in this example is the node with the value this example is the node with the value tree after that we will move the old tree after that we will move the old variable or pointer to point at the next variable or pointer to point at the next old node which have the value tree then old node which have the value tree then we will set the even next pointer to be we will set the even next pointer to be pointing at the next node after the new pointing at the next node after the new old node which have the value 5 and then old node which have the value 5 and then we move the even pointer to point at the we move the even pointer to point at the even next node which have the value of even next node which have the value of 5. so at the next iteration will repeat 5. so at the next iteration will repeat the same process by pointing the next the same process by pointing the next pointer of the current odd node to be pointer of the current odd node to be the next node after the even node which the next node after the even node which have the value 6 and then we're gonna have the value 6 and then we're gonna move the odd pointer to the next node move the odd pointer to the next node after that we set the next pointer or after that we set the next pointer or the even pointer to point at the next the even pointer to point at the next note after the odd node which have the note after the odd node which have the value 4 and next we move the even value 4 and next we move the even pointer to be pointing at the next node pointer to be pointing at the next node with the value of 4. so at the last with the value of 4. so at the last iteration we will move the next pointer iteration we will move the next pointer of the current or to be pointed at the of the current or to be pointed at the next note after the even node which have next note after the even node which have the value 7 and we move the odd pointer the value 7 and we move the odd pointer to be pointing at the node with the to be pointing at the node with the value 7. so after that we will set the value 7. so after that we will set the even North will be pointing at the node even North will be pointing at the node after the current odd node which is the after the current odd node which is the currently the end of the linked list so currently the end of the linked list so once we are at the end of the linked once we are at the end of the linked list and the even pointer is pointing to list and the even pointer is pointing to null we will break the loop and move to null we will break the loop and move to rearranging or group in the two linked rearranging or group in the two linked list so we're gonna set the next pointer list so we're gonna set the next pointer of the odd note to be pointing at the of the odd note to be pointing at the even list node which is the head of the even list node which is the head of the evil linked list and that's how we're evil linked list and that's how we're gonna group them in one linked list that gonna group them in one linked list that have the half of old nodes and half of have the half of old nodes and half of even notes so the time complexity for even notes so the time complexity for this solution is often since we are this solution is often since we are looping over the the linked list once looping over the the linked list once and the space complexities of one sense and the space complexities of one sense who are not allocating additional memory who are not allocating additional memory that's it guys so let's jump out code that's it guys so let's jump out code into solution so first we start by into solution so first we start by checking if the linked list is empty checking if the linked list is empty which are none or we return the empty which are none or we return the empty linked list then we initialize the two linked list then we initialize the two pointers the first variable will be the pointers the first variable will be the odd variable and its value will be set odd variable and its value will be set to the head of the linked list then we to the head of the linked list then we set the second variable event to be set the second variable event to be pointing at the second node which is the pointing at the second node which is the node after the odd node after that we node after the odd node after that we initialize the even list which will be initialize the even list which will be the head of the evil linked list at the the head of the evil linked list at the end of the loop and set his value to be end of the loop and set his value to be the even note then we will Loop over the the even note then we will Loop over the input linked list using the even node input linked list using the even node sole even and even dot next is not null sole even and even dot next is not null we move the next puncher of the null of we move the next puncher of the null of the old node to be pointing at the next the old node to be pointing at the next node after the even note and after that node after the even note and after that we move the odd pointer to point at the we move the odd pointer to point at the next odd note then we move the next next odd note then we move the next pointer of the even note to be punching pointer of the even note to be punching at the node after the current odd node at the node after the current odd node and the same thing that we did before and the same thing that we did before for keep tracking of the odd node we for keep tracking of the odd node we move the even node to the next node so move the even node to the next node so once they even not reach the end of the once they even not reach the end of the linked list we will group the two linked linked list we will group the two linked list by pointing the odd next pointer to list by pointing the odd next pointer to the even less node which represent the the even less node which represent the head of the even half of notes finally head of the even half of notes finally we return the head of the linked list we return the head of the linked list that's it guys thanks for watching see that's it guys thanks for watching see you in the next video
2024-03-24 10:34:50
328
https://i.ytimg.com/vi_w…xresdefault.webp
Odd Even Linked List - LeetCode 328 - Coding Interview Questions
lXMy03Mj21M
hello everyone so let us solve one more problem from lead code the problem name problem from lead code the problem name is plus one is plus one so the problem goes like this that so the problem goes like this that you're given a large integer represented you're given a large integer represented as an integer array digits where each as an integer array digits where each digit i is the eighth digit to the digit i is the eighth digit to the integer now the digits i ordered from integer now the digits i ordered from the most significant or least the most significant or least significant from the left to the right significant from the left to the right order we will understand more when we go order we will understand more when we go down to the inputs down to the inputs and the large integer does not contain and the large integer does not contain any leading zeros any leading zeros increment the number integer by one and increment the number integer by one and return the resulting array of digits so return the resulting array of digits so let us take the same example go to the let us take the same example go to the inputs as you can see that you are given inputs as you can see that you are given a number actually in a form of an array a number actually in a form of an array that is one 123 as you can see so 123 is that is one 123 as you can see so 123 is a number you're given as an array and a number you're given as an array and you have to add 1 to it you have to add 1 to it so the answer is 124 so the answer is 124 so you might be thinking that what is so you might be thinking that what is the actual problem like this is very the actual problem like this is very simple just adding one to it but hold on simple just adding one to it but hold on this is not a complete number i suppose this is not a complete number i suppose you got the thing you got the thing this is not a complete number this is this is not a complete number this is the number represented in the array form the number represented in the array form that is 123. so you have to print out that is 123. so you have to print out the answer such that you have to print the answer such that you have to print out the thinking that it is an actual out the thinking that it is an actual complete number and just adding one to complete number and just adding one to it what i mean by this is that's let's it what i mean by this is that's let's say that for this say that for this 123 the answer will become 124. 123 the answer will become 124. for for 4321 if you just add 1 to it it will 4321 if you just add 1 to it it will become 422 become 422 nothing more complicated but if you just nothing more complicated but if you just take let's say 99 if you add one to it take let's say 99 if you add one to it one number will be carry on and it will one number will be carry on and it will go out of bound and then you have to go out of bound and then you have to append it in the start like all together append it in the start like all together all new as you can see that it is nine all new as you can see that it is nine so one is added it will become one zero so one is added it will become one zero so a new array will be formed so that so a new array will be formed so that one is a patent trend so this is the one is a patent trend so this is the whole thing whole thing i will show you the actual uh what you i will show you the actual uh what you can do here is that you are given some can do here is that you are given some as you can see that is let's say 120 one as you can see that is let's say 120 one two three nine two three nine what you can do is that if you just add what you can do is that if you just add one to it what you just have to keep in one to it what you just have to keep in mind is what is the carry to the next mind is what is the carry to the next number so you can just assume that how number so you can just assume that how you actually add numbers that is the you actually add numbers that is the whole thing whole thing if you just take 123 if you just take 123 if you add one to it what you'll do or if you add one to it what you'll do or let's say that if you have 129 if you let's say that if you have 129 if you just add one to it what you'll do you just add one to it what you'll do you just add both of them it will become one just add both of them it will become one carry is there so you have to keep in carry is there so you have to keep in track what is the carry number track what is the carry number and then it will become three and this and then it will become three and this will become one so this is one twenty will become one so this is one twenty one thirty so if you just add one to it one thirty so if you just add one to it then it will become zero and you have to then it will become zero and you have to carry one thing so you can just take carry one thing so you can just take some number that is scary some number that is scary okay and then what you can do is let's okay and then what you can do is let's say the number is one two nine nine say the number is one two nine nine if you add one to it if you add one to it what will happen is that the carry is what will happen is that the carry is zero then you add one to it it will zero then you add one to it it will become become so what you will do the number will so what you will do the number will become ten become ten now what is the number that will be put now what is the number that will be put it here it is 10 mod 10 it here it is 10 mod 10 as you can see it becomes 0 so 0 is put as you can see it becomes 0 so 0 is put it here and 10 divided by 10 is the it here and 10 divided by 10 is the number that is taken to the carry that number that is taken to the carry that is equal to 1 is equal to 1 so one is added to the carry number so so one is added to the carry number so as you can see that is the same thing if as you can see that is the same thing if you have 10 you have 10 one is taken as the carry one means that one is taken as the carry one means that 10 divided by 10 10 divided by 10 that is equal to 1 that is equal to 1 and what is in the remainder 10 mod 10 and what is in the remainder 10 mod 10 is in the remainder that is you is in the remainder that is you so if you take this this is the carry so if you take this this is the carry now the next number then the next digit now the next number then the next digit actually is the digit so the number that actually is the digit so the number that will be placed here for this digit is will be placed here for this digit is actually your digit plus the carry actually your digit plus the carry okay so 9 plus the case so 9 plus the okay so 9 plus the case so 9 plus the carry that is equal to 10 again so the carry that is equal to 10 again so the number here will be zero and the number number here will be zero and the number passed on is one again the number plus passed on is one again the number plus carry so two plus one so it will become carry so two plus one so it will become three three so you will do the same thing for every so you will do the same thing for every digit actually digit actually what is here so you will place here the what is here so you will place here the modulus value and carry the dividing modulus value and carry the dividing value so 10 value so 10 mod like three mod 10 b will become mod like three mod 10 b will become three only so this is why three is there three only so this is why three is there and the carry is three divide button and the carry is three divide button that is zero which means that there is that is zero which means that there is nothing to be carried upon nothing to be carried upon and then as you can see that this is one and then as you can see that this is one plus zero as a carry it is only one plus zero as a carry it is only one the only only thing that will become the only only thing that will become complicated is if there are multiple complicated is if there are multiple lines only so if you just add one thing lines only so if you just add one thing it will become zero 0 and then a 1 will it will become zero 0 and then a 1 will be added as an extra appended one so be added as an extra appended one so because the array size fixed you can because the array size fixed you can either make a new complete array and either make a new complete array and just put one at the end and all the just put one at the end and all the zeros or as the other thing is that zeros or as the other thing is that what you can do here is that if you have what you can do here is that if you have a vector you can see that if you have a vector you can see that if you have vector of size let's say three vector of size let's say three you can only append a box in the vector you can only append a box in the vector at the end a block at the end not in the at the end a block at the end not in the start so what you can do is that if you start so what you can do is that if you have let's say if you want to let's say have let's say if you want to let's say make a number that is one zero zero make a number that is one zero zero and you have only three digits you can and you have only three digits you can first append a block at the end and then first append a block at the end and then like you can do that shift all the like you can do that shift all the numbers by numbers by one position or actually just fill all one position or actually just fill all of them by zero and then put the one of them by zero and then put the one number you can also do that whatever number you can also do that whatever whatever you like you can just push all whatever you like you can just push all the numbers to the left because you the numbers to the left because you actually want one in the start that is actually want one in the start that is the whole thing nothing more complicated the whole thing nothing more complicated i'll take you down to the code part it 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 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 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 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
2024-03-20 11:08:26
66
https://i.ytimg.com/vi_w…xresdefault.webp
66. Plus One | LEETCODE EASY | CODE EXPLAINER
cTBiBSnjO3c
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve a problem let's solve a problem daily temperatures we are just given an daily temperatures we are just given an array of array of integers which represent temperatures integers which represent temperatures and we want to return an array and we want to return an array answer such that at every single answer such that at every single position in answer it's going to be the position in answer it's going to be the same exact size as same exact size as our temperatures array and at every our temperatures array and at every single position in answer we want to single position in answer we want to know know for the eighth day whatever the for the eighth day whatever the temperature was on the i temperature was on the i day we want to find how many days did it day we want to find how many days did it take for us take for us to find a temperature that was greater to find a temperature that was greater than the temperature on the eighth day than the temperature on the eighth day so for example let's take a look at this so for example let's take a look at this uh uh temperatures array we can see there's temperatures array we can see there's eight values in the temperatures array eight values in the temperatures array and there's eight values in the output and there's eight values in the output for for each value in the temperatures array for each value in the temperatures array for example 73 example 73 how many days did it take us in this how many days did it take us in this array to array to to the right of of 73 how many days did to the right of of 73 how many days did it take us to find a new it take us to find a new temperature that was greater than 73 temperature that was greater than 73 well on the well on the on the exact next day we found 74 which on the exact next day we found 74 which is greater than 73 is greater than 73 so it took us one day so in the first so it took us one day so in the first position we're going to return a 1. position we're going to return a 1. what about 74 how many days did it take what about 74 how many days did it take us to find a new temperature that was us to find a new temperature that was greater than it greater than it 75 one day later right okay for 75 75 one day later right okay for 75 how many days did it take us 71 is not how many days did it take us 71 is not greater greater 69 is not greater 72 is not greater but 69 is not greater 72 is not greater but 76 76 is greater and you can see that took is greater and you can see that took about four about four days right so then we return a four in days right so then we return a four in that position now there are some that position now there are some temperatures temperatures that never had a temperature greater that never had a temperature greater than them look at these than them look at these last two temperatures we had a 76 last two temperatures we had a 76 nothing to the right of 76 is greater nothing to the right of 76 is greater than it and of course the last position than it and of course the last position 73 73 there's no temperatures to the right of there's no temperatures to the right of it in the first place so nothing it in the first place so nothing was greater than 73 to the right so for was greater than 73 to the right so for these ones we're gonna return a default these ones we're gonna return a default value of zero value of zero so we're gonna build an output array now so we're gonna build an output array now looking at the looking at the the input what's the brute force way to the input what's the brute force way to do it of course we could do an do it of course we could do an n squared approach right like for every n squared approach right like for every temperature we would look through the temperature we would look through the entire temperature array entire temperature array after it right and see okay how many after it right and see okay how many days did it take us to find a days did it take us to find a temperature that was greater than this temperature that was greater than this one right and then one right and then do the same thing for the next do the same thing for the next temperature over here look through the temperature over here look through the entire or i see entire or i see you know what's the first day that we you know what's the first day that we could find a greater temperature and could find a greater temperature and keep doing that now that's going to be keep doing that now that's going to be big o big o of n squared time complexity but there of n squared time complexity but there actually is an actually is an easier way to do this problem if we use easier way to do this problem if we use some extra memory some extra memory now let's just iterate through the input now let's just iterate through the input array once array once going to the right but we do need to going to the right but we do need to know that for example know that for example we have to remember the previous we have to remember the previous temperatures temperatures that we looked at so if we you know that we looked at so if we you know let's say the previous temperature here let's say the previous temperature here was a 73 like in the input example and was a 73 like in the input example and then the next temperature then the next temperature was a 74 when we get to this position we was a 74 when we get to this position we have to somehow remember have to somehow remember what was the temperature that came what was the temperature that came before it right now obviously we could before it right now obviously we could use a list for that or in this case a use a list for that or in this case a stack would be more intuitive stack would be more intuitive because one thing we're going to notice because one thing we're going to notice is if we get a temperature is if we get a temperature greater than at 74 right then we're greater than at 74 right then we're going to say okay what was our previous going to say okay what was our previous temperature 73 so this temperature is temperature 73 so this temperature is greater than it right greater than it right so we can we can keep track of what so we can we can keep track of what index this index this occurred at and what index we're at occurred at and what index we're at right now and say okay the difference right now and say okay the difference between these indexes between these indexes was one right we clearly found a was one right we clearly found a temperature the first temperature temperature the first temperature greater than the 73 so then what are we greater than the 73 so then what are we going to do from our stack well then we going to do from our stack well then we don't have to remember this anymore don't have to remember this anymore right we're going to say okay we're right we're going to say okay we're going to put a 1 in the output and we going to put a 1 in the output and we can pop this can pop this from our stack right so we're going to from our stack right so we're going to do stack.pop do stack.pop so this will be popped from the stack so this will be popped from the stack now when we get to a 75 the exact same now when we get to a 75 the exact same thing is going to happen right clearly thing is going to happen right clearly we see these temperatures are in we see these temperatures are in increasing order so we see okay one day increasing order so we see okay one day it took us it took us to get r to get a temperature greater to get r to get a temperature greater than this we'll put a one in the output than this we'll put a one in the output pop this from the stack and pop this from the stack and if we just had increasing temperatures if we just had increasing temperatures that would be really easy for us right that would be really easy for us right but it's not always going to happen but it's not always going to happen where we have increasing temperatures where we have increasing temperatures what happens what happens if we had a 72 that came after it if we had a 72 that came after it well we would we would look at the 72 well we would we would look at the 72 and compare it to the top of the stack and compare it to the top of the stack say okay this is not say okay this is not greater so we can't pop from the stack greater so we can't pop from the stack but we're also going to take this value but we're also going to take this value and add it to the sec so now we're going and add it to the sec so now we're going to have two values to have two values inside of our stack and what happens if inside of our stack and what happens if we got another we got another smaller value 71 right so far for none smaller value 71 right so far for none of these values of these values do they have a temperature to the right do they have a temperature to the right of them that's greater right of them that's greater right so all three of these are going to be on so all three of these are going to be on the stack what are we noticing about our the stack what are we noticing about our stack stack it's going to be in monotonic it's going to be in monotonic decreasing order right decreasing order right this is a type of stack problem that i this is a type of stack problem that i have solved on this channel a couple have solved on this channel a couple times but this is more of a beginner times but this is more of a beginner friendly monotonic friendly monotonic decreasing stack problem what this means decreasing stack problem what this means is that our stack is going to be in is that our stack is going to be in decreasing order that's what monotonic decreasing order that's what monotonic means it's always in decreasing order means it's always in decreasing order now technically now technically what if what happens if we got another what if what happens if we got another 71 over here right 71 over here right well in that case 71 is not greater than well in that case 71 is not greater than this so this so all four of these would be on our stack all four of these would be on our stack currently right so it's technically not currently right so it's technically not monotonic monotonic decreasing order it could be equal as decreasing order it could be equal as well right we're noticing it's not well right we're noticing it's not strictly decreasing if two values are strictly decreasing if two values are equal they're also going to go on the equal they're also going to go on the stack stack but if we got a greater value if i got but if we got a greater value if i got to a 72 right to a 72 right what am i gonna do clearly 72 is greater what am i gonna do clearly 72 is greater than the top of our stack so i pop than the top of our stack so i pop this one right but now we have a new this one right but now we have a new value on the top of our stack value on the top of our stack this one is is our 72 greater than this this one is is our 72 greater than this it's not it's not so so our stack is like this now we so so our stack is like this now we looked on our stack we took looked on our stack we took this guy out this is no longer in our this guy out this is no longer in our stack but these three values are in our stack but these three values are in our stack and still stack and still notice how the the stack is still in notice how the the stack is still in monotonic decreasing order it's always monotonic decreasing order it's always going to be the case going to be the case what happens if instead of a 72 i had a what happens if instead of a 72 i had a 73 then of course we'd still pop this 71 73 then of course we'd still pop this 71 and then we'd we'd also want to pop the and then we'd we'd also want to pop the 72 because now 73 72 because now 73 is greater than 72 we pop this but it's is greater than 72 we pop this but it's not the case not the case for this one but if you know we change for this one but if you know we change this value to a 74 this value to a 74 excuse my bad handwriting over here but excuse my bad handwriting over here but if we change this to a 74 if we change this to a 74 then yes we are going to pop this one as then yes we are going to pop this one as well so no matter what we do well so no matter what we do our stack is always going to be in our stack is always going to be in monotonic decreasing order if i monotonic decreasing order if i add a 70 over here it's we're not going add a 70 over here it's we're not going to pop anything to pop anything it's still in decreasing order so let's it's still in decreasing order so let's just run through a quick simulation let just run through a quick simulation let me show you how we can get this output me show you how we can get this output in linear time in linear time using a stack so first value 73 using a stack so first value 73 we're going to compare it to the top of we're going to compare it to the top of our stack our stack is empty so we're our stack our stack is empty so we're not going to do anything we're just not going to do anything we're just going to take the 73 add it to the stack going to take the 73 add it to the stack next we're at 74 we're going to compare next we're at 74 we're going to compare it to the top of the stack it to the top of the stack 74 is greater than 73 right what index 74 is greater than 73 right what index did 73 did 73 occur at at index 0 what index does 74 occur at at index 0 what index does 74 occur occur at index one so we take the difference at index one so we take the difference one minus zero so one minus zero so it took us one position to find a value it took us one position to find a value greater than greater than 73 so we can pop 73 from our stack and 73 so we can pop 73 from our stack and then 74 then 74 is going to be on the top of our stack is going to be on the top of our stack now now exact same thing is going to now now exact same thing is going to happen with 75 right happen with 75 right 75 is greater than this the difference 75 is greater than this the difference between the indexes between the indexes is one so we add a one to the output 474 is one so we add a one to the output 474 and we pop 74 now we're at and we add 75 and we pop 74 now we're at and we add 75 to the stack to the stack next we get 71. 71 is not greater than next we get 71. 71 is not greater than the top of our stack so all we do is add the top of our stack so all we do is add it it we don't update the output in either of we don't update the output in either of those positions those positions again we get a smaller value 69 so we again we get a smaller value 69 so we add it to the stack we can't pop any of add it to the stack we can't pop any of these 69's not these 69's not greater than either of these next we get greater than either of these next we get a 72 right a 72 right 72 is greater than 69 right so we pop 69 72 is greater than 69 right so we pop 69 what was the difference between the what was the difference between the indices it was one so we're going to indices it was one so we're going to take take in the corresponding output position in the corresponding output position which is in this position for 69 we're which is in this position for 69 we're going to say okay there was an going to say okay there was an index difference of 1. now we're going index difference of 1. now we're going to look at the next top for our stack to look at the next top for our stack 71. 71. so the difference between these two is so the difference between these two is two so for 71 we're going to say it took two so for 71 we're going to say it took two days for us to find a greater two days for us to find a greater temperature than 71 so temperature than 71 so for this position we add a 2 so we pop for this position we add a 2 so we pop 71 from our stack 71 from our stack now 72 is not greater than 75 so we now 72 is not greater than 75 so we still have a hole in our output over still have a hole in our output over here we never found a greater here we never found a greater temperature than 75 yet temperature than 75 yet and similarly for 72 we have a hole and similarly for 72 we have a hole next we get 76 and compare it to the top next we get 76 and compare it to the top of our stack of our stack so 76 is greater than 72 we pop 72 the so 76 is greater than 72 we pop 72 the difference difference the number of days it took us was just the number of days it took us was just one day so we can add a one one day so we can add a one for 72 and then we look at the next top for 72 and then we look at the next top of our stack of our stack yes we finally found a temperature yes we finally found a temperature greater than 75 greater than 75 it took us one two three four days to do it took us one two three four days to do that so we can add a that so we can add a four in the output in the corresponding four in the output in the corresponding position over position over here and we can pop 75 from our stack i here and we can pop 75 from our stack i think i just need one more think i just need one more square over here because we have one square over here because we have one last temperature in our input 73 so last temperature in our input 73 so we're going to add 73 we're going to add 73 see 73 is not greater than 76 so we see 73 is not greater than 76 so we can't pop that can't pop that and now at the end we have no more and now at the end we have no more temperatures to add right we still have temperatures to add right we still have two temperatures two temperatures left in our stack and whatever the left in our stack and whatever the default value default value for the unpopped uh temperatures is just for the unpopped uh temperatures is just gonna be zero right they told us gonna be zero right they told us in the uh description of the problem in the uh description of the problem that if we can't that if we can't get a greater temperature we're just get a greater temperature we're just gonna put zero for these gonna put zero for these so that's how we build the output you so that's how we build the output you can see it exactly matches can see it exactly matches the output that they built in the the output that they built in the example and example and we did that in linear time by using this we did that in linear time by using this monotonically monotonically decreasing stack in o of end time of and decreasing stack in o of end time of and memory memory so now let's jump into the code so we so now let's jump into the code so we are going to have a result or answer are going to have a result or answer array and it's initially going to be array and it's initially going to be default values of 0 because that's kind default values of 0 because that's kind of what they tell us of what they tell us and it's going to be the exact same and it's going to be the exact same length as the input array temperatures length as the input array temperatures i'm also gonna have a stack remember i'm also gonna have a stack remember this is our extra memory it's gonna this is our extra memory it's gonna uh contain a pair of values in the in uh contain a pair of values in the in the drawing example the drawing example i only showed that we're adding the i only showed that we're adding the temperature but we're also gonna add the temperature but we're also gonna add the index of the temperature so we can index of the temperature so we can calculate the difference basically calculate the difference basically calculate the number of days it took us calculate the number of days it took us to find a greater temperature so we're to find a greater temperature so we're going to be adding two values going to be adding two values to the stack a pair of temperature and to the stack a pair of temperature and the index that that temperature occurred the index that that temperature occurred at at next we're just going to iterate through next we're just going to iterate through the uh temperatures array we're going to the uh temperatures array we're going to enumerate this meaning we're going to enumerate this meaning we're going to get the in get the in the index of it and the value at the the index of it and the value at the same time it just makes the code a same time it just makes the code a little bit cleaner little bit cleaner i is the index t is the temperature i is the index t is the temperature first thing we're going to do is first thing we're going to do is see does is our stack empty and if it is see does is our stack empty and if it is is this temperature greater than the is this temperature greater than the temperature on the top of our stack temperature on the top of our stack the top of our stack is index negative the top of our stack is index negative one in python one in python and the temperature is the first value and the temperature is the first value in that pair so index in that pair so index zero and so if this is true of course we zero and so if this is true of course we can pop from our stack right so can pop from our stack right so stack.pop stack.pop so i'm going to call it the stack so i'm going to call it the stack temperature and the stack temperature and the stack index which we just popped right and for index which we just popped right and for this this temperature we want to you know in the temperature we want to you know in the result output say okay result output say okay whatever the index of this temperature whatever the index of this temperature was stack index we want to compute the was stack index we want to compute the number of days it took us to find a number of days it took us to find a greater temperature we can do that with greater temperature we can do that with i the current temperature that we're at i the current temperature that we're at minus minus the temp the index of the the temp the index of the uh temperature that we just popped and uh temperature that we just popped and we take the difference of those that we take the difference of those that gives us the number of days it took to gives us the number of days it took to find a greater temperature and then find a greater temperature and then we're just adding it to the stack at the we're just adding it to the stack at the corresponding position we want to corresponding position we want to and then once that while loop is done it and then once that while loop is done it might execute zero times it might might execute zero times it might execute multiple times execute multiple times after it's done then we finally want to after it's done then we finally want to append to the stack append to the stack the temperature that we're currently the temperature that we're currently traversing so a pair the traversing so a pair the t the temperature value and the index of t the temperature value and the index of that temperature that temperature and once we're done with that we can go and once we're done with that we can go ahead and return our result the reason ahead and return our result the reason we don't have to fill we don't have to fill in any extra zeros if our stack is in any extra zeros if our stack is non-empty is because we already non-empty is because we already initialized initialized our result to b0 so if we never filled our result to b0 so if we never filled anything in anything in the default value is automatically gonna the default value is automatically gonna be zero be zero so you can see the solution works and is so you can see the solution works and is pretty efficient so i hope this was pretty efficient so i hope this was helpful helpful if it was please like and subscribe it if it was please like and subscribe it supports the channel a lot supports the channel a lot and i'll hopefully see you pretty soon and i'll hopefully see you pretty soon thanks for watching
2024-03-21 12:00:21
739
https://i.ytimg.com/vi/c…axresdefault.jpg
Daily Temperatures - Monotonic Stack - Leetcode 739 - Python
7Tc7HWXmwmA
hey guys today we will be solving the problem 231 power of two so in this problem 231 power of two so in this problem what is given is like given an problem what is given is like given an integer n uh return true if the power of integer n uh return true if the power of it is a power of two otherwise return it is a power of two otherwise return Force so what they are saying that n is Force so what they are saying that n is an integer we need to check if n is an an integer we need to check if n is an power of two we need to return true power of two we need to return true otherwise false so this is one first otherwise false so this is one first example in which uh one and it's true example in which uh one and it's true because to keep power zero is one and because to keep power zero is one and then 16 it's again true because 2 power then 16 it's again true because 2 power four 4 is again uh 16 and then three and four 4 is again uh 16 and then three and three is not the power of 2 okay so as three is not the power of 2 okay so as question is clear right so let's uh find question is clear right so let's uh find a solution for this so for uh solution a solution for this so for uh solution to this one solution is that to this one solution is that uh we can just put a while loop uh we can just put a while loop here while loop and what we can do is here while loop and what we can do is like we can multiply n uh with two and like we can multiply n uh with two and then check if it's equal to and return then check if it's equal to and return true otherwise uh again multiply this true otherwise uh again multiply this number with two that's 4 into number with two that's 4 into 2 uh check if it's equal to n um so you 2 uh check if it's equal to n um so you need to stop this condition would be need to stop this condition would be like uh this number would be smaller like uh this number would be smaller than and then only this a break sorry than and then only this a break sorry greater than one then it's the breaking greater than one then it's the breaking condition but um this complexity of this 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 manipulation so for bit Manu uh 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 0 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 uh Power of Two And when we do nus one uh Power of Two And when we do nus one that's 9 which is again equal to 1 0 1 that's 9 which is again equal to 1 0 1 but now you do the bit manipulation it but now you do the bit manipulation it will not equal to Z not equal to zero uh so so here uh yes so let 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 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 answer okay answer okay so uh let's try if this is this runs yeah so our test Cas is pass let's it it yeah it yeah it works thanks works thanks guys
2024-03-22 11:16:09
231
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 231 Power of Two | Bit Manipulation | Math | Amazon | Adobe | Bloomberg
0CesZFo1yOQ
That a hello hi guys so all doing fine welcome back hello hi guys so all doing fine welcome back to the video english video bp looking to the video english video bp looking and another list to problem name dance red and another list to problem name dance red chilli powder mixing stomach set given chilli powder mixing stomach set given string gas follow on this internet string gas follow on this internet substring in s u majumdar do maximum substring in s u majumdar do maximum laptop testis 100 examples where laptop testis 100 examples where laptop testis 100 examples where 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 Consider And Consider And Consider And Examples Pe Abcd Possible Parents Examples Pe Abcd Possible Parents Mixer Stand For Example Earth Ways Mixer Stand For Example Earth Ways BBC BBC Ne Andi BBC BBC Ne Andi That Vikram Also Considered Single Characters That Vikram Also Considered Single Characters Stuck Half Inch Offline The World But They Also Considered Stuck Half Inch Offline The World But They Also Considered A Single Characters Abcd In A Single Characters Abcd In To-Do List Care Pregnancy Debt The Follow To-Do List Care Pregnancy Debt The Follow Roadways Pe Is Roadways Pe Is Roadways Pe Is loot snowdrift for this problem which can loot snowdrift for this problem which can that algorithm host algorithm solve this that algorithm host algorithm solve this particular problem to human being rhythm sale particular problem to human being rhythm sale attended it took to the streets abcd attended it took to the streets abcd faux slide show that and also create another app to pwn Slow Poison Slow Poison Slow Poison P 202 A Sukhmay Algorithm Begins Follow Us On Shri Krishna Leela Declaratii Interior Variables C21 Ameer 125 Boundary and Available Son and Directors of a Strange Son and Directors of a Strange 1518 Traversal Defines the Mirror Position of 1518 Traversal Defines the Mirror Position of Character and of Life But Character and of Life But Character and of Life But happened that sult science son and sun are the first so let's points 211 pm r12 so let's points 211 pm r12 that suvichar ko redmi arrangement by using the following that suvichar ko redmi arrangement by using the following formula with his to see - 500 formula with his to see - 500 riddle of mirror f1s riddle of mirror f1s facility element s well s meter of facility element s well s meter of known father of element life in location inch a look for a known father of element life in location inch a look for a day in all its not to give the part and they also day in all its not to give the part and they also chapter brother chapter brother that wrong side and bright side of it this that wrong side and bright side of it this location article and not a location article and not a that sindh characters are not equal to that sindh characters are not equal to proceed proceed this seat is not greater school profit rather 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 - 502 - 502 - 502 Hai Anjani Pithampur Badal And Srijan And Below Hai Anjani Pithampur Badal And Srijan And Below Smart Na Vyasyon Compare The Left Side Smart Na Vyasyon Compare The Left Side Android Side Of It Location On 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 Lokp Lokp Lokp President Brother Diwali Artis Of A President Brother Diwali Artis Of A Greater Than Maximum Justice Greater Than Maximum Justice Torch Initially Updated Dali And Max Torch Initially Updated Dali And Max Planck Specified Election The Value Of Great money and then the update wcc2 and 153 increment came was the convener of a provocation off was the convener of a provocation off a suit against chakra the left side android a suit against chakra the left side android side file location on side file location on I just dish two characters are not equal I just dish two characters are not equal wipro father and increment wi- wipro father and increment wi- wipro father and increment wi- 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 Out of the boy Out of the boy Out of the boy who inches after now 12345 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 On On On that thing after this characters unequal that thing after this characters unequal profit father increment wi-fi to point profit father increment wi-fi to point x6 x6 a mirror is account x2 that a mirror is account x2 that nine inches a glimpse Android file location nine inches a glimpse Android file location sims dish two characters are equal to the sims dish two characters are equal to the father with increment wi-fi on father with increment wi-fi on that tied elements now position for that tied elements now position for that tied elements now position for 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 Election Vacancy Director Position 200 Run Equal 10th Way Can Break Of The Boil Uvaach Equal 10th Way Can Break Of The Boil Uvaach Ki Sanjay Dutt Diwali Ki Sanjay Dutt Diwali Ki Sanjay Dutt Diwali Maximum Insaf And Spyder Quality Of Hello How To Update And CR Total 6 And When Because Of The Following Hello How To Update And CR Total 6 And When Because Of The Following His Condition Which His Condition Which 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 Location On Location On This Is My Real Is Divya Kit Location 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 Presides All The Others On That Presides All The Others On That Anupam Some Simple Steps For Each Character From The Opposition All Words And Ajay Ko Ajay Ko Now Suhaag Ka Completely Drivers In Now Suhaag Ka Completely Drivers In Now Suhaag Ka Completely Drivers In Sunao Vinod Now Turn This Point On The Sunao Vinod Now Turn This Point On The Length Of The Best Friend In asp.net Subscribe Subscribe To New Delhi For That Is Back In The Drivers Are APN Check The Value Of Measurement Of Ka Svabh Ka Svabh Ka Svabh Traversing Entry Find The Same Volume Two Sides Of A Single Platform This Difficult Volume Excellent Two Sides Of A Single Platform This Difficult Volume Excellent Difficult Top Player And Get Along Difficult Top Player And Get Along Spider-Man Movie Spider-Man Movie A Mountain Points World First Tips From A Mountain Points World First Tips From Director Seem Like This Director Seem Like This That 24 Points 260 That 24 Points 260 That Alarms Paladam That Alarms Paladam That Alarms Paladam 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 Is Is 56001 Contents Order Followed By His 's Facility And Creator Vector Some Toe 's Facility And Creator Vector Some Toe Demonstrate Were Demonstrate Were A Beautiful The A Beautiful The A Beautiful The ajay ko ajay ko drink drink drink drink loot video loot video that sophia bush and characters in to the that sophia bush and characters in to the whatsapp whatsapp and now even net declare variables in and now even net declare variables in pcs cut bluetooth on is the size of the pcs cut bluetooth on is the size of the best e know this is to finish best e know this is to finish best e know this is to finish Sweat In Explanation Part V Initial Ice Cream Variables Namely CR And Excellent C21 Notes20 Loot Notification Wedding The Original Ajay A+B Positive Pushva Character To New String Loot Character hai Character hai Character hai loot hua hai Ajay ko loot lo ki end ki meeting paan inch to value of in the in final Bigg Boss Dashrath symbol to back in final Bigg Boss Dashrath symbol to back toe top hua hai hua hai hua hai ko increment value of 10th Along with Along with Along with the amazing show the amazing show create another ap go to afternoon account at every character of team half create another ap go to afternoon account at every character of team half time liquid liner of business name script time liquid liner of business name script that size is equal to same as date of that size is equal to same as date of steel and initiated with 0 steel and initiated with 0 ajay ko ajay ko loot loot ajay ko hua hai Actual Code Tweet - Actual Code Tweet - Actual Code Tweet - Algorithm Scored A 100 Relative Products Character Tubelight Character Is That A Studying Dollar And Character Which That A Studying Dollar And Character Which Is The First And Last Characters Of Is The First And Last Characters Of Nutrition Is A Website In Life From Physical To Ancestry Ajay Ajay Was Proposed Was Proposed Was Proposed How to See - Aaye Thee Ki Investor Mother Ki Is Lesson 8 App On Karo Ki Tips That Day Updated Value of Why Is Loot in Thick Loot in Thick Loot in Thick Characters Are Equal in the Condition Increment The Value of Aaye Thee Ajay Ko Ajay Ko 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 The Following Condition Holes Which The Following Condition Holes Which The Following Condition Holes Which 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 Ajay Ko 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 declares and when serial star declares and when serial star casting off alarm gas on introductory casting off alarm gas on introductory start travels and tours on start travels and tours on Ajay Ajay that at yourself Bachat water purifier is that at yourself Bachat water purifier is equal to max length hai equal to max length hai that that Ajay Ajay aur hips aur bull press leaf and take off the aur hips aur bull press leaf and take off the loop hai loop hai ek ajeeb si the meaning of the video learn from ek ajeeb si the meaning of the video learn from camera features paint and wallet for both camera features paint and wallet for both cases option flat belly of a good english cases option flat belly of a good english me hua hai on karo MP3 MP3 loot loot Loot Loot Ajay Ajay Loot Loot Ajay Loot Ajay's Shopping Dream Road Pace and Landour Leaf Shopping Dream Road Pace and Landour Leaf Is Calculator First Name The First and Is Calculator First Name The First and Last Character Idea Dollar and a Great Last Character Idea Dollar and a Great Character Days Like This The Battle of Mines Two in 3D Battu System Between to that is the full Between to that is the full Between to that is the full 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 Which available in the string last Which available in the string last Which available in the string last year library year library is bay documents habit starting is bay documents habit starting index and the length finally returned aware what is the index and the length finally returned aware what is the longest born in a a man a code space decentralization aquot picture indicator flying find with boys and warning indicator flying find with boys and warning suggestion net profit suggestion net profit suggestion net profit Ajay Ko Lut Video Helpful And Brief Understanding Of Video Helpful And Brief Understanding Of - Algorithm Like Button - Algorithm Like Button subscribe To My YouTube Channel for More subscribe To My YouTube Channel for More Upcoming Videos Thank You To
2024-03-18 11:14:26
5
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 5 | Longest Palindromic Substring | Manacher's Algorithm |Strings | C++[ Algorithm + Code]
PPrjriHwnbA
hello everyone in this lecture i am going to explain you about what break so here in this question they given 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 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 so here the given so here the given string and in this list string they string and in this list string they given what given what dictionary already they given this okay dictionary already they given this okay so here so here first we need to create variable first we need to create variable in length equal to f dot in length equal to f dot length and here length and here boolean array f equal to boolean array f equal to new boolean in this boolean i will mention length plus 1 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 i less than len plus 1 and so here in this for int j equal to zero i and j increment okay i and j increment okay so in this nested loop i will mention so in this nested loop i will mention if f of j if f of j and dot contains so here simply dot contains so here simply i will i'm mentioning here i equal to 1 i will i'm mentioning here i equal to 1 and i'm trying to traverse 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 success so here yeah success so here simple first i'm taking length s dot simple first i'm taking length s dot length length and then i just created one array and i and then i just created one array and i named it as f named it as f and here is that f of 0 is equal to true and here is that f of 0 is equal to true and here and i just mentioned nested and here and i just mentioned nested loop loop and i traverse i'll if and and and i and i traverse i'll if and and and i traverse traverse for shillman to lost element with the for shillman to lost element with the help of two loops help of two loops after that here i mentioned condition if after that here i mentioned condition if this war dictionary this war dictionary contains the substrings contains the substrings j comma i then i am returning true j comma i then i am returning true and here at loss i am returning f of and here at loss i am returning f of length length so this is the logic behind it if you so this is the logic behind it if you have any queries have any queries you can mention your doubts in you can mention your doubts in commentary session and please do like commentary session and please do like and subscribe for more videos thank you
2024-03-21 12:24:57
139
https://i.ytimg.com/vi/P…axresdefault.jpg
LeetCode-139. Word Break
jlwmWjsZ-1A
hey what's up guys uh this is sean here so today uh 1808 so today uh 1808 maximize number of nice divisors maximize number of nice divisors uh this one you know okay so give me uh this one you know okay so give me like a positive integer like a positive integer prime factors and prime factors and so basically we need to find an integer so basically we need to find an integer and that you know that satisfies the and that you know that satisfies the satisfies the following condition satisfies the following condition you know so the first one is this one so you know so the first one is this one so the number of prime factors of the number of prime factors of n are not necessarily distinct n are not necessarily distinct right it's at most this number right it's at most this number these prime factors numbers okay these prime factors numbers okay and then the second one is that you know and then the second one is that you know the number of nice divisors of n is the number of nice divisors of n is maximized maximized right so and so what is the nice divisor right so and so what is the nice divisor of of n right so a nice divisor of n is that n right so a nice divisor of n is that is the is the number that is divisible is the is the number that is divisible by by this n and also divisible by every by by this n and also divisible by every prime factor of prime factor of n so it gives you an example n so it gives you an example right so for example we have n here right so for example we have n here right so the prime right so the prime factors for n is what is 2 factors for n is what is 2 2 and three right 2 and three right so what are the nice divisor for this so so what are the nice divisor for this so basically six and twelve basically six and twelve is a nice divider because is a nice divider because so now we have how many how many so now we have how many how many distinct uh distinct uh prime factors we have here we have two prime factors we have here we have two right we have two and three right we have two and three so which means that you know a nice so which means that you know a nice divisor has to be divisible divisor has to be divisible by by this by both of both of these by by this by both of both of these numbers which means two times six two numbers which means two times six two times three equal to six times three equal to six that's why the total is what total is that's why the total is what total is six six and so the total number of nice dividers and so the total number of nice dividers six and twelve six and twelve and then which is two right so and it just asks you to find the uh basically the the 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 one of the ways to get six is this one so we can have like three two and 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 so one of the examples here is that you so one of the examples here is that you know we can use this kind of know we can use this kind of uh uh prime factors uh uh prime factors and which has like six nice divisors and which has like six nice divisors which is which is 10 20 40 50 120. 10 20 40 50 120. and the limit of the and the limit of the the number of the prime factorization the number of the prime factorization factors is five that's why we have this factors is five that's why we have this three and two three and two uh division uh split here right that's uh division uh split here right that's why we have six why we have six and then we have prime factors 8 8 means and then we have prime factors 8 8 means that 18 that 18 right and the prime factors range is right and the prime factors range is pretty big 10 to the power of 9. pretty big 10 to the power of 9. so that's the uh the description of this so that's the uh the description of this problem problem you know you know at the first glance you know you know at the first glance right so this one is a little right so this one is a little it's pretty hard to come up with a it's pretty hard to come up with a straight answer straight answer right because you know with all those right because you know with all those kind of a prime kind of a prime factors so what are the problem factors factors so what are the problem factors we should use and how can we we should use and how can we know what are the combinations of the know what are the combinations of the prime factors can give us the maximum prime factors can give us the maximum maximum maximum nice divisors maximum maximum nice divisors right so to solve this right so to solve this problem we have to make a few problem we have to make a few observations observations you know so the first one is that you you know so the first one is that you know know um we have this kind of limits of prime um we have this kind of limits of prime factors factors right let's say for example we we have right let's say for example we we have five right we have five five right we have five uh prime factors and which means that we uh prime factors and which means that we need to fill in these five need to fill in these five five uh five slots by by five five uh five slots by by five prime factors prime factors and how what are the numbers we we need and how what are the numbers we we need to fill in here to fill in here right so the answer is like this right right so the answer is like this right so we are if we fill so we are if we fill uh three same number and two others uh three same number and two others same numbers we'll have six now why why six let's say we have uh we have uh three number three x and two y's here so the answer is 6. how can we get 6 so the answer is 6. how can we get 6 right because like i said you know the right because like i said you know the nice divisor nice divisor has to be at least the multiply has to be at least the multiply of x times y right of x times y right so that's the first that's the the first so that's the first that's the the first one right one right and then for the other possible possible and then for the other possible possible divisors divisors no this is the base right we can either no this is the base right we can either times another y right so this is an times another y right so this is an another nice number or we can uh another nice number or we can uh do an another times x here that's how we do an another times x here that's how we basically that's how we get this this basically that's how we get this this kind of numbers here kind of numbers here basically two times five is the base basically two times five is the base right because that's the minimum we need right because that's the minimum we need to get for the nice divisors to get for the nice divisors and based on the based on this ten here and based on the based on this ten here we can just we can just multiply on on the remaining five or multiply on on the remaining five or twos twos that's why we have this six which means that's why we have this six which means that you know that you know in this case right we have in this case right we have three times two equals to six right and similarly right so for prime eight how how did we get 18 right so so basically for eight we have the answer is this so we have three x we have three y that this is total eight prime factors that this is total eight prime factors right and again right to be for the right and again right to be for the for the base of the nice factors we need for the base of the nice factors we need x x times y times z times y times z that as as a base right that that's why that as as a base right that that's why the answer for this one for the total the answer for this one for the total nice divisor nice divisor of this one is 3 times 3 times 2 of this one is 3 times 3 times 2 right which is which is 18 that's how we right which is which is 18 that's how we get 18 here get 18 here this is pretty obvious right because we this is pretty obvious right because we need to the nice divisor has to be need to the nice divisor has to be able to divisible by each of the number able to divisible by each of the number here right that's why you know it's here right that's why you know it's three times three times three times three times times two this is a little bit math times two this is a little bit math calculation here okay so with this being calculation here okay so with this being said said right now we know given like the uh right now we know given like the uh the some numbers we can calculate the the some numbers we can calculate the prime factors we can calculate the final prime factors we can calculate the final answer answer right now the problems right now the problems converted to given like a total converted to given like a total numbers which is eight we need to split numbers which is eight we need to split this eight this eight into several groups into several groups so that you know the product of each so that you know the product of each group's group's number is maximum right so the problem is that how can we and so the split is like this so and so the split is like this so basically basically we should always split it into into we should always split it into into three three three and then two and why is that three and then two and why is that because you know because you know if we uh try a few examples right you if we uh try a few examples right you know for four know for four let's see you know for one for one one let's see you know for one for one one to four so to four so if if the number is one then of course if if the number is one then of course it's one it's one right how about if the number is two so right how about if the number is two so what is the what is the if we have the if prime factor is two if we have the if prime factor is two what's going to be the total number here what's going to be the total number here it's two right because if it's a prime it's two right because if it's a prime factor is two and then we need factor is two and then we need two same number here right which means two same number here right which means that you know we have that you know we have two possible we will have like two nice two possible we will have like two nice divisors here divisors here once with x the other one is with x once with x the other one is with x times x times x how about three so three we have two how about three so three we have two times one sorry not not two times one so three we have 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 the total nice divisor will be 2 times 1 which is 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 for four here you know uh we can 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 how about the five right so with five how about the five right so with five what's going to be the what's going to be the the best the biggest uh total number is the best the biggest uh total number is three times three times three times two which is six right and then if we continue doing this how about six six we need to split into three times three which is 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 times 2 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 into multiple three because three times three will always give give us like better answers right that's why you know we have this kind of like pattern here and then when the when the number becomes to uh becomes to 4 or or or 3 here we should just use this formula to calculate the the remaining right so now i think we we have already have the uh the basic logic here so which means that you know for eight years you know we 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 times three because you know for this one for because you know for this one for example we have eight example we have eight we have three we can if we do uh this uh we have three we can if we do uh this uh eight uh divided by three we have two eight uh divided by three we have two which means that we have three which means that we have three we have two threes out of out of eight we have two threes out of out of eight right so which means that we're gonna right so which means that we're gonna have like a three have like a three to the power of two and then times the to the power of two and then times the remaining which is two remaining which is two right so the so the solution will be right so the so the solution will be we will try to calculate how many we will try to calculate how many basically the power of 3 basically the power of 3 by from these prime factors and then by from these prime factors and then we'll just we'll just use the prime fact you use that power use the prime fact you use that power number to calculate number to calculate the the answers and then the the answers and then there's like a special case here there's like a special case here let's see the yeah actually seven is a is a good so let's say the the prime factor is so let's say the the prime factor is seven right seven right so the seven after the dot after so the seven after the dot after subtracting subtracting three we have we have four right so we three we have we have four right so we have four here which is three here have four here which is three here and then from four basically you know if and then from four basically you know if we do another three here we do another three here we we have one left right so if we split 7 into 3 plus 3 plus 1 then the final answer is 3 times 3 times 1 which is 9 right but the best answer for 7 is what we split 7 into into 3 plus 2 plus 2 which is 3 times 2 times 2 which is 12 right so what does this one tell us tells us you know when the remaining when when the modular right when the modular uh is one right it means that you know we don't for the last for the last four here right we don't want to split uh this four into three into three one instead we want to split this four into into a two times two right basically this is the uh like the cool so and that's that and another one cool so and that's that and another one is that you know when we calculate the is that you know when we calculate the uh uh the three times three times three right the three times three times three right we we cannot simply use three to the we we cannot simply use three to the power power of this of this power here right of this of this power here right because you know this power given the because you know this power given the the constraints here you know this this the constraints here you know this this part could be huge if we simply do a part could be huge if we simply do a three time three time to the power of of this power number to the power of of this power number here it will basically here it will basically it will overflow right so which means to it will overflow right so which means to calculate this one calculate this one the power of three right we have to use the power of three right we have to use the like the the like the the dynamic programming um so first we have a power right so the um so first we have a power right so the power will be the prime 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 if it remains zero right which means so if it remains zero right which means that you know if it's nine that you know if it's nine so if it's nice means uh we should split so if it's nice means uh we should split into a three threes which is the into a three threes which is the this one right because this one will this one right because this one will give us the give us the biggest uh the biggest biggest uh the biggest product right by splitting into several product right by splitting into several numbers numbers so which means that you know assuming we so which means that you know assuming we have a dp here have a dp here uh i'm going to create like create a dp uh i'm going to create like create a dp method to help me calculate the power of method to help me calculate the power of three three right so we have the uh 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 of the power right and then the answer i'll see if right out if the remain is i'll see if right out if the remain is one which is the one which is the the special case right so for this one the special case right so for this one you know you know we we want to save the last four we we we want to save the last four we don't want to divide it don't want to divide it uh divide this four into three uh divide this four into three one right which means that it means that one right which means that it means that we want to keep this 4 to 2 and 2. we want to keep this 4 to 2 and 2. so in this case we have answer because so in this case we have answer because it's going to be a dp of it's going to be a dp of power minus 1 right because we are we're power minus 1 right because we are we're subtracting subtracting saving one of the threes right and then saving one of the threes right and then instead we're instead we're going to cut multiply by three by four going to cut multiply by three by four which is two times two which is two times two right i'll see if right i'll see if the remain is is two there could be only the remain is is two there could be only these three possibilities because we do these three possibilities because we do a module of three right a module of three right so whenever this remains two it's so whenever this remains two it's actually it's a five case right so for actually it's a five case right so for this one we simply do this right this one we simply do this right and the dp of power and then we times and the dp of power and then we times two two right that's going to be the remaining right that's going to be the remaining number here and then we have a number here and then we have a mod right it goes to 10 to the power of mod right it goes to 10 to the power of nine plus seven nine plus seven and we simply return the answer modular and we simply return the answer modular of mod right so now for this dp right so of mod right so now for this dp right so this is this is like very classic dp basically if the like very classic dp basically if the current equals to one 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 do a three times dp do a three times dp of current divided by two basically we of current divided by two basically we cut it into half cut it into half right and then we do a module of two right and then we do a module of two so every time we cut this current to so every time we cut this current to half half answer is going to be the dp answer is going to be the dp of this one basically right of this one basically right and then we also need to do a modular and then we also need to do a modular here here because if we don't do it it will also because if we don't do it it will also be going to be overflow here right be going to be overflow here right do a mod and then we'll return the the do a mod and then we'll return the the answer um yeah i believe that that's it right so if i run the code here oh i need to define it at the very oh i need to define it at the very beginning i believe um 4 0 so when the the maximum recursion depth exceeded yeah actually so four is a special case yeah actually so four is a special case right so because you know when right so because you know when when uh the the prime factors equals to when uh the the prime factors equals to four four the power equals to 1 so here you know the power equals to 1 so here you know and the remains 1 right so here will be and the remains 1 right so here will be dp 0 basically so db 0 we didn't handle dp 0 basically so db 0 we didn't handle dp 0 here dp 0 here we don't handle it that's why you know we don't handle it that's why you know it will be it will be an infinite loop here a recursive recurs an infinite loop here a recursive recurs recursive call here so uh we can recursive call here so uh we can simply do a check here basically if the simply do a check here basically if the prime prime factors right is equal smaller than four factors right is equal smaller than four then we simply return the uh the prime then we simply return the uh the prime factors because we have already factors because we have already checked that you know whenever the prime checked that you know whenever the prime factor is equal to 4 the answer is 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 and once we have chosen a few uh combinations of the prime factors how can we calculate the the number of the the nice divisors based on these prime factors in this case which means that in the the total number of the nice prime nice divisors is the number of each of each distinct the the count of each distinct of the prime 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 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 of the group count is 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 the remaining there so which means that you know uh so given like these prime factors we should always split into two two two and then three three three and then five five five and then what and then uh seven seven seven and then here is like the um eleven eleven 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 with the remaining with the other two numbers which like this case like c11 and 11 right that's going to be the the strategy and there and we also talked about the 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 that the remaining is is one then this is not the optimal solution which means that for in this case instead of adding another another like a different prime numbers here we should uh make this one to be the same as seven where any of any of those uh previously three numbers because this will give us the best yep i think that's it right so i once as yep i think that's it right so i once as soon as you can figure out all those soon as you can figure out all those kind of scenarios and then kind of scenarios and then plus this kind of a little bit dp plus this kind of a little bit dp to calculate the the power of three to calculate the the power of three and yep so and this and yep so and this that's it for this problem and that's it for this problem and how to stop here thank you for watching how to stop here thank you for watching this video guys this video guys and stay tuned see you guys soon bye
2024-03-22 16:08:32
1,808
https://i.ytimg.com/vi/j…axresdefault.jpg
LeetCode 1808. Maximize Number of Nice Divisors
9ka66W53A6Y
hello guys uh i am the casper flaw from pt web 4 pt web 4 here i am to here i am to learn about binary search 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 right pointer you selected value r right pointer you selected value r and and take it as take it as a dot a dot length length minus one that will be the last index of minus one that will be the last index of the error the error run a while loop run a while loop where where l is always less than equal to r l is always less than equal to r and and here we have to here we have to take that will be middle element of the array middle element of the array left plus left plus right first position is minus one [Music] equal to the target value [Music] then return [Music] eos will be made last one and [Music] then also they index accepted it's all about the [Music] 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 just numbs of matrix equal to target 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
2024-03-20 08:52:06
35
https://i.ytimg.com/vi/9…axresdefault.jpg
35 Search insert position #leetcode
iXtqfIrWMZg
Hello everyone welcome to my channel code sorry with mike so today we are going to do with mike so today we are going to do video number 66 of our dynamic programming playlist video number 66 of our dynamic programming playlist ok and today's ok and today's question is lead code number 343 question is lead code number 343 is medium mark but this question can be made in a very easy way is medium mark but this question can be made in a very easy way ok ok ok 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 The main part of this question is The main part of this question is The main part of this question is that how to approach this, 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 You can break it into 2 + 1 1 + 3 and 3 + You can break it into 2 + 1 1 + 3 and 3 + You can break it into 2 + 1 1 + 3 and 3 + 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, many ways but if you take multiplication of all, like in this take multiplication of all 1 like in this take multiplication of all 1 * 1 * 1 * 1 1 * 2 * 1 1 * 3 * 1 * 1 * 1 1 * 2 * 1 1 * 3 * 1 * 1 * 1 1 * 2 * 1 1 * 3 * 2 4 Which is the maximum? If it is 4, then look, the answer is here again. Similarly, Nam = 6. So you can break 6 in many ways. 1 P P P P 4 4 4 P 2 done and so on 1 P 4 P 1 There P 2 done and so on 1 P 4 P 1 There are many ways but what is the best way 3 are many ways but what is the best way 3 P can be broken into 3 There will be P can be broken into 3 There will be no multiplication of these two This will be the best answer The no multiplication of these two This will be the best answer The biggest value is ok Similarly Sen's biggest value is ok Similarly Sen's answer will be 12 answer will be 12 answer will be 12 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, 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 If you If you If you assume that if you break it into 5 and five, 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 then the answer is 25. Then if you break it into seven and 3, then the answer is 21. But answer is 21. But here, if you break it into two parts, the answer will here, if you break it into two parts, the answer will not be good. Look here, these three parts. not be good. Look here, these three parts. Then the best answer will be 3 P 3 P Then the best answer will be 3 P 3 P 4, so 3 3 6 4 10 becomes even, 10, 4, so 3 3 6 4 10 becomes even, 10, what is the multiplication of all, if it is 36, then what is the multiplication of all, if it is 36, then the answer will be 36. Okay, so now let's come to the answer will be 36. Okay, so now let's come to how we will approach this. how we will approach this. how we will approach this. DP's playlist, so you must have already got the hint that DP is the question many ways to break this identification. The many ways to break this identification. The first way is to keep the first part as one, 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 second part as four, look at the sum of both, is it five ? ? ? what is the second way keep the first part as two keep the second part as three doti pa first part second part first part second part let's see here and what is the way first part keep three keep the second part It will be 5 minus 3 two, okay and what is one It will be 5 minus 3 two, okay and what is one It will be 5 minus 3 two, okay and what is one more way? Keep the first part as four, more way? Keep the first part as four, keep the second part as one. Okay, so keep the second part as one. Okay, so isn't this the only four way? There is another way, isn't this the only four way? There is another way, this second part which was four, is also this second part which was four, is also very good. very good. very good. 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 You can break it into You can break it into You can break it into Vanama Two Pe, it is ok or Tooma One Pe, Vanama Two Pe, it is ok or Tooma One Pe, here also you can break Two, One Kama One here also you can break Two, One Kama One Pe, the sum of both is two right and Pe, the sum of both is two right and you cannot break One into four parts because you have to you cannot break One into four parts because you have to break it into maximum two parts. break it into maximum two parts. break it into maximum two parts. 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 The The The diagram will be very long so I am diagram will be very long so I am not drawing it. Okay, when you make the complete tree diagram, not drawing it. Okay, when you make the complete tree diagram, you will see all the possibilities. 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. Look, this one, then this one, then this three Look, this one, then this one, then this three will break, right? will break, right? will break, right? 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 visible, many possibilities will be visible in the tree diagram, that is what I want to tell you. Okay, so now the point Now let's just Now let's just Now let's just look at this branch. look at this branch. Okay, look how many Okay, look how many possibilities you can see here. The first possibility possibilities you can see here. The first possibility you can see is that this can be a good answer. you can see is that this can be a good answer. 1 4, the sum of both is equal to five. 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 third possibility This one is taken Four I broke it into two parts One more possibility is this also so one So this one * * * 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 come, okay, now the question comes that out of come, okay, now the question comes that out of all the possibilities we have, we have to all the possibilities we have, we have to choose the max, right? choose the max, right? choose the max, right? 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 Let us Let us Let us assume that this number is n, then see 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. 1 n -1 means 5 - 1 4. After that 1 n -1 means 5 - 1 4. After that we saw that four we saw that four can be broken into more parts. can be broken into more parts. can be broken into more parts. 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 Na Na Na look at the first part for five, the second look at the first part for five, the second part was two, the third part was three, the fourth part was two, the third part was three, the fourth part was four, after that you can't do it, part was four, after that you can't do it, Na five, you can't do zero, right, na pa, Na five, you can't do zero, right, na pa, zero, you can't do it, so now look, this is one, zero, you can't do it, so now look, this is one, after that after that after that look from here, 1 * 3, 3 is coming from here, 2 * 4, 4 is coming from here, 3 and 3 are coming from here, which is the maximum among the three, if it is Which one do you choose c 1 out of Which one do you choose c 1 out of Which one do you choose c 1 out of these three choose the maximum one that comes these three choose the maximum one that comes maximum four c No ok ok, now it is maximum four c No ok ok, now it is clear till now, clear till now, now look pay attention to this very important part, now look pay attention to this very important part, see what I said here, see what I said here, here I told all the things. here I told all the things. here I told all the things. 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, If va is mine then n - aa then either If va is mine then n - aa then either 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 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 whatever maximum comes from there is fine then what can I say. fine then what can I say. fine then what can I say. 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 Give maximum, that is my Give maximum, that is my Give maximum, that is my answer. You can write it like this. Aa in answer. You can write it like this. Aa in maximum of either we will make it from n my aa 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 Whoever gives the best answer is clear, similar. is clear, similar. is clear, similar. will be my best answer 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 * 5-2 3 is the best answer 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 - Have you come Have you come Have you come in the Fardh Rishan? Send n to Aa. Wherever the 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, multiply it by the largest number I get. Okay, and the same thing will apply here and the same thing will apply here too. The same thing will apply here too. too. The same thing will apply here too. too. The same thing will apply here too. 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 It's going on, what am I It's going on, what am I It's going on, what am I saying? The first part will start from one saying? The first part will start from one and how far will that first part go? Will it go and how far will that first part go? Will it go till Mi? till Mi? I Plus I Plus Plus Okay now come see what will happen Aa Plus Okay now come see what will happen Aa Eve will happen Eve will happen right if A is my father then come right if A is my father then come right if A is my father then come i = 3 will be 4 will go to 4 because if i is 1 then 1 * 4 n - i will be 4 na what will this be 2 and 5 - 2 is 3 na one thing I understood that Q for I needed it, here if I needed it, here if 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 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 till now it is clear so for loop will be needed because you have it right. because you have it right. because you have it right. 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 second part as n - 2. Okay, so Here we came to know Here we came to know Here we came to know that for loop has to be used, but generally that for loop has to be used, but generally people ask, Sir, how will we know people ask, Sir, how will we know that for loop has to be written, okay, so friend, the that for loop has to be written, okay, so friend, the answer to everything is in the tree diagram, if you pay answer to everything is in the tree diagram, if you pay attention to the tree diagram. attention to the tree diagram. attention to the tree diagram. 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 I broke it and au, I broke it and au, I broke it and au, look here, the first part is broken into four, so look here, the first part is broken into four, so what I have broken into 1 2 3 4, you what I have broken into 1 2 3 4, you can achieve this only through for loop and how can achieve this only through for loop and how can you do it, right, that is, here can you do it, right, that is, here we have used for loop, it is okay. we have used for loop, it is okay. we have used for loop, it is okay. said later was that let's find the product i multiplied by the maximum of a - aa or that means i * n - aa will be the best answer or I will send n - aa to recursor and The The The biggest value will be the same and we will multiply it by a, biggest value will be the same and we will multiply it by a, okay this is what I told okay this is what I told you, okay till now it must be clear that what was you, okay till now it must be clear that what was told is exactly the same line of told is exactly the same line of code written and nothing extra is written, code written and nothing extra is written, what do we have to do after this. what do we have to do after this. what do we have to do after this. 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 This will also work, either This will also work, either This will also work, either put any value like 1 * n - 1, it will put any value like 1 * n - 1, it will work because what is its sum, work because what is its sum, 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 I have put 1 * n - 1 but here I have put 1 * n - 1 but here 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 I will keep doing it, okay, so I will keep doing it, okay, so I will keep doing it, okay, so now let's come here, the result is equal to now let's come here, the result is equal to maximum maximum of sorry, the maximum will be here, result of sorry, the maximum will be here, result comma and whatever my prod is getting now, comma and whatever my prod is getting now, okay, so the result is equal to maximum of okay, so the result is equal to maximum of result comma prod, so till here, result comma prod, so till here, well. well. well. end, what do we have to do, we have to give the return not even a datchi and we have completed it and what not even a datchi and we have completed it and what is this, we are writing the recursion only, it is is this, we are writing the recursion only, it is simple, okay, we are writing the simple recursion, simple, okay, we are writing the simple recursion, now you will ask here. now you will ask here. now you will ask here. 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 Here again or Here again or 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 two, then here was three, then this was four and so on, so we have options for each number, okay, options for each number, okay, similarly, look here, three also. similarly, look here, three also. similarly, look here, three also. can be broken, first part one, first part two and so on options, we have second second thing, see here there are all repeating problems, look carefully here, there is three, will you solve it further, see here If you had If you had If you had assumed that you would have stored the answer of 3 here and had assumed that you would have stored the answer of 3 here and had memoized it, then you memoized it, then you could have used it back here could have used it back here in the future, so here I saw what I saw in the future, so here I saw what I saw repeating all the problems brother, these two repeating all the problems brother, these two are enough to tell you. are enough to tell you. are enough to tell you. 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 n, okay so the simple one which will be deep is mine, take n n or sorry n + 1 so that it does not go out of bounds, take n + 1, okay it is 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. k option is right so for every n 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 There are There are There are so many possibilities, but if 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 * 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 so there are so many possibilities, and you are running a for loop for each possibility, you are ok. running a for loop for each possibility, you are ok. running a for loop for each possibility, you are ok. 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 1 1 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 Sent Sent Sent A solve function in my solve. Here we are creating A solve function in my solve. Here we are creating int A. Sent it. int A. Sent it. If there is a e ev in it then it will return one for me If there is a e ev in it then it will return one for me because I cannot break it into two parts. because I cannot break it into two parts. Right, we will return only Right, we will return only one. Okay, a result named one. Okay, a result named Keeping the variable in which I have put int man for Keeping the variable in which I have put int man for int aa = 1 aa < i n-1 aa p p ok now let's int aa = 1 aa < i n-1 aa p p ok now let's first take out the prod how much first take out the prod how much product will come i into the maximum of aa minus product will come i into the maximum of aa minus sorry n - we will multiply by aa or else sorry n - we will multiply by aa or else sorry n - we will multiply by aa or else 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 solve n - aa so that the best answer comes and I will update the maximum Why were we able to write prod and this code Why were we able to write prod and this code Why were we able to write prod and this code because we had made a tree diagram, it becomes because we had made a tree diagram, it becomes very easy with the tree diagram, okay, I have to return the very easy with the tree diagram, okay, I have to return the result in the last, so result in the last, so this is my recursive code, let's memoize it this is my recursive code, let's memoize it now, okay, let's say yes, this now, okay, let's say yes, this So the example is passing, the constraint is So the example is passing, the constraint is very small, it is of 58 size, so I very small, it is of 58 size, so I take dp here int t of 59 size take dp here int t of 59 size is ok, before doing everything, we will is ok, before doing everything, we will check here that if I have check here that if I have set off a is not equal to set off a is not equal to set off a is not equal to 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. You will get it in my Git You will get it in my Git You will get it in my Git Hub link which is on the description. Ok, let's 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. separate video for bottom up. Any doubt, raise it in the comment Any doubt, raise it in the comment section. section. section.
2024-03-24 11:01:13
343
https://i.ytimg.com/vi/i…axresdefault.jpg
Integer Break | Tree Diagram | Recursion | Memoization | AMAZON | Leetcode - 343
ggsBWg5qurE
hello everyone so today's problem is find center of the star graph find center of the star graph so it's an easy lead code problem so so it's an easy lead code problem so let's see how we can solve this so the let's see how we can solve this so the question is there is an undirected star question is there is an undirected star graph consisting of end nodes labeled graph consisting of end nodes labeled from 1 to n a star graph is a graph from 1 to n a star graph is a graph where there is one Center node and where there is one Center node and exactly n minus 1 edges that connect the exactly n minus 1 edges that connect the center node with each and every node center node with each and every node with every other node with every other node you are given a 2d integer array edges you are given a 2d integer array edges Fair each Edge I is equal to u i v i Fair each Edge I is equal to u i v i indicates that there is an a edge indicates that there is an a edge between the nodes UI and v i between the nodes UI and v i and we need to return the center of the and we need to return the center of the given star graph so 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 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 this line 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 we will create a for Loop I should be less than I should be less than edges and I plus 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 now we will create a vector array 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 I will copy paste this one and we will change it for two one so that we can access this one and this one and we will increase each and this one and we will increase each of them by one and this is for of them by one and this is for this one this one no no no no this one this one this one this one this one we will try to compare the in degree of we will try to compare the in degree of each and every node each and every node so the the so the in degree of the node so the the so the in degree of the node which is equal to n minus 1 will be our 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 and if in degree and if in degree if n degree is equal to n minus 1 then if n degree is equal to n minus 1 then we will store the value of we will store the value of I and the result I and the result we will store the value of I in the we will store the value of I in the result result and we will and we will break the statement so let's run it please like subscribe and please like subscribe and comment on my channel and do support me
2024-03-22 14:45:49
1,791
https://i.ytimg.com/vi_w…xresdefault.webp
Find the Center of the Star Graph | Leetcode problem - 1791 | C++ | @codecrash14
hND9YHeZJLA
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 balloon provided input is the start and the n-coordinates of the horizontal diameter 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 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 a balloon with x-star and 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 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 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
2024-03-22 14:21:02
452
https://i.ytimg.com/vi_w…xresdefault.webp
Minimum Number of Arrows to Burst Balloons | Leet code 452 | Theory explained + Python code
0kkVobZ6Ebc
hey what's up engineers today we're doing question number 255 verify doing question number 255 verify pre-order sequence in a binary search pre-order sequence in a binary search tree tree before you continue please check the before you continue please check the description because if there's anything description because if there's anything incorrect in this video i'll be making incorrect in this video i'll be making those corrections in the description those corrections in the description since i can't actually go back and edit since i can't actually go back and edit the physical video itself if you find the physical video itself if you find anything incorrect or misleading in this anything incorrect or misleading in this video please let me know in the comments video please let me know in the comments i will check it out and i will update i will check it out and i will update the description accordingly the description accordingly i don't want to be giving out you know i don't want to be giving out you know misleading or false information misleading or false information um if you guys like this video i mean um if you guys like this video i mean it's my first ever video it's my first ever video let me know as well it can be any let me know as well it can be any constructive criticism it's all really constructive criticism it's all really appreciated appreciated but today we're working on question but today we're working on question number 255 which is a number 255 which is a abstract question that's going to abstract question that's going to require us to think of binary search require us to think of binary search trees trees in a very very specific way and it took in a very very specific way and it took me me a couple hours to figure it out to fully a couple hours to figure it out to fully understand what we were actually doing understand what we were actually doing and i really hope you guys get some and i really hope you guys get some awesome uh information out of this awesome uh information out of this all right so let's go ahead and read all right so let's go ahead and read over the question real quickly given an over the question real quickly given an array of numbers array of numbers verify whether it is the correct verify whether it is the correct pre-order traversal sequence pre-order traversal sequence of a binary search tree which i'll be of a binary search tree which i'll be referring to as a bst referring to as a bst you may assume each number in the you may assume each number in the sequence is unique sequence is unique and so i just wrote a quick thing down and so i just wrote a quick thing down here here the the rules of the bst are pretty the the rules of the bst are pretty straightforward everything in the right straightforward everything in the right sub-tree sub-tree has to be less than the root or so it has to be less than the root or so it has to be greater than the root has to be greater than the root everything in the left sub-tree has to everything in the left sub-tree has to be less than be less than the root and this holds true for all the root and this holds true for all cases so even if we have something like cases so even if we have something like for example 9 up here and then we hold 6 for example 9 up here and then we hold 6 and 12 and then we have 11 and 12 and then we have 11 and 14. we can't have the number and 14. we can't have the number i don't know 7 down here because i don't know 7 down here because seven is well first of all sure it's seven is well first of all sure it's less than this that's that's fine less than this that's that's fine it's less than this that's fine however it's less than this that's fine however seven is not less than seven is not less than this so it's not fine this so it's not fine all right so let's go over what a all right so let's go over what a pre-order is a pre-order pre-order is a pre-order is root left then right is root left then right so keep in mind if we have a tree a so keep in mind if we have a tree a figurative tree figurative tree such as 99 98 such as 99 98 100 and then 98 goes all the way down to 100 and then 98 goes all the way down to zero like just you know 98 more numbers zero like just you know 98 more numbers down there 97 more numbers down there 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 will always will always go left it will go left go left it will go left infinite times theoretically and root infinite times theoretically and root and right and right once before it repeats the cycle so what once before it repeats the cycle so what does that mean so it does this one time does that mean so it does this one time this infinite this one time and then it this infinite this one time and then it repeats repeats so it'll go route 99 all the way down so it'll go route 99 all the way down the left to zero the left to zero then right 100. now if 100 happened to then right 100. now if 100 happened to have you know have you know infinite children left it would also go infinite children left it would also go infinite down infinite down left of 100 and then it would visit 101 left of 100 and then it would visit 101 for example for example keeping this rule in mind let's try to keeping this rule in mind let's try to actually apply it to a visual actually apply it to a visual binary search tree that we have here so binary search tree that we have here so visual binary search tree we know that visual binary search tree we know that we're going to start at the root we're going to start at the root and we're going to go left infinite and we're going to go left infinite times so that means we're going to start times so that means we're going to start selling this out of the way we're going selling this out of the way we're going to start to start here and we're going to go sorry we here and we're going to go sorry we should start at the root here should start at the root here and we're going to go left all the way and we're going to go left all the way down we're done down we're done that's our first iteration our next that's our first iteration our next iteration is we're going to go left iteration is we're going to go left again well of its first child which again well of its first child which happens to be happens to be here that's our second iteration then here that's our second iteration then we're gonna go left again we're gonna go left again third iteration then we're gonna go left third iteration then we're gonna go left again fourth iteration again fourth iteration 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 pre-order of this it'll get me five pre-order of this it'll get me five two one 4 two one 4 8 6 9. 8 6 9. so this is a valid binary search tree so this is a valid binary search tree since since um 5 2 1 4 8 6 9 um 5 2 1 4 8 6 9 just adds up to a valid binary search just adds up to a valid binary search tree what if we had a similar binary tree what if we had a similar binary search tree but that wasn't valid what search tree but that wasn't valid what if we had something else if we had something else five two one five two one four eight let's just do three here four eight let's just do three here three uh four three uh four nine like that well nine like that well everything looks good until you get to everything looks good until you get to this four here this four here and in our loop here how are we supposed and in our loop here how are we supposed to catch that to catch that because if you think about it we're only because if you think about it we're only going left only going left only sure one is less than two which is less sure one is less than two which is less than five so this is a fine loop than five so this is a fine loop this is a okay loop iteration one this is a okay loop iteration one you know then we go three three is less you know then we go three three is less than well nothing else so that's fine as than well nothing else so that's fine as well iteration two well iteration two but then we get eight and four and all but then we get eight and four and all this this thing sure four is less than eight but thing sure four is less than eight but four is not less than its highest parent four is not less than its highest parent five and then we go through 9 yep 9 is five and then we go through 9 yep 9 is fine as well okay fine as well okay however this one's not fine so we need however this one's not fine so we need to keep to keep track of the immediate parent of 4 first track of the immediate parent of 4 first of all of all so in case you know this was something so in case you know this was something like you know like 12 like you know like 12 well that's not less than eight at all well that's not less than eight at all that should be an immediate no but even that should be an immediate no but even if something like this like four if something like this like four we should see that okay well four sure we should see that okay well four sure is less than eight that's fine however is less than eight that's fine however four is not less than 5. four is not less than 5. so we can do this by just 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 give you if we pull up another example give you if we pull up another example here here we're going to have an example of we're going to have an example of 5 2 6 5 2 6 1 and 3. now using our little 1 and 3. now using our little algorithm formula left subtree kind of algorithm formula left subtree kind of only pattern here only pattern here we're going to recreate this using just we're going to recreate this using just left sub trees left sub trees so we're gonna start with five and we're so we're gonna start with five and we're gonna go okay gonna go okay five is that now we're looking at two five is that now we're looking at two well two is less than five so let's tell well two is less than five so let's tell me two should be in its left subtree me two should be in its left subtree and then six well now six is no and then six well now six is no it's not less than five so it's telling it's not less than five so it's telling me we're about to start a new iteration me we're about to start a new iteration of subtrees so now we're starting at six of subtrees so now we're starting at six here here okay one is less than six that's fine okay one is less than six that's fine and three is and three is not less than one so that tells me we're not less than one so that tells me we're gonna start a new iteration gonna start a new iteration of subtrees here assuming six is 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 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 one is less than six so one goes there that's fine and three 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 we can do this by keeping track of the we can do this by keeping track of the last last removed parent because if you think removed parent because if you think about it about it every single time we remove a parent every single time we remove a parent when we go when we go five and two and then we insert six five and two and then we insert six we remove two here and we remove five we remove two here and we remove five and six comes up here but what this is and six comes up here but what this is actually telling us if you think about actually telling us if you think about it like a tree you're telling me it like a tree you're telling me that you just want me to put six in here that you just want me to put six in here however the six is not going to be however the six is not going to be the left subtree of two because remember the left subtree of two because remember we're looking at left subtrees we're looking at left subtrees so every single time we remove one we're so every single time we remove one we're actually moving right actually moving right so you're telling me it's not going to so you're telling me it's not going to be the left of 2 so it's going to be to be the left of 2 so it's going to be to the right of 2. the right of 2. but then you're also telling me it's not but then you're also telling me it's not going to be left of 5 so it's going to going to be left of 5 so it's going to be to the right of 5 be to the right of 5 and there's no nothing else higher up and there's no nothing else higher up here to go so therefore 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 6 is going to be to the right of 5. 6 is going to be to the right of 5. and then when we keep going on you know and then when we keep going on you know we add 1 and we add whatever three we add 1 and we add whatever three whatever's next this pattern keeps going whatever's next this pattern keeps going however this is not a bsd and using this however this is not a bsd and using this weird abstract mathematical formulas is weird abstract mathematical formulas is not going to help so let's actually not going to help so let's actually translate this into a pattern which we translate this into a pattern which we can code can code and i'll give you a hint it's much and i'll give you a hint it's much easier than it looks so let's look at easier than it looks so let's look at the same array the same array one more time now but this time let's one more time now but this time let's follow two patterns that we know of follow two patterns that we know of we know for every integer x we know for every integer x for every integer shorten the int x if the if the last removed last removed whatever node or it's called ant whatever node or it's called ant actually rust removed actually rust removed and is and is greater than x greater than x and it's not and it's not a b s t a b s t so let me show you what this means on an so let me show you what this means on an actual example remember actual example remember using our left only tree our left using our left only tree our left only well not really a tree let's call only well not really a tree let's call it a tree for now it a tree for now our left only tree we are gonna have our left only tree we are gonna have five five we're gonna have two and then you're we're gonna have two and then you're gonna try shoving a six in there gonna try shoving a six in there and the six is gonna bubble up to there and the six is gonna bubble up to there and the last removed is going to be five and the last removed is going to be five so the last removed last removed so the last removed last removed is going to be five the resultant tree's is going to be five the resultant tree's gonna be six gonna be six then you're gonna shove a one in there then you're gonna shove a one in there and we're gonna check this first rule and we're gonna check this first rule here here is the last removed five is it greater is the last removed five is it greater than than the current integer x one yeah it is the current integer x one yeah it is therefore it's not a therefore it's not a b s t because b s t because when we remove this we're telling it when we remove this we're telling it we're going into this we're going into this right subarray of five and everything to right subarray of five and everything to the right of five the right of five must be greater than it okay so our second rule or our second pattern our second whatever up x 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 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 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 insert at the end and remove from the insert at the end and remove from the end end which sounds very very much like our which sounds very very much like our favorite data structure favorite data structure stack because if i do the same example stack because if i do the same example one more time but using a stack you'll one more time but using a stack you'll do the exact same thing do the exact same thing we have five we have two then we have in we have five we have two then we have in the waiting line we have the waiting line we have in our current so our x is going to be in our current so our x is going to be 2. we're going to put 2 in there our x 2. we're going to put 2 in there our x is going to be is going to be 6 and 6 won't fit in there so we're 6 and 6 won't fit in there so we're going to remove 2 going to remove 2 5 and 6 is sorry sorry 6 will fit in 5 and 6 is sorry sorry 6 will fit in there but 6 is greater than two so we're there but 6 is greater than two so we're gonna remove two gonna remove two six is greater than five we're gonna six is greater than five we're gonna remove five that's gonna give us the remove five that's gonna give us the resulting stack resulting stack of six okay of six okay now our x is gonna be one so i should now our x is gonna be one so i should put a little colon there put a little colon there one one is gonna fit perfectly there one one is gonna fit perfectly there and next one's gonna be three three is and next one's gonna be three three is gonna fit perfectly there gonna fit perfectly there this is just the second rule by the way this is just the second rule by the way i yeah if you're paying attention you i yeah if you're paying attention you should have immediately seen that this should have immediately seen that this right here breaks the first rule and so right here breaks the first rule and so what we can do is whenever we pop off we what we can do is whenever we pop off we can keep track of the last number we can keep track of the last number we removed removed so our last removed lr can be two and so our last removed lr can be two and then our lr will be five here then our lr will be five here and our lr won't change it'll still be and our lr won't change it'll still be five here and so we five here and so we put in that one it should have been a put in that one it should have been a flag right there that five is greater flag right there that five is greater than one 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 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 until bubble up x until it's parent so let me change this to until 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 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 all right so let's look at the actual all right so let's look at the actual code now i haven't spent too much time code now i haven't spent too much time trying to explain the actual code trying to explain the actual code because i feel like i did a fairly good because i feel like i did a fairly good job job in the previous section and so here's in the previous section and so here's the code uh this is the the code uh this is the algorithm up top here uh so for every algorithm up top here uh so for every last removed integer if it's greater last removed integer if it's greater than than x then we do not have a bst and we're x then we do not have a bst and we're gonna return false gonna return false otherwise we're gonna keep bubbling up x otherwise we're gonna keep bubbling up x until its parent is greater or until its parent is greater or null so you know we're using a stack our null so you know we're using a stack our last pop is going to be a min value and last pop is going to be a min value and the reason for that the reason for that is because if we have negative values in is because if we have negative values in the the um i didn't use like 0 or like a small um i didn't use like 0 or like a small number because theoretically there could number because theoretically there could always be something smaller always be something smaller min value is the absolute smallest that min value is the absolute smallest that we can get out of java 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 going to follow the first rule going to follow the first rule where if the last removed integer is where if the last removed integer is greater greater than the current integer then we know we than the current integer then we know we don't have a bst because it violates don't have a bst because it violates that rule that rule and the reason we use the greater than and the reason we use the greater than and not greater than or equal to and not greater than or equal to is because we are assuming that each is because we are assuming that each number is unique number is unique therefore we cannot have two duplicate therefore we cannot have two duplicate numbers and then we're going to follow numbers and then we're going to follow the second rule of the algorithm where the second rule of the algorithm where we're going to bubble up x until its we're going to bubble up x until its parent is greater or null parent is greater or null and so while the stack is not empty and and so while the stack is not empty and x is greater than the parent x is greater than the parent we're just going to pop off the parent we're just going to pop off the parent save it and we're going to save it and we're going to push x on once we find the uh push x on once we find the uh right spot for it and then once we're right spot for it and then once we're done this uh done this uh for loop since we went through every for loop since we went through every single x and it never violated the first single x and it never violated the first rule rule it must be a bst then um as for it must be a bst then um as for efficiency this is a little efficiency this is a little weird to calculate we know it's for sure weird to calculate we know it's for sure o squared of n here because we are going o squared of n here because we are going over over the pre-order list however here we the pre-order list however here we are um theoretically it could be are um theoretically it could be um like um like n log n because n log n because we are inside the end loop first of all we are inside the end loop first of all the log n the log n comes from the fact that if our array comes from the fact that if our array contains continuously descending numbers contains continuously descending numbers or or ascending numbers so if we have ascending numbers so if we have something like 1 2 something like 1 2 3 4 5 6 7 8 9 3 4 5 6 7 8 9 10 it will continuously pop off the last 10 it will continuously pop off the last immediate one and so it's really immediate one and so it's really like actually n because it's just like actually n because it's just removing the one previous one every time removing the one previous one every time however if we have something like you however if we have something like you know 10 9 know 10 9 8 7 6 5 4 3 2 1 55 8 7 6 5 4 3 2 1 55 that 55 is gonna have to remove the that 55 is gonna have to remove the majority of the majority of the array so it's it's the the complexity on array so it's it's the the complexity on this type of question is a little this type of question is a little ambiguous ambiguous a theoretically worst case scenario i a theoretically worst case scenario i believe it could be n log n believe it could be n log n however please correct me in the however please correct me in the comments comments and if uh if the actual efficiency is and if uh if the actual efficiency is discovered i will put it in the discovered i will put it in the description so if you're watching this description so if you're watching this at a later date at a later date check the description it might actually check the description it might actually have the actual efficiency of this have the actual efficiency of this algorithm algorithm anyways thank you guys so much for anyways thank you guys so much for watching uh first ever video i really watching uh first ever video i really like doing this type of stuff so if you like doing this type of stuff so if you guys enjoy it too guys enjoy it too let me know by using the thumbs up just let me know by using the thumbs up just leave me a comment and um leave me a comment and um i'm gonna keep making these uh time i'm gonna keep making these uh time permitting and energy permitting but um permitting and energy permitting but um i really hope it's helped you guys on i really hope it's helped you guys on your your path forward and uh happy happy happy path forward and uh happy happy happy coding
2024-03-22 12:10:22
255
https://i.ytimg.com/vi_w…c/sddefault.webp
LeetCode #255 Verify Preorder Sequence in Binary Search Tree (Explanation + Code)
s0p4OvLDdRw
this is 1757 recyclable and low-fat products all right let's do it we got a products all right let's do it we got a table here table here data types int for IDs primary key data types int for IDs primary key perfect and two enums right whereas just perfect and two enums right whereas just a y or n so like a true or false it a y or n so like a true or false it looks like this means why is this looks like this means why is this product is low fat and means it's not product is low fat and means it's not same thing why recyclable and it's not same thing why recyclable and it's not cool write a SQL query to find the cool write a SQL query to find the products that are both low-fat and products that are both low-fat and recyclable so once again recyclable so once again multi-like comment right right all this multi-like comment right right all this juicy info down and right we're saying juicy info down and right we're saying recyclable and low fats right so low fats needs to equal a y for it to be considered low fat and recyclable also needs to be why right return the result table in any order the query result format is in the following example cool so it looks like we're only outputting product IDs which is what the question says but you can be sure of it when you look at the output only products one and three are both only products one and three are both low-fat and recyclable cool low-fat and recyclable cool another straightforward question so another straightforward question so let's say select product ID right from let's say select product ID right from products where once again because we products where once again because we notated it when we were writing I think notated it when we were writing I think that's all we need that's all we need right low fats and recyclable um that looks good to me let's give it a run test case sweet submit
2024-03-22 12:06:49
1,757
https://i.ytimg.com/vi/s…axresdefault.jpg
Leetcode #1757: recyclable and low fat products
5PeqyiYifQ8
hi everyone welcome to lead code daily challenge challenge so the problem for today is to find the so the problem for today is to find the kth factor of a given number n kth factor of a given number n so we will be given two positive so we will be given two positive integers l integers l and k we need to find the kth factor of and k we need to find the kth factor of the given number the given number n so the given integer n so as you know n so the given integer n so as you know the factor is the factor is uh how do we define a factor so if the uh how do we define a factor so if the number the given number divides the number the given number divides the integer n integer n then the number is a factor of the then the number is a factor of the integer n integer n so if if you take an integer i and if it so if if you take an integer i and if it if the remainder of the n percent i is 0 if the remainder of the n percent i is 0 that means if that means if i is dividing in with a remainder of 0 i is dividing in with a remainder of 0 that means i is a factor of that means i is a factor of number n so we need to consider all the number n so we need to consider all the factors of n factors of n sorted in ascending order and then sorted in ascending order and then return the kth factor in this list return the kth factor in this list and if there is no kth factor that means and if there is no kth factor that means if they if they want a factor which is if they if they want a factor which is beyond a beyond a k which is beyond the number of k which is beyond the number of factors of the number n then we need to factors of the number n then we need to return minus 1 return minus 1 so let's say we have a m number of so let's say we have a m number of factors for the given integer n factors for the given integer n and if k k is greater than m that means and if k k is greater than m that means we don't have a kth factor 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 at the examples at the examples so the given number n is 12 and we need so the given number n is 12 and we need to find the third factor for the to find the third factor for the first 12 so the factorist is 1 first 12 so the factorist is 1 2 3 4 6 12 because all these numbers 2 3 4 6 12 because all these numbers will divide 12 with a remainder of 0 so will divide 12 with a remainder of 0 so the third factor here is 3 the third factor here is 3 and we need to remember that we need to and we need to remember that we need to include the number also in the factor include the number also in the factor list we have 1 list we have 1 as well as the number itself in the as well as the number itself in the factory list factory list and in the second example we have n and in the second example we have n equal to 7 and k equal to so the factor equal to 7 and k equal to so the factor list here is 1 comma 7 because n is a list here is 1 comma 7 because n is a prime number so we don't have anything prime number so we don't have anything other than 1 and the number itself other than 1 and the number itself so that so the second factor is 7 so that so the second factor is 7 and here we have n equal to 4 and k and here we have n equal to 4 and k equal to 4 equal to 4 and the factor list for the integer 4 and the factor list for the integer 4 are 1 2 4 and we don't have a fourth are 1 2 4 and we don't have a fourth factor here so factor here so 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 equal to 1 and k equal 1 and it is straight forward straight forward so the first factor is 1 itself and in so the first factor is 1 itself and in example 5 we have thousand and three example 5 we have thousand and three so the third factor is four in the list so the third factor is four in the list so it should be pretty straightforward so it should be pretty straightforward and let's see the and let's see the constraints so the k n can go uh constraints so the k n can go uh from one till thousand so it should be from one till thousand so it should be okay the constraints are not too hard so okay the constraints are not too hard so even off and square approach should be even off and square approach should be fine fine but anyway the problem is but anyway the problem is straightforward so let's see let's look straightforward so let's see let's look at the hints provided here so the at the hints provided here so the factors of factors of a number n will always be in the range 1 a number n will always be in the range 1 to m so that is pretty straightforward to m so that is pretty straightforward and from the hint to keep a list of all and from the hint to keep a list of all factors factors sorted loop i from 1 to n that means we sorted loop i from 1 to n that means we go from 1 to n and then go from 1 to n and then check if the number is dividing n with a check if the number is dividing n with a remainder of 0 then we add it to the our remainder of 0 then we add it to the our factories factories and we make sure that they are in the and we make sure that they are in the sort order sort order so i don't think we need any further so i don't think we need any further explanation so let's explanation so let's take a look at the source code so first take a look at the source code so first take a vector of take a vector of integers so that we store all the integers so that we store all the factors factors then as shown in the hint as provided in then as shown in the hint as provided in the hint we go from the hint we go from 1 to n we can go till n 1 to n we can go till n because we know that beyond n by 2 the because we know that beyond n by 2 the number will not divide number will not divide the given integer so let's say we have the given integer so let's say we have an 10 an 10 and equal to 10 so we know that beyond 5 and equal to 10 so we know that beyond 5 n by 2 m by 2 is 10 by 2 is 5 so beyond n by 2 m by 2 is 10 by 2 is 5 so beyond 5 we don't have to check because 5 we don't have to check because 6 7 8 9 they don't divide 10 so only 6 7 8 9 they don't divide 10 so only thing is we just make sure that we add thing is we just make sure that we add n to the factor then so we go n to the factor then so we go for loop from i equal 1 to 1 by 2 then for loop from i equal 1 to 1 by 2 then if the number is a dividing if the number is a dividing given integer when remainder is 0 given integer when remainder is 0 then we store our number in the factory then we store our number in the factory list list and finally we need to push the number and finally we need to push the number itself because n also itself because n also divides n and from this factor list divides n and from this factor list we need to make sure that the size is we need to make sure that the size is greater than or equal to k because greater than or equal to k because if it is less than k then we need to get if it is less than k then we need to get a minus 1 a minus 1 so if it is size is more than k then we so if it is size is more than k then we written factor of k minus 1 because 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 factor because the index starts from 0 factor because the index starts from 0 to to 0. so let's execute and see yeah so it works fine let's submit and 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 so instead of vector we take a real list so instead of vector we take a real list because we have a release to store because we have a release to store dynamic number of integers then dynamic number of integers then again we go from uh one to n by two again we go from uh one to n by two then if the number of the given integer then if the number of the given integer divides n divides n then we add it to our factors so factor then we add it to our factors so factor dot add then finally we add uh dot add then finally we add uh and itself to the factory list then we and itself to the factory list then we just check if the size is just check if the size is within the limit of size is more than k within the limit of size is more than k then we get then we get 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 get the integer at the k minus 1 index because because index starts from zero otherwise you'll index starts from zero otherwise you'll written minus one written minus one so i think we can directly submit so i think we can directly submit is pretty same as c plus plus except is pretty same as c plus plus except that release 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 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
2024-03-21 10:58:16
1,492
https://i.ytimg.com/vi_w…xresdefault.webp
The kth Factor of n | Leetcode 1492 | leetcode solution
vtEtO1CW8-Y
all right so this question is validated IP address so in this question you are IP address so in this question you are giving the string query IP so you either giving the string query IP so you either return ipv4 or IPv6 and if both are return ipv4 or IPv6 and if both are links are not true then you return links are not true then you return neither so ipv4 is this function so it's neither so ipv4 is this function so it's starting from 0 to 100 to 255. and the X starting from 0 to 100 to 255. and the X you know the X represents the you know the X represents the you know the string array you know the string array uh a split by the dot right and then you uh a split by the dot right and then you cannot have a leading zero and you also cannot have a leading zero and you also cannot apply some uh crappy you know cannot apply some uh crappy you know string so this is not allowed so IPv6 string so this is not allowed so IPv6 you can only contain digit and lowercase you can only contain digit and lowercase later later and also the application status from a and also the application status from a to f to f so so the reason why you you know contain a to the reason why you you know contain a to F this is because you know you have F this is because you know you have phones uh 0 to 16 for the hexadecimal phones uh 0 to 16 for the hexadecimal hex is for 16 right hex is for 16 right so uh you just have to follow the so uh you just have to follow the constraint so let's talk about some uh constraint so let's talk about some uh some constraints in ipv4 so I believe some constraints in ipv4 so I believe before you want to work you want to get before you want to work you want to get a a basically you want to get rid of what basically you want to get rid of what get rid of get rid of dating zero right dating zero right and this is pretty much it right and and this is pretty much it right and then also the you know then also the you know the ranges between the ranges between the zero to zero zero to 255 so let's the zero to zero zero to 255 so let's just start writing about ipv's ipv4 just start writing about ipv's ipv4 right right so uh I need a helper function I'm going 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 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 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 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 the string the string so if this is if this is not working so if this is if this is not working you need to try and cash to catch your you need to try and cash to catch your arrow and then your return false right arrow and then your return false right so I just have to make sure the norm is so I just have to make sure the norm is if the num is actually equal to no if the num is actually equal to no all the norm is less than zero all the all the norm is less than zero all the num is greater than 255. num is greater than 255. so this is like a range between I mean so this is like a range between I mean range uh range is cool right so you range uh range is cool right so you won't just you know return false right won't just you know return false right and then at the end of the ipv4 you just and then at the end of the ipv4 you just want to say return true but I can just using the helper function query IP right and this is ipv4 query IP right and this is ipv4 it's true then just return the string it's true then just return the string all right so the next one is going to be all right so the next one is going to be create IP V6 and then using the curry create IP V6 and then using the curry and then turn and then turn ipv 6 right and the last but not least all right so we need to create a 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 I can stop holding right so maybe I can stop holding right so showing the split showing the split type sorry so you still spill color dot type sorry so you still spill color dot middle one middle one and then if the shootout lens is I mean and then if the shootout lens is I mean that's not equal to eight right that's not equal to eight right just you just have to make sure I just just you just have to make sure I just have to make sure have to make sure this is what this is what this is eight one two three four five this is eight one two three four five six seven eight right eight and then if six seven eight right eight and then if this is not eight you return false this is not eight you return false and also if you look at the pattern and also if you look at the pattern uh it has to be less than equal to a uh it has to be less than equal to a fourth four right for every single uh fourth four right for every single uh string right so just say string sorry to string right so just say string sorry to follow string string 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 is y is greater than four is greater than 4 or Swindle length is actually equal to zero so this might be more real readable right 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 and then I just have to Traverse every and then I just have to Traverse every single chart single chart inside my string inside my string so if C is digit right if a c is digital so if C is digit right if a c is digital then I can use a character then I can use a character that is stated SC that is stated SC and I don't have to worry about right I and I don't have to worry about right I don't I mean I I don't have to worry don't I mean I I don't have to worry about like what did you what digit it is about like what did you what digit it is it can be zero it can be one it can be it can be zero it can be one it can be nine doesn't matter but if this is digit nine doesn't matter but if this is digit it's doable it's doable I just have to check for Korean what I just have to check for Korean what uh uh current character right so I'm uh uh current character right so I'm going to just you know convert the going to just you know convert the currency 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 so there are a lot of typing but you so there are a lot of typing but you know this is pretty straightforward know this is pretty straightforward uh if C is digit then I don't worry uh if C is digit then I don't worry about this and if this upper is this about this and if this upper is this uppercase I convert to lowercase is C uppercase I convert to lowercase is C slow case you know low case to Locus is slow case you know low case to Locus is you know no it doesn't change right so I you know no it doesn't change right so I will just make sure C is in the range will just make sure C is in the range between what a to F it if C is not between what a to F it if C is not inside the a2f range I will turn false inside the a2f range I will turn false so let me run it oh I see where's my so let me run it oh I see where's my arrow arrow okay here is it okay here is it um um so string dot chart at right so string dot chart at right this is the chart this is the chart so what am I doing so what am I doing using using so yeah so this might be okay oh so uh so yeah so this might be okay oh so uh look at this so this is what IPv6 right look at this so this is what IPv6 right and I'm actually and I'm actually one two three four five six seven eight one two three four five six seven eight so I'm actually so I'm actually um forget one uh one constraint um forget one uh one constraint so here is it let me so here is it let me pause the video for a second pause the video for a second yes I mean I don't have to pause you yes I mean I don't have to pause you know you know I I just realized I'm know you know I I just realized I'm using a semicolon right here I'm not 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 alright so this is a query alright so this is a query so I will enter here oh here's it yeah so again yeah so again he will return he will return uh straightforward solution uh straightforward solution so uh how about this this is also true so uh how about this this is also true well how about this well how about this uh uh let me just change a little bit to what let me just change a little bit to what to do to do so start debugging so start debugging and this will actually return first and this will actually return first right right so in a query so in a query I mean I don't have to trade this will I mean I don't have to trade this will give you false so I will jump to here 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 uh let me uh let me let me have a breakpoint right here as let me have a breakpoint right here as well well I'll break I'll break all right all right so I'm checking zero I'm also checking so I'm checking zero I'm also checking the next one zero the next one zero I'm also checking a a two e checking the last one seven three three checking the last one seven three three two this will actually give you two this will actually give you false two right convert to a lowercase and it's true inside my range no you and yeah and yeah so your return needle for this IP so your return needle for this IP address address all right so this question is a little all right so this question is a little bit long and spend some time understand bit long and spend some time understand the constraint the constraint and you should be okay I still have and you should be okay I still have questions leave a comment below questions leave a comment below subscribe if you want it and I will see subscribe if you want it and I will see you next time bye
2024-03-22 15:15:19
468
https://i.ytimg.com/vi/v…axresdefault.jpg
LeetCode 468 | Validate IP Address | IPv4 | IPv6 | String | Debug | Java
jl68j3vLHZk
Hello guys welcome to disrespect video andar only coding and horses bihar assembly only coding and horses bihar assembly problem that is gold coin change and where given problem that is gold coin change and where given point of different denominations and point of different denominations and total amount of money amount friday function total amount of money amount friday function to compute the furious number of the journey to make to compute the furious number of the journey to make update amount is the volume update amount is the volume update amount is the volume 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 ₹1 So This Level Rupee Coins And Rupee Coins And Rupee Coins And Voting On Voting On 200 Reporting And ₹2 Point Five Times 200 Reporting And ₹2 Point Five Times And Attractive One Rupee Coin Military Reading And Attractive One Rupee Coin Military Reading Scars But Still Its Alarms Loot Number Candy 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 k subscribe and subscribe and k subscribe and subscribe and k subscribe and subscribe and subscribe the Channel 121 121 subscribe the Channel 121 121 share neeraj problem vectors oil lekar share neeraj problem vectors oil lekar dp devil and angel om initially 500 k 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 time what is the subscribe to make ₹1 ₹1 time what is the subscribe to make ₹1 ₹1 1 ₹1 Supposed To Make Sure Subscribe To My Every Day Every Day And Sunao Left Right To Understand The And Sunao Left Right To Understand The Dry Sequence Lass Co Forward To Drops Understanding Supposed To May And Dry Sequence Lass Co Forward To Drops Understanding Supposed To May And You Have 0 100000000000000 9th 100000000000000 9th person's rupees during person's rupees during nomination till cash is diet suite 1200 10 nomination till cash is diet suite 1200 10 minutes and next assistant is next 9 newsroom minutes and next assistant is next 9 newsroom se or particular word to point to make se or particular word to point to make for 12345 600 the very very very large for 12345 600 the very very very large amount of ma twe no p Piece and Yours of Two Use Points Up to Piece and Yours of Two Use Points Up to Denomination of Mode Turn Volume Minimum Denomination of Mode Turn Volume Minimum Number of But You Can Make OK So My Number Number of But You Can Make OK So My Number to Make 3D Nomination Withdrawal from IGNOU to Make 3D Nomination Withdrawal from IGNOU FlashLights Pimples Balls Subscribe ₹1 FlashLights Pimples Balls Subscribe ₹1 ₹1 ₹1 OK Good Night I Love You ₹1 ₹1 OK Good Night I Love You ₹1 ₹1 OK Good Night I Love You Subscribe In A Reader 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 Go To And Next Data Entry 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 Next Next Next ₹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 Make ₹1 How Can You To That Can You Right Make ₹1 How Can You To That Can You Right 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 It Possible Not Possible Than What Will U It Possible Not Possible Than What Will U Care Love You All Care Love You Used For Care Love You All Care Love You Used For Information For Information You Can You Can You Do You Information For Information You Can You Can You Do You Can Can Can 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 entry sunao ya to make ₹2 ok using to entry sunao ya to make ₹2 ok using to form ₹2 point ok so how form ₹2 point ok so how The Meaning Of This Thank You To You To You To You To You To You To You To You To You To You To You To You You To You To You You To You To You - 2009 mein do to initially Aamir zero and now you are how to make a ₹2 this two rupee coins to America they need only one thing 1212 and you to you to you to you can locate the volume to To To To To To To To To To To To To To Make To To To To To To To To To To To To To Make To To To To To To To To To To To To To Make Love To You To You To You 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 Make ₹3 Using Two Rupees Make ₹3 Using Two Rupees Make ₹3 Using Two Rupees Coin Using Two Denominations Of Moksha Coin Using Two Denominations Of Moksha How Can You Don't See Weather You Take Two Rupees Coin 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 Third Option You Have Elaborate Systems Paid Third Option You Have Elaborate Systems Paid News Coins Of ₹2 Previous One To Three News Coins Of ₹2 Previous One To Three Times A Times A Times A 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 Two Rupees Coin Idli Sandwich Using Back to Rupees Coin - 20131 This Particular Amount 151 Minimum Minimum Number of Media in You to 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 look this is the meaning of the name of the state ₹1 ₹1 Person Ko Minimum Minimum Mittu Mittu ₹1 ₹1 Person Ko Minimum Minimum Mittu Mittu ₹1 ₹1 Person Ko Minimum Minimum Mittu Mittu Clear After Some Time Clear After Some Time A More Examples Next Will Have To Make It's A A More Examples Next Will Have To Make It's A Few Rupees And They Can Use To Few Rupees And They Can Use To Rupees Coin Okay So I Can You Two Rupees Coin Rupees Coin Okay So I Can You Two Rupees Coin And Let's Not You Studied For IF Possible Option And Let's Not You Studied For IF Possible Option That I hand election what do you do first ever take the That I hand election what do you do first ever take the 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 quality including one point to military quality including one point to military singer ₹2 crow but the Mukesh remaining amount singer ₹2 crow but the Mukesh remaining amount for minus point to make for minus point to make for minus point to make using two rupee coins the remaining amount is 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 To Make How To Make To Okay For To Make How To Make To Okay For To Make How To Make To Okay For - To Interest Amroha E Look At You That - To Interest Amroha E Look At You That Swarna Mitthu Amount Using Whisper I Kota Swarna Mitthu Amount Using Whisper I Kota You Married And You Married And Ajay Sallu-Cat Suvan Point Per Urine To Ajay Sallu-Cat Suvan Point Per Urine To Rupees Coin And One Way For Making Front Rupees Coin And One Way For Making Front Amount Friend Request To Number Of Amount Friend Request To Number Of Amount Friend Request To Number Of 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 299 299 minimum ex they can make the thing and co minimum 2420 That I Don't See 2420 That I Don't See 2420 That I Don't See The Thing For Its Soldiers Log In The The Thing For Its Soldiers Log In The Next Twenty Let Me Yes Yes OK Sir Next Twenty Let Me Yes Yes OK Sir No Data Entry if you liked The Video then subscribe to the Page if you liked The Video then subscribe to the Page if you Just AN About Your Data Entry About Your Data Entry About Your Data Entry Awards File OK Just Not During Early Awards File OK Just Not During Early 5.35 Is Minimum Three Minimum Right 5.35 Is Minimum Three Minimum Right Side Brightness Minimum Three Years Now Let Side Brightness Minimum Three Years Now Let Us Look At The Next Example Celebrate All This Us Look At The Next Example Celebrate All This School E Look At The Next School E Look At The Next Examples In The Next Example Of How To Make Examples In The Next Example Of How To Make 6 And 6 And 6 And To Rupees Coin And Don't War To Rupees Coin Slice Updates That Used ₹2 Youth To * War ₹2 Boys Don't See The Sorry Itna War ₹2 Point Pregnant Whats - 247 To make To make To make for rupees in minimum number of wages to for rupees in minimum number of wages to celebrate this particular day 2018 201 celebrate this particular day 2018 201 plus to three light on trees to connect with plus to three light on trees to connect with just look at the data entry now after just look at the data entry now after suicides 5.1 plus to three lenders sorry suicides 5.1 plus to three lenders sorry sorry for this I do and clear sorry for this I do and clear that that that 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 Key Key Key Point Feeling Dubitable Laddu Then Last Point Feeling Dubitable Laddu Then Last One Piece Leave It's Not Tried Everything From Left 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 ₹ Take me to Rupees during and from the same point of Take me to Rupees during and from the same point of ignorance I can not go for a greater than these ignorance I can not go for a greater than these leaders will be updated with one similar to the extent to make leaders will be updated with one similar to the extent to make creative things creative things for Rupee coins so glad that uses for a better way than for Rupee coins so glad that uses for a better way than you can use of Rupees you can use of Rupees you can use of Rupees Rupees Data Entry About Soldiers Killed To That I Will Go To The Native Under Its 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 Zoom ₹1000 Users Have To Use One Coin Turing ₹1 And Refine Used For Pyun Hai ₹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 Next 5 And I Am Who Is To 5 And I Am Who Is To 5 And I Am Who Is To Make Hussain Andar Love ₹10 Note Make Hussain Andar Love ₹10 Note Slapped In File Path To File Duty Sunao Slapped In File Path To File Duty Sunao Is Used For Rupee Coins In What They Say For Means 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 Front Front Part - 01 2013 Front Front Part - 01 2013 Ko Sukoon Deti In Ko Sukoon Deti In Ko Sukoon Deti In 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 for rupee coins with me soft mix rupee manav rupee coin her loud rupee coin 50.75 Using This For Rupees 50.75 Using This For Rupees 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 ₹2 Super Kings To Live With News24Online ₹2 Super Kings To Live With News24Online Three Minimum Of Two Three Minimum 232 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 A vector vector in deposit and withdrawal length and A vector vector in deposit and withdrawal length and A vector vector in deposit and withdrawal length and breath of the so let's check breath of the so let's check verses also appoint size plus one light verses also appoint size plus one light point size plus one white widow decide point size plus one white widow decide plus 151 the0 what is the role servi size plus 151 the0 what is the role servi size three years in this nation and have a feeling three years in this nation and have a feeling one and half one and half one and half 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 For For For Data Entry Will Get To Know What Will Be The Data Entry Will Get To Know What Will Be The First Infinity Var In Mid Point Amazon 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 I Am In Exam Plate Workshop For Equal To Holidays Equal To One So Equal Equal To Holidays Equal To One So Equal To One To High Court To One To High Court To One To High Court point is equal to zero I love you my plus feeling defeated love som one Roe and the Olympians to of Roe and the Olympians to of Roe and the Olympians to of Shravan equal to one year and he also liked they were Shravan equal to one year and he also liked they were fighting from one request fighting from one request for 1000 to 1500 for the role of York for 1000 to 1500 for the role of York State in the native and for starting State in the native and for starting from one or two from this person avoid from one or two from this person avoid subscribe and subscirbe water for subscribe and subscirbe water for example example example 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 - He - He - He Bigg Boss Setting of the First President of the Great Need to Look for Example of Equal I - One Who Can Do Do Do Do Do Do News of Your Destinations Data Entry From About His Future Point You How to Write Way IS TAKING PLACE WHAT YOU ARE IS TAKING PLACE WHAT YOU ARE IS TAKING PLACE WHAT YOU ARE DOING THIS YOU ARE LOOKING AND DEFEATED DOING THIS YOU ARE LOOKING AND DEFEATED LOOKING AFTER EMINENT TAMAL SWORDS WITH LOOKING AFTER EMINENT TAMAL SWORDS WITH 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 DURING THE COURSE OF - 100TH COMMENTS DURING THE COURSE OF - 100TH COMMENTS FOR EXAMPLE IN THE CASE FOR EXAMPLE IN THE CASE FOR EXAMPLE IN THE CASE Person Nomination For Adding One Point For Making The Way To Make To Make To Delhi Delhi To 16 To You Is Particular Person Person Ko Simro Ni Bullet Modified Minus Point Of Time - Coins of I - One is - Coins of I - One is - Coins of I - One is just for two years ago when this ended but not everyone can do just for two years ago when this ended but not everyone can do the last leaf - - - - - - - - - - Not possible to make a particular amount from this point will return - 110 subscribe 1000 City 110 Points Saver Mode 1000 City 110 Points Saver Mode 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 Call The Return Minus One Mist - Which Otherwise Can Call The Return Minus One Mist - Which Otherwise Can Reduce - Verb - Reduce - Verb - All Updates to 121 Civil Work and Languages ​​The Keep It's Working Switch to Work in Languages ​​Submit Switch to Work in Languages ​​Submit Switch to Work in Languages ​​Submit WILL WORK IN PROTEST AS A QUESTION ACCEPTED SOLUTION THANK YOU FOR
2024-03-24 10:27:59
322
https://i.ytimg.com/vi/j…axresdefault.jpg
Leetcode 322. Coin Change #Leetcode #322 #Amazon interview || Code + Explanation
zxv-0dOv-Lg
okay so lead code practice time so the question is friends of so the question is friends of appropriate ages so the two goals the appropriate ages so the two goals the first one is to see how to solve this first one is to see how to solve this problem then we are going to put some problem then we are going to put some some code here and the second one is to some code here and the second one is to see how to solve this problem in the see how to solve this problem in the real interview so 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 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 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 the friend request so let's take 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 one or more than one person one or more than one person in the age group so in the age 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 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 um i would say um i would say the individual person uh in this the individual person uh in this this question doesn't really matter it this question doesn't really matter it is more about the age group is more about the age group so first of all i was i would have a map so first of all i was i would have a map so the the the key of the map is going so the the the key of the map is going to be the age to be the age and the value is going to be the number and the value is going to be the number of people of people with this edge and then we are going to with this edge and then we are going to have a for loop with the another volume have a for loop with the another volume to it right through the map to it right through the map and then we are going to do the and then we are going to do the computation to computation to um to see uh how many friend um to see uh how many friend requests there are in total requests there are in total so the runtime so the runtime first of all we would need to go first of all we would need to go through the input h group through the input h group so it is going to be oliven and then so it is going to be oliven and then it's a follow pd another for loop it's a follow pd another for loop on top of this hash map uh remember that on top of this hash map uh remember that the age is the aegis fanat the age is the aegis fanat is is it is an infinite so it it has is is it is an infinite so it it has a certain range um so a certain range um so in this case uh i would say we can say in this case uh i would say we can say that that as as cons as constant as as cons as constant for the next for loop on top of this map for the next for loop on top of this map but but also we could say but 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 for the next round so in total it will be something like so n represents a length of the 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 turn the edge input array into a hashmap so it will be integer integer so this says age uh counts hcon so h as new so in isaac so so in isaac so into age in the ages into age in the ages so age counts so age counts that puts h 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 let's say in age let's say in age one uh let's say h one uh let's say h a for age count a for age count dot key set and then or into age b so if it is if we have already so let's say if we if we have already so let's say if we have already saying the have already saying the h5 so for each age we are going to see h5 so for each age we are going to see all the other edges all the other edges um yeah so because um yeah so because a can send a request to b and b can send a can send a request to b and b can send the request to a the request to a and the two requests are trade as and the two requests are trade as separate separate um yes so um conduct key set as well so here we need to use the 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 count a as h count target count a as h count target h a is count b h a is count b h count dot get h count dot get hb so hb so uh if h aj is equal to hb uh if h aj is equal to hb so we are actually looking at so we are actually looking at uh so we it would be something like uh so we it would be something like count a count a minus one times count a in this group minus one times count a in this group so it's like it's like so it's like it's like um everyone uh within this group um everyone uh within this group can send a friend request to can send a friend request to to the others um so we still need to the others um so we still need h counted and count b so h counted and count b so we need to send compute the we need to send compute the the the relationship so you say the the relationship so you say uh if uh if not can be friend not can be friend uh h a and h b uh h a and h b then you're just going to continue then you're just going to continue so we are going to define other helper so we are going to define other helper function function let's say say boring between boring let's say 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 otherwise uh if it is not equal if the h otherwise uh if it is not equal if the h is not equal then it is not equal then it is gonna be everyone from is gonna be everyone from age a send a friend request age a send a friend request to the people with the hp so it's gonna to the people with the hp so it's gonna be be count a times count b count a times count b yeah so yeah that's that's mostly about yeah so yeah that's that's mostly about it and finally we just 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 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 uh the can be friend helper function uh the can be friend helper function so it will not be friend so it will not be friend req i will not send friend request to be req i will not send friend request to be if any of the following conditions are if any of the following conditions are true true so let's say if h so let's say if h b is smaller or equal to b is smaller or equal to 0.5 times h a 0.5 times h a and then plus seven then you're just and then plus seven then you're just going to going to continue sorry uh you're just going to continue sorry uh you're just going to return return a false so if a false so if h b is larger than h a then you're going h b is larger than h a then you're going to return to return a false and 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 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 you can introduce some other test cases to increase the test coverage so let's 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 and then um you're going to iterate and then um you're going to iterate through the age count map through the age count map so so mathematically says that so so mathematically says that one oh sorry uh 17 can be one oh sorry uh 17 can be can be friend of for 16 and 18 can be can be friend of for 16 and 18 can be friend of friend of first 17 so when we are at 16 first 17 so when we are at 16 so that can be friend will never give so that can be friend will never give us a true so when we are at 17 us a true so when we are at 17 assuming that 16 uh assuming that 16 uh is can be friend and then we get the is can be friend and then we get the number of people from 16 number of people from 16 age group uh which is one age group uh which is one and from 17 it is one so request plus and from 17 it is one so request plus equal to one equal to one and similarly for 18 when aj is and similarly for 18 when aj is 18 um only when hp is 17 a satisfied 18 um only when hp is 17 a satisfied condition for can be friend then we go condition for can be friend then we go going to plus one so request is going to going to plus one so request is going to be two be two finally and finally and let's see the example one so for example let's see the example one so for example one we are going to have 16 one we are going to have 16 and two so it could be friends then we and two so it could be friends then we are going to get count a are going to get count a and count b both are equal to and count b both are equal to so you're going to say request plus so you're going to say request plus equal to this is one equal to this is one times two so request is equal plus equal times two so request is equal plus equal to two so it requires me you're going to to two so it requires me you're going to return two finally return two finally so i think it mostly looks good um let's so i think it mostly looks good um let's uh give it a try uh give it a try all right so it's good let's give it a 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 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 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
2024-03-22 14:32:23
825
https://i.ytimg.com/vi/z…axresdefault.jpg
Facebook Coding Interview Question | Leetcode 825 | Friends Of Appropriate Ages
sw4mNP23-v0
welcome to october sleep code challenge today's problem is serialize and today's problem is serialize and deserialize bst deserialize bst serialization is converting a data serialization is converting a data structure or object into a sequence of structure or object into a sequence of bits so that it can be stored in a file bits so that it can be stored in a file or memory buffer or memory buffer blah blah blah design an algorithm to blah blah blah design an algorithm to serialize and deserialize a binary serialize and deserialize a binary search tree search tree there is no restriction on how your there is no restriction on how your algorithm should work algorithm should work you need to ensure that a binary search you need to ensure that a binary search tree can be serialized to a string tree can be serialized to a string and this string can be deserialized to and this string can be deserialized to the original tree structure the original tree structure so the input is guaranteed to be a so the input is guaranteed to be a binary search tree binary search tree so that helps obviously here is an so that helps obviously here is an example binary search tree example binary search tree and you can see that the input is given 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 format format where it's going to be five three seven where it's going to be five three seven one four one four but when we serialize it we can only but when we serialize it we can only traverse the binary traverse the binary search tree in three ways we could search tree in three ways we could either go in order which would end up either go in order which would end up being like one being like one three four five seven uh we can go three four five seven uh we can go post order which would end up being like post order which would end up being like one four three one four three seven five or we can go pre-order which seven five or we can go pre-order which would be like five would be like five three one four seven so i think 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 you can make post-order work as well you can make post-order work as well by going backwards with our list but by going backwards with our list but that kind of gets confusing with the 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 will work fine so let's go to the will work fine so let's go to the notepad and think about notepad and think about how we might do this say we had how we might do this say we had my example and we had the numbers 5 my example and we had the numbers 5 5 3 5 3 7 one four 7 one four and if we visualize to that it would 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 would it look like well we can create a list going in 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 so five and now as long as the number so five and now as long as the number that comes after is less than the number that comes after is less than the number that we just entered we would know it that we just entered we would know it move it to add to the left move it to add to the left right so this can go on for a long time right so this can go on for a long time like five three as long as the numbers like five three as long as the numbers decreasing decreasing it's only when the number is increasing it's only when the number is increasing here that we need to start moving to the here that we need to start moving to the right so right so we move four here to the right we move four here to the right so that sounds pretty simple enough but so that sounds pretty simple enough but there's a problem here there's a big there's a problem here there's a big problem actually problem actually which is well how do we know which node which is well how do we know which node to add this right side to to add this right side to left side is easy as long as the number left side is easy as long as the number is smaller we can just go left is smaller we can just go left left all the way but what about the left all the way but what about the right so i mean say we had an example right so i mean say we had an example like 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 and the number below that would be the 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 so every time we add to the left we will so every time we add to the left we will check to see if check to see if it is within our bounds and we first go it is within our bounds and we first go to the left side to the left side all the way up until like we find that all the way up until like we find that it's no longer it's no longer in the bounds here so with eight we'll in the bounds here so with eight we'll see clearly that see clearly that okay it's not within you know um okay it's not within you know um five to whatever none here it's not five to whatever none here it's not going to be in here so we check here going to be in here so we check here is it within seven and one no it's not is it within seven and one no it's not here ten and five oh yes it is here ten and five oh yes it is add it there so knowing that add it there so knowing that then we can realize we need to store then we can realize we need to store some sort of upper and lower bound some sort of upper and lower bound and just move through our list 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 right so what we can do is start with a self variable and we'll call this lst make and we'll create a function called the and we'll create a function called the first search first search where we pass in the node so this is where we pass in the node so this is pretty standard if not node pretty standard if not node we simply return otherwise we add 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 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 put commas in between our integer values put commas in between our integer values and we will say and we will say join these values we need to convert join these values we need to convert them into back into a string or we need them into back into a string or we need to convert these integers to a string to convert these integers to a string so i guess we can say map 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 this string okay so let's make sure this this string okay so let's make sure this works i'm just going to print the data works i'm just going to print the data here here which should be a string and this which should be a string and this should look like just a bunch of commas should look like just a bunch of commas um um that did not work function and there we go this is my standard out 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 to split this into a list and we want to to split this into a list and we want to reconvert these back into integers right reconvert these back into integers right so so for data in data split for data in data split we will convert this into an integer our list so now we have it back into a our list so now we have it back into a list list so this is the part that's going to be so this is the part that's going to be hard we need to write some sort of hard we need to write some sort of recursive function recursive function that's going to pass in the list as well that's going to pass in the list as well as the lower as the lower and upper bounds and in the very and upper bounds and in the very beginning our lower and upper bounds are beginning our lower and upper bounds are going to be infinite it'll be going to be infinite it'll be negative infinity and infinity that way negative infinity and infinity that way we know we can always add it we know we can always add it okay so the first thing we need to check okay so the first thing we need to check is some base cases is some base cases if not list if there's nothing there if not list if there's nothing there obviously just return nothing return obviously just return nothing return none now we need to make sure none now we need to make sure this value is within our range this value is within our range and we have our list so it's going to be and we have our list so it's going to be the first value in there the first value in there so what we'll say is if not say lower so what we'll say is if not say lower list that value and i believe this is list that value and i believe this is now an integer 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 the root.right it's going to be the and the root.right it's going to be the same same we thing in our list but instead of this we thing in our list but instead of this lower bound lower bound being lower it's now going to be the being lower it's now going to be the root dot value 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 less because we're um less because we're um you know we're changing the upper bound you know we're changing the upper bound to a root value so as long as it's less to a root value so as long as it's less it's going to just continue going left it's going to just continue going left as soon as we find that that's not true as soon as we find that that's not true we'll start trying to check to the right we'll start trying to check to the right and add it to the right side and add it to the right side but we need to make sure that it's but we need to make sure that it's within the bounds of from our parent within the bounds of from our parent to our left child leaf node whatever to our left child leaf node whatever and if it's not then we'll just continue and if it's not then we'll just continue up the tree to see where we can add it up the tree to see where we can add it and because this is a binary search tree and because this is a binary search tree this works now we'll just say this works now we'll just say okay call our recursive function 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 all right so let's see if this works all right so let's see if this works and it looks like it's working so that's and it looks like it's working so that's great great uh there is one edge case here if we uh there is one edge case here if we pass in a blank pass in a blank list though i believe this airs out list though i believe this airs out because we try to convert because we try to convert empty strings into integers so just to empty strings into integers so just to com just to take care of that com just to take care of that we'll say if not blank string then just we'll say if not blank string then just return return that should take care of that and there we go now in terms of time and there we go now in terms of time complexity complexity this is an o of n solution we this is an o of n solution we move as many nodes as there are move as many nodes as there are we could have first thought to add we could have first thought to add null values to the children to kind of null values to the children to kind of like keep the whole structure but that like keep the whole structure but that is very inefficient and really doesn't is very inefficient and really doesn't take advantage of the fact that this is take advantage of the fact that this is a binary search tree a binary search tree so this um is probably the best way to so this um is probably the best way to do it and do it and this definitely wasn't an easy algorithm this definitely wasn't an easy algorithm this is pretty hard to come come up with this is pretty hard to come come up with but hopefully but hopefully this helped thanks for watching my this helped thanks for watching my channel and remember do not trust me channel and remember do not trust me i know nothing
2024-03-22 12:54:33
449
https://i.ytimg.com/vi/s…v0/sddefault.jpg
Leetcode - Serialize and Deserialize BST (Python)
4MU3cn_nAQQ
Hello everyone so today we will be discussing question number 203 of lead code which is question number 203 of lead code which is removed link list elements ok so removed link list elements ok so this one is the problem right this is a this one is the problem right this is a part of my recurring playlist and this is an easy part of my recurring playlist and this is an easy problem so what will be its flow that problem so what will be its flow that first of all first of all first of all 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, So let's see what is there So let's see what is there So let's see what is there in this question, so what is told to us in this question in this question, so what is told to us in this question that like this that like this node with six has to be removed, just don't do anything else, node with six has to be removed, just don't do anything else, this six has been given, they have given a value this six has been given, they have given a value whose value is in it. whose value is in it. whose value is in it. 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 And it is And it is And it is ending here, now here is ending here, now here is my well, which node I have to remove, that well is my well, which node I have to remove, that well is my four, so it my four, so it means I have to remove this and this node, means I have to remove this and this node, okay, so to remove the node. okay, so to remove the node. What is the method in this, it means What is the method in this, it means how do we remove the node in the Ling list. how do we remove the node in the Ling list. Removing the node in the Ling list is a very simple thing, Removing the node in the Ling list is a very simple thing, you just have to change the address. Okay, so you just have to change the address. Okay, so here if you look at the Ling list, like here if you look at the Ling list, like this cross B, this is its this cross B, this is its this cross B, this is its 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 If If If I remove this address, this pointer will also be removed. I remove this address, this pointer will also be removed. Okay, this arrow will also go away Okay, this arrow will also go away and what I will do is I will and what I will do is I will 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? which is the cross, so what is it doing now? It is pointing to this. It is pointing to this. It is pointing to this. 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 If I want to remove it, If I want to remove it, If I want to remove it, I have updated its address, I have updated its address, how did how did I update it, what will I put here, this will come to my e, so now I update it, what will I put here, this will come to my e, so now it is pointing to this, okay and if it is pointing to this, okay and if I remove this, I remove this, then my updated then my updated then my updated 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, I I I don't have to delete it. To delete it, I should have the information about its previous node 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 its next, that means I have to put a cross C, I have to put its next in the next 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, information about the next one, I also have the information about the next one, but there is but there is no information about the previous one, there is a link in the after, no information about the previous one, there is a link in the after, you will have to create a separate variable for that, you will have to create a separate variable for that, it will be a little Let me Let me Let me check its value because look, I have this check its value because look, I have this CRR, I have its next CRR, I have its next information available, its next information is also information available, its next information is also available, so with this I have the available, so with this I have the information of all three notes available, information of all three notes available, so I check the value of current dot next. 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 This is the current of next. This is the current of next. This is the current of next. What is stored in its next. What is stored in its next. Cross C right. This is what we have to store 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 because we do not want this current dot next. Now it is not here. here. Before this, there was B here. Before this, there was B here. Now we have to store Before this, there was B here. Before this, there was B here. Now we have to store that. that. that. dot next, what is 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, The The The problem is that we are problem is that we are ignoring the first element, here we are ignoring the first element, here we are starting from its second element, it is the starting from its second element, it is the first element which is ours, we first element which is ours, we gave it to it, we did not see its value, so gave it to it, we did not see its value, so we start directly from the second element. we start directly from the second element. we start directly from the second element. 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, I will I will I will do it but I hope you have understood the concept of what do it but I hope you have understood the concept of what I am trying to do, that is, I am trying to do, that is, this is the this is the right one, this is the crux of this algorithm, there is nothing else right one, this is the crux of this algorithm, there is nothing else in it, we just in it, we just code it. code it. code it. 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 That's two, isn't it? That's two, isn't it? That's two, isn't it? Now you see, the first three Now you see, the first three elements here are the same two, so in the elements here are the same two, so in the algorithm I just discussed, I am checking na dot next, which algorithm I just discussed, I am checking na dot next, which means I am means I am checking this element, then checking this element, then after that, then again. after that, then again. after that, then again. 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 I know 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 It is It is It is okay that the first element is okay that the first element is not equal to the well, if it is, then not equal to the well, if it is, then remove it, okay, we will keep doing this until remove it, okay, we will keep doing this until it is not equal to the well, so it is not equal to the well, so what we will do to deal with this is to what we will do to deal with this is to put a check in the beginning itself. put a check in the beginning itself. put a check in the beginning itself. element is equal to well then remove it, then go to the next element, if it is also equal to well, then remove it, then go to the next element, if it is also Now my Now my Now my head is pointing here, head is pointing here, my algorithm will start from here, my algorithm will start from here, right? Because see, the first element was missing, so I am putting this right? Because see, the first element was missing, so I am putting this check. check. Okay, so I am putting this check. I will Okay, so I am putting this check. I will head head and end E equal to well E equal to well E equal to well sorry okay so as long as it's like this so as long as it's like this next okay meaning I'm going to move the head forward next okay meaning I'm going to move the head forward so let's do like this if so let's do like this if it skips 2 2 2 and goes to three. it skips 2 2 2 and goes to three. Now from here I will start my algorithm. Now from here I will start my algorithm. Okay, so I take one item Okay, so I take one item because I need one item to because I need one item to implement my entire algorithm. implement my entire algorithm. Okay, here si RR will be Okay, here si RR will be equal to head head. Here head is now. equal to head head. Here head is now. equal to head head. Here head is now. 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 Four, Four, Four, here we have to remove four, okay, here we have to remove four, okay, so now the current is pointing to which head, which one, so now the current is pointing to which head, which one, is it pointing to this head, or is it pointing to this two, 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, What are you doing? What are you doing? 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, will check the value of current dot next. According to my algorithm, if this becomes null then my code can break, so for that if this becomes null then my code can break, so for that I I I 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 will run, okay, now this is my while loop has started, What did I do if that was my check What did I do if that was my check 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 Now look at whom my current dot next is pointing to. What does the current dot next mean? I am pointing to. What does the current dot next mean? I am checking this, I am checking this, I am checking the value of this, not the current dot. checking the value of this, not the current dot. checking the value of this, not the current dot. 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 okay, current off next dot next If If 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 Which Which Which is next to four, which is five is next to four, which is five here, you will assign it to the next of three 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 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. straight ahead but here. straight ahead but here. 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 sorry, not here. 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 The code is now The code is now The code is now in this item code, from here let's try to make my recursive. in this item code, from here let's try to make my recursive. Now Now what I told about recursive is that firstly the base condition is very what I told about recursive is that firstly the base condition is very important, firstly our recursive relation important, firstly our recursive relation is very important and thirdly what is the is very important and thirdly what is the task which I have to perform. task which I have to perform. Okay, after the recursion relation, and the base Okay, after the recursion relation, and the base condition, now here what is the base condition, now here what is the base condition, you can derive from here this while condition, you can derive from here this while current and current dot next is not current and current dot next is not equal to null, how can you derive the base condition, you think, Smollett valid Is it Smollett valid input? What can happen Is it Smollett valid input? What can happen Is it Smollett valid input? What can happen that brother, which is your node, which is your node, it becomes null? If brother, if it is a null node, what will you return? What will you return? What will you return? You will return nothing. Yes, you are the You are checking that the while loop will You are checking that the while loop will You are checking that the while loop will continue till current dot next is reached continue till current dot next is reached because our focus here was on because our focus here was on current dot next current dot next because we because we are looking for the value of current dot next, the value of current dot next, so are looking for the value of current dot next, the value of current dot next, so whatever. whatever. 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, If dot If dot If dot next is not null then we next is not null then we will run the loop till then. As soon as the current dot next is 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 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 same is true for the receiver too. When do we have to end it when our node is the one with which we are when our node is the one with which we are dealing. dealing. dealing. 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 tap We will tap We will tap because the head tap has already been done so this will because the head tap has already been done so this will be our stopping condition. So, our be our stopping condition. So, our base is fixed. The base condition is fixed. base is fixed. The base condition is fixed. Now we have the example. Now we have the example. 4 5 4 Okay, so what will I do? 4 5 4 Okay, so what will I do? Here I will take this element, I will take this node, this Here I will take this element, I will take this node, this node, I will take this two node node, I will take this two node and the recursive relation will be and the recursive relation will be called on the remaining link list and from what I will called on the remaining link list and from what I will say, I will infer that the say, I will infer that the remaining link list will be remaining link list will be to me. Okay, I will tell the function that brother, the first 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 remove those elements from the remaining link list and give it to me. I will just attach two to it. attach two to it. attach two to it. I give it, the function said, okay, I will do all that, but what if your node is equal to the value, what if what if your node is equal to the value, what if it So you So you So you said, brother, don't take tension about four, take said, brother, don't take tension about four, take tension about the remaining penis list, remove four from it and give it to tension about the remaining penis list, remove four from it and give it to my butt and then to yourself. Function again my butt and then to yourself. Function again said, brother, you also have said, brother, you also have four, what will you do with it, so you four, what will you do with it, so you Told him again that brother, if the Told him again that brother, if the value of the node I have is equal to well, 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 give it. Do you understand, otherwise I will return it as it is, meaning see what was here earlier 2. what was here earlier 2. what was here earlier 2. 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 Returned Returned when 35 was returned and I when 35 was returned and I attached two to it and got it returned, okay now attached two to it and got it returned, okay now this is my four here, this is my four here, okay I got released [ __ ] man, this is okay I got released [ __ ] man, this is four, I can't return this, four, I can't return this, so this is not the answer so this is not the answer so this is not the answer 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 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. Answer: I will not return it, I Answer: I will not return it, I Answer: I will not return it, I will not attach it to my one, will not attach it to my one, but if it is not equal to it, then I but if it is not equal to it, then I will attach it to my one and give it to him. will attach it to my one and give it to him. This is our task. This is our task. If you understand, then our recursive save relation is done. Our task is done The base condition is done, so now we are ready to code it. Let's The base condition is done, so now we are ready to code it. Let's The base condition is done, so now we are ready to code it. Let's write it quickly write it quickly because it is a very small code. because it is a very small code. Okay, so let's quote it quickly. Okay, so let's quote it quickly. First of all, what will I write? My base First of all, what will I write? My base condition is okay. What is the base condition? condition is okay. What is the base condition? condition is okay. What is the base condition? head is equal to null then return null, okay, now what will happen to me here, I will see the recursive relation, 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 How will How will How will my code look like Head my code look like Head of of Sorry Head of Next is equal to Sorry Head of Next is equal to remove element Remove remove element Remove element Remove element and what will I element Remove element and what will I send in it Smaller input Head of Next send in it Smaller input Head of Next I sent the remaining list I sent the next remaining I sent the remaining list I sent the next remaining list and well it will list and well it will remain the same Okay now here remain the same Okay now here remain the same Okay now here 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 If yes, then simply return the head, 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 Ok now let's submit it and Ok now let's submit it and Ok now let's submit it and see if see if it is submitted then you must have understood what it is submitted then you must have understood what I am doing, here I am doing, here how we are converting an IT problem to recursive how we are converting an IT problem to recursive and how small it and how small it is becoming by thinking recursively. is becoming by thinking recursively. is becoming by thinking recursively. understood it well and see you in the next video. Thank
2024-03-22 09:48:30
203
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode 203: Remove Linked List Elements | Intuition and Approach | Iterative + Recursive
NMhmTC88HJs
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 plus, whatever you have learned, This program must have been made 100% by myself, This program must have been made 100% by myself, This program must have been made 100% by myself, then I saw this program in the delete code then I saw this program in the delete code and it was in the starting itself, and it was in the starting itself, so I thought let's do this also first, so I thought let's do this also first, easy level is difficult, the question is easy level is difficult, the question is first, what is a drone, I am getting talent, I first, what is a drone, I am getting talent, I hope you all. hope you all. hope you all. 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 Read Read Read this too, you too, one, you one, read from the back, even then, this too, you too, one, you one, read from the back, even then, one, one, one, and here is an example that it one, one, one, and here is an example that it is okay to race, is okay to race, if if you read from the front, it is okay. If you read from the back, it is okay to race. This is an example 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. in the spring. in the 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 What I am doing here is What I am doing here is What I am doing here is my number here in Max which is my number here in Max which is 121, I am modeling it here, 121, I am modeling it here, modules means here we modules means here we understand with a simple logic, in second class or understand with a simple logic, in second class or third class you have learned to divide a. third class you have learned to divide a. How do we divide a number? How do we divide a number? Okay, so here I am dividing 121, Okay, so here I am dividing 121, here it is okay by 10, one is gone, 10 is gone here, here it is okay by 10, one is gone, 10 is gone here, okay you are here, one is gone here, one is gone here, okay you are here, one is gone here, one is gone here, you are D, how much is it? you are D, how much is it? you are D, how much is it? 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 what do I have here, I have what do I have here, I have 121 here, I have 121 here, I have 121 here, I have 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, Let's take it Let's take it Let's take it and if and if it breaks here in the Ara of characters, after that we put a it breaks here in the Ara of characters, after that we put a loop here and by putting a loop loop here and by putting a loop here we check the first number with the last number here we check the first number with the last number whether the Eric of the first whether the Eric of the first digital is the Erica. digital is the Erica. digital is the Erica. it equal? ​​If it is equal, then extend this here, 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, I plus plus here I plus plus here I plus plus here you did K mines mines till then you have to you did K mines mines till then you have to expand it here and reduce it till it becomes I. If it does expand it here and reduce it till it becomes I. If it does n't cross here then it would have n't cross here then it would have removed these how off strings removed these how off strings are okay but what do I have here. are okay but what do I have here. But wait, there is a number, now I have to find But wait, there is a number, now I have to find each element of the number, how will it each element of the number, how will it come out, it will come out from the modules, you come out, it will come out from the modules, you see here, like I did the modules of 121 here, so I have see here, like I did the modules of 121 here, so I have one A here, one A here, first I have a digital A. first I have a digital A. first I have a digital A. 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 When I When I When I divided divided 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 will do it but this time I will do it but this time I will do it but this time in 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 Next it will go to a reminder, so what will happen in this how will this 10 be zero, how much will it in this how will this 10 be zero, how much will it become, it will be zero here, okay one, become, it will be zero here, okay one, I have a reminder here, so what is there I have a reminder here, so what is there in tempo, what is your one in tempo, in tempo, what is your one in tempo, your one is here in your one is here in If I get the sum from zero here, I already have If I get the sum from zero here, I already have 12 in it, then it is 12 * 10, 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 It's a simple It's a simple It's a simple logic, so this is a very good method, logic, so this is a very good method, meaning it will come to you in future too, if meaning it will come to you in future too, if you have this train, okay, you have a you have this train, okay, you have a string here, how will it come, I will string here, how will it come, I will tell you here if you have a tell you here if you have a string. string. string. 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 You have to pick only You have to pick only You have to pick only one element of the wait because as soon as one element of the wait because as soon as it gets converted here, you it gets converted here, you can pick one element of it, but can pick one element of it, but how will you do the wait, this method is taught to us from the very beginning You must have You must have You must have started programming in college, you must have started from started programming in college, you must have started from first air to second air, whenever first air to second air, whenever you have created it in the very beginning, you have created it in the very beginning, first in D is number and it is first in D is number and it is okay, like palindrome is okay, like palindrome is okay, factorial is okay and okay, factorial is okay and Fibonacci series is okay, so these are some Fibonacci series is okay, so these are some Fibonacci series is okay, so these are some 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 If If If you see its logic here then it is good, you see its logic here then it is good, here we are searching the numbers one by one from here onwards, here we are searching the numbers one by one from here onwards, we have we have created the same number again and again here we will check created the same number again and again here we will check whether this number till the original number here whether this number till the original number here or that number. or that number. or that number. 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, 0, 0, 0, I have put it here, okay, the same way, 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 okay, so if it is equal to this, then it will obviously return true, It's It's It's not sure, he will do it playing then it's ok, I submitted it playing then it's ok, I submitted it and the result is very correct, and the result is very correct, 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 taken it from nine and have beaten 99.32%. taken it from nine and have beaten 99.32%. taken it from nine and have beaten 99.32%. question must have been cleared. If you have any butter solution then
2024-03-19 12:14:29
9
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode Problem: 9. Palindrome Number | Java Solution
9nKsH6T9cag
A Heaven President will take according to the channel, that question is account number of consistent question is account number of consistent subscribe then what is this question saying, subscribe then what is this question saying, first what will I do read the question now first what will I do read the question now what am I doing now friend my what am I doing now friend my question craft so that you can practice question craft so that you can practice in this palace in this palace in this palace 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 That was that you will have to That was that you will have to That was that you will have to think yourself that how can you approach this? think yourself that how can you approach this? White then this question must have been tried for biopsy. White then this question must have been tried for biopsy. If not dry then please If not dry then please like it. Then you can set it on video and like it. Then you can set it on video and many more must have happened. Heroine keep watching my tablets to see whether many more must have happened. Heroine keep watching my tablets to see whether this question is right. this question is right. Intermediate is used in many places because Intermediate is used in many places because what are we thinking in this that it takes what are we thinking in this that it takes more quantity to enter the question, it tastes good, it is more quantity to enter the question, it tastes good, it is very simple and the question is hello, very simple and the question is hello, what is the question saying, we have been given an award, what is the question saying, we have been given an award, that is also these words. that is also these words. that is also these words. 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, The same characters The same characters The same characters should be pregnant except the 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 ghr tk CC mein mein chale ka or beech nahi chalega BA will not chalaga chale ka or beech nahi chalega BA will not chalaga BSC will not chalaga BD will not chalaga BSC will not chalaga BD will not chalaga Aisi Aisi Chalega Aur DB Chalega Total Kitna Aisi 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 like this, now we like this, now we confuse you, what we used to think. Do confuse you, what we used to think. Do n't forget to subscribe. How can you do Subscribe to the trick, we can't decide that the Subscribe to the trick, we can't decide that the whole character has to be decided by tracking a world, understand this thing, tracking a world, understand this thing, you loot, there is no problem here, you loot, there is no problem here, now brother, like give us someone else's but will take it now brother, like give us someone else's but will take it like B.Sc. like B.Sc. like B.Sc. 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, So what So what So what is the point, now look, now you people is the point, now look, now you people cannot do this every time that you will make it drivers crores and one cannot do this every time that you will make it drivers crores and one senior vice president who travels, 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 make unwanted sets, this set needs tempered glass. tempered glass. tempered glass. 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 We We We also raised the issue of starting to drive it, asking whether also raised the issue of starting to drive it, asking whether you are also there or not, otherwise it is done, after 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, get AC, first they do Abhishek, they get SIM, then what to do, then what to do, commitment, overall what we got. commitment, overall what we got. commitment, overall what we got. 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, president of any subscribe and subscribe, that in this case, whatever it is, I have told whatever it is, I have told you that you do not need to use it. you that you do not need to use it. That we simple 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 we found out We know if there We know if there We know if there is a present, the present is different and is present, is a present, the present is different and is present, we should look at it, start looking and we should look at it, start looking and I equal G OLX in and half I equal G OLX in and half inch plus plus first character found inch plus plus first character found character temple character found word I to be character temple character found word I to be exactly like this so what is the president or exactly like this so what is the president or not 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 But But But brother, he is not worthy of you, will you be thrown out or will you be brother, he is not worthy of you, will you be thrown out or will you be shifted to another ward, shifted to another ward, as if we had the words that as if we had the words that directly lead, trick, play chief defect, directly lead, trick, play chief defect, then you are behind the gift tax, we will directly say these words: Oh wow, Ramla, set the alarm clock. wow, Ramla, set the alarm clock. wow, Ramla, set the alarm clock. CVD in the village this kind of this kind of problem problem problem problem subscribe has to be done that that Aishwarya more can message this for Aishwarya more can message this for all to were that Hansi Ko must have answered the Hansi Ko must have answered the whole whole question, and and that we are doing this very sentimental thing, it is very widely painted, even when everyone is undergoing treatment, the Karna for Karna for Karna for dayan adh world.com If we meter every actor of this award, world.com If we meter every actor of this award, then we could have put it here, we then we could have put it here, we checked that dot checked that dot wow and this is a wow and this is a no-no no-no daughter does daughter does not put that status, it is not put that status, it is assuming that he is liking the status. assuming that he is liking the status. increase our maji by subscribing to the total number of hits on WhatsApp status or subscribing to the total number of hits on WhatsApp status or subscribing to the war subscribing to the war but as soon as but as soon as this particular water is appointed, this particular water is appointed, what we will do is simply what we will do is simply pause the status clip and make it great. pause the status clip and make it great. Okay but if we do one then it will come out from the for form Okay but if we do one then it will come out from the for form just like the hair then we will just like the hair then we will put it below that if the status is still now if the status is put it below that if the status is still now if the status is still sorry stry still sorry stry vidru then simple simple what we vidru then simple simple what we because now till here because now till here because now till here 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 you are not subscribed then please subscribe this video. If you have subscribed our channel till now and I keep and I keep doing it together, then doing it together, then subscribe. [Music] Video song of Aur Video song of Aur Sunao Sunao Main Main Tera Amazon
2024-03-20 12:12:42
1,684
https://i.ytimg.com/vi_w…xresdefault.webp
Count the Number of Consistent Strings | Leetcode | Complete Full Tree Data Structure | Hello World
_XnO2Yrfhio
Are Hello Guys Welcome To Another Interesting Problem Industries According School Check Problem Industries According School Check Formation Cry Coordination Lecture Are Formation Cry Coordination Lecture Are Updating Teachers Are Three Fatty Dare Updating Teachers Are Three Fatty Dare Pieces Vendors In Peace And Established For My Pieces Vendors In Peace And Established For My Bay Contesting The Amazing Pieces In This Bay Contesting The Amazing Pieces In This However Not Allowed Studio Dealers In Which However Not Allowed Studio Dealers In Which Are Peace And Tours Are Peace And Tours Are Peace And Tours The Are From Teachers Were Written For Selected For Example In The First K Subscribe Our Are So It's After Peeth Subscribe 30 Please Subscribe Indian Subscribe 30 Please Subscribe Indian Channels Pe Channels Pe Problems Try To Understand As To If Problems Try To Understand As To If We Should The Amazing Which Have Right Nor Prabash We Should The Amazing Which Have Right Nor Prabash Se Zauq Sudhir They Have Nothing To Refill Se Zauq Sudhir They Have Nothing To Refill Element 100 OK Share and Subscribe Element 100 OK Share and Subscribe 602 subscribe The Channel Please subscribe 602 subscribe The Channel Please subscribe this Video Please subscribe and Ninth Fifty Shades of Fitting Par Click Here Voor Against Against Against Let's Move To The Lord Buddha Code And So Let's See Let's Move To The Lord Buddha Code And So Let's See What We Can Do And Ask What We Will Do It What We Can Do And Ask What We Will Do It Is Best Example Ke Sapoch Us Is Best Example Ke Sapoch Us Plu Cert 1234 For Him Raphael Plu Cert 1234 For Him Raphael December Wrong Are Supposed To Be Something Like 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 Vibrating over this will Vibrating over this will Vibrating over this will fight for winter index of the white fight for winter index of the white vinegar index of this to big boss winner too vinegar index of this to big boss winner too sided over and need to check the element in this are also going to sided over and need to check the element in this are also going to be equal to the be equal to the next index ok and see the limits to next index ok and see the limits to be the next Indian of be the next Indian of be the next Indian of For Example 2100 Against Tiffin To Three Look Do Subscribe My Channel Thank You Index Of Elements Indori Morning Previous Index Of Elements Indori Morning Previous Fields And Electrons To Understand This Fields And Electrons To Understand This Properly Switch 12345 Debit Creator Map Properly Switch 12345 Debit Creator Map So And * If Atom Of So And * If Atom Of So And * If Atom Of 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 find the length of the map champ * find the length of the map champ * find the length of the map champ * for example check the element 2012 - for example check the element 2012 - inside these 0512 we check the two elements on two inside these 0512 we check the two elements on two elements and seams to be next elements and seams to be next travel destination of maths y3 ladies travel destination of maths y3 ladies equal to and second list of pieces are equal to and second list of pieces are completed it's not 2362 celebrate servi 40 will return 2362 celebrate servi 40 will return forms will return all subscribe dispur otherwise forms will return all subscribe dispur otherwise return rule in this case ok i will return rule in this case ok i will call you have another case left right call you have another case left right same chord without another place value same chord without another place value system for slaps govardhan extra system for slaps govardhan extra part of the places f4 that is san tt part of the places f4 that is san tt Industry Suna Fold Excited Checking Industry Suna Fold Excited Checking After 10 Of These Taxes And I Will Check Puri After 10 Of These Taxes And I Will Check Puri Equal To For World Go To The Equal To For World Go To The Next9 Item White Sesame 125 Increase The End Next9 Item White Sesame 125 Increase The End Of The Places Where Is The Are And Hydrating Of The Places Where Is The Are And Hydrating Suggestion Defined But Reach Only In Place Of Suggestion Defined But Reach Only In Place Of The Fennel And The Fennel And The Fennel And 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 To give this broad hua tha main 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 Switch Switch Switch 72000 Is Vansh Opposite This Old World Which Will Find 72000 Is Vansh Opposite This Old World Which Will Find The Next Point Speaking Thoughts The Next Point Speaking Thoughts Matching Correctly In This Case Which Can Be Done Through So Let's Matching Correctly In This Case Which Can Be Done Through So Let's Get Started The Logic Get Started The Logic Eastern So Let's Get Started Eastern So Let's Get Started Implementation Of The World Map Map In Implementation Of The World Map Map In Comment And Vibrate Over All Elements Comment And Vibrate Over All Elements Comment And Vibrate Over All Elements 32.20 Reddy I Plus 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 That for you That for you That for you and water dries initially belongs to and water dries initially belongs to decide to entertain is equal to part size decide to entertain is equal to part size so will have between part size and also check so will have between part size and also check for the president of the first element of for the president of the first element of part to switch in its present at ward part to switch in its present at ward level to that somewhere in the distance map 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 to me to me you are aware boon elements present not particular are you are aware boon elements present not particular are ok 919 we start oil that ok 919 we start oil that waste oil waste oil that your I is going into villages and they will have to declare is that your I is going into villages and they will have to declare is winter is equal to winter is equal to zero morning sex zero morning sex zero morning sex of the past and also in to check ander inch the end of the race and Also Index Plus Plus And Also Index Plus Plus And Can Also Check Effigy Can Also Check Effigy That I Am Having Divya Sequel For Its Ok That I Am Having Divya Sequel For Its Ok Part Swift Of I Is Not Shrinking Part Swift Of I Is Not Shrinking Tours Of Index In Case Of Mind Values Tours Of Index In Case Of Mind Values Are Not Equal Daily Night K Cycle Are Not Equal Daily Night K Cycle Return Forms One Know Case When Will Return Forms One Know Case When Will Have To Have To coming out with a smile on being can also check this is not equal to coming out with a smile on being can also check this is not equal to part size his just is not equal to part size his just is not equal to partner with lots of this is not equal to and partner with lots of this is not equal to and switch board ke song for example switch board ke song for example also also also 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 Working the soldiers fine for this test case instead of stagnation between formal test cases such a practice solution thank you please like and
2024-03-19 15:52:44
1,640
https://i.ytimg.com/vi/_…axresdefault.jpg
Check Array Formation Through Concatenation
IOO7XoEDHOM
are you calling enthusiasts welcome back to another episode of Code Master Quest to another episode of Code Master Quest today we are diving into a drilling today we are diving into a drilling puzzle involving songs and some smashing puzzle involving songs and some smashing logic so let's get started and find out 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 to solve this question there is two to solve this question there is two different ways uh first you can make a different ways uh first you can make a while loop and while we have more than while loop and while we have more than one element inside the array we can sort one element inside the array we can sort the array and find the most heaviest the array and find the most heaviest element inside the array and then element inside the array and then perform the smash operation right but perform the smash operation right but for this solution we need to perform the for this solution we need to perform the search operation search operation each time but for the second option and each time but for the second option and time efficient option we can make a hit time efficient option we can make a hit and use a heap data structure to perform and use a heap data structure to perform the smash operation right so now let's the smash operation right so now let's define the function signature and then define the function signature and then solve this question with a heated solve this question with a heated structure and if you're interested in structure and if you're interested in the implementation of hip in Surf you the implementation of hip in Surf you can check the link in the description can check the link in the description below below now let me Define the function signature now let me Define the function signature here function last stone weight here function last stone weight then the input which is stones then the input which is stones array of integer and then integer array of integer and then integer there we go now let me come back to the there we go now let me come back to the browser and copy the implementation of browser and copy the implementation of my hip Direction structure in Swift from my hip Direction structure in Swift from this link you can find this link in the this link you can find this link in the description below also description below also so there we go I made a copy from it and so there we go I made a copy from it and let me come back here okay see just let me come back here okay see just right here right here okay okay since the data type of this element since the data type of this element inside the arrays in is integer we need inside the arrays in is integer we need to make a hip fit integer data type so to make a hip fit integer data type so let's say if our if let's say if our if and here for integer and it's empty body and here for integer and it's empty body now we need to make our here so let's now we need to make our here so let's say from Stone in stones say from Stone in stones hip dot insert hip dot insert let's stop there we go after this for let's stop there we go after this for operation this for Loop we will have our operation this for Loop we will have our heated structure heated structure you can find the definition of insert you can find the definition of insert function here in the hip data structures function here in the hip data structures now let me say a while now let me say a while keep elements we have an array of keep elements we have an array of elements here elements here you've got elements that count is you've got elements that count is greater than one then we should say if greater than one then we should say if let Y is let Y is keep remove we have the remove function keep remove we have the remove function here as well here as well and the return type for this remove and the return type for this remove function is optional right so we need to function is optional right so we need to unwrap it so let's say if let y equal to unwrap it so let's say if let y equal to heat dot remove and let x equal to heat heat dot remove and let x equal to heat plot remove again because we need to plot remove again because we need to have the have the heaviest element inside the uh here and heaviest element inside the uh here and then if then if X is not equal to Y then we should say X is not equal to Y then we should say Heap that insert Heap that insert uh y minus X right and at the end of uh y minus X right and at the end of this for Loop we are pretty sure that we this for Loop we are pretty sure that we have at most one element inside them have at most one element inside them right so at the end we need to return right so at the end we need to return Heap dot Peak Heap dot Peak and we should unwrap it because Peak and we should unwrap it because Peak function will return an optional data function will return an optional data type as well right so if it's empty we type as well right so if it's empty we should return zero based on the question should return zero based on the question description otherwise we will return the description otherwise we will return the last element inside last element inside this should be the correct solution for this should be the correct solution for this problem but to make sure about our this problem but to make sure about our implementation let's come back to the implementation let's come back to the browser and paste our implementation browser and paste our implementation here here and hit the subject button there we go here's the solution for this
2024-03-25 15:49:38
1,046
https://i.ytimg.com/vi_w…xresdefault.webp
Last Stone Weight - LeetCode 1046 - Swift
luWRwWO34D0
hey hello there let's talk about today's liquid and challenge question liquid and challenge question add digits giving a non-negative integer add digits giving a non-negative integer we want to repeatedly add all its digits we want to repeatedly add all its digits up up until the resulting number has only one until the resulting number has only one digit digit looking at the example we have the looking at the example we have the integer that's 38 integer that's 38 so we add all its digits up 3 plus 8 we so we add all its digits up 3 plus 8 we get 11. the output get 11. the output number is still not a single digit number is still not a single digit number so we have to repeat this process number so we have to repeat this process again again we add 1 and 1 we get 2 so the output is we add 1 and 1 we get 2 so the output is now a single digit number so the process now a single digit number so the process terminated terminated and we returned that as the output so and we returned that as the output so that's the question that's the question and the example and how the process and the example and how the process looks like looks like the brute force solution is basically to the brute force solution is basically to simulate this process simulate this process until the number has been transformed until the number has been transformed into a single digit number into a single digit number uh we have to repeat this sum replace uh we have to repeat this sum replace the number by its the number by its sum of its digits so let's just code 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 we can forget about this transformation otherwise we have to repeatedly transform the number by its sum of its so the function transformative formation so the function transformative formation function is to replace 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 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 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 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 10 number 10 is it's actually two digits 10 number 10 is it's actually two digits but if you take log 10 of 10 it's just but if you take log 10 of 10 it's just one so one so uh in that case you have to add one uh in that case you have to add one otherwise if like 20 or something otherwise if like 20 or something that's that should be one point that's that should be one point something if you take the ceiling it something if you take the ceiling it will become two that tells you the will become two that tells you the number of digits to learn so that's uh number of digits to learn so that's uh what this what this uh and roughly is is the total number of uh and roughly is is the total number of digits digits uh if we plug that if we look at the uh if we plug that if we look at the formula for f formula for f x uh summing up all the digits since x uh summing up all the digits since that every digit has to be that every digit has to be less than 10 otherwise it wouldn't be a less than 10 otherwise it wouldn't be a single digit single digit uh so this summation is actually upper uh so this summation is actually upper bounded by bounded by i just replace every digit with 10 so i just replace every digit with 10 so it's 10 multiplied by n it's 10 multiplied by n so adding the information about so adding the information about the number of digits uh we can see that the number of digits uh we can see that the series is basically having the the series is basically having the original input transform that into original input transform that into something that's less than 10 x something that's less than 10 x log 10 of x and the next log 10 of x and the next element in the sequence is log 10 element in the sequence is log 10 base 10 of that second term second base 10 of that second term second element in there element in there so it's repeatedly taking log 10. so the so it's repeatedly taking log 10. so the runtime complexity will be runtime complexity will be order of log log base 10 of x order of log log base 10 of x now so that shows how fast would this now so that shows how fast would this converge converge so this code here simulation so this code here simulation submit simulate will be in 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 we solve it without any loop or recursion in recursion in constant time so this is clear that constant time so this is clear that we we have to look up look for some kind we we have to look up look for some kind of pattern of pattern for this problem so for that reason for this problem so for that reason we're just going to we're just going to run this simulation process on a bunch run this simulation process on a bunch of numbers in sequence and of numbers in sequence and see can we find any kind of pattern in see can we find any kind of pattern in there so let's see how how it works just run this uh 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 it's not a code uh so let's add self so this is a number by running this so this is a number by running this simulation simulation add digital simulation on numbers from 0 add digital simulation on numbers from 0 to to 99. so zero will be transformed into 99. so zero will be transformed into zero one to one zero one to one two to two so below below ten uh two to two so below below ten uh for single digit number it's just the for single digit number it's just the number number itself number number itself from 10 it goes back to one uh one two from 10 it goes back to one uh one two three four five six three four five six seven eight nine nine and nineteen you seven eight nine nine and nineteen you become one again become one again and just if you keep looking and keep and just if you keep looking and keep looking looking uh it's repeating itself one two three uh it's repeating itself one two three four five six seven eight nine four five six seven eight nine over and over and over and over again over and over and over and over again uh so it's clear that the pattern here uh so it's clear that the pattern here is is just do a modular of nine and we can just do a modular of nine and we can directly figure out to the number so the 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 so it's modular 9 or not yourself so it's modular 9 or not yourself if it's zero then we're operating nine if it's zero then we're operating nine so that's the so that's the uh formula regular solution to this 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 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 for single digit case we start with the 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 except for number nine number nine you except for number nine number nine you modular now you get zero modular now you get zero uh so that's uh that's this for a number uh so that's uh that's this for a number that's less than nine that's less than nine if you modular that by nine you get that if you modular that by nine you get that number back number back uh then that's the base case so when the uh then that's the base case so when the siri converges siri converges um in the in the convert phase um in the in the convert phase the x is basically modular by name the x is basically modular by name we can return that otherwise we want to we can return that otherwise we want to look at look at the relationship between x modular 9 the relationship between x modular 9 and fx modular by 9. if they are and fx modular by 9. if they are equivalent equivalent then then that's saying then then that's saying we don't need to go through this process 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 we want to show that x modular 9 we want to show that x modular 9 is equivalent to f x of modular 9. is equivalent to f x of modular 9. if that's the case then we can skip us if that's the case then we can skip us through through all this higher order function calls all this higher order function calls directly directly apply this module by 9 apply this module by 9 so that we basically know the single so that we basically know the single digit cases digit cases so let's plug in the formula for x and f so let's plug in the formula for x and f x x onto that formula that we want to show 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 sum of numbers then modular 9 it's equal to the individual number modulo 9 sum all those up and then do a final so that's to put the number to the 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 this is equal to d multiplied by the this is equal to d multiplied by the single digit single digit multiplied by 9999 multiplied by 9999 some a bunch of nine plus one so that if you think about consideration and then just separating the summation it becomes d it becomes d times let's actually just putting that into let's actually just putting that into the second line here the second line here because it's a little bit crowded now the first tutorial here d multiplied 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 yeah so after kind of show why this yeah so after kind of show why this formula works so we can say that 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
2024-03-22 12:14:19
258
https://i.ytimg.com/vi/l…axresdefault.jpg
Leetcode 258 Add Digits
A9XzJ9moZxY
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 And All Deepanshu Toli 500 And All Deepanshu Toli 500 And All Deepanshu Toli 500 Total 4505 Fruit To Leaf With U Will Find Total 4505 Fruit To Leaf With U Will Find All Parts In This Form Will Convert Them Into The All Parts In This Form Will Convert Them Into The Equivalent Decimal In More Noida Equivalent Decimal In More Noida Decimal Numbers And Returned 2 Results From This Question Simple Will Find All Posts By Others On Part In This Form And Part In This Form And Part In This Form And Convert Them And Every ES Node Will Convert Convert Them And Every ES Node Will Convert 500 Form Into Decimal Form And Will 500 Form Into Decimal Form And Will Examine Them Will For Binary ES File Path Will Take Examine Them Will For Binary ES File Path Will Take A String Variable In This Will A String Variable In This Will Happen When Love Starts From Null 999 Happen When Love Starts From Null 999 9999 For String Dad For String Dad For String Dad Notification 108 No Veer Voter List Note And Notification 108 No Veer Voter List Note And Give Up And They Should You To Strings And Give Up And They Should You To Strings And Not Getting Them 100 98100 Function Which Will Not Getting Them 100 98100 Function Which Will Convert String Into Its Equivalent Convert String Into Its Equivalent Decimal Number Story In Different Look At First I Will Declare String First I Will Declare String Variable Is Variable Is Variable Is 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 Will pass Will pass Will pass through to this function spring handsome through to this function spring handsome and anil bhai definition of this function int and anil bhai definition of this function int helper MP3 that ajay ko the root string is that and int sump dec bill pass reference because its and int sump dec bill pass reference because its value will keep on changing value will keep on changing from this course of destruction of nodes from this course of destruction of nodes This root is internal the This root is internal the return is wife and now but meanwhile write note on this root roots left wife and now but meanwhile write note on this root roots left 112 null key 112 null key and roots light is 112 null what will we do a note via a lips note a note via a lips note a note via a lips note on increase in do real note Nobel price appendice 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 String Noble String Noble String Noble can be exactly a primary function which will convert can be exactly a primary function which will convert string into its equivalent string into its equivalent binary binary which is in the mid wicket boundary function on I which is in the mid wicket boundary function on I Ariba pass induct nor will not be the best Ariba pass induct nor will not be the best number which will assist in subscribing In achievement position like In achievement position like In achievement position like share 14012 in this case first will up and these values share 14012 in this case first will up and these values for string on fast on left side and person possible but this fast on left side and person possible but this train will pass singh will contain co train will pass singh will contain co like bihar and country notification soviet like bihar and country notification soviet then add 200 value then add 200 value then add 200 value superstition amused at not being royal a as plus similarly in this case also will a as plus similarly in this case also will up and value the songs of a message are the value of paint on I am available Chot North 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 To Our Definition Version Is To Our Definition Version Is To Our Definition Version Is So Ant Answer So Ant Answer 's Record 208 Restore Answer Int Power 's Record 208 Restore Answer Int Power Equal To One Camp At Nine Question Is That Equal To One Camp At Nine Question Is That Person That Don't Know What Is The Most Person That Don't Know What Is The Most Significant Positive Vibes Hair Last But Significant Positive Vibes Hair Last But Will Help You Get A String Of Will Help You Get A String Of Words Words Was Was And pant fire equals to a good balance And pant fire equals to a good balance 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 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 into power power is initially into power power is initially into power power is initially 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 The The The Best Kasba Angry When Converting Dad Path Into Its Corresponding Best Kasba Angry When Converting Dad Path Into Its Corresponding Decimal Decimal That Decimal Form No After Discussions Ro Va That Decimal Form No After Discussions Ro Va Dasham Va Vishwas Pass Filled Container Answer Will Return Dasham Va Vishwas Pass Filled Container Answer Will Return Some Note Sandhi Ko A 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
2024-03-25 15:01:40
1,022
https://i.ytimg.com/vi_w…xresdefault.webp
Sum of Root To Leaf Binary Numbers | Leetcode 1022 | Leetcode September challenge
OWwsycApNNg
Hi gas welcome and welcome back to my channel so today our problem is which concatenation so today our problem is which concatenation of consecutive numbers so on this problem of consecutive numbers so on this problem statement what have you given us here we have given statement what have you given us here we have given a wait and and a wait and and what we have to do is to find the decimal value what we have to do is to find the decimal value of of of 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 If you want to find, If you want to find, If you want to find, then let's then let's first understand this problem through an example, first understand this problem through an example, whether the problem is exactly ours, then whether the problem is exactly ours, then we will see how you can solve it. Okay, we will see how you can solve it. Okay, so look, here we have given the end, so look, here we have given the end, I have taken two examples, I have taken two examples, first and second. first and second. first and second. 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 If yes, then the If yes, then the If yes, then the answer is your WAN. Okay, this is your end. If you were there 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 First connect the numbers from WAN to 2. If you connect its binary representation, then WAN will be representation, then WAN will be What happens to you is one and what happens to you is What happens to you is one and what happens to you is 10, if you cut these two then 10, if you cut these two then this becomes this then this is the this becomes this then this is the final answer, what is your four, you are final answer, what is your four, you are six, right then end is three, then it is six, right then end is three, then it is n3. n3. then van ka van tu ka van zero and three then van ka van tu ka van zero and three ka van van write it jo van tha 27, this would be your ka van van write it jo van tha 27, this would be your answer. Ok, if there was four then answer. Ok, if there was four then what should I do? what should I do? what should I do? disconnected. One van zero is yours, then three, then 1 0 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? and and what do we have to do with the binary value, if we add it, what do we have to do with the binary value, if we add it, then these two then these two then these two 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 It will leave its space and will come here, It will leave its space and will come here, It will leave its space and will come here, this here, this here, this here, this here, this here, this here, this here, this here, what do you say a little from here, what do you say a little from here, you are shifting towards the left, this is shifting to the left, you are shifting towards the left, this is shifting to the left, so we are shipping to the left, then so we are shipping to the left, then look, it will become adding it here. adding it here. adding it here. your 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, now it will add this 10 in itself, okay, it will add it in its last okay, it will add it in its last i.e. here. i.e. here. keep it for both of them, so it will be from keep it for both of them, so it will be from here, towards the left, okay, here, towards the left, okay, this will be sip and what will come in its place, this will be sip and what will come in its place, 10 A will go, how will it come, I will 10 A will go, how will it come, I will tell you, okay. tell you, okay. tell you, okay. this van van will come, this van 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. last one, okay, here two positions last one, okay, here two positions will come here towards the left because the count here is will come here towards the left because the count here is yours, so this 11 will be here, the yours, so this 11 will be here, the final sting will be here, this is what we have to make, final sting will be here, this is what we have to make, this is the right one. this is the right one. this is the right one. 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 van Value of four 1 0 0 If you connect this then what will be formed Van Van Zero Van Van Zero 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 Have to add, if you have to Have to add, if you have to 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, so this is this two, this will create space here, okay, what will come here, 10, you have done 101, which okay, what will come here, 10, you have done 101, which one has done this, one has done this, now you have done this. now you have done this. now you have done this. 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, you will bring this van here, okay now, but in the end, what do we want, we That is, three spaces should be free here, That is, three spaces should be free here, That is, three spaces should be free here, three spaces should be free, three spaces should be free, then what do we have to do, we have to then what do we have to do, we have to shift three spaces here, this will be here, shift three spaces here, this will be here, this van here, this zero this van here, this zero here, it is okay, this man here, this van here, it is okay, this man here, this van here. here. here. it will be filled here right, we will get it, so how will we solve this problem, total beat is zero, how much is there in it, you 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 see that, okay people, there are two bitters in it, so what are you see that, okay people, there are two bitters in it, so what are you 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 Pe zero zero a goes right, Pe zero zero a goes right, Pe zero zero a goes right, after that what will we do, whatever number is here, we will after that what will we do, whatever number is here, we will add its decimal value to it. add its decimal value to it. Okay, whatever it is, if we add it to it, then what will become of us, this van van will become zero, What has become 110, What has become 110, What has become 110, after that what do we have to do, we have to after that what do we have to do, we have to add it here, at the end of this, add it here, at the end of this, it will have to be shifted by how many beats, its it will have to be shifted by how many beats, its length will be by that number of beats, what is the 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 total bits in it, if there are two beats, then there are two beats here. here. here. positions, then this van will come here, 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. What will they become? What will they become? 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: This here, this here, this will shift here, van, this van, Pay this zero here, this van here, Pay this zero here, this van here, Pay this zero here, this van here, this van here, three spaces here, it is empty here, this van here, three spaces here, it is empty here, what will we do, it will become what will we do, it will become 00 when you shift, then 00 when you shift, then what will you do with it, by adding it here, people are fine, I have what will you do with it, by adding it here, people are fine, I have added it van van added it van van added it van van zero 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, There are There are There are also numbers A, from 1 to N, also numbers A, from 1 to N, we will see how many we will see how many bits are there in each, okay, so what we have bits are there in each, okay, so what we have done, here we have created a function, it will done, here we have created a function, it will return you and give the total bits, okay, return you and give the total bits, okay, after that what we did is answer zero. after that what we did is answer zero. We will start from and we have to We will start from and we have to do the mode because your answer can be bigger. do the mode because your answer can be bigger. Okay, so here you take the mode 10, 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, so here we have also taken the now. so here we have also taken the now. so here we have also taken the now. 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 We will take N zero, We will take N zero, We will take N zero, sorry, here the number of bits will be A, sorry, here the number of bits will be A, then what will we do with the answer? By then what will we do with the answer? By how much will we shift here, as much as your total 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 number of bits will be on the right, here you will shift here, if you are shifting towards the left, then shifting towards the left, then this is this is this is 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. The side is towards the The side is towards the The side is towards the left and here we are showing you in the example that on the left and here we are showing you in the example that on the left side, we have to do it left side, we have to do it with how many, what will be the number of with how many, what will be the number of total bits, we have to do it with that much, okay, total bits, we have to do it with that much, okay, here we will do it with the mode key, then I with here we will do it with the mode key, then I with plus. plus. plus. what should we do after right shift, we are making the i plus, this is what we are doing, look here, here you set it, then what did you do, mode, we will do that, okay so mode, we will do that, okay so mode, we will do that, okay so 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.
2024-03-20 11:16:57
1,680
https://i.ytimg.com/vi/O…axresdefault.jpg
1680. Concatenation of Consecutive Binary Numbers
2faFbsdSOy8
problem 1678 called parser interpretation you own a gold parser that can interpret a string command the command consists of open and close scope and or Al open and close scope and or Al in some order the call part server will in some order the call part server will interpret J as a string Jake interpret J as a string Jake s scope and as a string o and Al inside s scope and as a string o and Al inside of a scope will be as a string Al of a scope will be as a string Al the interpreted strings are then the interpreted strings are then concatenated in the original order given concatenated in the original order given the swing command return the call the swing command return the call parser's interpretation of command parser's interpretation of command so the idea here is pretty simple so the idea here is pretty simple we are given a string that will consist we are given a string that will consist of either j a l or scopes of either j a l or scopes as it says here as it says here command consists some over there command consists some over there so our goal is to to so our goal is to to concatenate the result so we can concatenate the result so we can so it can be so it can be released something as this let's go so first thing we're going to create a string named output [Music] value value each character each character no this one it will hold the no this one it will hold the Kong Kong ated result ated result from command string 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 so every time the for Loop runs it will so every time the for Loop runs it will go through each element of the string so go through each element of the string so first we will go through J and then first we will go through J and then these open close scope and then again these open close scope and then again and so on to reaches the and so on to reaches the the last element of the string okay I'll save command index I this this and command that index five plus one and command that index five plus one equal to equal to this to accumulate else if command index I will be equal to a actually at all actually at all and at the end we're just gonna return and at the end we're just gonna return back the back the the result that we get based on this the result that we get based on this for Loop that we created back to the for Loop that we created back to the main function to see let's see if it main function to see let's see if it works works nope it didn't because this one's nope it didn't because this one's supposed to be oh run the code again to see if it works foreign does
2024-03-20 11:07:45
1,678
https://i.ytimg.com/vi/2…axresdefault.jpg
Goal Parser Interpretation LeetCode
hSBOIbmbssE
hey everybody this is Larry I'm doing this problem as part of a contest so this problem as part of a contest so you're gonna watch me live as I go you're gonna watch me live as I go through my daughter's I'm coding they've through my daughter's I'm coding they've been explanation near the end and for been explanation near the end and for more context they'll be a link below on more context they'll be a link below on this actual screen cats of the contest this actual screen cats of the contest how did you do let me know you do hit how did you do let me know you do hit the like button either subscribe button the like button either subscribe button and here we go 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 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 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 other people are having the same issues other people are having the same issues of the internet okay let's go of the internet okay let's go who's I shuffled away giving it away who's I shuffled away giving it away numbs instead of to n elements so numbs instead of to n elements so there's we turned away the form okay there's we turned away the form okay yeah so this one it's just pretty yeah so this one it's just pretty straightforward in that you just it is a straightforward in that you just it is a classic shuffle method basically you classic shuffle method basically you take what I did was that I just have two take what I did was that I just have two pointers right one pointers right one starting at point of one and then a starting at point of one and then a second one persona in the middle and second one persona in the middle and then just moved one at a time and that's then just moved one at a time and that's basically what I did here with the point basically what I did here with the point is to the left and then an implicit is to the left and then an implicit corner to the right with just plus half corner to the right with just plus half the right way and then after that we put the right way and then after that we put it in the answers and that's pretty much it in the answers and that's pretty much what you won yeah and the only thing what you won yeah and the only thing that I had to double check was whether that I had to double check was whether it's odd or even because if it's odd it's odd or even because if it's odd then maybe grab too well then we apply then maybe grab too well then we apply again and off by one even if and in again and off by one even if and in index error but this was not the case so index error but this was not the case so that's good that's good yeah pretty straight for all we I mean I yeah pretty straight for all we I mean I don't think this would be an interview don't think this would be an interview question but it would be part of a question but it would be part of a bigger interview question was definitely bigger interview question was definitely I've seen people give interviews on like I've seen people give interviews on like hey here's you know a deck of cards hey here's you know a deck of cards you know shuffle it with the perfect you know shuffle it with the perfect shuffle or something like that way so shuffle or something like that way so these things you should probably these things you should probably practice on and yeah this is doing a practice on and yeah this is doing a competitive programming but it also competitive programming but it also comes up enough during competitor comes up enough during competitor programs that definitely recommend it programs that definitely recommend it yeah
2024-03-21 02:58:42
1,470
https://i.ytimg.com/vi_w…xresdefault.webp
1470. Shuffle the Array (python) (Leetcode Easy)
QhPdNS143Qg
everyone welcome back and let's write some more neat code today so today let's some more neat code today so today let's solve the problem valid parentheses solve the problem valid parentheses string we've solved a few parentheses string we've solved a few parentheses related problems on this channel but related problems on this channel but this is a pretty unique one so we're this is a pretty unique one so we're given a string s and it could contain given a string s and it could contain three types of characters a left three types of characters a left parenthesis a right parenthesis and a parenthesis a right parenthesis and a wild card character and the wild card wild card character and the wild card character could character could be a three possibilities it could be an be a three possibilities it could be an empty string which is the simplest right empty string which is the simplest right so basically in that case we would so basically in that case we would ignore the wild card it could be a right ignore the wild card it could be a right parenthesis or it could be a left parenthesis or it could be a left parenthesis so parenthesis so each time we reach a wild card each time we reach a wild card in terms of a decision tree we really in terms of a decision tree we really have three branches right we have three have three branches right we have three different things we could consider it different things we could consider it could be a space it could be a left could be a space it could be a left parenthesis it could be a right parenthesis it could be a right parenthesis so already we're kind of parenthesis so already we're kind of getting the intuition of how to solve getting the intuition of how to solve this problem or at least enumerate all this problem or at least enumerate all possibilities our goal is to determine possibilities our goal is to determine if the given string could be valid if if the given string could be valid if it's possible we return true if it's it's possible we return true if it's impossible we return false and you can impossible we return false and you can go over this to understand what makes go over this to understand what makes parentheses valid and invalid the main parentheses valid and invalid the main thing is as you scan through a string thing is as you scan through a string suppose this one what has to really suppose this one what has to really happen is that every left parenthesis happen is that every left parenthesis has to have a matching right parenthesis has to have a matching right parenthesis and the matching right parenthesis has and the matching right parenthesis has to come after the left parentheses and to come after the left parentheses and the natural order for it is kind of like the natural order for it is kind of like first in first out so you can see we first in first out so you can see we have a left parenthesis then we have have a left parenthesis then we have another left parenthesis then we have a another left parenthesis then we have a right parenthesis and this right right parenthesis and this right parenthesis matches this one okay then parenthesis matches this one okay then we have another left parenthesis then we we have another left parenthesis then we have a right parenthesis this matches have a right parenthesis this matches the most recent one and then we have the most recent one and then we have another right parentheses and this another right parentheses and this matches this one but suppose we had a matches this one but suppose we had a slightly different string maybe we have slightly different string maybe we have three right parentheses in a row this three right parentheses in a row this would be invalid and you can see why would be invalid and you can see why these two match each other great this these two match each other great this one matches this one great but the right one matches this one great but the right parentheses then comes before the left parentheses then comes before the left parenthesis we can't have that and this parenthesis we can't have that and this is one way to understand that but the is one way to understand that but the easiest way to know that we have an easiest way to know that we have an invalid parenthesis combination is that invalid parenthesis combination is that at any given point of the string the at any given point of the string the number of left parentheses that we have number of left parentheses that we have can never be less than the number of can never be less than the number of right parentheses and you can see that right parentheses and you can see that that happens here right we have two left that happens here right we have two left parentheses then we have three right parentheses then we have three right parentheses and we are never going to be parentheses and we are never going to be able to recover from this because at one able to recover from this because at one point in time we had more right point in time we had more right parentheses than we had left it doesn't parentheses than we had left it doesn't matter if we get more left parentheses matter if we get more left parentheses we cannot recover from this ever and we cannot recover from this ever and that's how you know it's invalid let's that's how you know it's invalid let's take a very simple input string and then take a very simple input string and then determine if this is valid or not and we determine if this is valid or not and we can tell that it is how would it be can tell that it is how would it be valid if the wild card was empty and it valid if the wild card was empty and it would look like this right just a left would look like this right just a left and a right parenthesis but how can we and a right parenthesis but how can we do that uh brute force and we would we do that uh brute force and we would we could possibly have more complex strings could possibly have more complex strings how could we determine that well the how could we determine that well the brute force is going to be a decision brute force is going to be a decision tree because if we weren't given any tree because if we weren't given any wild cards we have a very simple wild cards we have a very simple algorithm just to scan through the algorithm just to scan through the parentheses to know if they were valid parentheses to know if they were valid or not just like i talked about but with or not just like i talked about but with wild cards there's lots of possibilities wild cards there's lots of possibilities we're going to go through each character we're going to go through each character in the string and have a decision tree in the string and have a decision tree so first character we see is a left so first character we see is a left parenthesis that's perfectly fine and parenthesis that's perfectly fine and then we get to the wild card right when then we get to the wild card right when you get to a wild card that's when you you get to a wild card that's when you actually need to branch we don't need to actually need to branch we don't need to just branch when we get to a regular just branch when we get to a regular parenthesis because that's already parenthesis because that's already determined it could be another left determined it could be another left parenthesis it could be a space or it parenthesis it could be a space or it could be a right parenthesis could be a right parenthesis and then we're going to get to the third and then we're going to get to the third character uh but we have to do that character uh but we have to do that third character it's already determined third character it's already determined it's a right parenthesis but we have to it's a right parenthesis but we have to do it for all three of our branches now do it for all three of our branches now so you can kind of see if we had a lot so you can kind of see if we had a lot of wild cards uh this decision tree of wild cards uh this decision tree would get very big but let's just finish would get very big but let's just finish it up real quick so here we'll have a it up real quick so here we'll have a right parenthesis here we'll have a right parenthesis here we'll have a right parentheses here we'll have a right parentheses here we'll have a right parenthesis so among all three of right parenthesis so among all three of these combinations you can see that this these combinations you can see that this is invalid because it has two open it is invalid because it has two open it has two left one right that's invalid has two left one right that's invalid this one you can see is also invalid it this one you can see is also invalid it has one left and then two right but the has one left and then two right but the middle one you can see it is valid it middle one you can see it is valid it has a left a space and then a right and has a left a space and then a right and the way we could do this problem the way we could do this problem recursively the decision tree portion is recursively the decision tree portion is kind of simple we would make three kind of simple we would make three recursive calls every time recursive calls every time we got to a wild card but to determine we got to a wild card but to determine if it was valid or not one we would keep if it was valid or not one we would keep track of how many left parentheses we track of how many left parentheses we had how many open left parentheses we had how many open left parentheses we had at this point we had one open had at this point we had one open if we're just considering the middle if we're just considering the middle branch here we also had a one open and branch here we also had a one open and then by the end of it we had zero open then by the end of it we had zero open zero left open parenthesis by the end we zero left open parenthesis by the end we should have exactly zero because they should have exactly zero because they should all match each other and the should all match each other and the number of left open should never be number of left open should never be negative for example if we started like negative for example if we started like this right if we started with a right this right if we started with a right parenthesis that's automatically invalid parenthesis that's automatically invalid okay so that's the recursive solution okay so that's the recursive solution and you can actually add dynamic and you can actually add dynamic programming and by dynamic programming i programming and by dynamic programming i mean memoization that's the easier way mean memoization that's the easier way to do it to this recursive solution and to do it to this recursive solution and i will actually link the code to that in i will actually link the code to that in the description if you want to take a the description if you want to take a look uh the overall time complexity of look uh the overall time complexity of first of all the brute force solution is first of all the brute force solution is in the worst case going to be a 3 to the in the worst case going to be a 3 to the power of n because that's how many power of n because that's how many branches we have n is going to be the branches we have n is going to be the size of the string because that's going size of the string because that's going to be the height of this decision tree to be the height of this decision tree but when you add memoization to this the but when you add memoization to this the overall time complexity actually becomes overall time complexity actually becomes n cubed and the way we would do that is n cubed and the way we would do that is by caching and we would cache uh with by caching and we would cache uh with two parameters one would be i which is two parameters one would be i which is the index of the position that we're at the index of the position that we're at and the other parameter would be uh the and the other parameter would be uh the number of left open parentheses at any number of left open parentheses at any given point uh in the string that we're given point uh in the string that we're at now a caching with two different at now a caching with two different parameters like this will cause us to parameters like this will cause us to have a two-dimensional matrix uh the have a two-dimensional matrix uh the size of that matrix is going to be n size of that matrix is going to be n squared but to calculate each value in squared but to calculate each value in that matrix would would take big o of n that matrix would would take big o of n time complexity that's how i'm getting n time complexity that's how i'm getting n cubed from but i don't expect you to cubed from but i don't expect you to understand all of this if you want to understand all of this if you want to understand it a bit more you can look at understand it a bit more you can look at the code that i'll have in the the code that i'll have in the description but there's actually an even description but there's actually an even more efficient way to solve this problem more efficient way to solve this problem and that is the greedy solution and it's and that is the greedy solution and it's very difficult to come up with now even very difficult to come up with now even if you can't come up with the greedy if you can't come up with the greedy solution by yourself it might still solution by yourself it might still occur to you in a real interview that occur to you in a real interview that maybe there's some kind of trick to this maybe there's some kind of trick to this problem that if only you could figure it problem that if only you could figure it out you would be able to solve this out you would be able to solve this problem in linear time is there a trick problem in linear time is there a trick like that well hopefully in a real like that well hopefully in a real interview your interviewer would give interview your interviewer would give you a hint for that but let's see how we you a hint for that but let's see how we could maybe come up with it ourselves we could maybe come up with it ourselves we know that one variable is going to be a know that one variable is going to be a mandatory for us and i'm going to call mandatory for us and i'm going to call it left it's going to be the number of it left it's going to be the number of left open parentheses we have and when left open parentheses we have and when we reach the first character it's a left we reach the first character it's a left open parenthesis initially our total is open parenthesis initially our total is going to be zero but after seeing the going to be zero but after seeing the left open parenthesis we increment it by left open parenthesis we increment it by one now we have one left open one now we have one left open parenthesis and that would be very easy parenthesis and that would be very easy uh suppose we didn't have the wild card uh suppose we didn't have the wild card then we would have a right parenthesis then we would have a right parenthesis and we would do the exact opposite we'd and we would do the exact opposite we'd say okay left uh open parenthesis has say okay left uh open parenthesis has been decremented by one so now we're been decremented by one so now we're back to zero left open parenthesis and back to zero left open parenthesis and that makes sense but wild cards create that makes sense but wild cards create multiple possibilities and three exactly multiple possibilities and three exactly right one the simplest would be to right one the simplest would be to ignore this right if we ignore it okay ignore this right if we ignore it okay we're still left with one open we're still left with one open parenthesis that's the simplest but it parenthesis that's the simplest but it could there could be multiple could there could be multiple possibilities right and we need to possibilities right and we need to consider all possibilities if we want to consider all possibilities if we want to be sure that we can determine if this is be sure that we can determine if this is possibly valid or not possibly valid we possibly valid or not possibly valid we do have to consider every possibility so do have to consider every possibility so another possibility is this wild card another possibility is this wild card could be a could be a left open parenthesis if that's the case left open parenthesis if that's the case we would take our left and actually we would take our left and actually increment it by one to make it two but increment it by one to make it two but another possibility is that this a wild another possibility is that this a wild card could be a right parenthesis and in card could be a right parenthesis and in that case we would take this and then that case we would take this and then decrement it by one see how this wild decrement it by one see how this wild card is creating some divergence for us card is creating some divergence for us we can't maintain all possibilities in a we can't maintain all possibilities in a single variable like we could before so single variable like we could before so this is kind of a hint to you that maybe this is kind of a hint to you that maybe we need two variables let's go to the we need two variables let's go to the third character before we actually third character before we actually create those two variables now we have a create those two variables now we have a right parenthesis now what are we gonna right parenthesis now what are we gonna do well with right parentheses we're do well with right parentheses we're gonna decrement our left count but now gonna decrement our left count but now we have to decrement two variables so we have to decrement two variables so this would become one and then this this would become one and then this would become zero what do these actually would become zero what do these actually represent the reason we have two in the represent the reason we have two in the first place is from the wild card first place is from the wild card basically these are gonna represent the basically these are gonna represent the i'm gonna call it the left max and the i'm gonna call it the left max and the left min and what that means is what's left min and what that means is what's the the maximum left open left parenthesis we maximum left open left parenthesis we could have and what's the minimum open could have and what's the minimum open left parenthesis we could have depending left parenthesis we could have depending on how we choose our wild card okay now on how we choose our wild card okay now let's go to another character and again let's go to another character and again we have a wild card now let me explain we have a wild card now let me explain to you what these two variables are to you what these two variables are supposed to represent they're supposed supposed to represent they're supposed to represent the range of possibilities to represent the range of possibilities we could have zero left open parentheses we could have zero left open parentheses or we could have one left open or we could have one left open parentheses depending on how we chose parentheses depending on how we chose the first wild card but now we have a the first wild card but now we have a second wildcard now if we made this a second wildcard now if we made this a left open parenthesis that would mean left open parenthesis that would mean it's possible for us to have two left it's possible for us to have two left open parentheses so we would update our open parentheses so we would update our left max in that case but if we made it left max in that case but if we made it a closing parenthesis then we would want a closing parenthesis then we would want to update our minimum because this is to update our minimum because this is supposed to represent all possibilities supposed to represent all possibilities so let's do exactly that if so let's do exactly that if let's increment our left max to be 2 let's increment our left max to be 2 then let's decrement our left min to be then let's decrement our left min to be negative one but hold on for a second negative one but hold on for a second this isn't just the range of this isn't just the range of possibilities this should also be the possibilities this should also be the valid range of possibilities we should valid range of possibilities we should never have our left min become negative never have our left min become negative because that would imply that the because that would imply that the choices we made caused our left min to choices we made caused our left min to be negative and we know that's invalid be negative and we know that's invalid so we're never going to allow our left so we're never going to allow our left min to become negative if it ever does min to become negative if it ever does become negative we're going to reset it become negative we're going to reset it back to b0 so now you can see that these back to b0 so now you can see that these are the range of possibilities between are the range of possibilities between zero and two and now we're just going to zero and two and now we're just going to continue through the rest of the array continue through the rest of the array we're going to get a left open we're going to get a left open parenthesis which uh we're going to parenthesis which uh we're going to increment both of our variables so this increment both of our variables so this is going to be 1 this is going to be a 3 is going to be 1 this is going to be a 3 and then we're going to get a closing and then we're going to get a closing parenthesis so this is going to be parenthesis so this is going to be decremented down to 0. this is going to decremented down to 0. this is going to be decremented down to 2. and now how do be decremented down to 2. and now how do we know if we can return true or false we know if we can return true or false is this valid or is it not valid well we is this valid or is it not valid well we know it's balanced if the left open know it's balanced if the left open parenthesis count is zero so does zero parenthesis count is zero so does zero fall in between our range right now it fall in between our range right now it does because our left min is exactly does because our left min is exactly zero so that's how you know we can zero so that's how you know we can return true if our left min is equal to return true if our left min is equal to zero and before we get into the code i zero and before we get into the code i just want to show you another way that just want to show you another way that our solution could have been invalid uh our solution could have been invalid uh suppose you know our string had two uh suppose you know our string had two uh closing parentheses and then two open of closing parentheses and then two open of course our left min is never going to be course our left min is never going to be uh negative because uh if it becomes uh negative because uh if it becomes negative we reset it back to zero but if negative we reset it back to zero but if our left max does become negative uh in our left max does become negative uh in this case it'll be negative two uh from this case it'll be negative two uh from this uh at this after we've seen these this uh at this after we've seen these two that's how you know we can return two that's how you know we can return false because it'll never be valid we'll false because it'll never be valid we'll never recover from this because if the never recover from this because if the maximum number of left open parentheses maximum number of left open parentheses we could have is negative that means we could have is negative that means there's no choices we could possibly do there's no choices we could possibly do to make this valid okay so before we get to make this valid okay so before we get into the code as you could tell from into the code as you could tell from this algorithm we don't even need any this algorithm we don't even need any extra space so the space complexity is extra space so the space complexity is bigger of zero and we only need to scan bigger of zero and we only need to scan through the string once so the time through the string once so the time complexity is big o of n so now let's complexity is big o of n so now let's code it up okay so now let's code it up code it up okay so now let's code it up and like i said we're gonna have two and like i said we're gonna have two variables left min and left max variables left min and left max initially they're both gonna be a zero initially they're both gonna be a zero and then we're just going to go through and then we're just going to go through every single character in the string if every single character in the string if we get a open parenthesis a left open we get a open parenthesis a left open parenthesis we're going to increment parenthesis we're going to increment both of our variables so leftmin and both of our variables so leftmin and leftmax are going to be incremented by leftmax are going to be incremented by one because here we don't really have one because here we don't really have any choices we have to increment the any choices we have to increment the count by one and in the opposite case count by one and in the opposite case where we do have a closing parenthesis where we do have a closing parenthesis we also don't have a choice so i'm going we also don't have a choice so i'm going to copy and paste this but in that case to copy and paste this but in that case we're going to be decrementing the count we're going to be decrementing the count by one for each of them uh and the else by one for each of them uh and the else case is when we have a wild card we case is when we have a wild card we don't have to specify that character and don't have to specify that character and this is the part where we do have a this is the part where we do have a choice so i'll copy and paste again but choice so i'll copy and paste again but with the left min we're going to with the left min we're going to decrement that count in the case that we decrement that count in the case that we have a closing parenthesis and in the have a closing parenthesis and in the case that we choose the wild card to be case that we choose the wild card to be an open parenthesis we're going to an open parenthesis we're going to increment the left max by 1. but increment the left max by 1. but remember if the left max ever is remember if the left max ever is negative that means it's impossible for negative that means it's impossible for our parentheses to be valid so in that our parentheses to be valid so in that case we're just going to immediately case we're just going to immediately return false but in the similar case return false but in the similar case where our left min is negative we're not where our left min is negative we're not necessarily going to return false necessarily going to return false because that would mean our left max is because that would mean our left max is not negative so it technically is not negative so it technically is possible for the string to still be possible for the string to still be valid we don't want to continue assuming valid we don't want to continue assuming that our string up until this point is that our string up until this point is invalid so we're going to reset it back invalid so we're going to reset it back to zero and if to zero and if this part is unclear and i don't expect this part is unclear and i don't expect it to be too clear because it's actually it to be too clear because it's actually complicated to understand this is the complicated to understand this is the string that i would kind of run the code string that i would kind of run the code on and this is the example i would on and this is the example i would really try to understand if you don't really try to understand if you don't get this part this string is impossible get this part this string is impossible to make valid no matter what we choose to make valid no matter what we choose for the wild card but if you don't for the wild card but if you don't include this if statement in your code include this if statement in your code you'll end up returning true for this you'll end up returning true for this when you should be returning false when you should be returning false that's kind of what i'll leave it at but that's kind of what i'll leave it at but other than that once we exit the loop we other than that once we exit the loop we will return true if the left min is will return true if the left min is equal to zero if it's not equal to zero equal to zero if it's not equal to zero then we return false now let's run the then we return false now let's run the code to make sure that it works and as code to make sure that it works and as you can see on the left yes it does and you can see on the left yes it does and it's pretty efficient so i really hope it's pretty efficient so i really hope that this was helpful if it was please that this was helpful if it was please like and subscribe it really supports like and subscribe it really supports the channel a lot consider checking out the channel a lot consider checking out my patreon where you can further support my patreon where you can further support the channel and hopefully i'll see you the channel and hopefully i'll see you pretty soon thanks for watching
2024-03-20 16:00:25
678
https://i.ytimg.com/vi/Q…axresdefault.jpg
Valid Parenthesis String - Leetcode 678 - Python
FiawvsBgYVs
hey guys welcome to a new video in today's video we're going to look at the today's video we're going to look at the lead code problem and the problem's name lead code problem and the problem's name is sort and array so in this question we is sort and array so in this question we are given an array called nums and we are given an array called nums and we need to sort the array ascending order need to sort the array ascending order and return it coming to the functions and return it coming to the functions have given us this is the function name have given us this is the function name and this is the input array we have to and this is the input array we have to work on and we have to return an integer work on and we have to return an integer array there are many types of sorts to array there are many types of sorts to begin with bubble sort insertion sort begin with bubble sort insertion sort and selection sort but their time and selection sort but their time complexity goes to O of Big O of n complexity goes to O of Big O of n Square for this program I'm going to Square for this program I'm going to show you how to do the counting sort the show you how to do the counting sort the countings on basically uses a hash map countings on basically uses a hash map to store the frequencies of each element to store the frequencies of each element inside the input array and then we need inside the input array and then we need to find the Min and Max element from the to find the Min and Max element from the input area and run a for loop from Min input area and run a for loop from Min until Max and then we have to access the until Max and then we have to access the elements from the map we created elements from the map we created according to its frequency and printed according to its frequency and printed so let me show you how the problem is so let me show you how the problem is solved so in counting sort we have to solved so in counting sort we have to first create a hash map to the first create a hash map to the frequencies so for this example the hash frequencies so for this example the hash map is going to look like this so the map is going to look like this so the key and values are going to be integer key and values are going to be integer so the keys are going to be the array so the keys are going to be the array elements 5 2 3 and 1 and the frequencies elements 5 2 3 and 1 and the frequencies are going to be its frequencies like how are going to be its frequencies like how many times each element is appearing many times each element is appearing inside the input array and for this inside the input array and for this example it is going to be so let's take example it is going to be so let's take this example and see how this is going this example and see how this is going to be solved so this is the input array to be solved so this is the input array nouns we are going to solve and the nouns we are going to solve and the indexes are written in blue it will indexes are written in blue it will start from 0 to 5 and this is the map start from 0 to 5 and this is the map for that input array first we need to for that input array first we need to find out the minimum and Max element find out the minimum and Max element from the input array we iterate through from the input array we iterate through the input array from left to right and the input array from left to right and we find out the values inside the map we find out the values inside the map and we also find out the Min and Max and we also find out the Min and Max element in the same iteration so once element in the same iteration so once you solve this the Min element is going you solve this the Min element is going to be 0 and the max element is going to to be 0 and the max element is going to be 5. we cannot assign a new array to be 5. we cannot assign a new array to display the output we have to do it in display the output we have to do it in place inside the input array itself so place inside the input array itself so we also need a index called index we also need a index called index variable which is initially pointing at variable which is initially pointing at zero so index is here now we iterate for zero so index is here now we iterate for Loop will run from Min to Max Loop will run from Min to Max so Min to Max and in each iteration I so Min to Max and in each iteration I will increment by 1 and these are the will increment by 1 and these are the elements inside the input array so we elements inside the input array so we take the element 0 and check its take the element 0 and check its frequency frequency of 0 is equal to 2 frequency frequency of 0 is equal to 2 which means 0 should appear two times which means 0 should appear two times inside the array so first we take the inside the array so first we take the element 0 and replace 5 with 0 and next element 0 and replace 5 with 0 and next iteration index will be pointing here iteration index will be pointing here and the value of 0 will be decremented and the value of 0 will be decremented by 1 and now 0 is having the count of by 1 and now 0 is having the count of one so once you access an element it one so once you access an element it will be printed until the value becomes will be printed until the value becomes 0 now it is 1 right so again we have to 0 now it is 1 right so again we have to add another 0 inside the output add another 0 inside the output so this will be replaced by zero so this will be replaced by zero decrement is count by 0 so 0 is now decrement is count by 0 so 0 is now having count 0 so we'll move on to the having count 0 so we'll move on to the next element I plus plus so I it was 0 next element I plus plus so I it was 0 now it is one now we check if 1 is now it is one now we check if 1 is present inside the map yes one is present inside the map yes one is present and its frequency is 2. now present and its frequency is 2. now index is pointing here so frequency of 1 index is pointing here so frequency of 1 is 2 so again we need to print 1 inside is 2 so again we need to print 1 inside the output array two times the output array two times so first iteration one will be printed so first iteration one will be printed here and it's count is here and it's count is updated to 1 inside the map updated to 1 inside the map and index is pushed forward and index is pushed forward and again one is inserted and its and again one is inserted and its frequency is decremented to zero and now frequency is decremented to zero and now we can proceed to the next element we can proceed to the next element incrementing I so I is now 2 I will incrementing I so I is now 2 I will check for 2 inside the map S2 is present check for 2 inside the map S2 is present and its frequency is equal to 1 push and its frequency is equal to 1 push index forward so index is now pointing index forward so index is now pointing here and we need to replace that element here and we need to replace that element with the current element 2 inside the with the current element 2 inside the map which is having frequency 1 and we map which is having frequency 1 and we decrement its frequency by 1 and it decrement its frequency by 1 and it becomes 0 and we move on to the next becomes 0 and we move on to the next element by I is equal to 3 it is not element by I is equal to 3 it is not present inside the map so we increment I present inside the map so we increment I I is equal to 4 it is not present inside I is equal to 4 it is not present inside the map increment I is equal to 5 which the map increment I is equal to 5 which is Max so this is the last element to be is Max so this is the last element to be added inside the map so we increment added inside the map so we increment index so index is now pointing here and index so index is now pointing here and the frequency of 5 is 1 so add it inside the frequency of 5 is 1 so add it inside the array and decrement its frequency by the array and decrement its frequency by 1 and become 0 and we reach the end of 1 and become 0 and we reach the end of the iteration the for Loop will run from the iteration the for Loop will run from Min to Max right with I plus plus and we Min to Max right with I plus plus and we reached 5 the next iteration the for reached 5 the next iteration the for Loop will break and we come outside the Loop will break and we come outside the for Loop and we can finally return our for Loop and we can finally return our result which is present inside the input result which is present inside the input array Norms so Norms will be returned as array Norms so Norms will be returned as the output and this is the output for the output and this is the output for our question now that we have seen the our question now that we have seen the working let us code it up as I have said working let us code it up as I have said first we need a hash map to store the first we need a hash map to store the frequencies frequencies so the key and value are going to be 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 frequency map dot get of nums of five we frequency map dot get of nums of five we are getting its current frequency are getting its current frequency and increasing it with one each time you and increasing it with one each time you see it see it and in the IELTS block and in the IELTS block so this else block will be executed for so this else block will be executed for every unique element so if that element every unique element so if that element is not present inside the map as key we is not present inside the map as key we need to put that element as map inside need to put that element as map inside key map dot put off key map dot put off nums of I nums of I and set its frequency to 1 and from the and set its frequency to 1 and from the next time whenever it is present inside next time whenever it is present inside the map this statement will be executed the map this statement will be executed and its frequency will be incremented and its frequency will be incremented now in this for Loop only we can find now in this for Loop only we can find the minimum and maximum element so if the minimum and maximum element so if the current element nums of I the current element nums of I is less than the current min is less than the current min we need to assign Min as the current we need to assign Min as the current element element s of I s of I and now we can also find out if it is and now we can also find out if it is the maximum element by checking if the the maximum element by checking if the current element Norms of I current element Norms of I is greater than the current Max 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 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 until I is equal to Max because Max is until I is equal to Max because Max is also present inside the array so we need also present inside the array so we need to run until I is equal less than or to run until I is equal less than or equal to Max equal to Max now we cannot create another array we now we cannot create another array we need to store the output array inside need to store the output array inside the input array itself for that let us the input array itself for that let us use the index use the index and assign it to 0 now I is equal to the and assign it to 0 now I is equal to the least element in this example Min is least element in this example Min is equal to 0 and Max is equal to 5 so I is equal to 0 and Max is equal to 5 so I is equal to Min so I is equal to 0. now we equal to Min so I is equal to 0. now we need to get the frequency of 0 because 0 need to get the frequency of 0 because 0 appears twice inside the array we need appears twice inside the array we need to get its frequency and print the two to get its frequency and print the two zeros at once in the beginning of the zeros at once in the beginning of the array here as you can see two zeros are array here as you can see two zeros are printed at the beginning so for that printed at the beginning so for that let's check if the frequency of element let's check if the frequency of element at I is less than zero so until then we at I is less than zero so until then we can print it for that we can use a while can print it for that we can use a while though so while app dot we can use the though so while app dot we can use the get or default method foreign get or default method foreign has to parameters the first parameter I has to parameters the first parameter I is for this so get of I will get the is for this so get of I will get the frequency of I if that element is not frequency of I if that element is not present print 0 as out is greater than 0 present print 0 as out is greater than 0 so until then this while loop will run so until then this while loop will run we get the frequency of 0 which is 2 we get the frequency of 0 which is 2 this while loop will run for three time this while loop will run for three time and on the third time when I will become and on the third time when I will become 0 this while loop will break now we need 0 this while loop will break now we need to print 0 2 times inside the output to print 0 2 times inside the output array but we haven't declared output array but we haven't declared output array because we need to print the sort array because we need to print the sort the elements in place so nums of index the elements in place so nums of index so index is now pointing at 0 and we so index is now pointing at 0 and we need to print the two zeros from here so need to print the two zeros from here so these two elements will be replaced by these two elements will be replaced by zeros is equal to I which is currently 0 zeros is equal to I which is currently 0 and then we need to increment the index and then we need to increment the index for the next iteration first we have for the next iteration first we have printed 0 now index plus plus means printed 0 now index plus plus means index is 1 so here again we print 0 each index is 1 so here again we print 0 each time we print a zero we need to decrease time we print a zero we need to decrease its frequency inside the map by one so its frequency inside the map by one so we need to replace its frequency by we need to replace its frequency by decreasing it by one so mad dot put decreasing it by one so mad dot put of 0 is I and map dot get of I of 0 is I and map dot get of I the current frequency and decrease it y1 the current frequency and decrease it y1 so in the third iteration first two so in the third iteration first two times T these two zeros will be printed times T these two zeros will be printed and in the third iteration the value of and in the third iteration the value of the key 0 is equal to 0 so it comes out the key 0 is equal to 0 so it comes out of the while loop so two zeros are are of the while loop so two zeros are are printed now I is equal to 1 because I printed now I is equal to 1 because I plus plus so mean was 0 now it is 1 so plus plus so mean was 0 now it is 1 so it will access these two elements from it will access these two elements from the map and print it two more times the map and print it two more times using this while loop and next I is using this while loop and next I is equal to 2 it will access 2 and print it equal to 2 it will access 2 and print it inside the array next I is equal to 3 3 inside the array next I is equal to 3 3 is not present inside the input because is not present inside the input because here map dot get of 3 using or default here map dot get of 3 using or default default value are used when that element default value are used when that element is not present so 0 will be returned is not present so 0 will be returned here 0 is greater than zero so it won't here 0 is greater than zero so it won't enter this low I plus plus I is equal to enter this low I plus plus I is equal to 4 4 is not present again 0 will be 4 4 is not present again 0 will be returned here and it won't enter next I returned here and it won't enter next I is equal to 5 yes 5 is present it will is equal to 5 yes 5 is present it will be printed here because index value is be printed here because index value is now pointing here now pointing here so 5 will be printed and we reach the so 5 will be printed and we reach the end of the program finally outside the end of the program finally outside the for Loop you can return the input array for Loop you can return the input array norms norms now let's run the code now let's run the code let's submit the code there you have it let's submit the code there you have it a solution has been accepted so the time a solution has been accepted so the time complexity of this approach is of n plus complexity of this approach is of n plus K where n is the number of elements K where n is the number of elements inside the nums array and K is the range inside the nums array and K is the range between Min and Max because here we are between Min and Max because here we are using a for low which will run from I using a for low which will run from I equal to Min till Max and the space equal to Min till Max and the space complexity is also of n because we're complexity is also of n because we're using a map to store the frequency of using a map to store the frequency of the array elements thank you for the array elements thank you for watching and I'll see you in the next watching and I'll see you in the next one one foreign
2024-03-25 10:51:10
912
https://i.ytimg.com/vi/F…axresdefault.jpg
Leetcode | 912. Sort an Array | Medium | Java Solution [Counting Sort]
3vkRrZUXi5Q
so this question is lead code 396 rotate function we are given a nums array of function we are given a nums array of length n and we have to calculate F of K length n and we have to calculate F of K function for 0 to n minus 1. function for 0 to n minus 1. how we calculate F of K is for f of 0 how we calculate F of K is for f of 0 we will have to multiply each we will have to multiply each number with its index number with its index and sum it up and sum it up then we rotate the number once numbs then we rotate the number once numbs array ones and we repeat it we repeat it array ones and we repeat it we repeat it for 0 to n minus 1. so let's see how we for 0 to n minus 1. so let's see how we do it do it so given this function we can first so given this function we can first start calculating the F of 0 for this start calculating the F of 0 for this array F of 0 means we have rotated r a array F of 0 means we have rotated r a zero times and we are calculating the zero times and we are calculating the function function so we can say 4 times its index that is so we can say 4 times its index that is 0. 0. plus 3 times its index plus 3 times its index plus 2 times its index plus 2 times its index plus 6 times its index plus 6 times its index which gives us a total of which gives us a total of 4 4 18 22 and 25. now for f of 1 this increases by one 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 and the index of 6 is and the index of 6 is 0. for 4 it's one three it's two and two 0. for 4 it's one three it's two and two it's three it's three if we sum it up we get 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 and we also and we also removed six three times removed six three times this term which gives us 16. so what happened here is we added the sum to it because each term we added the sum to it because each term increased by one 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 from from 25 25 Plus 15. the previous function that is f of 1 the previous function that is f of 1 which is 16 which is 16 plus 15 the last term which is 2 so minus 2 times the length of the array and we will get 31 minus 8 that is 23. 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 and the length of the array and the length of the array so so we'll say we'll say size for that and total sum can be size for that and total sum can be obtained by sum of nums and this is line obtained by sum of nums and this is line of numbers of numbers now we can start iterating backwards for size minus 1 up to 0 step of -1 so we get the num from nums of I can be calculated as can be calculated as previous previous function 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 Max function Max function is the max of Max function and make sure to assign previous and make sure to assign previous function function to the next function and finally return the max function again and it is not callable okay we missed and it is not callable okay we missed multiplication sign so as you can see it works
2024-03-24 12:15:14
396
https://i.ytimg.com/vi/3…axresdefault.jpg
Leetcode 396. Rotate Function
uwzCdK9M1PY
hey what's up guys this is sean here so uh today let's take a look at so uh today let's take a look at this 1254 this 1254 number of closed islands so i mean number of closed islands so i mean the media one it's this one is not the media one it's this one is not definitely not not that hard definitely not not that hard i mean okay so given like a 2d i mean okay so given like a 2d grades here consists of either zeros grades here consists of either zeros represents the land represents the land or ones represents water and an island or ones represents water and an island is a is a is like a maximum four directional is like a maximum four directional connected groups of connected groups of zeros and the closed island is an zeros and the closed island is an island totally surrounded by ones so it island totally surrounded by ones so it means that means that an island is a closed island if and only an island is a closed island if and only if if they're like basically the the whole island is is surrounded the whole island is surrounded by by ones here okay right for example this one here we have 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 i think all of you knows the unknowns there 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 in our in our code here so i'm i'm pretty sure there are like 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 uh the part of the island i check if that island is is uh is on the edge on edge means if it's on if the 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 you know for dfs you know we can either use like a recursive recursion call or we can use a 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 i don't know i don't care which direction is this but all i know is that i need to define zero one okay and then zero one okay and then uh you know for this like dfs search we uh you know for this like dfs search we need to keep track of the visited set need to keep track of the visited set a visited island here right but in this a visited island here right but in this case we can just utilize case we can just utilize the original grid here so every time the original grid here so every time when we happen when we saw when we happen when we saw we see a land here after visiting that we see a land here after visiting that that's that a cell we can just set it that's that a cell we can just set it back to the to zero which is water back to the to zero which is water so that you know we can we won't visit so that you know we can we won't visit the lens multiple times okay so the lens multiple times okay so basically if the i in range basically if the i in range i'm here and for j in range i'm here and for j in range and here okay if and here okay if if the grid inj if the grid inj is equal to zero it means it's a length is equal to zero it means it's a length it's a length right and then uh it's a length right and then uh so here we're gonna add these things to so here we're gonna add these things to the the to the queue right inj to the queue right inj and then i just set these things and then i just set these things to one okay now this is my flag here to one okay now this is my flag here okay okay it's closed just like available the regular bf just like available the regular bf uh bfs search or in this industry in uh bfs search or in this industry in this case it's like a this case it's like a queue okay current i current queue okay current i current j uh in the queue 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 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 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 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 for the new new js here okay new j uh n okay and of course we need to we also need to check if the the new ion new j is a land okay right don't then we add this q then we add this q we add this new new i and j to the to we add this new new i and j to the to the q here the q here and then after that same thing we're and then after that same thing we're gonna set these things two to one okay or we can just use like two to one okay or we can just use like uh uh define like uh a separate visited set define like uh a separate visited set every time we add it to the set but every time we add it to the set but since we can use the same same grid here since we can use the same same grid here we can we can save that and then in the end here we save that and then in the end here we only increase the answers when the only increase the answers when the this flag is true right so in the end reach right so in the end reach just return okay so i think that's that's through the work wow oh sorry here oh okay wow oh sorry here oh okay yeah okay it should be inside this if yeah okay it should be inside this if here okay five that's weird hmm yeah this one shouldn't hmm yeah this one shouldn't be that hard so but why i'm getting a be that hard so but why i'm getting a different answer here different answer here append this inj okay that's right append this inj okay that's right it's close equals to true while q is it's close equals to true while q is here here we pop and we check this one we set it we pop and we check this one we set it to false to false and then we do what directions here okay and then we do what directions here okay i i and oh sorry and oh sorry yeah current i and carter j yeah this is yeah current i and carter j yeah this is the uh 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 cool so i mean this thing i mean it's cool so i mean this thing i mean it's it's it's pretty straightforward problem it's it's pretty straightforward problem i mean the only different the only i mean the only different the only uh difference here is that you have to uh difference here is that you have to check check you have to make make sure if this you have to make make sure if this island is closed or not so the way i i'm island is closed or not so the way i i'm doing it is like right doing it is like right by checking if any of the the part of by checking if any of the the part of the island is the island is is on the edge of the 2d grades okay and is on the edge of the 2d grades okay and yeah and space and time complexity so yeah and space and time complexity so the time complexity of course is the time complexity of course is like m times n right like m times n right because we have a we have a four loop here right but you know even though we have we have a q here but doesn't really matter because each of the i each of the the cell will only be in the queue one time so here you can think it's so i mean so in total the the time so i mean so in total the the time comprises the m times n comprises the m times n and space since we're not the space and space since we're not the space is the space is 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 uh cool i think that's it for this uh cool i think that's it for this problem thank you so much problem thank you so much for watching the videos guys stay tuned for watching the videos guys stay tuned see you guys soon see you guys soon yeah bye
2024-03-19 17:28:22
1,254
https://i.ytimg.com/vi/u…axresdefault.jpg
LeetCode 1254. Number of Closed Islands
HvCaMw58_94
good morning everyone today is January 14th Saturday morning 14th Saturday morning um I randomly looked up this problem um I randomly looked up this problem because this is the problem for leave because this is the problem for leave code has a daily problem challenge so code has a daily problem challenge so this is today's problem this is today's problem um 10 legal problem um 10 legal problem 1061. this is today's problem challenge 1061. this is today's problem challenge you see all the other problems I started you see all the other problems I started in the ascending order except in this in the ascending order except in this one because this is the daily problem one because this is the daily problem little has a monthly challenge you have little has a monthly challenge you have like until seven hours I think it's UTC like until seven hours I think it's UTC time not Pacific Time day 14 I just time not Pacific Time day 14 I just finished this problem for the first finished this problem for the first month of this year this is the first month of this year this is the first problem that I've finished for the lead problem that I've finished for the lead code daily problem challenge code daily problem challenge um I think this is a very good refresher um I think this is a very good refresher and we can introduce a template for and we can introduce a template for solving problems like this let's take a solving problems like this let's take a look at the problem first look at the problem first lexical graphically small is the lexical graphically small is the equivalent string equivalent string it's not a new problem it's a pretty old it's not a new problem it's a pretty old problem and you know right now we have problem and you know right now we have like more than 2 000 problems this one like more than 2 000 problems this one is only one thousand uh its number is is only one thousand uh its number is 1061. so let's take a look you're given 1061. so let's take a look you're given two strings of the same length as one two strings of the same length as one and S2 and a stream bass string we say and S2 and a stream bass string we say S1 I and s2i are equivalent categories S1 I and s2i are equivalent categories by nothing else as long as they are in by nothing else as long as they are in the same position in the two different the same position in the two different strings they are equivalent characters strings they are equivalent characters so this is this problem's definition so this is this problem's definition okay not by any other definition for okay not by any other definition for example if S1 is a b c as 2 is CDE then example if S1 is a b c as 2 is CDE then we have a is equivalent to C because we have a is equivalent to C because they are in the same position in two they are in the same position in two different strings same as b and d b and different strings same as b and d b and d and c and e because they are in the d and c and e because they are in the same positions in the two different same positions in the two different strings strings and then equivalent characters follow and then equivalent characters follow the usual rules of any equivalence the usual rules of any equivalence relation relation reflexivity a is equivalent to a itself reflexivity a is equivalent to a itself symmetry if a is equivalent to B then B symmetry if a is equivalent to B then B is equivalent to a easy to understand is equivalent to a easy to understand the third one is important is the third one is important is transitivity if a equals to b and b transitivity if a equals to b and b equals to b b is equivalent to C that equals to b b is equivalent to C that means C is equivalent to a means C is equivalent to a is transitive Okay so for example given is transitive Okay so for example given the equivalency information from S1 the equivalency information from S1 equals ABC as 2 equals CDE ACD and aab equals ABC as 2 equals CDE ACD and aab are equivalent strings of Base strain are equivalent strings of Base strain Eed okay so we're introducing a third Eed okay so we're introducing a third parameter in the API that is base string parameter in the API that is base string so this is the string that we would like so this is the string that we would like to come up with the lexicographically to come up with the lexicographically smallest string with smallest string with okay written so the problem is asking us okay written so the problem is asking us to return the lexical graphic response to return the lexical graphic response to string of the base string by using to string of the base string by using the re by using the equivalency the re by using the equivalency information from S1 and S2 so it might information from S1 and S2 so it might be a difficult it might be a bit be a difficult it might be a bit difficult to understand why difficult to understand why we reached at this conclusion we reached we reached at this conclusion we reached a a b is the lexicographically smallest a a b is the lexicographically smallest let's take a look at one example it will let's take a look at one example it will help us understand help us understand suppose S1 is Parker as two as Mars base suppose S1 is Parker as two as Mars base string is this let's forget about base string is this let's forget about base string for a moment let's just figure string for a moment let's just figure out the equivalency relationship between out the equivalency relationship between S1 and S2 first S1 and S2 first based on the equivalency information based on the equivalency information what we have is M and P M P and M what we have is M and P M P and M they're in the same positions so they they're in the same positions so they are equivalent are equivalent a and o they are equivalent R okay R and a and o they are equivalent R okay R and are the third a third position R and R are the third a third position R and R okay okay via equivalent to itself right and then via equivalent to itself right and then K and R so R and K they are equivalent K and R so R and K they are equivalent so we have 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 so moving on we have e and I so e and i these two are equivalent and then we these two are equivalent and then we have the last one is S and R so R occurs have the last one is S and R so R occurs again but we have encountered R here so again but we have encountered R here so we put s into the same batch the same we put s into the same batch the same hash set or three set or whatever it's a hash set or three set or whatever it's a union union all of these three characters they are all of these three characters they are equivalent because of transitivity right equivalent because of transitivity right it transits it's transitive okay it transits it's transitive okay So So based on the first example we can tell based on the first example we can tell we basically need to find the we basically need to find the lexicographically smallest character in lexicographically smallest character in the same batch because in one batch the same batch because in one batch every single character they are every single character they are equivalent so then we find the smallest equivalent so then we find the smallest and the lexical graphic mismanus and the lexical graphic mismanus character in this patch that is character in this patch that is basically a representative so we'll use basically a representative so we'll use that one to represent the whole batch that one to represent the whole batch then we form a string that is lexical then we form a string that is lexical graphically smallest based on the base graphically smallest based on the base string so then we go through the space string so then we go through the space stream which is parser so P stream which is parser so P lexicographically smallest is M so we lexicographically smallest is M so we replace it by m a is still a it's a is replace it by m a is still a it's a is lexical graphic smallest character in lexical graphic smallest character in the alphabet and then r r smallest the alphabet and then r r smallest smallest is this batch okay so this one smallest is this batch okay so this one is already sorted like lexicographically is already sorted like lexicographically so it's k k is the representative so we so it's k k is the representative so we replace r with K right so and then we replace r with K right so and then we encounter s s is also in this batch so encounter s s is also in this batch so its representative is also K so we its representative is also K so we replace it with K here and then we replace it with K here and then we encounter Eid e is in this batch itself encounter Eid e is in this batch itself is the representative of this batch so is the representative of this batch so we keep e here and then we encounter r r we keep e here and then we encounter r r is in this patch which represents is in this patch which represents sensitive is K sensitive is K so we formed this lexical graphically so we formed this lexical graphically 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 so walking through the first example we know exactly what we need to do right so know exactly what we need to do right so we basically need to find we go through we basically need to find we go through the two equivalent strings we hash out the two equivalent strings we hash out all of the strings as long as they are all of the strings as long as they are equivalent based on the three rules they equivalent based on the three rules they are re flexitivity symmetry transitivity are re flexitivity symmetry transitivity based on these three rules we hash them based on these three rules we hash them into different by hashing I don't mean into different by hashing I don't mean hash map but it just means we sort out hash map but it just means we sort out all of the equivalency relationships all of the equivalency relationships between each character in these two between each character in these two strings and then we can go through the strings and then we can go through the space string one by one we find the space string one by one we find the representative which is the lexical representative which is the lexical graphically splawnist graphically splawnist character and then we can just return character and then we can just return um so I think um so I think um the most challenging or the most um the most challenging or the most interesting uh the most media part of interesting uh the most media part of this problem is that how do we translate this problem is that how do we translate this transitivity rule into actual this transitivity rule into actual coding coding um the problem the first thing that came um the problem the first thing that came into my mind is Union find and the only into my mind is Union find and the only uh related topic here is Union fine so uh related topic here is Union fine so we can introduce a template here to we can introduce a template here to tackle Union fine basically it's tackle Union fine basically it's similar to almost like a recursive or we similar to almost like a recursive or we can solve it in the iterative way so can solve it in the iterative way so what I usually do is I introduce a class 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 blah blah all the way to Z so here and if we have an array we can easily 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 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 so here we want to introduce another so here we want to introduce another method which is basically to iteratively method which is basically to iteratively to find the smallest index that can to find the smallest index that can represent this group so we'll use x represent this group so we'll use x introduce another one a and Y introduce another one a and Y B B and if x is smaller than and if x is smaller than y so this is the index of y so this is the index of um of this character A or B that we can um of this character A or B that we can find inside this find inside this IDs array IDs array if this is the case IDs y if this is the case IDs y will use x as the representative for y will use x as the representative for y otherwise otherwise will use IDs X as the or use y as the will use IDs X as the or use y as the representative of IDs X okay now we need representative of IDs X okay now we need one more one more method which is called find find or just method which is called find find or just taking X taking X which is the chart itself so as long as which is the chart itself so as long as while while while x minus so here is a one more a while x minus so here is a one more a little bit tricky thing but also little bit tricky thing but also something something to remember as well something something to remember as well which is which is um I know how to handle missing Java in um I know how to handle missing Java in other programming languages you can do other programming languages you can do similar things which is use the similar things which is use the character minus this character a which character minus this character a which is the base of all of the 26 characters is the base of all of the 26 characters then you get an integer if this one is then you get an integer if this one is not equals to not equals to this one itself what we will do is that this one itself what we will do is that we will keep doing so until we find it IDs 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 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 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 uh class uh class we we will have we we will have an instance of this data and this class an instance of this data and this class that we just defined you we can call it that we just defined you we can call it Union f Union f e oops I'll just call it UF e oops I'll just call it UF and then and then what we will do is we will Union these what we will do is we will Union these two c one and C2 and then after we Union two c one and C2 and then after we Union all of them we have completely mutated all of them we have completely mutated this IDs right when we call Union we this IDs right when we call Union we basically hash these two into the same basically hash these two into the same equivalence set which is represented by equivalence set which is represented by this IDs array okay this IDs array okay after we initialize so first step is we after we initialize so first step is we initialize this a new instance of this initialize this a new instance of this class which caused this Constructor class which caused this Constructor which initialized this is this idea which initialized this is this idea array which has all of the index as its array which has all of the index as its value value and after we call Union it's going to and after we call Union it's going to call find and construct all of the call find and construct all of the equivalency in relationship and then equivalency in relationship and then afterwards what we'll do is we'll just afterwards what we'll do is we'll just go through go through this base string to channel array this base string to channel array what we can do we want to have a string what we can do we want to have a string Builder 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 accepted accepted um um beats 76 percent beats 76 percent um memory bits sixty percent uh anyways um memory bits sixty percent uh anyways um so this is the uh a very uh um so this is the uh a very uh interesting problem and very interesting problem and very um core problem and it basically um core problem and it basically um so what I would do what I would share um so what I would do what I would share with you guys is to apply in this with you guys is to apply in this template this is one of my favorite template this is one of my favorite templates templates you can construct a Class A customized you can construct a Class A customized class and you can have an array of IDs class and you can have an array of IDs in this case for solving legal problems in this case for solving legal problems is usually 26 or 52 of a very small is usually 26 or 52 of a very small number and then you construct it number and then you construct it initialize it with the value as with the initialize it with the value as with the index as its value and then we always index as its value and then we always based on the problem requirements in based on the problem requirements in this case we try to find the smallest this case we try to find the smallest index as the group representative index as the group representative basically basically and then you you call you you and then you you call you you iteratively call this ID until you find iteratively call this ID until you find that this ID is really representing that this ID is really representing itself basically like a this index is itself basically like a this index is representing itself in this case we exit representing itself in this case we exit uh we know we find the smallest group uh we know we find the smallest group representative representative um all right I hope this is a pretty um all right I hope this is a pretty long video but I hope I've conveyed my long video but I hope I've conveyed my points clearly enough and very points clearly enough and very worthwhile very immediate problem if you worthwhile very immediate problem if you can deeply understand that problem a lot can deeply understand that problem a lot of other Union find Lincoln problems of other Union find Lincoln problems that it can solve that it can solve um I strongly encourage you guys to um I strongly encourage you guys to really use your use a piece of use a really use your use a piece of use a piece of paper uh like I I did use a piece of paper uh like I I did use a piece of paper and a pencil to hash out piece of paper and a pencil to hash out everything why we need to uh for the everything why we need to uh for the fine method and for example why do we fine method and for example why do we need to have such a while method to find need to have such a while method to find the lowest one is this like an elegant the lowest one is this like an elegant way could it be more efficient things way could it be more efficient things like this to figure it out like this to figure it out um yeah if you guys find this video um yeah if you guys find this video helpful and please do me a favor helpful and please do me a favor subscribe first and then hit the like subscribe first and then hit the like button that really means a lot to me and button that really means a lot to me and helps helps with the YouTube algorithm helps helps with the YouTube algorithm so so um and I'll see you guys in the next one um and I'll see you guys in the next one thank you so much
2024-03-25 16:34:45
1,061
https://i.ytimg.com/vi/H…axresdefault.jpg
LeetCode 1061. Lexicographically Smallest Equivalent String - Interview Prep Ep 130
TTT_tLA5aMY
word abbreviation so we are given an array of nonempty strings and then we array of nonempty strings and then we need to generate minimal possible need to generate minimal possible abbreviations and we have some rules so abbreviations and we have some rules so we need to begin with the first we need to begin with the first character then the number of characters character then the number of characters abbreviated followed by the last abbreviated followed by the last character and then if there's a conflict character and then if there's a conflict we need to abbreviate the word some more we need to abbreviate the word some more until uh we have one unique abbreviation until uh we have one unique abbreviation for each word for each word if that's not if we can't then we just if that's not if we can't then we just want to return the original words then want to return the original words then finally uh if the abbreviation doesn't finally uh if the abbreviation doesn't make the word shorter then you want to make the word shorter then you want to keep it as the original so uh that's the keep it as the original so uh that's the question so for now I'll get the input question so for now I'll get the input then we can work through uh the rules to then we can work through uh the rules to make them much more clearer so for now make them much more clearer so for now I'll just do this and then I'll do this I'll just do this and then I'll do this so uh here I'll increment my so uh here I'll increment my Visual and then I'll also wrap them so 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 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 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 10 yeah so sorry I think I I might have 10 yeah so sorry I think I I might have miscounted but if we add the we have 1 2 miscounted but if we add the we have 1 2 3 4 five so we have five so I'm just 3 4 five so we have five so I'm just going to change it to five and then here going to change it to five and then here we also want to do the same we want to we also want to do the same we want to add the T and then when we add the T now add the T and then when we add the T now we remain with five items we remain with five items that we want to retain as part of the that we want to retain as part of the abbreviation so since the abbreviation abbreviation so since the abbreviation is still same what you want to do is is still same what you want to do is want to add the next letter so in this want to add the next letter so in this case we add E when you add e we remain case we add E when you add e we remain with four words that we will remove and with four words that we will remove and then here we want to do the same so we then here we want to do the same so we want to add R and then we'll remain with want to add R and then we'll remain with four so at this point our abbreviations four so at this point our abbreviations are unique and since they're unique we are unique and since they're unique we can return them so others were like this can return them so others were like this one for good one for good so this one for God we have taken so this one for God we have taken according to the first rule we will have according to the first rule we will have begin with the first character which is begin with the first character which is G then the number of characters that we G then the number of characters that we want to remove which is one and then D want to remove which is one and then D and then doing that it breaks the last and then doing that it breaks the last rule which is the abbreviation uh if it rule which is the abbreviation uh if it doesn't make it shorter then we stick doesn't make it shorter then we stick with it so here it will have been God with it so here it will have been God then uh going to me we can just come and then uh going to me we can just come and do that so for me here we we have me so do that so for me here we we have me so if you are to do it we will have ADD M if you are to do it we will have ADD M then we have e then we add a zero so as then we have e then we add a zero so as you see this breaks the third rule so it you see this breaks the third rule so it means we want to rain the original word 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 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 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 abbreviation and then uh the another abbreviation and then uh the another thing that we want to have is we want to thing that we want to have is we want to have a Q so a q will help us like when have a Q so a q will help us like when we keep on like uh increasing the prefix we keep on like uh increasing the prefix so it will keep us it will help us to so it will keep us it will help us to track this uh which word we need to track this uh which word we need to continuously map so we'll have that and continuously map so we'll have that and then once we have a queue then uh then once we have a queue then uh finally we can have our final variable finally we can have our final variable which will just be result which will be which will just be result which will be a list that we want to return at the end a list that we want to return at the end of the day so uh with all our variables of the day so uh with all our variables now we can start so the first thing we now we can start so the first thing we want to do is we'll want to Loop through want to do is we'll want to Loop through our dictionary not through our list of our dictionary not through our list of words and uh in their case they call it words and uh in their case they call it dict so Loop through list of dict so Loop through list of strings it's called strings it's called dict then once we Loop so we'll start at dict then once we Loop so we'll start at the first one which is like then we want the first one which is like then we want to get the abbreviation then once you to get the abbreviation then once you get the abbreviation we want to add it get the abbreviation we want to add it to our obviation dictionary so we Loop to our obviation dictionary so we Loop through the list so when we are looping through the list so when we are looping so our second point it's going to be so our second point it's going to be inside the loop so we get inside the loop so we get abbreviation abbreviation of current of current word and then once we get the word and then once we get the abbreviation of current word we want to 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 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 i7n and then I want we do for i7n and then I want we do for intention we want to do for our face so intention we want to do for our face so for face it will be F2 e and then our for face it will be F2 e and then our want to do for face we also want to do want to do for face we also want to do for intrustion which will be for intrustion which will be uh this one i7 n so we'll add it here so uh this one i7 n so we'll add it here so once we get the abbreviation for our B once we get the abbreviation for our B so at the point that our Loop ends this so at the point that our Loop ends this is how our abbreviation day should look is how our abbreviation day should look like so once we have all these items in like so once we have all these items in our dictionary now we the loop has ended our dictionary now we the loop has ended so we want to add we want to check like so we want to add we want to check like are some of these items like like uh are some of these items like like uh since it's it's only one word with the since it's it's only one word with the abbreviation we just want to put it abbreviation we just want to put it inside our final dictionary then when inside our final dictionary then when you come to good since it's also one you come to good since it's also one we'll want to put it that so that's what we'll want to put it that so that's what you want to do so we're going to Loop you want to do so we're going to Loop through all the items inside our through all the items inside our dictionary and then this item so like dictionary and then this item so like here we get the value we check if the here we get the value we check if the length is one we add it to our final length is one we add it to our final dictionary but if the length is not one dictionary but if the length is not one then we want to add it to our queue so then we want to add it to our queue so that we can continue continue like that we can continue continue like abbreviating it some more so that's what abbreviating it some more so that's what you want to do so for our step three as you want to do so for our step three as we have said we look through our we have said we look through our dictionary so look through our a BRI dictionary so look through our a BRI dictionary and then when we are looping dictionary and then when we are looping through what we've said we want to do is through what we've said we want to do is we want to check for the length so we we want to check for the length so we looping through our division dictionary looping through our division dictionary then we check uh if the length of the then we check uh if the length of the value uh is one uh if it is then we want to dictionary and then uh if it's not one dictionary and then uh if it's not one else what we want to do is we want to 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 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 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 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 conflict so for our this conflict we conflict so for our this conflict we want to instantiate it as want to instantiate it as true so once we instantiate it as true true so once we instantiate it as true we want the following step steps to keep we want the following step steps to keep on repeating so long as that's true so on repeating so long as that's true so uh the first uh the first step is we want it to do what we want to step is we want it to do what we want to so we yeah so we want to when whenever so we yeah so we want to when whenever we start we want to uh mark it as false we start we want to uh mark it as false so course during this step we hope so course during this step we hope to uh to kind of fix the conflict issues to uh to kind of fix the conflict issues so we'll just mark it as false and then so we'll just mark it as false and then in case we don't fix it we'll return it in case we don't fix it we'll return it to tr true so once we've marked it as to tr true so once we've marked it as false then we want to remove everything false then we want to remove everything we want to clear our abbreviation 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 so long as our Q isn't empty so it means we want to L as long as we have that and then uh once we have everything that and then uh once we have everything in our queue so what we want to do is if in our queue so what we want to do is if we have an item in our que what we want we have an item in our que what we want to do is we want to get the abbreviation to do is we want to get the abbreviation then once we get the abbreviation the then once we get the abbreviation the new abbreviation then we want to add it new abbreviation then we want to add it to our dictionary and then once we add to our dictionary and then once we add it to our dictionary we want to remove it to our dictionary we want to remove it from our yeah we want to remove it it from our yeah we want to remove it from our queue then we want to add it to from our queue then we want to add it to our dictionary so that's all we going to our dictionary so that's all we going to do so uh here we going to start here do so uh here we going to start here we'll remove the first left item then we'll remove the first left item then once we remove it we going to get the once we remove it we going to get the next abbreviation so in this case our next abbreviation so in this case our next abbreviation it will have been I next abbreviation it will have been I and 5 L as we had previously this and 5 L as we had previously this discuss on the rules so since this is discuss on the rules so since this is our next abbreviation we want to now add our next abbreviation we want to now add this one inside our abbreviation this one inside our abbreviation dictionary and then so we're going to dictionary and then so we're going to add it as the key and then the internal add it as the key and then the internal as its value so that's what you want to as its value so that's what you want to do so we look through then uh here we do so we look through then uh here we want to pop so pop uh want to pop so pop uh off an off an item then once we pop off the item then item then once we pop off the item then the next thing want should do is we want the next thing want should do is we want to get the next abbreviation so we can to get the next abbreviation so we can just say next just say next abbreviation for it then once we get the abbreviation for it then once we get the next abbreviation for it then sorry I next abbreviation for it then sorry I I've mistaken my numbering so we have I've mistaken my numbering so we have eight then we have eight then we have n then uh finally we have 10 so we get n then uh finally we have 10 so we get the next abbreviation then once we get the next abbreviation then once we get the next abbreviation we want to add the the next abbreviation we want to add the abbreviation 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 at so uh we can uh go through all this at so uh we can uh go through all this step we can now check this step step we can now check this step together so here we say we create a together so here we say we create a variable is conflict true then uh we variable is conflict true then uh we mark it as false then we want to remove mark it as false then we want to remove everything from our abbreviation everything from our abbreviation dictionary then we want to loop as long dictionary then we want to loop as long as we have items in our que so here we as we have items in our que so here we have our Q so earlier on our Q had six have our Q so earlier on our Q had six this so this is we'll just get it this so this is we'll just get it quickly and then just paste it so when quickly and then just paste it so when we pop off we will remove this part so we pop off we will remove this part so uh this is this part here so this is uh this is this part here so this is what we have at this SP so you're going what we have at this SP so you're going to get its next abbreviation we said to get its next abbreviation we said that the next abbreviation was i n 5 l that the next abbreviation was i n 5 l so this is our next abbreviation and so this is our next abbreviation and then uh once we get our next subd then uh once we get our next subd deviation which is I in 5 L then what we deviation which is I in 5 L then what we want to do is we want to add it inside want to do is we want to add it inside our abbreviation dictionary so at this our abbreviation dictionary so at this point our abbreviation dictionary point our abbreviation dictionary should have i n 5 L and then the value 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 intention and then uh once it does that intention and then uh once it does that then uh it's done with this one so again then uh it's done with this one so again it comes and pops off this one so we'll it comes and pops off this one so we'll pop it off again then once we pop it off pop it off again then once we pop it off we get the next iation which is i6n then we get the next iation which is i6n then we want to add the same to our we want to add the same to our dictionary so here we'll have dictionary so here we'll have in so uh with this uh we will uh be done in so uh with this uh we will uh be done with the so yeah so once at this point with the so yeah so once at this point now we don't have anything in our queue now we don't have anything in our queue so we'll finish this so once we finish so we'll finish this so once we finish that then now we want to come to our that then now we want to come to our Step 11 so for our Step 11 uh it will Step 11 so for our Step 11 uh it will just be uh doing what we had just be uh doing what we had in step three so we'll just have this in step three so we'll just have this part but it's okay we'll just come and part but it's okay we'll just come and we'll copy it cuz it's easier so our we'll copy it cuz it's easier so our Step 11 will just be step three so I'll Step 11 will just be step three so I'll just do that so our 11 will be equals to just do that so our 11 will be equals to step three so we look through our step three so we look through our obviation dictionary in case any of them obviation dictionary in case any of them has a value of one we want to add it to has a value of one we want to add it to our final dictionary if that's not the our final dictionary if that's not the case then what we want to do is uh we case then what we want to do is uh we want to add it to our queue so here this want to add it to our queue so here this is not the case so our final dictionary is not the case so our final dictionary will remain as it is then here for our Q will remain as it is then here for our Q our Q now we have i n 5 L our Q now we have i n 5 L cuz cuz like we are looking through this cuz cuz like we are looking through this item so it's going to come to the first item so it's going to come to the first one get this part so here it will be I one get this part so here it will be I in5 L then here it's also going to be i in5 L then here it's also going to be i n 5 L and then here it will be i n n 5 L and then here it will be i n 6n which uh it's going to get from our 6n which uh it's going to get from our dictionary here and then also this one dictionary here and then also this one is going to be i n 6n so it will do this is going to be i n 6n so it will do this until we'll have no until we'll have no items uh left we will'll have no items items uh left we will'll have no items with a length of more than that and then with a length of more than that and then at the end of the at the end of the day uh what will happen is now we will day uh what will happen is now we will come out of oh yeah so here when we are come out of oh yeah so here when we are adding it to the que once we finish adding it to the que once we finish adding everything to the queue we want adding everything to the queue we want to add another step where we Mark our to add another step where we Mark our conflict as true CU we found uh some conflict as true CU we found uh some that share the same abbreviation so once that share the same abbreviation so once we find that then we want to come out of we find that then we want to come out of it so uh that means that at this point it so uh that means that at this point now we'll come back to here on step four now we'll come back to here on step four so once we come up to back to step four so once we come up to back to step four then uh what we can now currently do at then uh what we can now currently do at this point our final this some is going to come and copy this some is going to come and copy it and then so once it's this way so uh it and then so once it's this way so uh it will have this other one so for it will have this other one so for internal we know it's internal we know it's internal so it will be internal internal so it will be internal internal and then uh for Interval it internal and then uh for Interval it will be will be interval and then after interval we have interval and then after interval we have another one so we have internal interval another one so we have internal interval then we have intention and then we also then we have intention and then we also have intrusion but for intention and have intrusion but for intention and intrusion we s earlier that the last intrusion we s earlier that the last point will be here where we had int four point will be here where we had int four and then intrustion will be this so I'll and then intrustion will be this so I'll just copy this and for in 10 yeah so just copy this and for in 10 yeah so we'll have something like this so this we'll have something like this so this one is one is for sorry it's supposed to be the other for sorry it's supposed to be the other way around so here we'll have intention I wish is I intention I wish is I in for n so we'll have this and then I in for n so we'll have this and then I yeah this one will be for yeah this one will be for Interval so uh with this we'll have this Interval so uh with this we'll have this so this is our at this point this will so this is our at this point this will be our dictionary and then now we want be our dictionary and then now we want to uh look through uh the list of to uh look through uh the list of strings that you were given earlier so strings that you were given earlier so I'll just come and copy it I'll just come and copy it so at this point we just want to do this so at this point we just want to do this so you look through this and then when so you look through this and then when you Loop through this uh now you just you Loop through this uh now you just add them to our rest variable so you add them to our rest variable so you just do rest just do rest append so we do like the first one was append so we do like the first one was like on the left side so here on the vs like on the left side so here on the vs code the first one is like so that's code the first one is like so that's what you want to do so you just come and what you want to do so you just come and do final day at like so we just do final do final day at like so we just do final D dictionary and then we do at like and D dictionary and then we do at like and then we see it's L2 e so it means here 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 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 declaration and then uh once I copy it declaration and then uh once I copy it I'll make now this one bigger and then I'll make now this one bigger and then I'll save this and then I'll split it to I'll save this and then I'll split it to the the right and then once I split it now I'll right and then once I split it now I'll just come here and do that so uh just come here and do that so uh probably the only thing that we want to probably the only thing that we want to do is from collections we are going to do is from collections we are going to import a deck so that you can have our 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 this so we want to start 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 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 E so uh we can Define it so it will be E so uh we can Define it so it will be def this and then here uh we want to def this and then here uh we want to return something so this one was the return something so this one was the first part so this one was on rule one first part so this one was on rule one where you take the first letter as the where you take the first letter as the prefix then the last letter as the prefix then the last letter as the suffix then the two items that you want suffix then the two items that you want to remove as the number of items to to remove as the number of items to remove so that's what you want to do so remove so that's what you want to do so you want to do you want to do prefix so we said our prefix should be a prefix so we said our prefix should be a word at index zero so it means that we word at index zero so it means that we will need to pass in a word here and will need to pass in a word here and then uh once we do that then we want to then uh once we do that then we want to do num remove so these are the number of do num remove so these are the number of characters that you will remove uh so characters that you will remove uh so basically basically here it's two we can get this two by here it's two we can get this two by also getting the length of the string also getting the length of the string and then subtracting two from it so it and then subtracting two from it so it will be length of will be length of oneus 2 and then for our suffix it's oneus 2 and then for our suffix it's going to be the last letter on our word going to be the last letter on our word so we can just do that word and then we so we can just do that word and then we do negative one so this is basically our do negative one so this is basically our suffix then here we want to do suffix then here we want to do prefix and then we want to do uh num so prefix and then we want to do uh num so so we we have two ways of doing this the so we we have two ways of doing this the eest ways we can just de to have a eest ways we can just de to have a prefix number remove so instead of prefix number remove so instead of having this as a string we can just do having this as a string we can just do it as a tle to make the work easier so it as a tle to make the work easier so uh that's what we going to do for now so uh that's what we going to do for now so here we can have the here we can have the remove and then uh finally we can have remove and then uh finally we can have the suffix so that's going to be our the suffix so that's going to be our abbreviated one so here we have this so abbreviated one so here we have this so since it's a member of the class it will since it's a member of the class it will be self do that and then you don't want be self do that and then you don't want to pass in self you want to pass in the to pass in self you want to pass in the word that's coming here when you're are word that's coming here when you're are looping so uh we've done the first part looping so uh we've done the first part uh which is to get the verion of our uh which is to get the verion of our current word then we've added it to our current word then we've added it to our abbreviation so once this Lo Loops abbreviation so once this Lo Loops completes we expect it to be this way completes we expect it to be this way and then uh that's the first part so uh and then uh that's the first part so uh no we haven't added it sorry so I'm just no we haven't added it sorry so I'm just going to add it quickly so uh to add it going to add it quickly so uh to add it we'll just do this and then uh we wanted we'll just do this and then uh we wanted to add the abbreviation as the key so we to add the abbreviation as the key so we can just do this and then our python can just do this and then our python allows us to kind of check uh inside a allows us to kind of check uh inside a dictionary if you have it if you have it dictionary if you have it if you have it then uh it's just going to add but if it then uh it's just going to add but if it doesn't you can specify something as doesn't you can specify something as default so for in our case we wanted to default so for in our case we wanted to specify the empty list uh which is in specify the empty list uh which is in accordance to the value that we provided accordance to the value that we provided here in line 15 so uh with that we want here in line 15 so uh with that we want to also add uh the word so that uh we to also add uh the word so that uh we can have this so this is this and then can have this so this is this and then at this point uh if we we were to run at this point uh if we we were to run this function up to this point so our this function up to this point so our abbreviation dictionary on the left here abbreviation dictionary on the left here will look like this so here with that we will look like this so here with that we are done with number one and two so you are done with number one and two so you want to come to step want to come to step three so let step three is just looking three so let step three is just looking through the abbreviation D and then we through the abbreviation D and then we want to check if the length of the value want to check if the length of the value uh is one if it is we want to add it to uh is one if it is we want to add it to the final the final dictionary so here we check uh here in dictionary so here we check uh here in the dictionary that we had above like the dictionary that we had above like what's the length of the value so here what's the length of the value so here the length of this one is one so you add the length of this one is one so you add it to our final dictionary so that's it to our final dictionary so that's what you want to do so we'll just look what you want to do so we'll just look through so we'll just do through so we'll just do four uh we have the key and then the four uh we have the key and then the value so we can just do 4 KV in value so we can just do 4 KV in abvd uh do abvd uh do items and then uh once we do that so we items and then uh once we do that so we check if the length of V so you can just check if the length of V so you can just do if Len of do if Len of V is equals to one so uh in this case uh V is equals to one so uh in this case uh it it is so we want to to add so we just come is so we want to to add so we just come and do final day add the current cuz we and do final day add the current cuz we want the abbreviation no we want the want the abbreviation no we want the word first so we'll get V at zero so you word first so we'll get V at zero so you you see here our like is in the v and you see here our like is in the v and then the index is at index zero so then the index is at index zero so that's how you do v0 and then we are that's how you do v0 and then we are going to use the same structure for going to use the same structure for python where we if we don't have it then python where we if we don't have it then uh no actually we don't need to do this uh no actually we don't need to do this structure because for the final one it structure because for the final one it should always be like one item so since should always be like one item so since it's one item we will just do the key it's one item we will just do the key like that and then we are done with that like that and then we are done with that and then so we we've done this part here and then so we we've done this part here so that's step four and then now we want so that's step four and then now we want to do step five which is add it to the to do step five which is add it to the que so if it's not so you're going to do que so if it's not so you're going to do an else then want to do an else then want to do Q do append Q do append and then uh we want to look at the and then uh we want to look at the structure so uh in our case we appended structure so uh in our case we appended the abbreviated word and then the word the abbreviated word and then the word that we have so but you remember where that we have so but you remember where we had like the values that's inter we had like the values that's inter internal we came we did for I6 L internal we came we did for I6 L internal then we did this so it means we internal then we did this so it means we want to look we get the first word then want to look we get the first word then we add it to the que then we look again we add it to the que then we look again we get the next so and add it to the Q we get the next so and add it to the Q so that's what you want to do so we so that's what you want to do so we going to do for in going to do for in v and then we want to come and do that v and then we want to come and do that so we just want to do Q do append and so we just want to do Q do append and then we want to append our key and our then we want to append our key and our Val so uh with this uh we are done with Val so uh with this uh we are done with step three up to step three up to five so once we are done with that now five so once we are done with that now we can continue so we can just come in we can continue so we can just come in now go to step four which is creating a now go to step four which is creating a variable is variable is conflict so I just come and do that so conflict so I just come and do that so for our conflict we want to start it as for our conflict we want to start it as false and then we'll just look so long false and then we'll just look so long as no sorry uh we said that we always as no sorry uh we said that we always want to instantiate it with true so want to instantiate it with true so sorry about that so here we want to do sorry about that so here we want to do true and then we want to Loop so long as true and then we want to Loop so long as uh there's a conflict so you can just uh there's a conflict so you can just come and do wi listen conflict come and do wi listen conflict then uh always cuz if this step if we then uh always cuz if this step if we run through this Loop we expect to run through this Loop we expect to resolve the conflict so here we want to resolve the conflict so here we want to mark it at false but in case we don't mark it at false but in case we don't resolve it we'll mark the conflict as resolve it we'll mark the conflict as true as you will true as you will see so once we do that then now we want see so once we do that then now we want to remove everything from our to remove everything from our abbrv so there are so many ways of doing abbrv so there are so many ways of doing it in Python for now we can just do this it in Python for now we can just do this and then once we do this then now we and then once we do this then now we want to start so we going to look as want to start so we going to look as long as we have items in the que so you 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 left yeah so once we pop off the item left yeah so once we pop off the item then we want to get the next then we want to get the next abbreviation so we can just call here abbreviation so we can just call here next next abbreviation and then uh we've said we abbreviation and then uh we've said we we're going to define the function so we're going to define the function so it's going to be get next it's going to be get next abbreviation yeah so once we do this abbreviation yeah so once we do this then uh okay so let's just go and Define then uh okay so let's just go and Define this function and then we can come back this function and then we can come back so for this function so for this function uh it will just be almost like the first uh it will just be almost like the first one uh the only difference is uh we'll one uh the only difference is uh we'll also want to pass in the abbreviated so also want to pass in the abbreviated so we want to have this abbreviations and we want to have this abbreviations and then also we want to pass in the word so then also we want to pass in the word so this will be the only this will be the only difference so for now I'll copy this and difference so for now I'll copy this and then uh as I'm doing this I've then uh as I'm doing this I've remembered that we also like when you're remembered that we also like when you're getting the abbreviation getting the abbreviation we don't want to get the abbreviation we don't want to get the abbreviation for letters such as God since God is for letters such as God since God is like three and the abbreviation will like three and the abbreviation will have been G and D which is three so we have been G and D which is three so we don't want to do that or for me because don't want to do that or for me because the abbreviation will be the abbreviation will be M3 e so we just want to do if the length M3 e so we just want to do if the length of the word so you can just come and do of the word so you can just come and do if length of if length of word uh is less than four so like if word uh is less than four so like if it's three like God we just want to it's three like God we just want to return the word so here we can just do return the word so here we can just do return word and then uh if that's not return word and then uh if that's not the case then continue so for this one the case then continue so for this one for getting the next abbreviation we for getting the next abbreviation we want to have the same thing but here want to have the same thing but here what we want to do is we want to check what we want to do is we want to check so if at any point our abbreviation is so if at any point our abbreviation is equals to the word that we want to equals to the word that we want to abbreviate or if at any point like here abbreviate or if at any point like here where you are doing i6 I five like that where you are doing i6 I five like that so if it at any point that number so if it at any point that number reaches two so this this number that you reaches two so this this number that you are removing if at any point it reaches are removing if at any point it reaches two CU if we do 2 minus zero we want to two CU if we do 2 minus zero we want to stop and return just the word so we can stop and return just the word so we can just do a at V at index one isal to just do a at V at index one isal to 2 then we want to return our word and 2 then we want to return our word and then if that's not the case then we want then if that's not the case then we want to do that so for our prefix right now to do that so for our prefix right now what we can do is we can have the prefix what we can do is we can have the prefix that's coming inside our abbreviation so that's coming inside our abbreviation so we can just come and we can just come and do abbreviation that we are coming at uh do abbreviation that we are coming at uh the first index which is at index zero the first index which is at index zero and then if we do that plus the and then if we do that plus the length length of its length this should give us the of its length this should give us the new new so I'm just going to do this with you so I'm just going to do this with you guys so that you can also be able to see guys so that you can also be able to see so here we had I6 l so when we did I I6 so here we had I6 l so when we did I I6 L we abbreviated it so right now the L we abbreviated it so right now the abbreviation is I6 l so as we've said uh abbreviation is I6 l so as we've said uh we first check so our abbreviation is we first check so our abbreviation is a6l it's not equals to internal so since a6l it's not equals to internal so since it's not equals to then it will go to it's not equals to then it will go to the next condition uh is the this one the next condition uh is the this one this one is six is this 6 equals to 2 no this one is six is this 6 equals to 2 no it's not equals to 2 so it means line 67 it's not equals to 2 so it means line 67 won't run so we'll find the prefix the won't run so we'll find the prefix the prefix is just what's coming in our prefix is just what's coming in our abbreviation so in this case our abbreviation so in this case our abbreviation at index Z which is I so abbreviation at index Z which is I so whatever's coming there is I so it's whatever's coming there is I so it's going to get to the I then we want to going to get to the I then we want to add so what's the what's its length so add so what's the what's its length so in this case the length is one so get in this case the length is one so get that and also get the word at index one that and also get the word at index one so in this case the word at index one uh so in this case the word at index one uh for for Interval for internal the it's n so it's Interval for internal the it's n so it's going to get that so now our new prefix going to get that so now our new prefix will be i n so that's what we are just will be i n so that's what we are just doing here and then here the number doing here and then here the number removed so here we were doing the length removed so here we were doing the length one minus 2 right now what you can do is one minus 2 right now what you can do is since you know that number six is coming since you know that number six is coming in as the next item we can just get it in as the next item we can just get it and then we subtract one sorry so I just and then we subtract one sorry so I just come here and get it so it will be a come here and get it so it will be a RV at index one and then what we want to RV at index one and then what we want to do is we want to subtract one CU we've do is we want to subtract one CU we've added like when we did when we we add n added like when we did when we we add n so it means we will only be removing the so it means we will only be removing the next five items so that's why we next five items so that's why we subtract one and then uh the suffix will subtract one and then uh the suffix will still be our last letter so uh this will still be our last letter so uh this will be how we will be getting the next be how we will be getting the next abbreviation so true to that we want to abbreviation so true to that we want to pass that so we've said that when we pop pass that so we've said that when we pop the queue we said that when you're the queue we said that when you're adding items to the queue we can come adding items to the queue we can come and check here we had the abbreviation and check here we had the abbreviation and we also add the word so right now and we also add the word so right now the first item is the abbreviation so we the first item is the abbreviation so we can just come and do pop l at index zero can just come and do pop l at index zero which is the first item then our next which is the first item then our next item is at index item is at index one so uh this is going to be uh give us one so uh this is going to be uh give us the next the next abbreviation so once we get the next abbreviation so once we get the next abbreviation we want to add the next abbreviation we want to add the next abbreviation to abbreviation d as the abbreviation to abbreviation d as the key then the value will be the word so key then the value will be the word so this is what you want to do so you want this is what you want to do so you want to come and you want to do to come and you want to do abbreviation abbreviation D D sorry yeah at next abbreviation d uh yeah sorry I was supposed to use get no it's okay sorry I 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 that's all so here we have this then 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 it and then uh once I copy it I'm just it and then uh once I copy it I'm just going to indent this and also this and going to indent this and also this and this and this and this so uh we've done this and this and this so uh we've done that then yeah so here we look through that then yeah so here we look through abbreviation dictionary then we check if abbreviation dictionary then we check if the length of the value is one if it is the length of the value is one if it is we add it to the final dictionary uh if we add it to the final dictionary uh if it's not then we want to add it to our it's not then we want to add it to our queue and then the moment we've added it queue and then the moment we've added it to our que we want to mark that there's to our que we want to mark that there's a conflict you remember how we said that a conflict you remember how we said that we hope to resolve the conflict in that we hope to resolve the conflict in that call but when it reaches this call but when it reaches this point uh it means that there's a point uh it means that there's a conflict cuz here we've added it to our conflict cuz here we've added it to our que and then since there's a conflict we que and then since there's a conflict we want to and abbreviate it again so this want to and abbreviate it again so this will happen so we've done that so at will happen so we've done that so at this point once we come out of this our this point once we come out of this our Loop so we'll be here at this point what Loop so we'll be here at this point what happens is now our final dictionary will happens is now our final dictionary will look like this and then now we just want look like this and then now we just want to Loop through our our list of strings to Loop through our our list of strings and then once we look through that we and then once we look through that we want to add them to our rest and then want to add them to our rest and then finally you want to return finally you want to return ours so I'm just going to do that so ours so I'm just going to do that so we're going to do we're going to do for uh so I can just call it item but for uh so I can just call it item but let me just call it forward in our dict let me just call it forward in our dict above so we just want to do uh okay so above so we just want to do uh okay so we want to add the abbreviation so we we want to add the abbreviation so we can just come and do abbreviation so uh can just come and do abbreviation so uh okay so one thing here we were using the okay so one thing here we were using the strings because uh we could see them strings because uh we could see them visually visually but at this point as you guys youve but at this point as you guys youve noticed we are using two PS so since we noticed we are using two PS so since we using two PS We want to make sure that using two PS We want to make sure that we we don't have them when you want to we we don't have them when you want to add the abbreviation we want to convert add the abbreviation we want to convert them to Strings so to do that we want to them to Strings so to do that we want to look through uh the the two PS so we look through uh the the two PS so we just want to do for I in uh our final just want to do for I in uh our final dictionary and then the word so here for dictionary and then the word so here for for example our final dictionary we get for example our final dictionary we get the word our word is like so we come and the word our word is like so we come and we look at like so when you look at like we look at like so when you look at like we will see L2 e so the thing is this L we will see L2 e so the thing is this L is a string the two is a number the e is is a string the two is a number the e is a string so since that's the case we a string so since that's the case we want to convert everything to a string want to convert everything to a string so I'll just do string at so I'll just do string at a and then once we do that then we want a and then once we do that then we want to use join so we just do do join to use join so we just do 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 rest and then uh once we done that then rest and then uh once we done that then at the end of the day we just want to at the end of the day we just want to return return rest and then our we want to test to see rest and then our we want to test to see uh if it works so we just do s equal to uh if it works so we just do s equal to solution and then uh once you do that solution and then uh once you do that you want to do you want to do print and then you want to do sorry print and then you want to do sorry s s dot word dot word abbreviation and then we want to get the 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 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 then I'll just copy and then we submit so uh so far it's submit so uh so far it's accepted so since uh it's accepted we're accepted so since uh it's accepted we're just going to try and just going to try and submit and see yay yeah fast so thank submit and see yay yeah fast so thank you guys for listening yeah bye
2024-03-22 16:47:29
527
https://i.ytimg.com/vi/T…oWvQn27lV-mkuc9A
Leetcode 527. Word Abbreviation
2yZxiW6gnis
so welcome back guys today I'm here to solve a deep equation which was I was solve a deep equation which was I was solving and I just solved by my own with solving and I just solved by my own with the help of the previous rated question the help of the previous rated question so I am want to explain my strategy what so I am want to explain my strategy what I have used to solve this question you I have used to solve this question you will find many of the solution out there will find many of the solution out there with the different YouTubers but I want with the different YouTubers but I want to explain my strategy to you so if you to explain my strategy to you so if you want to you can watch this video so it want to you can watch this video so it will be simple solution first of all the will be simple solution first of all the question is that shortest comma question is that shortest comma subsequence first of all I will explain subsequence first of all I will explain you what do you mean by this problem as you what do you mean by this problem as in this question you have given two in this question you have given two substring two string S1 and S2 you have substring two string S1 and S2 you have to combine these two string and you have to combine these two string and you have to combine in this way that the string to combine in this way that the string between combined should have the between combined should have the shortest length so that both the string shortest length so that both the string or the string uh subsequence of the bow or the string uh subsequence of the bow string should be lie in that long string string should be lie in that long string what do you understand it Let Me Show what do you understand it Let Me Show You by You by illustrations illustrations I was just recording this video but I I was just recording this video but I was not able to record the volume of was not able to record the volume of audio audio so I'm recording this again no problem so I'm recording this again no problem at all at all first of all okay first of all okay I have a string I have a string a b a c a string two a b a c a string two wait a minute I have to see with the wait a minute I have to see with the example c a b okay c a p example c a b okay c a p so what do you mean if I'm combining so what do you mean if I'm combining both the string together as I will just both the string together as I will just add a concatenate this bootstring add a concatenate this bootstring a b a c and c a b a b a c and c a b as I the answer is 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 sorry for the or okay so you can see that so you can see that I can find a b a c and c a b in this I can find a b a c and c a b in this string but the the question is not string but the the question is not satisfied with the solution why because satisfied with the solution why because this string can be more strong more this string can be more strong more small as a quotient volt as you can small as a quotient volt as you can introduce this string as a b a c and c a introduce this string as a b a c and c a b has uh you can reduce by writing this b has uh you can reduce by writing this as BAC and c a b a b 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 a b a c here and you can answer find a c a b c a b here so what you are saying that I have to reduce this whole big string okay okay so how you can do this as a b a c and c a b the 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 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 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 a b now I will remove from one of the string I just removed I will just add c a b a 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 you have cleared what you have to think you have cleared what you have to think you have to just find this common you have to just find this common sequence common logins from a sequence common logins from a subsequence then you have to delete from subsequence then you have to delete from one of the air one of the string okay one of the air one of the string okay now now if you are doing this as uh you have a if you are doing this as uh you have a array strings as well as array strings as well as what uh three uh what I am saying a a c what uh three uh what I am saying a a c a c b a and S2 as three as a b c a 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 a c a okay so a c a c a b so this is the subsequence longest a c a 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 tabulation method okay tabulation method okay as you're using the tabulation method or as you're using the tabulation method or you have done this question with the you have done this question with the helper tabulation method so what you are helper tabulation method so what you are getting as I'm just keep taking a string getting as I'm just keep taking a string as okay this string only I'm taking the as okay this string only I'm taking the small string for the small demonstration small string for the small demonstration then we will just move forward to move then we will just move forward to move forward move forward towards the code as forward move forward towards the code as a a a b c a a b c a okay ABC and cab so this is our one two three and this is straight end 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 he sorry he sorry can we use a different color a b c now my code will work like that if for now my code will work like that if for Loop enter I equals to 1 Loop enter I equals to 1 and I is smaller than M and M is equals and I is smaller than M and M is equals to size of S Plus 1. to size of S Plus 1. size of s plus 1 size of s plus 1 and I plus plus and I plus 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 now check if now check if as one as one I minus 1 is equal equals to S2 J minus 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 what the hell condition is DP of what the hell condition is DP of I and J is equals to I and J is equals to Max of Max of DP of I minus 1 or J and DP of DP of I minus 1 or J and DP of i j minus 1 i j minus 1 okay so what is the DP of I minus 1 DBI okay so what is the DP of I minus 1 DBI minus 1 here and this both maximum it's minus 1 here and this both maximum it's zero now I move ahead are the same C and zero now I move ahead are the same C and B I can take the refrigerant are the B I can take the refrigerant are the same no same no these are not same so we will take 0. these are not same so we will take 0. and maximum maximum is the maximum is 0 and maximum maximum is the maximum is 0 okay okay uh now I will move ahead uh now I will move ahead cnz yes they are equal so what I will do cnz yes they are equal so what I will do I will just DP of I I will store the I will just DP of I I will store the answer right here answer right here inj plus 1 I think this is not visible 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 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 1 now I will just fill up the whole thing as the array maximum is one I will just fill it okay now this this match yes this match this match yes this magnesium maximum 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 okay 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 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 okay this match is clear as I am okay this match is clear as I am standing over here this index why I will standing over here this index why I will just use the while loop and I will just just use the while loop and I will just reduce see that if it should not equals reduce see that if it should not equals to 0 and and J should not equals to zero to 0 and and J should not equals to zero I am sending I will show you why I am I am sending I will show you why I am doing this this is my base condition now doing this this is my base condition now if I will see that if I will see that if if string ones string ones I minus 1 is equal equals to S2 I minus 1 is equal equals to S2 J minus 1 J minus 1 means this is equals to this means this is equals to this so what I will do and else this is not so what I will do and else this is not equal else okay okay now now what do you mean by when you're standing what do you mean by when you're standing here and what are these here and what are these these are the same answer which we have these are the same answer which we have used here used here you can see this code here you can see this code here you can see that these are the same word you can see that these are the same word that this is greater which one is that this is greater which one is greater are being stored the answer yes greater are being stored the answer yes 2 is greater in the both maximum number 2 is greater in the both maximum number is 2 H2 is stored here is 2 H2 is stored here now as the condition is like that if you now as the condition is like that if you are not this as characters are not are not this as characters are not matching so you will move to one of any matching so you will move to one of any one of the column okay either you will one of the column okay either you will move here either you move here let us move here either you move here let us see let us assume that we are moving see let us assume that we are moving towards minus I or this is I and this is towards minus I or this is I and this is J so we are using minus I okay J so we are using minus I okay so our else condition is if if DP I minus and J is greater DP I DP I J minus 1 so we will move J minus 1 so we will move this side this side as this is the as this is the this is greater I minus 1 is greater so this is greater I minus 1 is greater so move we will move this side move we will move this side this side okay we are moving this side so we will minus I I now what you have to do okay what you have to do you have to just you have to use you have to print the you have to use you have to print the longest string so I will just take a longest string so I will just take a very well string very well string A and S I'll just take a string A and S now I will just push answer string push to to S1 as I is rated to S1 S1 as I is rated to S1 minus 1 I as it is already reduced so I minus 1 I as it is already reduced so I will just move here now will just move here now what we will I will just explain you one what we will I will just explain you one minute I will just choose just complete minute I will just choose just complete the code because it's been a long video the code because it's been a long video I was not expecting that I would take 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 and I have just moved here okay now I and I have just moved here okay now I can see that this is also and this also can see that this is also and this also not matching so I will move not matching so I will move to the maximum one and I'm reviewing to the maximum one and I'm reviewing this one so I will just add here C this one so I will just add here C okay now see I've added now I will see okay now see I've added now I will see that these are matching I will just move that these are matching I will just move add one string I have just added one add one string I have just added one string I will move here string I will move here and I will just move backward here and I will just move backward here because I am just moving minus 1 and because I am just moving minus 1 and minus 1 in the both because I've just minus 1 in the both because I've just added this as you can see that I have added this as you can see that I have just come from minus 1 i n minus j i just come from minus 1 i n minus j i okay okay okay okay now where I am I have just added B now now where I am I have just added B now again I will check which is the smallest 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 J but my index is here at I J but my index is here at I means I am just trying to say that means I am just trying to say that as I was moving with this Loop my as I was moving with this Loop my condition this is true or false so this condition this is true or false so this is not completed this is true means I is not completed this is true means I have to just to move through for the have to just to move through for the next string means that my string is not next string means that my string is not completed mtds for the second one so I completed mtds for the second one so I will just so will just so right and while loop here for that J is right and while loop here for that J is smaller or greater than 0 so I will smaller or greater than 0 so I will write pushback write pushback push back push back has to has to J J minus minus minus minus as I have interested as I have interested int reduce also int reduce also and uh for same for and uh for same for same for I okay so this is the final same for I okay so this is the final code I will show you on the vs code okay is this is my simple this is my simple uh subsequence code from here you can see that I've just tried to use the base condition 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 was checking that is which one is was checking that is which one is smaller so I will just push then push smaller so I will just push then push again then I will just tell you I have again then I will just tell you I have just to use the while loop for the rest just to use the while loop for the rest over string then I have just revert the over string then I have just revert the string because I will just try them we string because I will just try them we are are traversing from back as this is from the traversing from back as this is from the reverse order BAC okay you can reverse order BAC okay you can understand that 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
2024-03-25 17:15:27
1,092
https://i.ytimg.com/vi_w…xresdefault.webp
DP | Shortest Common Supersequence | leetcode | 1092
IqU9i_vHdkY
[Music] October lead code challenge the problem October lead code challenge the problem that we have in today is path sum this that we have in today is path sum this is a fairly easy problem on lead code is a fairly easy problem on lead code and I believe the subscribers of coding and I believe the subscribers of coding decoded will be able to solve this decoded will be able to solve this question by themselves however if you question by themselves however if you are new then this video is for you the are new then this video is for you the question says you're given a binary tree question says you're given a binary tree and an integer value what do you need to and an integer value what do you need to do you need to identify whether there do you need to identify whether there exist a path starting from the root to exist a path starting from the root to the leaf such that all these nodes that the leaf such that all these nodes that lie in that path sum together to give lie in that path sum together to give you the target sum value if that path you the target sum value if that path exists you need to return true if that exists you need to return true if that path doesn't exist you need to return path doesn't exist you need to return false without further Ado let's quickly false without further Ado let's quickly walk through the presentation and I'll walk through the presentation and I'll be explaining the algorithm behind it be explaining the algorithm behind it why the BBD that I usually here you are why the BBD that I usually here you are given a binary tree I have taken the given a binary tree I have taken the same example and you are given a total same example and you are given a total value which is 22 in this case what will value which is 22 in this case what will I do I'll perform the DFS reversal and I do I'll perform the DFS reversal and I'll use recursion for this and I'll I'll use recursion for this and I'll keep track of the target sum that I'm keep track of the target sum that I'm looking for as that travs to the child looking for as that travs to the child nodes and I'll reduce the target node nodes and I'll reduce the target node value by the node value that we have for value by the node value that we have for example here the value is five so the example here the value is five so the target node that we are looking for gets target node that we are looking for gets reduced by five and I make the reduced by five and I make the invocation on the rest of the two sub invocation on the rest of the two sub trees that I have what I'm trying to say trees that I have what I'm trying to say let's understand it by the let's understand it by the iteration the target value given to you iteration the target value given to you in the question is 22 and the current in the question is 22 and the current root value is five so you subtract 5 by root value is five so you subtract 5 by 22 what do you get you get 17 so 17 gets 22 what do you get you get 17 so 17 gets percolated onto the left subtree and the percolated onto the left subtree and the target for this sub tree becomes 17 and target for this sub tree becomes 17 and the target for the right subtree also the target for the right subtree also become 17 so let's start the iteration become 17 so let's start the iteration and we will exactly do the same steps as and we will exactly do the same steps as I have just talked here 17 minus 4 what I have just talked here 17 minus 4 what does it lead to it leavs leads to 13 so does it lead to it leavs leads to 13 so the target for the left sub tree which the target for the left sub tree which is this sub tree becomes 13 and since is this sub tree becomes 13 and since the right sub tree of four is null uh we the right sub tree of four is null uh we will not do any invocation over here will not do any invocation over here let's proceed stay ahead and uh the let's proceed stay ahead and uh the target for this sub tree was 13 the target for this sub tree was 13 the current value is 11 11us 13 what does it current value is 11 11us 13 what does it give you it give you two so the target give you it give you two so the target for this sub tree becomes two and the for this sub tree becomes two and the target for this sub tree also becomes target for this sub tree also becomes two two is the Target that we are two two is the Target that we are looking for seven is a current node looking for seven is a current node value and what do you see you see here value and what do you see you see here this is a leaf node uh you subtract uh 2 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 reduced to 0 as a result of which uh reduced to 0 as a result of which uh this is not a happy path we will return this is not a happy path we will return Falls from over here because this is a Falls from over here because this is a leaf node and we haven't found the path leaf node and we haven't found the path that we were looking that we were looking for let's walk through the right path for let's walk through the right path and let me just change the color of and let me just change the color of pen here you see the Target that you pen here you see the Target that you were looking for is two the current node were looking for is two the current node value is also two these two are equal value is also two these two are equal and this node happens to be the leaf and this node happens to be the leaf node that means we have successfully node that means we have successfully identified a happy path we will be identified a happy path we will be returning true from over here true gets returning true from over here true gets returned from here true gets returned returned from here true gets returned from over here two gets returned from from over here two gets returned from over here and the final answer that gets over here and the final answer that gets returned out turns out to be true so we returned out turns out to be true so we will be performing or of the result will be performing or of the result returned from the right sub tree and the returned from the right sub tree and the or of the result returned from the left or of the result returned from the left sub tree so false minus false or true sub tree so false minus false or true gives you true as a result of which the gives you true as a result of which the final answer that gets percolated to the final answer that gets percolated to the top is true and this is what we are top is true and this is what we are going to do in the coding section as going to do in the coding section as well you can iterate over the right subt well you can iterate over the right subt by yourself but to conclude it further by yourself but to conclude it further let's look at the coding part I have let's look at the coding part I have written the code in a very simple manner written the code in a very simple manner I check if my root is null I return I check if my root is null I return false otherwise I check if my target sum false otherwise I check if my target sum happens to be equal to my root do Val happens to be equal to my root do Val that means I have found a happy case that means I have found a happy case along with this I should also check along with this I should also check whether the current node happens to be whether the current node happens to be the leaf node if that is the case as the leaf node if that is the case as well I return true otherwise I I trade well I return true otherwise I I trade it over the left sub tree and I reduce it over the left sub tree and I reduce the Target by Target sub minus root. Val the Target by Target sub minus root. Val similarly I rate over the right sub Tre similarly I rate over the right sub Tre I reduce the Target by Target sub minus I reduce the Target by Target sub minus root. Val exactly same in both these uh root. Val exactly same in both these uh iterations just root one in one case we iterations just root one in one case we are iterating over the left sub Tre in are iterating over the left sub Tre in other case we are iterating for the 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
2024-03-21 10:43:43
112
https://i.ytimg.com/vi/I…axresdefault.jpg
Leetcode 112 Path Sum | Coding Decoded SDE Sheet
K-Jz5eB1NIw
welcome to this new video where we will solve the heater's problem we have a solve the heater's problem we have a horizontal line and it will have houses horizontal line and it will have houses for example here the house is 1 3 4 6 8. for example here the house is 1 3 4 6 8. and these houses have to be heated for and these houses have to be heated for that we have heaters at certain that we have heaters at certain positions for example at positions 1 and positions for example at positions 1 and 5 here 5 here and we are given the ability to modify and we are given the ability to modify their radius the more we increase the their radius the more we increase the radius of a heater the more it covers radius of a heater the more it covers houses houses and the problem says that we need to and the problem says that we need to find the minimum radius that we give to find the minimum radius that we give to the heaters to cover all the houses the heaters to cover all the houses for example here they have a radius of for example here they have a radius of zero only house one is covered we zero only house one is covered we increase the radius now houses 1 4 and 6 increase the radius now houses 1 4 and 6 are covered but 3 and 8 are not are covered but 3 and 8 are not we increase the radius again houses 1 3 we increase the radius again houses 1 3 4 and 6 are covered we increase again 4 and 6 are covered we increase again now all the houses are covered now all the houses are covered so the minimum radius is three return so the minimum radius is three return three three note that you can neither modify note that you can neither modify positions of heaters nor add new ones positions of heaters nor add new ones and the same radius is applied to all and the same radius is applied to all the heaters the heaters okay how do we solve this problem okay how do we solve this problem we can think of a brute-force solution we can think of a brute-force solution that works as we did with the example that works as we did with the example now we start with a radius of zero and now we start with a radius of zero and we keep increasing until all houses are we keep increasing until all houses are covered covered for that we need two structures a set of for that we need two structures a set of uncovered houses and an array that uncovered houses and an array that contains the boundaries of the wrench contains the boundaries of the wrench covered by each heater covered by each heater in this example and covered initially in this example and covered initially contains one three four six eight contains one three four six eight but we move houses on positions where we but we move houses on positions where we have a heater because they are already have a heater because they are already covered even with a radius of 0 house 1 covered even with a radius of 0 house 1 gets removed gets removed and our heaters are in positions 1 and 5 and our heaters are in positions 1 and 5 who initialize their range at 1 1 and 5 who initialize their range at 1 1 and 5 5 respectively because their radius is 0 5 respectively because their radius is 0 they cover their position only they cover their position only now first iteration we increase the now first iteration we increase the radius we modify the ranges by radius we modify the ranges by decrementing the left boundary and decrementing the left boundary and incrementing the right boundary incrementing the right boundary here that one now covers front from 0 to here that one now covers front from 0 to 2 and healer 2 covers from 4 to 6. 2 and healer 2 covers from 4 to 6. the new covered positions are 0 2 4 and the new covered positions are 0 2 4 and 6 we'll remove houses that are in these 6 we'll remove houses that are in these positions positions the uncovered set isn't empty yet we the uncovered set isn't empty yet we continue we increment the radius the continue we increment the radius the ranges become one is one to three and ranges become one is one to three and three to seven three to seven in newly covered positions we can find in newly covered positions we can find how three we remove it from uncovered how three we remove it from uncovered we continue we increment the radius the we continue we increment the radius the ranges become minus two to four and two ranges become minus two to four and two to 8. to 8. in newly covered positions we can find in newly covered positions we can find house 8 remove it house 8 remove it uncovered set is empty now return radius uncovered set is empty now return radius is 3 we need a radius of at least 3 to 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 for the time complexity we put n as the for the time complexity we put n as the number of houses ammo the number of number of houses ammo the number of heaters and r as the final radius heaters and r as the final radius we have and for creating the set of we have and for creating the set of houses and for creating the set of houses and for creating the set of heaters and for calculating the set heaters and for calculating the set difference and to amp for creating the difference and to amp for creating the ranges array ranges array then for the loop at each iteration then for the loop at each iteration we're incrementing the radius so the we're incrementing the radius so the number of iterations is equal to r the number of iterations is equal to r the final value of radius final value of radius at each iteration we're traversing the m at each iteration we're traversing the m heaters while doing one operations heaters while doing one operations in total we get t of n m r is equal to in total we get t of n m r is equal to two n plus three m plus r times m which two n plus three m plus r times m which gives an o of n plus r times m time gives an o of n plus r times m time complexity complexity we can say that this algorithm is output we can say that this algorithm is output sensitive its running time depends on sensitive its running time depends on the output r in our case the output r in our case and for the space complexity we have n and for the space complexity we have n for the set of houses and for the set of for the set of houses and for the set of heaters and 2m for the ranges array we heaters and 2m for the ranges array we get m plus 3m which gives an of and plus 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 the idea of this second solution is that the idea of this second solution is that because all the heaters will have the because all the heaters will have the same radius a house will necessarily same radius a house will necessarily start being heated by its closest heater start being heated by its closest heater because when we keep increasing the because when we keep increasing the radius its closest heater is the first radius its closest heater is the first one that starts covering it one that starts covering it what we can do with this information is what we can do with this information is that for each house we calculate the that for each house we calculate the distance between it and its closest distance between it and its closest heater and after doing so we take the heater and after doing so we take the maximum amount the distances it maximum amount the distances it represents the smallest radius to cover 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 after the loop we just return the after the loop we just return the maximum distance which represents the maximum distance which represents the smallest possible radius smallest possible radius we can even keep track of the maximum we can even keep track of the maximum value which is the radius while value which is the radius while traversing houses to avoid losing space traversing houses to avoid losing space on storing the distances on storing the distances for the top complexity the outer loop is for the top complexity the outer loop is doing any iterations the number of doing any iterations the number of houses the envelope is doing m houses the envelope is doing m iterations the number of heaters and iterations the number of heaters and we're doing all one operations inside we we're doing all one operations inside we get an off and times m time complexity get an off and times m time complexity and for the space complexity we get one and for the space complexity we get one because we're not using size related 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 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 the first house is three and the first the first house is three and the first heater is one smaller so we increment i heater is one smaller so we increment i now heroes of is4 greater we stop we now heroes of is4 greater we stop we found where house at position 3 belongs found where house at position 3 belongs the distances between house and haters the distances between house and haters of i and heroes of i minus 1 are 1 and of i and heroes of i minus 1 are 1 and 2. the smallest one is 1 radius becomes 2. the smallest one is 1 radius becomes 1. next house is at position 12 we 1. next house is at position 12 we increment i we increment i we increment increment i we increment i we increment i and we found the right position i and we found the right position distances are 3 and 2 minimum is 2 it distances are 3 and 2 minimum is 2 it replaces radius replaces radius next house is at position 20 we next house is at position 20 we increment i we increment i and we found increment i we increment i and we found the right position the right position distances are three and four minimum is distances are three and four minimum is three it replaces radius three it replaces radius next house is at position 21 will next house is at position 21 will already have the right position of i already have the right position of i because the heaters of i is greater than because the heaters of i is greater than 21. 21. distances are 2 and 5 minimum is 2 is distances are 2 and 5 minimum is 2 is not greater than radius it doesn't not greater than radius it doesn't replace replace next house is at position 22 same thing next house is at position 22 same thing we don't increment i distances are 1 and we don't increment i distances are 1 and 6 minimum is 1 it doesn't replace 6 minimum is 1 it doesn't replace next one is at position 31 we increment next one is at position 31 we increment i we increment i we increment i and i we increment i we increment i and heroes of i is now greater than house we heroes of i is now greater than house we stop distances are infinity and two stop distances are infinity and two minimum is two it doesn't replace radius minimum is two it doesn't replace radius we finish traversing houses the value of we finish traversing houses the value of radius is three so we need a minimum radius is three so we need a minimum radius of three to cover all the houses radius of three to cover all the houses you can see that we're traversing houses you can see that we're traversing houses and heaters in a sorted way but the and heaters in a sorted way but the input is not necessarily sorted so we input is not necessarily sorted so we need to sort both arrays before starting need to sort both arrays before starting in code we sort houses we add infinity in code we sort houses we add infinity and minus infinity to heaters and we and minus infinity to heaters and we sort heaters sort heaters now we initialize radius to 0 i2 1 to now we initialize radius to 0 i2 1 to escape minus infinity then for each escape minus infinity then for each house we keep incrementing i1 heaters of house we keep incrementing i1 heaters of ice smaller than house ice smaller than house after doing so the distances are the after doing so the distances are the distances between house and heroes of i distances between house and heroes of i and heroes of i-1 we take the minimum and heroes of i-1 we take the minimum among them it represents the distance among them it represents the distance between house and its closest heater between house and its closest heater after it we see if we replace radius after it we see if we replace radius radius becomes mass between its actual radius becomes mass between its actual value and min dist value and min dist after the loop we just return the radius after the loop we just return the radius for the time complexity we have analog for the time complexity we have analog and the sword houses and analog m to and the sword houses and analog m to sort heaters sort heaters and for the loops even if we have nested and for the loops even if we have nested loops the inner loop won't always do the loops the inner loop won't always do the same number of iterations we just know same number of iterations we just know that in total the end loop will do at that in total the end loop will do at most and iterations because each heater most and iterations because each heater is traversed once is traversed once plus any iterations to traverse the plus any iterations to traverse the houses we get an plus m for the loops houses we get an plus m for the loops in total we have analog n plus m log m in total we have analog n plus m log m plus n plus m it gives a time complexity plus n plus m it gives a time complexity of o of analog and plus m log m of o of analog and plus m log m and for the space complexity it depends and for the space complexity it depends on the space complexion of the sorting on the space complexion of the sorting function function this solution and the previous one both this solution and the previous one both have a good time complexity but the have a good time complexity but the second one gave better results on lead second one gave better results on lead code code we reached the end of this video i hope we reached the end of this video i hope that you understood all the solutions if that you understood all the solutions if you enjoyed like and subscribe to the you enjoyed like and subscribe to the channel and see you in the next one
2024-03-18 10:56:52
475
https://i.ytimg.com/vi/K…axresdefault.jpg
Heaters problem (LeetCode #475) - Inside code
wLXMu_XJnLo
Hello hello everyone welcome welcome back to my channel today were going to discuss in two channel today were going to discuss in two problem problem split air a large sum problem problem split air a large sum suji problem suji problem value given here which consists of negative value given here which consists of negative teachers and teachers day mam teachers and teachers day mam are you can play in 2m non anti quantity are you can play in 2m non anti quantity quantity just save this quantity just save this quantity just save this 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 To survey research what i can do i To survey research what i can do i To survey research what i can do i 10 10 sentences for saver and rest where for the sentences for saver and rest where for the second merit ki ukta and second merit ki ukta and but i can do i contact 72 but i can do i contact 72 in one saver and five tanning second in one saver and five tanning second servants servants ko aur badha guddu 1972 and five in one ko aur badha guddu 1972 and five in one saver liye beyhad savere saver liye beyhad savere saver liye beyhad savere 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 Sundhi Subodh Officer Sundhi Subodh Officer Sundhi Subodh Officer They Shouldn't The Possibility This Settings To Medium Is The Largest Among Themselves To Give One Most Likely In 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 So divide divide divide So divide divide divide So divide divide divide f11 avengers elements and f11 avengers elements and the morning so maximum clear 325 the morning so maximum clear 325 a little 1008 will not and share a little 1008 will not and share 12853 to here them maximum maximum 12853 to here them maximum maximum sunshine and misses maximum maximum 2388 sunshine and misses maximum maximum 2388 228 228 and affidavit but is to here 12915 and affidavit but is to here 12915 08 2018 for here in directions maximum 15th 08 2018 for here in directions maximum 15th According to Twitter The Amazing According to Twitter The Amazing Sort and Share It Well 1954 Sure Joe Hair Sort and Share It Well 1954 Sure Joe Hair Oil 728 Oil 728 Yesterday Morning Two Siddha Maximum Largest Maximum Somewhere Yesterday Morning Two Siddha Maximum Largest Maximum Somewhere in the Water Into * in the Water Into * Minimize This Minimize What is the Minimum Minimize This Minimize What is the Minimum Volume Close Vicious Right A Divided Like Volume Close Vicious Right A Divided Like Is the largest sum is Is the largest sum is Is the largest sum is minimize which minimize is minimize which minimize is 828 's settings feature hotspot 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 Maximum All Maximum San Gap Maximum All Maximum San Gap Maximum All Maximum San Gap Mangal Savare This Unmangal Savare Should Be Mangal Savare This Unmangal Savare Should Be Minimum Minimum You all friends are like ok my mother must have come You all friends are like ok my mother must have come inside problem not just closed inside problem not just closed side of problems in life in ubuntu leg minimize maximize something side of problems in life in ubuntu leg minimize maximize something and and maximize minimum of something to hear what maximize minimum of something to hear what is is is maximum benefit jasmine maximize light minimize maximize something 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 that talibani soch that talibani soch 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 To leave apply binary search only are To leave apply binary search only are To leave apply binary search only are very much needed notice for kids learn how will very much needed notice for kids learn how will avoid this meaning subscribe weather avoid this meaning subscribe weather times also apply - research only when times also apply - research only when excited but finally search can also be excited but finally search can also be applied in balance notes2 on this applied in balance notes2 on this side of problems and chords side of problems and chords binary search binary search mode on mode on mode on 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 Answer 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 Find The Minimum Semi Urban God Twitter Minimum Santosh Vyas To Have Song Is the volume minimum Is the volume minimum Is the volume minimum 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 beawar inch to the same aravind minimum which is possible for sparing minimum san a is possible for sparing minimum san a for for me savere e agree with them maximum song ko maximum san ki minimum mari what we can only minimum mari what we can only Had One Element Inner Were Not Have Had One Element Inner Were Not Have Attempted Suicide Attempted Suicide Volume Minimum Shift Savere So Let's Say Volume Minimum Shift Savere So Let's Say Bigg Boss They Riched Her Only One Element Bigg Boss They Riched Her Only One Element 10 Element So Let's Check The Element See What You 10 Element So Let's Check The Element See What You Think Vidhi Ideal Only One Think Vidhi Ideal Only One Element Tiffin Savere What Should Be A That Should Element Tiffin Savere What Should Be A That Should Be Minimum Be Minimum Be Minimum 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 Is the maximum Is the maximum Is the maximum anil bind saver and restaurant element anil bind saver and restaurant element with Govind second survey report hai with Govind second survey report hai to vansham overall enhanced saver will to vansham overall enhanced saver will reduce effect reduce effect 10 and 10 and ine different width maximum element which state in the ine different width maximum element which state in the same days they will increase monday 80s same days they will increase monday 80s minimum re tu minimum re tu ki patel bhagya ki patel bhagya ok ok ok mid term of all its elements officer maximum committee taxes for all exams morning so what will be the summit se tujhse bhi choti hoon hai tujhse bhi choti hoon hai i hope or west west i hope or west west nominative and doing so will discuss right with nominative and doing so will discuss right with skin skin skin Binary Search And The Answer Is My Research Binary Search On Answer And What Is The Answer The Answer Itself Will Be Hai Winner Inch Dada Value No That Understanding Time Understanding Time Informations Handicapped Certificate - Year Man Informations Handicapped Certificate - Year Man Whose Log To Log Hua Tha Special 10 Highway Whose Log To Log Hua Tha Special 10 Highway Hai Hai 132 To Is Note 4 How Brain Research Works Will Hear A 132 To Is Note 4 How Brain Research Works Will Hear A Comment Just Watch Ka Binary Search Comment Just Watch Ka Binary Search Video For Your Will Be Able To Understand Why Video For Your Will Be Able To Understand Why You Search And Footer In The Destruction You Search And Footer In The Destruction Of The Video Of The Video The 15-minute The 15-minute Tweet 1032 Tweet 1032 Mera Device Abhi Tu Tujhe Mein Mera Device Abhi Tu Tujhe Mein Mera Device Abhi Tu Tujhe Mein Divided By Two Is Just 2 F '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 to to 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 this this number number in this regard there is a system of middle morning in this regard there is a system of middle morning Is savere kutbi maximum Is savere kutbi maximum 21 21 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 a 102 savere possible in 10k chowk so let's check seven plus two will be so let's check seven plus two will be notes15 that 14th stand with 45 going great and does but maximum which Not Not Not Take This Train Will Not Understand This Will Observe Every Take This Train Will Not Understand This Will Observe Every Day Day That Jab Viman Savere Share Maximum That Jab Viman Savere Share Maximum 2114 Savere Sudesh Viman Savere And Dressed With This 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 West 216 West 216 West 216 A Message To 2021 DR Answer Sheet Also A Message To 2021 DR Answer Sheet Also Answer So What Will You Make An Answer Pray Answer So What Will You Make An Answer Pray And Will 20182 Ki And Will 20182 Ki Rihit Swift Mid Week Calculated Come And Rihit Swift Mid Week Calculated Come And Meet's Month Wash Which Will Check Weather Meet's Month Wash Which Will Check Weather By Two Morning Possible Absolutely Maximum Clear By Two Morning Possible Absolutely Maximum Clear That Morning 221 And That Morning 221 And That Morning 221 And 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 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 - Dos 1522 Dos 1522 Dos 1522 ok to now high is bunty ok to now high is bunty aur sunao le sakne calculate made the aur sunao le sakne calculate made the software meet will be software meet will be 110 plus 2 and to which is 110 plus 2 and to which is 3215 ok 3215 ok no which is the nearest to dawn possible no which is the nearest to dawn possible evening morning is maximum maximum evening morning is maximum maximum Flexible a Flexible a Flexible a ki swami ne jaisi year ki swami ne jaisi year me knowledge check weather zara to morning is possible 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 80 will start from setting morning will 80 will start from setting morning will start from start from 08 2018 anil ko greater 08 2018 anil ko greater 08 2018 anil ko greater 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 So That They Can Make Too Savor This So That They Can Make Too Savor This So That They Can Make Too Savor This Note 3 Note 3 That They Getting More Savor It Means Diet Which Value Fifteen That They Getting More Savor It Means Diet Which Value Fifteen Visit This Article To Increase It Visit This Article To Increase It 16 Tweet Have Too Savor Mode 16 Tweet Have Too Savor Mode Turn Turn That You Ultimately To Increase Drishti Value What That You Ultimately To Increase Drishti Value What Me Too Will Need To Increase Your Me Too Will Need To Increase Your Value to give low to meet class ninth Value to give low to meet class ninth 120 b 120 b id 115 shifting plus 168 id 115 shifting plus 168 ki ukta hai ki ukta hai tu aur yeh raw tweet bhi reduce i no veer veer increase tu aur yeh raw tweet bhi reduce i no veer veer increase look a look a poem in anger poem in anger shri navaleshwar game calculate mid-week shri navaleshwar game calculate mid-week eviction plus 2 and divide divide eviction plus 2 and divide divide 253 6 253 6 253 6 and hear will check weather were right to serve possible that they do save is possible if the maximum hypnotized saver that they do save is possible if the maximum hypnotized saver something is equal to 8 something is equal to 8 maximum maximum 52.72 notes15 52.72 notes15 that and greater on forty plus channel the that and greater on forty plus channel the native should take medicine saver native should take medicine saver 110 110 places in places in places in 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 ok sona bougainvillea absolutely end mid ok sona bougainvillea absolutely end mid ki sudeshwar bhi ki sudeshwar bhi 1617 and 21 vich will be 1617 and 21 vich will be 3133 bittu hai 3133 bittu hai and relating something rating and relating something rating points ke this person check weather in observance points ke this person check weather in observance possible this maximum submit 16th possible this maximum submit 16th ki flexid this metro chief ki flexid this metro chief ki flexid this metro chief 127 plus to 9 0 in the morning early in the morning 110 plus ATM Vikram Greater Suji in the morning 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 If If If in its basis low value need to increase the in its basis low value need to increase the twin increment low low web twin increment low low web complete raw one British English 172 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 Awaited Bhi 7 Awaited Bhi 7 Awaited Bhi 7 That Flexed A Joe Here Once Away With One Main One Are Bhi Dushman 2018 Tanksi Twenty Are Bhi Dushman 2018 Tanksi Twenty Match 2017 Sauda Tweet And Here S2 And You Will Then Match 2017 Sauda Tweet And Here S2 And You Will Then Be Be Meaning 2000 Value Of Review Been Created Nor Meaning 2000 Value Of Review Been Created Nor Man Nor Will Wake Up Sid Plus Man Nor Will Wake Up Sid Plus 1718 1718 Om Namah Om Namah Om Namah Z10 Sponge Will Stop At Z10 Sponge Will Stop At The Best Of Advance Avinash Available On The Best Of Advance Avinash Available On Like Minimum Some That We Can Get I So Like Minimum Some That We Can Get I So Divided Tuesday Just Samosa Divided Tuesday Just Samosa Different Skin Different Skin Problem's Just Once Problem's Just Once Upon A Upon A Few Not Getting Few Not Getting Few Not Getting pet kapoor dynasty hain to kisi object or doing a photo from being taken as latter function which has given to taken and are taken and are an alarm for alloy from 1000 an alarm for alloy from 1000 k and volume maximum k and volume maximum element in are element in are element in are 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 Check Weather Sooner or later it's possible to serve it's possible Check Weather Sooner or later it's possible to serve it's possible 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 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 that is maximum hands free hands free hands free 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 sweet will this is possible will give me 3S Is is the account that this is 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 Person who went to meet and Person who went to meet and Person who went to meet and also ill not army in this not approved answer find also ill not army in this not approved answer find behaving an answer behaving an answer for this is possible function will tell me how for this is possible function will tell me how most possible with the given them which most possible with the given them which met met that Sushil that Sushil painting account me ribbon tam to I'm painting account me ribbon tam to I'm going going going 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 ki boat ki boat What We Will Do What We Will Do 180 You Might Be Confused Weather In 180 You Might Be Confused Weather In Preventing Account Plus After But I Do Not Want To This What You Can Do You Can Preventing Account Plus After But I Do Not Want To This What You Can Do You Can E E Slide Account Scholar Will Be A Okay Know Slide Account Scholar Will Be A Okay Know Love Morning Special See At Least One Love Morning Special See At Least One Survey Will Be At Least Once When Survey Will Be At Least Once When Survey Will Be At Least Once When from whom you are earning i love you can do it i love from whom you are earning i love you can do it i love you can have a near the you can have a near the three nine to 10 otherwise if you want to three nine to 10 otherwise if you want to initiate free mode initiate free mode on the year unit-2 increment watch you will on the year unit-2 increment watch you will drive drive drive 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 And from here And from here And from here morning to starting from this greater than the morning to starting from this greater than the value which 1772 thanks the value which 1772 thanks the festival increment account Vikas 10th festival increment account Vikas 10th wasted and what you have wasted and what you have stopped twist French twist stopped twist French twist to the current element Vikas Yadav and from to the current element Vikas Yadav and from conservation starting from you conservation starting from you on OK 08082080820 From Near From Near From Near Account Will Increment And I Will Create Account Will Increment And I Will Create Sign This To Take Off But That Sign This To Take Off But That You Are Being Good Preservative But Here You Are Being Good Preservative But Here Account Dr To 1972 Incremented One Account Dr To 1972 Incremented One Last Time After Coming We Last Time After Coming We Improve Or Year Improvement In Improve Or Year Improvement In 512 Problem Share Also Submitted His Will Not 512 Problem Share Also Submitted His Will Not Accepted and Accepted and write the time, what will be the time, write the time, what will be the time, which is happening every which is happening every time is possible and it's going and so time is possible and it's going and so it's time for it's time for active in that that active in that that Android but here with hubrs by loop 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 A Specific Mouni Roy Ok No Problem Ko Ok No Problem Ko Middle School Please Subscribe My Channel Middle School Please Subscribe My Channel Thank You
2024-03-22 10:46:03
410
https://i.ytimg.com/vi/w…axresdefault.jpg
Split Array Largest Sum | Leetcode 410 | Binary Search | Day-31
_5tE0YlIpjc
hey guys welcome back today let's solve the problem add digits so in this the problem add digits so in this problem given an integer num our task is problem given an integer num our task is to repeatedly add all of its digits such to repeatedly add all of its digits such that the result has only one digit so if that the result has only one digit so if you're given an example of two digits 38 you're given an example of two digits 38 what we can do is to take the two digits what we can do is to take the two digits three and eight and add them together three and eight and add them together this will result in 11 and once we have this will result in 11 and once we have 11 we can split the two digits again 11 we can split the two digits again because our solution requires us to because our solution requires us to return a single digit number once it return a single digit number once it split the two digits we'll be having one split the two digits we'll be having one and one and the sum of these two digits and one and the sum of these two digits will be equal to 2 which is the result will be equal to 2 which is the result as you can see in this given example for as you can see in this given example for this problem we have a constraint that this problem we have a constraint that we should not be using a loop or a we should not be using a loop or a recursion and I'll be showing you the recursion and I'll be showing you the most Optimum solution which will give most Optimum solution which will give you a time complexity of all of One how you a time complexity of all of One how can we approach this problem the first can we approach this problem the first thing that we need to notice that thing that we need to notice that whenever num is 0 whenever num is 0 if we ever take zero add it to any other if we ever take zero add it to any other zero the solution will always be one so zero the solution will always be one so if the given num is equal to zero then if the given num is equal to zero then our solution will pretty much be equal our solution will pretty much be equal to zero which is a single digit number to zero which is a single digit number the second thing that we need to the second thing that we need to consider is the divisibility of 9 and by consider is the divisibility of 9 and by divisibility you will see that whenever divisibility you will see that whenever we have any given digit that is we have any given digit that is divisible by 9 say 9 itself 18 27 108 or divisible by 9 say 9 itself 18 27 108 or any other number the sum of all of its any other number the sum of all of its digits will always be equal to nine nine digits will always be equal to nine nine itself will be added to zero to equal 9 itself will be added to zero to equal 9 itself again if we consider 18 the itself again if we consider 18 the digits are one and eight if we take the digits are one and eight if we take the sum of the two digits we'll always have sum of the two digits we'll always have nine which is one plus eight nine which is one plus eight 27 is the same case 2 plus 7 which will 27 is the same case 2 plus 7 which will always be 9. 108 it's 8 plus 1 plus 0 always be 9. 108 it's 8 plus 1 plus 0 which will be or this should be in it which will be or this should be in it and the sum of this will be 1 plus 0 and the sum of this will be 1 plus 0 Plus 8 which is also equal to nine so Plus 8 which is also equal to nine so what does this tell us so how can we use what does this tell us so how can we use this to solve part of this given problem this to solve part of this given problem we can notice this pattern whenever we we can notice this pattern whenever we take any given value like 108 27 18 or 9 take any given value like 108 27 18 or 9 and do a modulation with 9 itself so if and do a modulation with 9 itself so if we take any given value that is we take any given value that is divisible by name or that is a multiple divisible by name or that is a multiple of nine like 108 27 18 9 or any other of nine like 108 27 18 9 or any other value and we modulate it with a nine the value and we modulate it with a nine the result will always be a zero so if you result will always be a zero so if you have an encounter such a scenario then have an encounter such a scenario then we clearly know that the sum of the we clearly know that the sum of the digits as we've proven just above the digits as we've proven just above the sum of the left hand side digits will sum of the left hand side digits will always be equal to nine so this is the always be equal to nine so this is the second case now what about values that second case now what about values that are not divisible by name how do we are not divisible by name how do we handle them in our code handle them in our code the case where we have values that are the case where we have values that are not divisible by nine so again I have not divisible by nine so again I have three different values like 11 23 and three different values like 11 23 and 199. if we modulate with name the 199. if we modulate with name the remainder will always be equal to the remainder will always be equal to the sum of the two digits or the three sum of the two digits or the three digits forming the given number so as digits forming the given number so as you can see 11 modulus 9 will give us 2 you can see 11 modulus 9 will give us 2 which is also equal to the sum of the which is also equal to the sum of the two digits one and one again if we take two digits one and one again if we take 23 in this case and modulate it with 9 23 in this case and modulate it with 9 the result will be 5. if we add the two the result will be 5. if we add the two digits the result is also equal to 5. in digits the result is also equal to 5. in the case of 199 as you can see 1 plus 9 the case of 199 as you can see 1 plus 9 plus 9 will equal to 19 and from 19 here plus 9 will equal to 19 and from 19 here we can take 1 and 9 add them together we can take 1 and 9 add them together this will result into a 10. and then for this will result into a 10. and then for this 10 we can take its individual this 10 we can take its individual digits which is 1 and 0 and the result digits which is 1 and 0 and the result will always be a one that is why we have will always be a one that is why we have a one in this spot so the rule in this a one in this spot so the rule in this case is that whatever remainder we have case is that whatever remainder we have when we take a number and check its when we take a number and check its modulus with 9 will always be the sum of modulus with 9 will always be the sum of these digits of the number but it will these digits of the number but it will always be less than nine always be less than nine as you can see any number that is less as you can see any number that is less than 9 is always equal to 2 is always than 9 is always equal to 2 is always equal to a single digit so with these equal to a single digit so with these three cases we can be sure that we can three cases we can be sure that we can compute any given value to its single compute any given value to its single digit without using any kind of digit without using any kind of recursion or Loops in an O of one time recursion or Loops in an O of one time complexity complexity let's jump on the code and you can see let's jump on the code and you can see how we'll do this how we'll do this if you can remember the first condition if you can remember the first condition that we need to check is whether this that we need to check is whether this given number is equals to zero so if we given number is equals to zero so if we check if the number is equals to zero check if the number is equals to zero then we will simply return 0 because then we will simply return 0 because that is the default solution the second that is the default solution the second case that we need to check is whether if case that we need to check is whether if we take the number and modulate it with we take the number and modulate it with 9 9 the result is zero in this case it must the result is zero in this case it must mean that the sum of the given number mean that the sum of the given number that we have is also equal to nine so that we have is also equal to nine so this is assured this is assured otherwise if these two base cases are otherwise if these two base cases are not executed we can simply return the not executed we can simply return the remainder of taking the number and remainder of taking the number and modulating it with name and we can be modulating it with name and we can be sure that one this result will always be sure that one this result will always be less than or equal to name and the less than or equal to name and the result represents the sum of the digits result represents the sum of the digits in this number simplified as per this in this number simplified as per this given solution let's run the code and given solution let's run the code and see if it works and as you can see it see if it works and as you can see it works and the code is pretty efficient works and the code is pretty efficient if you enjoyed this session please like if you enjoyed this session please like And subscribe and I will see you in the And subscribe and I will see you in the next one
2024-03-22 12:15:02
258
https://i.ytimg.com/vi/_…axresdefault.jpg
Leetcode 258 - Add Digits - Python Solution
8BDKB2yuGyg
hey what's up guys and they're quite here I do tecnico ting stuff on Twitch here I do tecnico ting stuff on Twitch in YouTube check the description you get in YouTube check the description you get all my information discord is pretty all my information discord is pretty cool if you want to join that and I do cool if you want to join that and I do all these premium problems on patreon all these premium problems on patreon also help me up on github you are given also help me up on github you are given to a raise I don't like hit me up so to a raise I don't like hit me up so forget I said that but that was just forget I said that but that was just bothering me sorry this is called next bothering me sorry this is called next grader element one you're given to a grader element one you're given to a raise and there's no duplicates so raise and there's no duplicates so they're all unique values in the arrays they're all unique values in the arrays num1 and num2 where nums one elements num1 and num2 where nums one elements are a subset of nums two elements so for are a subset of nums two elements so for one and two are automatically going to one and two are automatically going to be you know the numbers 1 elements are a be you know the numbers 1 elements are a subset of these elements right so you 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 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 have to be in the same indices it's just a subset of the elements so what we want a subset of the elements so what we want to do is find the next greater numbers to do is find the next greater numbers for num ones elements in the for num ones elements in the corresponding places of num two's corresponding places of num two's elements and what is the next greater elements and what is the next greater element that means the next greater element that means the next greater number of a number X in nums 1 is the number of a number X in nums 1 is the first greater number 2 it's right in first greater number 2 it's right in nums 2 so basically what they're saying nums 2 so basically what they're saying is if we look through this list we want is if we look through this list we want to find 4 4 we want to find the next to find 4 4 we want to find the next greater element in this list so there is greater element in this list so there is none and it has to be to the right of 4 none and it has to be to the right of 4 in this list and there's nothing greater in this list and there's nothing greater than 4 so we have to put negative 1 if than 4 so we have to put negative 1 if it does not exist negative 1 when we it does not exist negative 1 when we look at 1 in this list in num from nums look at 1 in this list in num from nums 1 when we look at 1 and nums to there 1 when we look at 1 and nums to there our next greater elements right and the our next greater elements right and the next greatest one to the right is 3 so next greatest one to the right is 3 so we put 3 4 2 we look in the next list we put 3 4 2 we look in the next list there's nothing to the right of 2 so there's nothing to the right of 2 so it's negative 1 again there's nothing it's negative 1 again there's nothing okay let's go through one more example okay let's go through one more example when we look at 2 in this list the next when we look at 2 in this list the next query is 1 is 3 when we look at 4 in query is 1 is 3 when we look at 4 in this list there's nothing to the right this list there's nothing to the right so we put negative 1 hopefully you so we put negative 1 hopefully you understand it now so what are the understand it now so what are the solutions how do we solve this solutions how do we solve this intuitively I would say that I also say intuitively I would say that I also say intuitively and not a lot so I should intuitively and not a lot so I should stop saying that so much but um just stop saying that so much but um just brute force wise you would think okay brute force wise you would think okay well let's loop through this well you're well let's loop through this well you're going going have to loop through the arrays no have to loop through the arrays no matter what but let's loop through this matter what but let's loop through this and then let's do a nested loop through and then let's do a nested loop through this and then just find the next this and then just find the next greatest one to the right right greatest one to the right right and then make like an output array that and then make like an output array that is a solution that's bird force though is a solution that's bird force though and it's pretty slow there's a better and it's pretty slow there's a better way to do this and you can use things way to do this and you can use things you can use data structures so what you can use data structures so what we're gonna use to solve this problem is we're gonna use to solve this problem is a stack in the hash map the hash map is a stack in the hash map the hash map is going to keep track of it's gonna we're going to keep track of it's gonna we're gonna loop through this nums to array gonna loop through this nums to array and we're just gonna build a hash map up and we're just gonna build a hash map up with you know the number each number and with you know the number each number and its next greatest element even if the its next greatest element even if the number doesn't exist so like 3 doesn't number doesn't exist so like 3 doesn't exist in nums 1 but we're gonna find exist in nums 1 but we're gonna find whatever that we're gonna say oh we'll whatever that we're gonna say oh we'll put 3 and the next greatest number is 4 put 3 and the next greatest number is 4 in the hash map so we're just going to in the hash map so we're just going to loop through this array build a hash map loop through this array build a hash map and then at the end we'll loop through and then at the end we'll loop through this array do lookups into the hash map this array do lookups into the hash map in return we'll be like oh we look in in return we'll be like oh we look in the hash map what's 4 is next greatest the hash map what's 4 is next greatest element oh there's nothing so it's element oh there's nothing so it's negative 1 there you go so that's it negative 1 there you go so that's it you're gonna build a hash map we're also you're gonna build a hash map we're also gonna use a stack to help us but I'll gonna use a stack to help us but I'll explain that in a second so let's just explain that in a second so let's just start off by initializing our hash map start off by initializing our hash map it's gonna be in the integer the current it's gonna be in the integer the current integer and then another integer that integer and then another integer that represents the next greatest element so represents the next greatest element so we could call this hash map next we could call this hash map next greatest equal new hash map okay great greatest equal new hash map okay great and then we're gonna have a stack like I and then we're gonna have a stack like I said I'll talk about this in a second said I'll talk about this in a second we'll just call it stack for now new we'll just call it stack for now new stack and we're gonna be looping through stack and we're gonna be looping through nums to at first to build this hash map nums to at first to build this hash map look I just said so we're gonna go look I just said so we're gonna go integer for integer num num in nums to integer for integer num num in nums to we're gonna say okay stack dot push num we're gonna say okay stack dot push num so we're gonna be pushing these numbers so we're gonna be pushing these numbers on to a stack as we loop through and on to a stack as we loop through and we're gonna do a check each time this is we're gonna do a check each time this is how we're putting them in the hash map how we're putting them in the hash map and I'll explain it right after I write and I'll explain it right after I write this if the stack is not empty this if the stack is not empty this is the main part of the whole this is the main part of the whole problem this is the only hard part if problem this is the only hard part if the stack is not empty and stack peak is the stack is not empty and stack peak is less than num we're gonna put the value less than num we're gonna put the value into the hash into the hash map next greatest dot put and we're map next greatest dot put and we're gonna put stack dot pop so we're gonna gonna put stack dot pop so we're gonna pop off the stack and we're gonna put pop off the stack and we're gonna put them so let's walk through what this them so let's walk through what this means we're looping through this array means we're looping through this array and we want to build this hash map with and we want to build this hash map with the next greatest elements right we're the next greatest elements right we're gonna put the number onto the stack so gonna put the number onto the stack so when the stacks empty we're gonna put a when the stacks empty we're gonna put a number onto the stack right so we would number onto the stack right so we would put one onto the stack so right in this put one onto the stack so right in this example right here let's just grab this example right here let's just grab this so we can look at the example we're so we can look at the example we're gonna have our stack equal to this right gonna have our stack equal to this right so our stack we're gonna put one on it so our stack we're gonna put one on it at first right the stacks not empty so at first right the stacks not empty so we're looping through the numbers we're we're looping through the numbers we're looping through all these numbers so looping through all these numbers so let's just put one onto the stack right let's just put one onto the stack right now now the stack isn't empty and we're now now the stack isn't empty and we're gonna be looking at three and we're gonna be looking at three and we're gonna say okay the stacks not empty gonna say okay the stacks not empty anymore and is stack dot peak is one anymore and is stack dot peak is one less than three yes one is less than less than three yes one is less than three so we found the next greatest three so we found the next greatest element if whatever's in the stack is element if whatever's in the stack is less than the current number then we less than the current number then we found the next greatest element so you found the next greatest element so you could see we would do we would pop this could see we would do we would pop this element off so we take the one off and element off so we take the one off and we would do map dot put and we would put we would do map dot put and we would put that one in the next greatest element that one in the next greatest element into the hashmap into the hashmap then the stack gets pushed on the three then the stack gets pushed on the three value and then we repeat the process value and then we repeat the process where we say okay now we check is 3 less where we say okay now we check is 3 less than num okay three is less than in than num okay three is less than in we're on four so 3 is less than four so we're on four so 3 is less than four so we say ok 3 is less than four so we we say ok 3 is less than four so we found the next greatest to three so we found the next greatest to three so we say mapped up put three and then four say mapped up put three and then four and we keep doing this and then we put and we keep doing this and then we put in we you know we popped three off of in we you know we popped three off of the stack and then four goes on to the the stack and then four goes on to the stack etc so that's how it works and stack etc so that's how it works and here's the only change you have to make here's the only change you have to make this is pretty much like the solution this is pretty much like the solution because we build our hash map right so because we build our hash map right so the hash map is going to be built after the hash map is going to be built after this point and what we want to do is we this point and what we want to do is we want to loop through now we want to loop want to loop through now we want to loop through nomes one because the hash map through nomes one because the hash map is built and we just want to say we want is built and we just want to say we want to reconstruct nums one so we have to to reconstruct nums one so we have to output this array with all the next output this array with all the next greater values so we might as well just greater values so we might as well just modify instead of making a new array modify instead of making a new array let's just modify do let's just modify do right so we just say numbs one is equal right so we just say numbs one is equal to you know next greatest doc gets or to you know next greatest doc gets or default gets or default so if the number default gets or default so if the number has a value for numbs one of I so if the has a value for numbs one of I so if the current element so when we look at four current element so when we look at four we're gonna say okay it is four in the we're gonna say okay it is four in the hashmap of an escalator element if it hashmap of an escalator element if it doesn't well it defaults to negative one doesn't well it defaults to negative one and then after that you just return and then after that you just return numbers one array because it'll be numbers one array because it'll be reconstructed to have all the next reconstructed to have all the next greater elements this is the solution greater elements this is the solution but this isn't the full solution this but this isn't the full solution this isn't going to work because we have to isn't going to work because we have to make this a while loop so why do we have make this a while loop so why do we have to make this a while loop we have to to make this a while loop we have to make this a while loop because of make this a while loop because of decreasing elements let's say that the decreasing elements let's say that the array looks something like this when we array looks something like this when we want to construct our hash map if it's want to construct our hash map if it's one three four five or one you know one three four five or one you know sorry there's no duplicates so we can do sorry there's no duplicates so we can do eight seven six five and then ten look eight seven six five and then ten look at this so let's say this is our array at this so let's say this is our array if we wanted to construct our hash map if we wanted to construct our hash map we need to make sure that we are not we need to make sure that we are not putting the this isn't gonna work we're putting the this isn't gonna work we're just going to keep pushing things onto just going to keep pushing things onto the stack if we make this a while loop the stack if we make this a while loop this is gonna work because we're gonna this is gonna work because we're gonna be putting things onto the stack in this be putting things onto the stack in this condition will never trigger because condition will never trigger because stack dot peak won't be less than num stack dot peak won't be less than num for example when we get to you know for example when we get to you know eight goes onto the stack and then is eight goes onto the stack and then is stack top peak less than seven no eight stack top peak less than seven no eight isn't less than seven so we keep we put isn't less than seven so we keep we put seven on then we put six on then we put seven on then we put six on then we put five on so it's just a stack with all five on so it's just a stack with all these values but once we see a ten and these values but once we see a ten and we see that stack top peak is less than we see that stack top peak is less than num now we just keep popping off those num now we just keep popping off those stacks and we put into the hash map stacks and we put into the hash map every single value because you'll notice every single value because you'll notice that all decree if it's a row of that all decree if it's a row of decreasing values followed by an decreasing values followed by an increased value it will put the every increased value it will put the every single one of these indexes the next single one of these indexes the next greater value put into the hash map is greater value put into the hash map is going to be 10 so 5s next greatest is going to be 10 so 5s next greatest is town town ten seven eight so we need a while loop ten seven eight so we need a while loop to pop all of those off to the stat off to pop all of those off to the stat off of the stack and put that next greatest of the stack and put that next greatest value so that's the whole problem pretty value so that's the whole problem pretty straightforward we could run it make straightforward we could run it make sure it's all good let me know if you sure it's all good let me know if you guys have any questions about this it's guys have any questions about this it's not too difficult to understand but I not too difficult to understand but I mean it's a little bit of a trick for an mean it's a little bit of a trick for an easy problem you know but I don't think easy problem you know but I don't think it's too difficult so let me know if you it's too difficult so let me know if you guys have any questions I'll be glad to guys have any questions I'll be glad to answer them and yeah definitely thank answer them and yeah definitely thank you guys for watching I'm gonna continue you guys for watching I'm gonna continue going I guess there's a next greatest going I guess there's a next greatest element too as well and some other ones element too as well and some other ones I do think they throw you off with these I do think they throw you off with these two arrays because in some of them I've two arrays because in some of them I've seen it looks like there's a you know seen it looks like there's a you know some extra I mean someone just wanna some extra I mean someone just wanna write some all right and that's what we write some all right and that's what we kind of do we just ignore the first kind of do we just ignore the first array honestly so alright see you guys array honestly so alright see you guys in the next one
2024-03-18 11:25:01
496
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode Next Greater Element I Solution Explained - Java
twdKXe7gl8c
welcome to the channel this is vaga we are going to solve another reach good are going to solve another reach good question and the question in question question and the question in question is going to be basic calculator and um is going to be basic calculator and um you're basically given a string you're you're basically given a string you're supposed to evaluate the value in this supposed to evaluate the value in this case 3 plus 2 times 2 case 3 plus 2 times 2 is going to be 7 right so how we do this is going to be 7 right so how we do this is pretty straightforward 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 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 the 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 we're including the sign is that you can add the 11 right and afterwards we 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 with the with the characters we can add with the with the characters we can add the current number of zero to the current number of zero to the string right um so that when we are the string right um so that when we are completely done with this the current completely done with this the current number will be set to zero and we just number will be set to zero and we just want to add it to the stack right so we want to add it to the stack right so we add a plus here add a plus here so that it can have the sign can be the so that it can have the sign can be the plus you will see it when we plus you will see it when we write out the code right so we could say write out the code right so we could say if um if um i is is digit i is is digit and we check if i is a digit if it is a and we check if i is a digit if it is a number we want to number we want to run our code to convert it into uh run our code to convert it into uh a number that we can add to it to our a number that we can add to it to our stack right and stack right and in case it's a number that is greater in case it's a number that is greater than nine right so for that we could than nine right so for that we could just say num is going to be just say num is going to be num multiplied by 10 plus num multiplied by 10 plus i plus i and we convert i into an i plus i and we convert i into an integer right integer right so we just say i and we put into like so so we just say i and we put into like so right and then okay right and then okay like so and then else if like so and then else if alif we want to check um alif we want to check um alif uh i alif uh i if it's any of the operators right so we if it's any of the operators right so we come here and say lfi come here and say lfi in um we put uh the various operators in um we put uh the various operators that we want to consider that we want to consider and the operators are going to be plus and the operators are going to be plus minus minus multiply and divide right and if it's multiply and divide right and if it's that that and we check if and we check if sine if the sine is going to be if we sine if the sine is going to be if we have a plus have a plus right if we have a plus and we're going right if we have a plus and we're going to start off with a plus at the to start off with a plus at the beginning remember so you can add our beginning remember so you can add our number number and all we need to do is we just need to and all we need to do is we just need to come to our stack come to our stack and what we want to do is we want to and what we want to do is we want to append and what we want to append is the append and what we want to append is the actual number right so in this case here actual number right so in this case here what that would do it would lead to the what that would do it would lead to the first number being appended right first number being appended right if we start off with the same with this if we start off with the same with this string i'm talking about in the strings string i'm talking about in the strings example right example right so also our first number whichever way so also our first number whichever way if we start off with a number if we start off with a number we will start off if we have a number we will start off if we have a number like we will skip over the space but if like we will skip over the space but if we have a number it is going to be added we have a number it is going to be added to our stack right to our stack right and after that we want to check if we and after that we want to check if we have a negative right have a negative right so we could just come here and just copy so we could just come here and just copy this this we need to type it all out right we need to type it all out right and we paste this and what we want is a and we paste this and what we want is a negative negative and if it is negative what we want to do and if it is negative what we want to do is we want to append the number is we want to append the number stack dot append and if you can remember stack dot append and if you can remember we just do negative number we just do negative number right because we do 11 plus minus 5 right because we do 11 plus minus 5 right right so we do that and we come here and we so we do that and we come here and we paste and the next thing we want to do paste and the next thing we want to do is we want to check if is we want to check if we are dealing with a multiplication we are dealing with a multiplication right right if the sign is a multiplication what we if the sign is a multiplication what we want to do is want to do is we want to append to our stack but first we want to append to our stack but first we want to pop off the last number right we want to pop off the last number right we want to we want to say stack dot pop we remove the last say stack dot pop we remove the last number number and then we multiply it by the num right and then we multiply it by the num right by the current number right by the current number right so in this case we would come here and so in this case we would come here and um the previous number is um the previous number is four right we would remove this four four right we would remove this four multiply four times three and then multiply four times three and then append it to append it to the to the stack right the to the stack right so we just do that and then we come here so we just do that and then we come here and we paste this and we paste this and um after that and um after that what we want to do is um we want what we want to do is um we want to do the division and the division is to do the division and the division is going to be pretty much going to be pretty much the same it's just going to be tac the same it's just going to be tac and what we're going to append is going and what we're going to append is going to be stack to be stack dot pop the last number and we want to dot pop the last number and we want to multiply it by multiply it by the number in question right and after the number in question right and after that we just want to set that we just want to set our sign our sign is going to be our sign our sign is going to be i whatever is the last sign the last i whatever is the last sign the last character in this case character in this case when we come to the end we're going to when we come to the end we're going to get a plus and afterwards get a plus and afterwards we're just going to set the number to we're just going to set the number to zero right before we add make a quick zero right before we add make a quick correction correction what we could do here is we could divide what we could do here is we could divide and afterwards we need to get the and afterwards we need to get the truncation of it so we say math truncation of it so we say math dot shrunk and dot shrunk and um what we're going to do is come to the um what we're going to do is come to the stack here and uh stack here and uh envelope that like that and afterwards envelope that like that and afterwards all we need to do is just return all we need to do is just return the sum of the stack like so right the sum of the stack like so right and if we run our code and if we run our code it's accepted and if we submit it 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 oven for both of them thank you for watching subscribe to the channel and i'll see you in the next
2024-03-22 11:04:03
227
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 227 Basic Calculator II- Python
pmD2HCKaqRQ
hey everyone welcome back and let's write some more neat code today so today write some more neat code today so today let's solve the problem Ki symbol in let's solve the problem Ki symbol in grammar we are given a bunch of rows grammar we are given a bunch of rows that I guess are one indexed and to go that I guess are one indexed and to go through it quickly the first row is through it quickly the first row is going to have a single value zero and going to have a single value zero and then the rule is that we build every then the rule is that we build every subsequent row by taking Zer and subsequent row by taking Zer and replacing them with 01 and now since we replacing them with 01 and now since we have a one here we have an additional have a one here we have an additional rule which is we replace zeros with 0 rule which is we replace zeros with 0 1es but we replace ones with 1 Z and so 1es but we replace ones with 1 Z and so the next row would look like this where the next row would look like this where we take this guy and make it 01 this one we take this guy and make it 01 this one would be 1 Z this one would also be 1 would be 1 Z this one would also be 1 Zer this one would be 0 1 so that's the Zer this one would be 0 1 so that's the idea here so this would be the first row idea here so this would be the first row this is the second this is the third and this is the second this is the third and this is the fourth and in this row we this is the fourth and in this row we want to choose the kith element so n is want to choose the kith element so n is going to be one parameter in this going to be one parameter in this problem n is going to tell us which row problem n is going to tell us which row we want to select so for example if n is we want to select so for example if n is equal to 4 we are going to choose this equal to 4 we are going to choose this row and then in that row we only care row and then in that row we only care about the K element so if K was one this about the K element so if K was one this is going to be one index by the way so is going to be one index by the way so if K is one we choose the first element if K is one we choose the first element if K is two we choose the second if K is if K is two we choose the second if K is three we choose the third etc etc and we three we choose the third etc etc and we are guaranteed that K is always going to are guaranteed that K is always going to be in bounds if you don't believe me you be in bounds if you don't believe me you can read the bottom of the description can read the bottom of the description of this problem but basically they tell of this problem but basically they tell us that K is always going to be less us that K is always going to be less than or equal to 2 to the power of n than or equal to 2 to the power of n minus1 this isn't a coincidence this is minus1 this isn't a coincidence this is going to be how many elements are going going to be how many elements are going to be in the nth row because we start to be in the nth row because we start with one and we double them every single with one and we double them every single time that's the idea now the first time that's the idea now the first approach you might think of the most approach you might think of the most brute force would literally be to build brute force would literally be to build every single row and technically that every single row and technically that works I'm pretty sure it will get you works I'm pretty sure it will get you time limit exceeded though because I time limit exceeded though because I believe the time complexity would be believe the time complexity would be roughly 2 the^ of n minus one so pretty roughly 2 the^ of n minus one so pretty inefficient but is there a better inefficient but is there a better approach is there some kind of trick approach is there some kind of trick that we can do well the idea actually is that we can do well the idea actually is just by looking at this picture it kind just by looking at this picture it kind of looks like a tree doesn't it now let of looks like a tree doesn't it now let me redraw this exact same thing like me redraw this exact same thing like this we start with zero the left child this we start with zero the left child is going to be zero the right child is is going to be zero the right child is going to be one from this zero same going to be one from this zero same exact thing it's kind of cursive isn't exact thing it's kind of cursive isn't it we have a zero here and then a one it we have a zero here and then a one here with this one we're going to get a here with this one we're going to get a one here and then we're going to get a one here and then we're going to get a zero here so the first observation to zero here so the first observation to make is this is kind of like a tree okay make is this is kind of like a tree okay with that in mind how is that going to with that in mind how is that going to help us don't we still have to Traverse help us don't we still have to Traverse every single element to then like once every single element to then like once we get to the kith row choosing the Ki we get to the kith row choosing the Ki element well maybe the fact that we element well maybe the fact that we already know which K value we're looking already know which K value we're looking for can be used to our advantage and in for can be used to our advantage and in this case it can think about it this way this case it can think about it this way we know we're looking for the nth row we know we're looking for the nth row let's say we know that the nth row has let's say we know that the nth row has four elements in it this is the third four elements in it this is the third row and has four elements in it and we row and has four elements in it and we want suppose the third element let's say want suppose the third element let's say k is equal to 3 we want this target k is equal to 3 we want this target element do we really have to do a bread element do we really have to do a bread for search on this tree do we really for search on this tree do we really have to do a depth for search where we have to do a depth for search where we go through every single node no because go through every single node no because we can do kind of like a binary search we can do kind of like a binary search or just like a traditional search on a or just like a traditional search on a binary tree where the time complexity is binary tree where the time complexity is actually going to be the height of the actually going to be the height of the tree and the reason that we can do that tree and the reason that we can do that is because from the root position here is because from the root position here we know this is our Target we know that we know this is our Target we know that there are four elements in the row that there are four elements in the row that we're looking for and we happen to know we're looking for and we happen to know that K is in the second half of those that K is in the second half of those elements our Target is in the second elements our Target is in the second half half of those elements so from The half half of those elements so from The Roots perspective we have two choices we Roots perspective we have two choices we either go left or we go right with this either go left or we go right with this in mind don't you think we should in mind don't you think we should probably go right no need to go left we probably go right no need to go left we can forget that this ever even existed can forget that this ever even existed but the hard part or at least this might but the hard part or at least this might not be obvious to you how do we do it not be obvious to you how do we do it now when we started with the entire row now when we started with the entire row it was pretty easy to know because we it was pretty easy to know because we could just take the length of the row could just take the length of the row divide it by two and then we would know divide it by two and then we would know is the K value in the first half or the is the K value in the first half or the second half well the easiest way at second half well the easiest way at least in my opinion is to have two least in my opinion is to have two pointers one pointer is going to pointers one pointer is going to initially be set to this position which initially be set to this position which is going to be one cuz like I said this is going to be one cuz like I said this is going to be one indexed that's is going to be one indexed that's according to this problem and the second according to this problem and the second value is going to be here in this case value is going to be here in this case it's four but in the general case it's 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 this case let's say is going to be four this case let's say is going to be four so that's how we're going to do this so that's how we're going to do this with two pointers very simple so so here with two pointers very simple so so here when we decided to go right what we when we decided to go right what we would do kind of like in binary search would do kind of like in binary search take this pointer shift it to the right take this pointer shift it to the right so then it would be here and now that so then it would be here and now that our pointers are here we are at this our pointers are here we are at this position by the way and once again we're position by the way and once again we're going to check should we go left or going to check should we go left or should we go right well this pointer is should we go right well this pointer is at Value three this pointer is at Value at Value three this pointer is at Value four K is equal to three so it clearly four K is equal to three so it clearly lies in the left half so here we would lies in the left half so here we would choose to go to the left and at this choose to go to the left and at this point we would stop we're going to stop point we would stop we're going to stop once we reach that particular level and once we reach that particular level and we know how many levels to Traverse we know how many levels to Traverse based on the N parameter so that's kind based on the N parameter so that's kind of the idea of this problem we're sort of the idea of this problem we're sort of doing a augmented binary search or of doing a augmented binary search or you could think of it as a search on a you could think of it as a search on a tree structure with this the time tree structure with this the time complexity is just going to be the complexity is just going to be the height of the tree which like I said is height of the tree which like I said is going to be based on the N input so the going to be based on the N input so the time complexity is going to be Big O of time complexity is going to be Big O of n what do you think about the memory n what do you think about the memory complexity since we just have two complexity since we just have two pointers and we're not really building pointers and we're not really building this tree structure nor are we this tree structure nor are we traversing it with recursion we actually traversing it with recursion we actually don't need any extra memory memory is don't need any extra memory memory is going to be constant so knowing this going to be constant so knowing this let's go ahead and code it up one quick let's go ahead and code it up one quick thing I want to mention though is when thing I want to mention though is when we compute the Midway point we know like we compute the Midway point we know like we can have a left pointer here a right we can have a left pointer here a right pointer here uh let's assume that this pointer here uh let's assume that this is one let's assume that this is four is one let's assume that this is four when we calculate the Midway point we do when we calculate the Midway point we do so usually by adding these two together so usually by adding these two together and dividing by two if I take 1 + 4 and and dividing by two if I take 1 + 4 and divide that by two and we round down divide that by two and we round down we're going to get two so that kind of we're going to get two so that kind of tells us that the Midway point is always tells us that the Midway point is always going to be here and we pretty much are going to be here and we pretty much are guaranteed that the size of our search guaranteed that the size of our search space is always going to be even so this space is always going to be even so this is pretty much always going to be the is pretty much always going to be the case so when we check if our K value is case so when we check if our K value is in the left half or the right half we're in the left half or the right half we're going to compare it with mid you'll see going to compare it with mid you'll see what I mean in the code explanation what I mean in the code explanation right now so one obvious thing that we right now so one obvious thing that we need to keep track of is what our need to keep track of is what our current value happens to be we know it's current value happens to be we know it's initially going to be zero because initially going to be zero because that's kind of the root of our tree the that's kind of the root of our tree the first row is a single value with just first row is a single value with just zero and this is also what we're going zero and this is also what we're going to be returning but we know that we have to be returning but we know that we have a search space to keep track of as well a search space to keep track of as well I'm going to have two pointers called I'm going to have two pointers called left and right to Define that left is left and right to Define that left is going to be 1 right is going to be 2 to going to be 1 right is going to be 2 to the power of the power of nus1 like I mentioned earlier and then nus1 like I mentioned earlier and then we're going to iterate roughly n times we're going to iterate roughly n times but I'm actually going to iterate in but I'm actually going to iterate in range of n minus one times because we're range of n minus one times because we're already at the first row we've already already at the first row we've already computed the first row and we just need computed the first row and we just need to compute n minus one more rows if n is to compute n minus one more rows if n is one this Loop isn't going to execute and one this Loop isn't going to execute and we're going to return zero regardless so we're going to return zero regardless so that works out in that case the reason that works out in that case the reason this is an underscore is because we're this is an underscore is because we're actually not going to need this variable actually not going to need this variable at all now it's pretty much just the at all now it's pretty much just the binary search that I talked about we binary search that I talked about we compute mid it's going to be left plus compute mid it's going to be left plus right divide that guy by two and then we right divide that guy by two and then we do our comparison like I just mentioned do our comparison like I just mentioned our K variable we need to know is it in our K variable we need to know is it in the left half or the right half if it's the left half or the right half if it's equal to the middle value it's in the equal to the middle value it's in the left half if it's less than the middle left half if it's less than the middle value it's also in the left half so this value it's also in the left half so this is the comparison that we do if K is is the comparison that we do if K is less than or equal to Mid we are in the less than or equal to Mid we are in the left half in the other case we're in the left half in the other case we're in the right half but what do we do if we're in right half but what do we do if we're in the left half or rather if our K value the left half or rather if our K value is in the left half we should move to is in the left half we should move to the left half so what we do is set our the left half so what we do is set our right pointer now equal to Mid if we right pointer now equal to Mid if we were in if our K value is in the right were in if our K value is in the right half then we'd want to search in the half then we'd want to search in the opposite direction so we would set left 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 most important part of the problem but most important part of the problem but there's one last thing left remember there's one last thing left remember when we have a zero like I have drawn up when we have a zero like I have drawn up above or written up above its left child above or written up above its left child is going to be zero and Its Right child is going to be zero and Its Right child is going to be one when we have a one is going to be one when we have a one its left child is going to be one and its left child is going to be one and Its Right child is going to be zero so Its Right child is going to be zero so we could write out a bunch of if we could write out a bunch of if statements to get this exactly right but statements to get this exactly right but there's actually a bit of a pattern that there's actually a bit of a pattern that you might notice if we move to the left you might notice if we move to the left half like here is when we're moving to half like here is when we're moving to the left side of the search space when the left side of the search space when we do that the value doesn't change does we do that the value doesn't change does it zero goes to zero one goes to one so it zero goes to zero one goes to one so actually there's nothing needed here we actually there's nothing needed here we don't need to update our current integer don't need to update our current integer when we move to the left but when we when we move to the left but when we move to the right we swap it 0o becomes move to the right we swap it 0o becomes one 1 becomes zero so that's the pattern one 1 becomes zero so that's the pattern so here what we're going to do is Set so here what we're going to do is Set current equal to zero if current is current equal to zero if current is equal to 1 a shorter way to write this equal to 1 a shorter way to write this is just if Curr else this is going to be is just if Curr else this is going to be set to one we're basically swapping it set to one we're basically swapping it so that's all we are doing here so when so that's all we are doing here so when you look at the solution code this seems you look at the solution code this seems like a very very trivial problem and it like a very very trivial problem and it kind of is once you understand that this kind of is once you understand that this is sort of like a binary search problem is sort of like a binary search problem but it's not a trivial problem to solve but it's not a trivial problem to solve so don't feel bad if you weren't able to so don't feel bad if you weren't able to solve it by yourself so let's run this solve it by yourself so let's run this to make sure that it works and as you to make sure that it works and as you can see on the left yes it does and it's can see on the left yes it does and it's pretty efficient if you found this pretty efficient if you found this helpful please like And subscribe if helpful please like And subscribe if you're preparing for coding interviews you're preparing for coding interviews check out NE code. thanks for watching check out NE code. thanks for watching and I'll see you soon
2024-03-21 16:25:22
779
https://i.ytimg.com/vi/p…axresdefault.jpg
K-th Symbol in Grammar - Leetcode 779 - Python
TndF9V2UyHE
Ki gas welcome tu take tu vedita and its video c r going tu solve count of video c r going tu solve count of smaller numbers after self so smaller numbers after self so what is given in this problem statement here I have given you what is given in this problem statement here I have given you a vein and you have to make it a vein and you have to make it how will count aunteric be made what to do here how will count aunteric be made what to do here What is the rectangle index one, we have to take the What is the rectangle index one, we have to take the particular index, okay and we have to see particular index, okay and we have to see how many such elements are there on the right side of it how many such elements are there on the right side of it which are smaller than the element at the index, which are smaller than the element at the index, what do we have to do, we have to what do we have to do, we have to keep it in the count teddy, okay, keep it in the count teddy, okay, what will happen to us with this? what will happen to us with this? what will happen to us with this? 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 So there is only one, okay, if there So there is only one, okay, if there So there is only one, okay, if there is no element, otherwise is no element, otherwise it will be zero, so what will be our output? Okay, so it will be zero, so what will be our output? Okay, so how are we going to solve this problem, how are we going to solve this problem, here we here we can solve the problem by doing our sort of thing, okay? can solve the problem by doing our sort of thing, okay? Look, first what do I do, let me Look, first what do I do, let me tell you in brief about our sort, tell you in brief about our sort, what is my shot, okay, after that what is my shot, okay, after that we will come to our problem, okay look, we will come to our problem, okay look, what is given here, one is given, now what is given here, one is given, now what we have to do is our shot. what we have to do is our shot. I have to sort it by doing that, what is the short, you have I have to sort it by doing that, what is the short, you have a sorting algorithm, a sorting algorithm, what can you do by doing that, look, you can sort, what can you do by doing that, look, you can sort, okay, so what is this based on, divide and okay, so what is this based on, divide and best, what do we do in this, let's best, what do we do in this, let's keep dividing. keep dividing. keep dividing. 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 The element is sorted in itself. The The element is sorted in itself. The The element is sorted in itself. The single element is single element is sorted in itself. Okay, so what sorted in itself. Okay, so what will we do here, when we will sort, that is, we will divide, then will we do here, when we will sort, that is, we will divide, then what will we do again, we will what will we do again, we will start merging it, now how will start merging it, now how will we merge that too? we merge that too? we merge that too? 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 Okay guys, if you divide both of them by two, you will Okay guys, if you divide both of them by two, you will Okay guys, if you divide both of them by two, you will get three, then the first get three, then the first half will be yours from zero to three, and the half will be yours from zero to three, and the next half will be yours, look at four to six, next half will be yours, look at four to six, here it is from zero to 3, from here it is from zero to 3, from four to six. four to six. four to six. 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 in our hands, then this is also in our hands, this is also in our hands, divide this is also in our hands, Has the Has the Has the single element been converted into a single element? single element been converted into a single element? Now what will we do? We will Now what will we do? We will start merging here. Now how will we merge? start merging here. Now how will we merge? What will we do here? We What will we do here? We will compare both of them. Which of the two is ours? will compare both of them. Which of the two is ours? Here, we are going to do ascending order. Here, we are going to do ascending order. What will we do in ascending order? Which is the What will we do in ascending order? Which is the smaller element? Which is the smaller element? The one that is smaller will smaller element? Which is the smaller element? The one that is smaller will come first, the one that is come first, the one that is greater than that will come after that, so greater than that will come after that, so here 27 will be 38, here will be yours, you will here 27 will be 38, here will be yours, you will compare 433, what is yours, smaller is compare 433, what is yours, smaller is three. three. three. will compare these two 9 first 382 then 10 10 next this this then here what we will do is start merging these two then what do we do in this let's compare Okay guys, Okay guys, Okay guys, first come and see, you will first come and see, you will compare which of the two is smaller? 3 is smaller, compare which of the two is smaller? 3 is smaller, put three first and then increment k. put three first and then increment k. Okay guys, then come and see, Okay guys, then come and see, compare which of the two is smaller? 27 is 27, compare which of the two is smaller? 27 is 27, put 27 here. put 27 here. put 27 here. 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 We will sort i, we will take We will sort i, we will take We will sort i, we will take k, then we will compare both, k, then we will compare both, which is smaller, nine, nine, we will which is smaller, nine, nine, we will keep here, we will increment i, then keep here, we will increment i, then if we compare these two, we will compare if we compare these two, we will compare which is smaller among the two, 10, which is smaller among the two, 10, then we will keep 10 here. then we will keep 10 here. then we will keep 10 here. 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 We will We will We will sort both of them again, then we will start from i here, we will start from sort both of them again, then we will start from i here, we will start from here, here, ok, then we will ok, then we will compare both, which one is yours, if yours is compare both, which one is yours, if yours is smaller, then three are small, then three will be the first ones, smaller, then three are small, then three will be the first ones, then you will increment i, then then you will increment i, then compare both of them. compare both of them. compare both of them. element, then put nine here, increment K, then you increment them, then what is yours, if you compare both, then put it here, increment I, then put it here, increment I, people will be here. people will be here. people will be here. 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, here we will take the first input, five to six one, okay Here, Here, Here, what do we do? We will what do we do? We will not sort it in ascending order. What will we not sort it in ascending order. What will we do? We will sort it in order. Okay, I will explain to you, you will understand. Okay, look, Have given van given Have given van given 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 when you divide in half then this is your five You are yours, okay, then what is six, this is yours, 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, Now this is you here, then Now this is you here, then Now this is you here, then six here, van here, now six here, van here, now what will we do with this? what will we do with this? Along with the element, I Along with the element, I will also take care of its index, this is zero, van is you, will also take care of its index, this is zero, van is you, this is three, so here. 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 by incrementing it here? What will we do by incrementing it here? Van Van Van what will you do, people put five here and so what will we do here, so what will we do here, update it and make it van, update it and make it van, we will sort both of them, what will we get, we will 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, 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 Let's do this here, let's Let's do this here, let's Let's do this here, let's put this one van here and put you here, put this one van here and put you here, now he is left with the van next to this one, now he is left with the van next to this one, see, you have got 21100, see, you have got 21100, see here, I understand the code for you, see here, I understand the code for you, then through the code, we then through the code, we then through the code, we 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, Will do it Will do it Will do it but it won't do it for all, so 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 show you here ok how are we going to show different faces ok so see here how are we going to show different faces ok so see here what we will do see this what we will do see this what we will do see this 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, what will we do to that, what will we do to that, vector of feet, we will do that, okay, where what will we do, we If we If we If we keep that also, then what will we do for this? We will keep that also, then what will we do for this? We will do that and we are going to do that for sorting. do that and we are going to do that for sorting. Okay, so coming Okay, so coming to the code part, look at account is small. Okay, here we have given NMPS, account is small. Okay, here we have given NMPS, what will we do? what will we do? what will we do? 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 So So So here we have created a foot here, here we have created a foot here, I is yours, then the I index is yours, okay, the I is yours, then the I index is yours, okay, the index of the element on the index has been index of the element on the index has been updated here, now here we have updated here, now here we have taken a vector count which will taken a vector count which will create our account. create our account. create our account. 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 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, Now what is happening in our short, first of all we are looking at L, first of all we are looking at L, if it is 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 index of L, what is yours, look, this is the next zero and - yours, look, this is the next zero and - yours, look, this is the next zero and - 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 Let's do this, Let's do this, Let's do this, what will we do, what will we do, we will first divide it into half parts, we are dividing, we will sort it we will first divide it into half parts, we are dividing, we will sort it on the right, we will divide the on the right, we will divide the half part first, then half part first, then how will we do it again, what will we do on this, we will how will we do it again, what will we do on this, we will call research call research which will take which will take which will take Okay, we are doing it till Mir, then 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 Plus van R and we have called it merge Plus van R and we have called it merge Plus van R and we have called it merge here, what will it do for you, here, what will it do for you, finally sort it, whatever you want 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, 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 You are dividing, you are dividing these two, you are You are dividing, you are dividing these two, you are You are dividing, you are dividing these two, you are dividing right, dividing right, your size is always changing, right your size is always changing, right size is always changing, so here whatever size is always changing, so here whatever we will take, we will take one of the sizes up to R - L + 1. we will take, we will take one of the sizes up to R - L + 1. Okay in which we are going to store after Okay in which we are going to store after sorting means after merging sorting means after merging not so three sorting so not so three sorting so in our sod after that what we are doing is in our sod after that what we are doing is margining right so mars margining right so mars we will do and keep one in in we will do and keep one in in we are going to keep we are going to keep we are going to keep 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 What we have What we have What we have done here is that we have created a temporary vector 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 You are giving me You are giving me You are giving me how far your eye was going, see here, how far your eye was going, see here, understand here, your eye was going understand here, your eye was going till its size, then it was till its size, then it was going till its size, right, so yes, see, this going till its size, right, so yes, see, this is till the sweet element, understand here. is till the sweet element, understand here. is till the sweet element, understand here. two if you said these two if you are sorting then I start from here and go till here which is your which is your we are rich plus which is which is your we are rich plus which is start start start 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, So So So what will we do here, we will what will we do here, we will compare with the first, compare with the first, which is the first element, I think next, which is the which is the first element, I think next, which is the first, that is, which element is, is it first, that is, which element is, is it less than equals, you arrange first, less than equals, you arrange first, if yes, then what will we do, which is the greater, which is if yes, then what will we do, which is the greater, which is We will store K's in temk++, We will store K's in temk++, We will store K's in temk++, okay if respect vice, okay if respect vice, what will we do, update the count errors here, what will we do, update the count errors here, plus R mines, K plus R mines, K plus van, now why are we doing this here, let me plus van, now why are we doing this here, let me tell you, okay here tell you, okay here I I I this, 1998 and 45 here, what are we going to do, so we will not do anything, simply will not operate, so we will not do anything, simply will not operate, okay, so what will we do, okay, so what will we do, give nine first. give nine first. give nine first. index of nine is van and its zero is ok then what will we do with this we will merge these then what will we do last is last is your total we 2 - 2 + 1 So there will be 2 - 2 + 1 So there will be 2 - 2 + 1 So there will be van here. See, by law there should be van van here. For this, for the van here. See, by law there should be van van here. For this, for the van van index, van index pe because index, van index pe because what is eight is smaller than nine, so there what is eight is smaller than nine, so there should be van here and we also get van. should be van here and we also get van. should be van here and we also get van. 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, Wait Wait Wait because this smaller one has not got the right because this smaller one has not got the right index, which is this one, if you have not found it, the index, which is this one, if you have not found it, the smaller one cannot be updated here, smaller one cannot be updated here, further let's leave it as it is, then what will we further let's leave it as it is, then what will we do, do, it is finished, whatever is left, it is finished, whatever is left, we will update it here. we will update it here. we will update it here. we got 981, now we will do 7 and 5, okay we will do 7 and 5, when we are here, what is yours, what is yours, then how do we count it? then how do we count it? then how do we count it? 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, in which index will it go, Pay van ok this Pay van ok this Pay van ok this van is done now what will we do if we van is done now what will we do if we sort both then we will get 75 ok now this came sort both then we will get 75 ok now this came and ok if we compare with seven then nine is yours what is ok if we compare with seven then nine is yours what is greater then what we store in yer greater then what we store in yer If you store the nine then it is okay If you store the nine then it is okay and since what is this, your 7 has already been and since what is this, your 7 has already been found, that means 7, what is this, what is this, it is found, that means 7, what is this, what is this, it is smaller than 9, okay, it is smaller, so now tell me, there is only smaller than 9, okay, it is smaller, so now tell me, there is only one smaller nine, you have paid here. one smaller nine, you have paid here. Now you do seven by increments, you Now you do seven by increments, you guys do it here, it's okay, you guys do theirs by doing guys do it here, it's okay, you guys do theirs by doing nine, you have got your I stored here, nine, you have got your I stored here, now you go ahead guys, it's okay, now you go ahead guys, it's okay, you guys even five is smaller than this, isn't 9 to 5 you guys even five is smaller than this, isn't 9 to 5 also smaller? also smaller? also smaller? 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 It It It is smaller but we will store the nine. is smaller but we will store the nine. If I am then we will never be able to If I am then we will never be able to compare again because compare again because our number has already moved forward. So what will we do in this condition. our number has already moved forward. So what will we do in this condition. Look, if it is small R Look, if it is small R then it is sorted. We know this. then it is sorted. We know this. then it is sorted. We know this. 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 R, what will happen to it, four will be then 4 - what will we do from here, 4 minus what is its index. here we are, if we here we are, if we have to add right then it will become three, what will have to add right then it will become three, what will be our answer, you will get the accurate answer, be our answer, you will get the accurate answer, see, here I had done the see, here I had done the increment by doing that, so here increment by doing that, so here what we got is not 3. what we got is not 3. what we got is not 3. you got it, okay, so what we are doing here is R - j+1 Okay, then we stored it in the tempo by doing i plus plus of k + r a r because what is yours 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 We will need a sorting one, We will need a sorting one, We will need a sorting one, so what will we do, we will update it here to so what will we do, we will update it here to Eric, so this is our Eric, so this is our solution, let's run it solution, let's run it once, thank you.
2024-03-24 10:19:25
315
https://i.ytimg.com/vi/T…axresdefault.jpg
315. Count of Smaller Numbers After Self
IwCPpY12or8
hello hello today we're gonna be talking about the good problem 1477 fine to about the good problem 1477 fine to non-overlapping subarrays each would non-overlapping subarrays each would target some so I think it's pretty easy target some so I think it's pretty easy conceptually we have to find two conceptually we have to find two non-overlapping subarrays such that the non-overlapping subarrays such that the target is equivalent to equal to the sum target is equivalent to equal to the sum of those two subarrays and if you can't of those two subarrays and if you can't find two subarrays you return negative find two subarrays you return negative one so you know in just a brief example one so you know in just a brief example let's get a better example so here we let's get a better example so here we can see we have to return the sum of the can see we have to return the sum of the two sub arrays so the solution here we two sub arrays so the solution here we can see with target of three we have one can see with target of three we have one the solution is this sub array and then the solution is this sub array and then either this sub array or this suburb and either this sub array or this suburb and since that's size one plus size two or since that's size one plus size two or answer is three alternatively you know answer is three alternatively you know you could look at this and say well this you could look at this and say well this is target three but you know that has a is target three but you know that has a size of three and then you know this is size of three and then you know this is size one so we would have a sum for size one so we would have a sum for which is greater than our previous sum which is greater than our previous sum of three so let's just go right into the of three so let's just go right into the problem so the first thing I'd like to problem so the first thing I'd like to do with any problem is sort of talk do with any problem is sort of talk about intuition and go over sort of base about intuition and go over sort of base cases or or cases that fail so initially cases or or cases that fail so initially you might think well if I just keep a you might think well if I just keep a sliding window and I go through the sliding window and I go through the array maybe I can greedily pick array maybe I can greedily pick intervals if their shortest so for intervals if their shortest so for example let's start with this array and example let's start with this array and in red on the right you know our target in red on the right you know our target is 15 we would discover that right here is 15 we would discover that right here we we see that we reach our target so we we see that we reach our target so maybe we store this you know as a 5 and maybe we store this you know as a 5 and it's of length 5 and you know maybe we it's of length 5 and you know maybe we say well let's keep going so we can you say well let's keep going so we can you know discover another interval here know discover another interval here that also sums to 15 and that's size that also sums to 15 and that's size four so lets you know replace this five four so lets you know replace this five with the four let's assume that any with the four let's assume that any overlapping interval and if it's shorter overlapping interval and if it's shorter is just gonna get replaced right so we is just gonna get replaced right so we discover a four we replace our five it's discover a four we replace our five it's overlapping because they're using the overlapping because they're using the same three and then when we get to the same three and then when we get to the end we realize there's a 1 in the 14s end we realize there's a 1 in the 14s but that overlaps with our answer from but that overlaps with our answer from before so you know if they cross this before so you know if they cross this out there's no solution we've only found out there's no solution we've only found one interval clearly that's not the one interval clearly that's not the right answer because the right answer is right answer because the right answer is if we you know exclude this interval if we you know exclude this interval entirely and we keep these two now entirely and we keep these two now what's the idea behind this you know what's the idea behind this you know sort of in a more abstract sense so if I sort of in a more abstract sense so if I told you the answer if I told you the told you the answer if I told you the shortest two intervals in this range was shortest two intervals in this range was 7 and 1 could you tell me the answer to 7 and 1 could you tell me the answer to this problem I would argue you can this problem I would argue you can because you can immediately see an because you can immediately see an interval here that satisfies our target interval here that satisfies our target of 12 and I just told you the shortest of 12 and I just told you the shortest two intervals or seven and one so you two intervals or seven and one so you would conclude well they have an would conclude well they have an internal else has one I only have an internal else has one I only have an interval size two so our answer is three interval size two so our answer is three all right because you can you can all right because you can you can clearly see that you know this interval clearly see that you know this interval doesn't overlap with anything in this doesn't overlap with anything in this sort of region the now the the the next sort of region the now the the the next sort of idea that we will have is how do sort of idea that we will have is how do we formalize this into something that we formalize this into something that can be written in code right and can be written in code right and furthermore what's the actual sort of furthermore what's the actual sort of algorithm right that's more specifically algorithm right that's more specifically what the question is so let's imagine we what the question is so let's imagine we initialize our sort of world in a place initialize our sort of world in a place where there is no solution where there is no solution both intervals just don't exist right both intervals just don't exist right and when we first look at the array can and when we first look at the array can we know immediately if the sort of we know immediately if the sort of interval satisfies the target oh yeah we interval satisfies the target oh yeah we can write we can look at the first index can write we can look at the first index and if that satisfies the target oh and if that satisfies the target oh we've discovered an interval so the we've discovered an interval so the question we have now now that we've question we have now now that we've discovered an interval that you know discovered an interval that you know equals our target is okay what came equals our target is okay what came before me and do I want to use this before me and do I want to use this interval at all so you know you would interval at all so you know you would ask given this position what's before me ask given this position what's before me well null and null is okay well an well null and null is okay well an interval size 1 is definitely better interval size 1 is definitely better than an interval size null but I haven't than an interval size null but I haven't discovered a second interval yet so discovered a second interval yet so basically what you're doing is you're basically what you're doing is you're looking at this interval size 1 and looking at this interval size 1 and you're taking the sort of minimum the you're taking the sort of minimum the two minimum numbers of the set of three two minimum numbers of the set of three you have two numbers here that tell you you have two numbers here that tell you the best up to that certain point and the best up to that certain point and you have the new interval that you just you have the new interval that you just discovered so in this case it's gonna be discovered so in this case it's gonna be you know 1 and null right we've only you know 1 and null right we've only discovered one interval so let's keep discovered one interval so let's keep going with the algorithm now what does going with the algorithm now what does it do me logically do well since we're it do me logically do well since we're kind of done with this interval we can't kind of done with this interval we can't really use anything with this interval really use anything with this interval again since we know the target since we again since we know the target since we know the array is all sort of positive know the array is all sort of positive integers moving only one pointer isn't integers moving only one pointer isn't going to help us right so let's just going to help us right so let's just move both of the pointers let's just move both of the pointers let's just simplify things whenever you have a simplify things whenever you have a window that sums to the target you're window that sums to the target you're done with those you're done with both of done with those you're done with both of these positions of those pointers these positions of those pointers there's not going to be another window there's not going to be another window that helps you so we move over by one that helps you so we move over by one and we observe that our sum is and we observe that our sum is one let me go okay well that's you know one let me go okay well that's you know less than our target so we know there's less than our target so we know there's no possible interval that ends on this no possible interval that ends on this position so what can we conclude we can position so what can we conclude we can clearly that the best point up until clearly that the best point up until this position is literally just the this position is literally just the previous one there's nothing we can do previous one there's nothing we can do here same thing with the next point here same thing with the next point literally just the previous point we've literally just the previous point we've only discovered one and we'll move the only discovered one and we'll move the pointer up again oh we go okay now I pointer up again oh we go okay now I realize our sum and by the way while realize our sum and by the way while we're sort of moving these pointers we we're sort of moving these pointers we can easily compute the next sum in sort can easily compute the next sum in sort of constant time right we don't need to of constant time right we don't need to go back and add this interval up go back and add this interval up starting from this starting from the starting from this starting from the beginning right we can just as we move beginning right we can just as we move this pointer over look at this value and this pointer over look at this value and say oh it's a 1 ok add 1 to my son say oh it's a 1 ok add 1 to my son alternatively if you move the left alternatively if you move the left pointer over by 1 say okay well we're pointer over by 1 say okay well we're removing this element so we're removing this element so we're subtracting that right so we're so we're subtracting that right so we're so we're not sort of computing this sum over and not sort of computing this sum over and over and over again and going back and over and over again and going back and forth in the array so we discover an forth in the array so we discover an interval here besides 3 what does that interval here besides 3 what does that mean well that means that we need to ask mean well that means that we need to ask the question 3 and all non-overlapping the question 3 and all non-overlapping intervals up to a certain point where intervals up to a certain point where are the non overlapping intervals with are the non overlapping intervals with this position given or sorry not that this position given or sorry not that position the interval so the non position the interval so the non overlapping intervals are going to be overlapping intervals are going to be everything to the left of our left everything to the left of our left pointer all right everything sort of pointer all right everything sort of over here which happens to be right here over here which happens to be right here we've already computed that we already we've already computed that we already know the answer to that so we have a know the answer to that so we have a question of three null and one give me question of three null and one give me the two smallest numbers from that set the two smallest numbers from that set let's assume null is infinitely big and let's assume null is infinitely big and by that token in my code I implemented by that token in my code I implemented this as actually infinity instead of this as actually infinity instead of null but I think nulls null but I think nulls little bit easier to explain three and little bit easier to explain three and one are the best we can do up to this one are the best we can do up to this point which to know some stuff for sore point which to know some stuff for sore answer right now is four but that's not answer right now is four but that's not the only question we need to ask so I the only question we need to ask so I sort of didn't ask this question sort of didn't ask this question immediately because I didn't want to immediately because I didn't want to overwhelm but we also need to ask is overwhelm but we also need to ask is what we observe here given this 3 and what we observe here given this 3 and this non-overlapping intervals better this non-overlapping intervals better than everything else we've found up to than everything else we've found up to this point and in this case and actually this point and in this case and actually in this problem example it is always in this problem example it is always going to be better but you can imagine going to be better but you can imagine that we discover some solution maybe that we discover some solution maybe here that is not better than the three here that is not better than the three and one that we discovered previously so and one that we discovered previously so we need to be asking the question is our we need to be asking the question is our three and one better than the sort of three and one better than the sort of one and null and you know if you one and null and you know if you initialize these to infinity you know initialize these to infinity you know you can just ask is the sum of of sort you can just ask is the sum of of sort of this less than the sum of this and if of this less than the sum of this and if it is then we want to stay with the it is then we want to stay with the solution we had so let's continue with solution we had so let's continue with this example so this interval is done so this example so this interval is done so we need to move our left and our right we need to move our left and our right foot in river by 1 and we realize our foot in river by 1 and we realize our sum is greater than 3 so you know it's 7 sum is greater than 3 so you know it's 7 so we have to move our left pointer if I so we have to move our left pointer if I want and still larger I move our left want and still larger I move our left pointer over my 1 again and it's still pointer over my 1 again and it's still larger so let's you know the left larger so let's you know the left whatever I want and let's be smart about whatever I want and let's be smart about the right pointer and say you know if the right pointer and say you know if the right pointer ever falls behind just the right pointer ever falls behind just move that up I want move that up I want so right now you know the this 5 that so right now you know the this 5 that we've moved our right pointer off of we we've moved our right pointer off of we conclude there's no interval that ends conclude there's no interval that ends on 5 because we moved our right pointer on 5 because we moved our right pointer right so we just look back and we fill right so we just look back and we fill in the best answer up to the point not in the best answer up to the point not including 5 because there's no interval including 5 because there's no interval that ends on 5 and we also observe that ends on 5 and we also observe there's no interval ends on 1 there's no interval ends on 1 but now that somes too small so we move but now that somes too small so we move our right pointer and whenever we move our right pointer and whenever we move our right pointer we literally just look our right pointer we literally just look back let me say just just give me the back let me say just just give me the best that you have up to this point and best that you have up to this point and now we realize that there is an interval now we realize that there is an interval that sums to three so we asked the same that sums to three so we asked the same question we asked over here we have this question we asked over here we have this entity three and one and we have all entity three and one and we have all non-overlapping intervals which just non-overlapping intervals which just happens to be three and one as well and happens to be three and one as well and we asked sorry this is a two of size two we asked sorry this is a two of size two and we asked the question give me the and we asked the question give me the three give me the two smallest numbers three give me the two smallest numbers from these numbers well that's going to from these numbers well that's going to be two and one and is two and one better be two and one and is two and one better than this guy well yeah it is so we keep than this guy well yeah it is so we keep the two in the one and as we sort of the two in the one and as we sort of continue this problem on we can see that continue this problem on we can see that you know we shift the left over by one you know we shift the left over by one we shift the right over by one we we shift the right over by one we realize this sums too large so maybe the realize this sums too large so maybe the left over by one and we realized we're left over by one and we realized we're at the end of the array and the sums at the end of the array and the sums still too large so we just record our still too large so we just record our previous up to that point and then we're previous up to that point and then we're done and then algorithm terminates so done and then algorithm terminates so what's the run time of this algorithm what's the run time of this algorithm well the run time is gonna be of it well the run time is gonna be of it right we're only going through this rate right we're only going through this rate once and we do have two pointers so once and we do have two pointers so maybe it's on the order of something maybe it's on the order of something like 2n but we only go through the like 2n but we only go through the algorithm we only go through the array algorithm we only go through the array once and as long as we're sort of once and as long as we're sort of storing these in a constant time lookup storing these in a constant time lookup hash table and computing this sum in hash table and computing this sum in constant time as we're moving through constant time as we're moving through this array then we're gonna be you know this array then we're gonna be you know running this algorithm in 11 time so running this algorithm in 11 time so hopefully this was helpful the code is hopefully this was helpful the code is going to be you know in the comments going to be you know in the comments below and I hope to see you in the next below and I hope to see you in the next video
2024-03-21 03:02:13
1,477
https://i.ytimg.com/vi/I…r8/sddefault.jpg
FAANG INTERVIEW PREP - Leetcode #1477 - Find Two Non-overlapping Sub-arrays with Sum
PXIFRk4wWzc
hello in this video we're going to be going through Lois common ancestor of a going through Lois common ancestor of a binary tree three which is lead code binary tree three which is lead code problem problem 1650 this problem is marked as a medium 1650 this problem is marked as a medium and it's fairly new and fairly popular and it's fairly new and fairly popular but um it is high on the but um it is high on the frequency frequency list given two nodes of a binary tree p list given two nodes of a binary tree p and Q return their lowest common and Q return their lowest common ancestor ancestor LCA each node will have a reference to LCA each node will have a reference to its parent node the definition for node its parent node the definition for node is below yada yada according to the is below yada yada according to the definition of LSA and Wikipedia which we definition of LSA and Wikipedia which we know Wikipedia is always right the know Wikipedia is always right the lowest common ancestor of two nodes p lowest common ancestor of two nodes p and Q and A tree is the lowest node that and Q and A tree is the lowest node that has both p and Q as descendants and we has both p and Q as descendants and we also allow a descendant to be a also allow a descendant to be a descendant of itself allow me to descendant of itself allow me to introduce myself to introduce myself to myself all right root just cuz I figured myself all right root just cuz I figured out how to read these so three 5 1 6 2 out how to read these so three 5 1 6 2 08 the null null 08 the null null because the six doesn't have a left or because the six doesn't have a left or right child then we have seven and four right child then we have seven and four and apparently we don't care about the and apparently we don't care about the children of the zero and the eight so if children of the zero and the eight so if p is five and Q is p is five and Q is 1 then the parent of these is going to 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 Q all right so while these don't equal 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 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 P otherwise we'll assign it to P whoops P otherwise we'll assign it to P whoops P2 P2 parent and then those will keep going parent and then those will keep going through through until they equal each through through until they equal each other and then we'll just return P1 we other and then we'll just return P1 we can return P1 or P2 it doesn't matter can return P1 or P2 it doesn't matter because they equal each other so let's because they equal each other so let's debug this and see what we get okay for debug this and see what we get okay for this example I just used example this example I just used example one and so p is going to be one and so p is going to be five Q is going to be one so we'll just five Q is going to be one so we'll just go through here you can see P1 is five go through here you can see P1 is five P2 is P2 is 1 so while P1 is not equal to P2 which 1 so while P1 is not equal to P2 which is is true so P1 is not null so we're going to true so P1 is not null so we're going to sign P1 to its parent which is parent is sign P1 to its parent which is parent is three three and then P2 is not null so three three and then P2 is not null so we're going to ass P2 to the we're going to ass P2 to the parent which is also three so that's parent which is also three so that's boom easy peasy return boom easy peasy return P1 which is three and that's all she P1 which is three and that's all she wrote all right let's try running this wrote all right let's try running this see if I did it right looks like I did see if I did it right looks like I did submit submit it e faster than 28 and 22 let's try it e faster than 28 and 22 let's try again who we got 65 that time I'll take again who we got 65 that time I'll take it now do the time complexity time it now do the time complexity time complexity is O of n we're just looping complexity is O of n we're just looping through uh the binary tree so we through uh the binary tree so we don't um increase or decrease the time don't um increase or decrease the time needed based on the needed based on the inputs is O of one we're not using more inputs is O of one we're not using more space we're just looping through the space we're just looping through the tree and that is it so let me know if tree and that is it so let me know if you have questions thanks for watching you have questions thanks for watching and we'll see you next time
2024-03-19 18:11:46
1,650
https://i.ytimg.com/vi/P…axresdefault.jpg
[SOLVED!] Lowet Common Ancestor of a Binary Tree III - LeetCode 1650 - Java
RfG7vR06R1g
hey everyone let's talk the today's lad code challenge find unique binary code challenge find unique binary strings so in this problem we are given strings so in this problem we are given a string array nums containing n unique a string array nums containing n unique binary strings and all of that binary binary strings and all of that binary strings are of length n and we have to strings are of length n and we have to return any binary string of length n return any binary string of length n which does not appear in that nums array which does not appear in that nums array and you can return any answer so let's and you can return any answer so let's have a look on this example here we are have a look on this example here we are given we are given binary strings of given we are given binary strings of length two so for two length how many length two so for two length how many binary string we can have we can have 0 binary string we can have we can have 0 0 0 1 1 0 0 1 1 0 and 1 1 these are the possible options 0 and 1 1 these are the possible options we can have in our nums array and what we can have in our nums array and what are the options given to us those are 0 are the options given to us those are 0 1 and 1 0 and we have to return any 1 and 1 0 and we have to return any binary string from this array which is binary string from this array which is not present in our not present in our given nums so first approach can be like given nums so first approach can be like convert converting those element to the convert converting those element to the base base 10 so if we have converted those binary 10 so if we have converted those binary string to base 10 we can just directly string to base 10 we can just directly iterate over the candidate options so 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 3 from binary string you can also check 3 from binary string you can also check 0 1 2 0 1 2 3 so these four are our candidate 3 so these four are our candidate options and we can compare these value options and we can compare these value to the values given uh given in the to the values given uh given in the problem so in the problem the in the problem so in the problem the in the problem we are given with two binary problem we are given with two binary string which are 0 1 and 1 0 so 0 1 is 1 string which are 0 1 and 1 0 so 0 1 is 1 1 0 is 2 so we are given 1 and two and 1 0 is 2 so we are given 1 and two and we can have 0 1 2 3 in that array we can have 0 1 2 3 in that array so by iterating that array we can get to so by iterating that array we can get to know which is the element not present in know which is the element not present in our nums array so we'll iterate over our nums array so we'll iterate over this array 0 1 2 3 0 is 0 is not present this array 0 1 2 3 0 is 0 is not present in that set it means we can return zero in that set it means we can return zero as an answer so later on we will convert as an answer so later on we will convert 0 0 to base 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 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 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 1 0 0 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 at every point I'm just adding 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 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 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 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 program okay program okay let's try to submit this problem let's let's try to submit this problem let's try writing the code for this problem try writing the code for this problem here we are going to check all the here we are going to check all the possibilities for these binary string of possibilities for these binary string of length length n so firstly let's capture the length n so firstly let's capture the length num num St and we are adding our existing binary St and we are adding our existing binary search in a set so I'm also taking a set search in a set so I'm also taking a set of string in and for the size set equal to Hash Hash Hash 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 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 return that set do contains temp equal to equal to false in that case we can just directly temp otherwise otherwise we can check for left part left part we can check by adding zero to our existing string so solution plus Z if we are able to achieve the plus Z if we are able to achieve the answer by adding zero if left not equal answer by adding zero if left not equal to n then we will just return left else to n then we will just return left else we will check for the right case we will check for the right case solution m solution m + 1 E right not equal to + 1 E right not equal to n otherwise we are just going to return n otherwise we are just going to return now let's try to run this code output 0 zero I forgot to add the existing nums in the set so for string s nums set to s memory limit exceeded okay so maybe it s memory limit exceeded okay so maybe it it is going to process the elements with it is going to process the elements with length more than n so in that case what 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 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 [Music] [Music] again again sorry it is iner now let's try to submit this problem okay it is submitted successfully beats 77% of the users okay guys I hope you understood you
2024-03-25 12:48:29
1,980
https://i.ytimg.com/vi_w…xresdefault.webp
Solving LeetCode 1980 Find Unique Binary String | Meta | Google | Backtracking
dpq9n85yJ-s
in this video we're going to take a look at a legal problem called combination at a legal problem called combination sum four so uh previously i did a sum four so uh previously i did a legal video called combination sum uh legal video called combination sum uh number one number two number three number one number two number three 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 i should say another question that's related to combination sum related to combination sum but this question i find is kind of but this question i find is kind of similar to dp right similar to dp right dynamic programming which follows the uh dynamic programming which follows the uh the distinct ways the distinct ways dynamic programming pattern where we dynamic programming pattern where we want to find the total distinct ways want to find the total distinct ways for the given parameters or the given for the given parameters or the given values right so you can see here given a values right so you can see here given a array of distinct integer values and a array of distinct integer values and a target integer target integer value return the number of possible value return the number of possible combinations combinations that can add up to this target so you that can add up to this target so you can see the target is guaranteed to fit 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 we have an example of we have an example of integer array which has distinct values integer array which has distinct values we will not have uh we will not have uh values that are same to each other and values that are same to each other and you can see here we also have a target you can see here we also have a target of four so we want to know how many of four so we want to know how many combinations can we come up with combinations can we come up with that has a sum that's equal to four that has a sum that's equal to four right you can see here we have one plus right you can see here we have one plus one plus one plus one one plus one plus one uh because you can see here we can use uh because you can see here we can use the same element more than once the same element more than once right and you we can also have uh just right and you we can also have uh just one plus one plus two one plus one plus two or one plus two plus one you can see or one plus two plus one you can see that this is a different combination is that this is a different combination is this this right even though those values are the right even though those values are the same but different combination different same but different combination different order order but it still counts right we can also but it still counts right we can also have one plus three have one plus three uh two plus one plus one two plus two uh two plus one plus one two plus two three plus three plus one so we want to know how many one so we want to know how many combinations combinations can we come up with have it has a sum can we come up with have it has a sum that's equal to the target right and no that's equal to the target right and no the different sequence are counted as the different sequence are counted as different combinations different combinations and let's say we have a situation where and let's say we have a situation where we have we have the value right in this case there's the value right in this case there's only one element and this element is only one element and this element is actually bigger than actually bigger than the target sum then there's no way that the target sum then there's no way that we can come up with a target sum which we can come up with a target sum which is going to return 0 right because is going to return 0 right because there's no combinations there's no combinations because even though if i nine plus nine because even though if i nine plus nine plus nine it still plus nine it still will never reach two to three because will never reach two to three because nine is all it's always bigger than nine is all it's always bigger than three right three right so how can we solve this problem so so how can we solve this problem so let's say we have an example like this let's say we have an example like this right so in this case if our current sum right so in this case if our current sum is is 4 and or i should say the target sum is 4 and or i should say the target sum is 4 4 we want to find total combinations that we want to find total combinations that we can we can find that has a sum that's equal to 4. find that has a sum that's equal to 4. so in this case what we can do is we can so in this case what we can do is we can choose choose n number of uh well i should say we can n number of uh well i should say we can go down go down a number of paths because in this case a number of paths because in this case we we can first take the first element or the can first take the first element or the second element or the third element second element or the third element to be added onto our combination right to be added onto our combination right as long as as long as it satisfy the condition of course so it satisfy the condition of course so first we're going to do is we're going first we're going to do is we're going to add to add 1 onto our combination so now we have a 1 onto our combination so now we have a target now that we have a current sum of target now that we have a current sum of 3. 3. we can also add the second element we we can also add the second element we have a current sum of have a current sum of 2. we add a third element we have a 2. we add a third element we have a current sum of one current sum of one and now in this case we can also and now in this case we can also choose to go down a number of paths choose to go down a number of paths right in this case for each and every right in this case for each and every current sum current sum so if i occur if i have a current sum of so if i occur if i have a current sum of three i can choose three i can choose one added onto our combination so now i one added onto our combination so now i have a have a current sum of two right and then i also current sum of two right and then i also can choose can choose to add two onto our combination now i to add two onto our combination now i have a current sum of one have a current sum of one left to fill right in this case i can left to fill right in this case i can also have also have add three onto our current combination add three onto our current combination and you can see we have a zero and you can see we have a zero and you can see we have a current sum and you can see we have a current sum which is equal to zero that means we which is equal to zero that means we found a path found a path that has a sum that's equal to four that has a sum that's equal to four right because you can see here i i right because you can see here i i add a one here and i also add a three add a one here and i also add a three here here so one plus three will pretty much give so one plus three will pretty much give us uh us uh four right so that's why you can see we four right so that's why you can see we have zero have zero uh uh zero sum left to fill uh uh zero sum left to fill so now what we're going to do is we're so now what we're going to do is we're going to return to its parent going to return to its parent say we found one combination say we found one combination and same thing if i go down this path i and same thing if i go down this path i can choose can choose choose to um in this case i can choose choose to um in this case i can choose say i want uh i want to add one say i want uh i want to add one in this case if i add one and in this in this case if i add one and in this case it will give us case it will give us zero then we also have a combination so zero then we also have a combination so it's we're also going to return back to it's we're also going to return back to its parent and say okay well we also its parent and say okay well we also have one combination here have one combination here right and if i try to go down to out of right and if i try to go down to out of 2 2 in this case we're going to get a in this case we're going to get a negative value right if we get a negative value right if we get a negative value we're just going to negative value we're just going to return 0 because there's no way we can return 0 because there's no way we can add or find add or find a combination and same thing for 2 if i a combination and same thing for 2 if i add one add one i have one common a current sum of one i have one common a current sum of one left left if i add a two i have zero combination if i add a two i have zero combination some left some left if i add a three i have a negative value if i add a three i have a negative value so i won't count that so i won't count that right and if i have a one left in this right and if i have a one left in this case i can continue i can choose a one case i can continue i can choose a one in this case i give in this case i give i get a sum of zero if i get a i get a sum of zero if i get a out of two in this case i will get a out of two in this case i will get a negative value right so in this case negative value right so in this case i won't count that right so what's going i won't count that right so what's going to happen is we found a path so what's to happen is we found a path so what's going to happen is we're going to return going to happen is we're going to return back to his parents saying back to his parents saying there's one way one combination that has there's one way one combination that has a sum that's equal to 4 a sum that's equal to 4 and it's also going to return to its and it's also going to return to its parent stack to say well there is one parent stack to say well there is one combination for its uh to find combination for its uh to find a sum that's equal to four a sum that's equal to four or a target and this we also have one or a target and this we also have one path as well because path as well because in this case two minus two is zero right in this case two minus two is zero right so we also have one path so we also have one path or one combination so you can see there or one combination so you can see there there's total of two combinations there's total of two combinations for this element right here right so for this element right here right so what's going to happen is this element what's going to happen is this element is going to return back to its parent is going to return back to its parent stack say okay i have two combination stack say okay i have two combination sum that has a sum that's equal to four sum that has a sum that's equal to four so now for three so now for three if i want to find the total combinations if i want to find the total combinations uh for if the sum is three uh for if the sum is three then there are one two plus then there are one two plus three plus four so there are total four three plus four so there are total four combinations combinations right you can choose one plus one plus right you can choose one plus one plus one right one right one plus two uh two plus one right one plus two uh two plus one right or even a a three right so you can see or even a a three right so you can see we have a three path or we have a three path or actually four path right because you can actually four path right because you can see here i can have one plus one plus see here i can have one plus one plus one plus one one plus one or one plus two uh sorry yeah one plus or one plus two uh sorry yeah one plus two two or two plus one or just plus three right or two plus one or just plus three right so i have four so i have four combinations and then now we have four combinations and then now we have four combinations combinations then we're gonna return back to his pair then we're gonna return back to his pair and say okay for a combination sum and say okay for a combination sum for assignments equal four equal three i for assignments equal four equal three i have four combinations have four combinations and then you can see here we also have and then you can see here we also have to do the same thing for this path to do the same thing for this path but wait a second we already compute but wait a second we already compute this path already in here this path already in here we know that two has a total of two we know that two has a total of two combinations combinations in this case we can do one plus one or in this case we can do one plus one or one plus two one plus two so we're going to return back to step so we're going to return back to step pair and say i have two pair and say i have two two combinations right if i have a two combinations right if i have a current sum one current sum one wait a second i also compute that before wait a second i also compute that before you can see here if i have a current sum you can see here if i have a current sum is equal to one i have one combination is equal to one i have one combination which is just one which is just one so i'm going to return back to this pair so i'm going to return back to this pair and say i have one so four plus two plus and say i have one so four plus two plus one one how many combinations do i have if i how many combinations do i have if i have a current some four have a current some four in this case it's going to be seven in this case it's going to be seven right so i have seven combinations right so i have seven combinations uh for if i if the current sum is seven uh for if i if the current sum is seven or sorry if the current sum is four or sorry if the current sum is four right right uh so what we're going to do here is uh so what we're going to do here is we're going to do a top down approach we're going to do a top down approach with minimization with minimization and this will improve time complexity and this will improve time complexity down to down to a down from exponential to a a down from exponential to a t times n t is basically target t times n t is basically target right and the and the end is number right and the and the end is number of elements right so for each and every of elements right so for each and every single single recursion stack we have to make recursion stack we have to make a number of choices right and for a number of choices right and for each and every those choices we have to each and every those choices we have to do that t number of times right in this do that t number of times right in this case the height of the tree is t case the height of the tree is t so to do this in code first i create a so to do this in code first i create a nums integer array and nums integer array and we're basically going to make this as a we're basically going to make this as a global variable so that i can global variable so that i can create a helper function and be able to create a helper function and be able to use the nums integer array use the nums integer array right and then i also gonna create a right and then i also gonna create a cache array cache array and this cache integer array is going to and this cache integer array is going to have a size of targets have a size of targets right because what we're trying to do right because what we're trying to do here is we're trying to cache for each here is we're trying to cache for each and every single and every single targets for each and every single sum targets for each and every single sum that we have left that we have left uh we're going to be able we're going to uh we're going to be able we're going to be able to be able to cache that right if we visit that cache that right if we visit that element element again we can be able to return the again we can be able to return the precomputed value precomputed value so what we're going to do first is we're 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 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 integer variable called total which keep integer variable called total which keep track of total combinations that we have track of total combinations that we have seen so far seen so far so initially zero right so in this case so initially zero right so in this case we're going to say total we're going to say total plus equal to helper at num plus equal to helper at num so in this case we're going to say 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 if we have a current sum if this is our current sum right so in this case what we're going to do 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 does not equal to null then we can just does not equal to null then we can just return return cash at current sum cash at current sum otherwise what we're going to do is otherwise what we're going to do is we're going to compute it and then we're we're going to compute it and then we're going to cache it going to cache it cache at current sum cache at current sum has this number of combinations has this number of combinations that has a sum that has a sum that's e that has a sum that has a sum that's e that has a sum is equal to current sum that has a sum is equal to current sum right right and now we're just going to run our code and now we're just going to run our code and you can see we also have our success and you can see we also have our success and now let's try to submit our code and and now let's try to submit our code and you can see we have our success you can see we have our success so this is how we solve the combination so this is how we solve the combination sum number four and now let's take a sum number four and now let's take a look at how we can do this using 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 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 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 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 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 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 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 i have zero combination right so again it'll just have zero so one plus 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 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 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 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 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 if this is our current sum if this is our target cell right so now and uh now let's try to six and uh now let's try to six submit and you can see we have our submit and you can see we have our success and success and as you can see here the time complexity as you can see here the time complexity uh in this case is going to be uh in this case is going to be m time or n times t right t is the m time or n times t right t is the target target and uh n is going to be the number of and uh n is going to be the number of items that we have in nums and the space items that we have in nums and the space complexity is also going to be t complexity is also going to be t right where we have uh basically for right where we have uh basically for each and every single sum each and every single sum uh we're going to compute the total uh we're going to compute the total number of combinations number of combinations and to get the current total and to get the current total of combinations right for the current of combinations right for the current target sum target sum we have to get the sum of all the we have to get the sum of all the all the total combinations for its all the total combinations for its uh children stack right for or is uh children stack right for or is each and every single path so there you each and every single path so there you have it and thank you for watching
2024-03-24 11:44:51
377
https://i.ytimg.com/vi_w…xresdefault.webp
[Java] Leetcode 377. Combination Sum IV [DP Distinct Ways #4]
_Uq02Cifywo
hello guys welcome back to the channel and today we're going to solve this Le and today we're going to solve this Le code question which is intersection of code question which is intersection of two arrays this question we basically two arrays this question we basically given two integer arrays nums one and given two integer arrays nums one and nums two and we need to return return nums two and we need to return return the array of their intersection each the array of their intersection each element in the result must be unique and element in the result must be unique and you may return the result in any order you may return the result in any order so basically we given two arrays and we so basically we given two arrays and we need to return the common elements in need to return the common elements in both the arrays but they should be both the arrays but they should be unique right they should be unique mean unique right they should be unique mean there cannot be any duplicates in the there cannot be any duplicates in the result so if You observe carefully in result so if You observe carefully in this array and in this in this two this array and in this in this two arrays there are two twos which are arrays there are two twos which are common but we need to return only a common but we need to return only a single two right and in these two arrays single two right and in these two arrays we see that four and nine are common so we see that four and nine are common so we need to return we can also return we need to return we can also return four and N or we can also return return four and N or we can also return return 9 on 9 and four so when we look at the 9 on 9 and four so when we look at the keyword uh keyword uh unique the first thing that comes to for unique the first thing that comes to for mind is use a hash set right so a set is mind is use a hash set right so a set is used to basically remove all the used to basically remove all the duplicates and store only the unique duplicates and store only the unique elements right so in the first approach elements right so in the first approach we'll use a hash set so let's see how we we'll use a hash set so let's see how we are going to solve that so initially are going to solve that so initially I'll take a set I'll take a set one I'll take two one I'll take two sets set I'm sorry the set one sets set I'm sorry the set one stores the set one stores are unique stores the set one stores are unique elements of the first array and the set elements of the first array and the set two stores unique element unique two stores unique element unique elements of the secondary right in the elements of the secondary right in the first are what are the unique elements 1 first are what are the unique elements 1 comma 2 right and in the second area comma 2 right and in the second area what are the unique elements there is what are the unique elements there is only two right so after after doing this only two right so after after doing this you know what I'll do is I'll Traverse you know what I'll do is I'll Traverse through the second set or the first set through the second set or the first set and check if the element is present in and check if the element is present in the first set or not so uh I will Trav the first set or not so uh I will Trav to the second set and I'll check if the to the second set and I'll check if the same element is in the first set or not same element is in the first set or not if it is in the first set then I will if it is in the first set then I will add it to my array so let's suppose this add it to my array so let's suppose this is my resultant array I'll be right here is my resultant array I'll be right here and I'll check if two is present in the and I'll check if two is present in the in the set or not it is present right so in the set or not it is present right so I will add this to my answer and since I will add this to my answer and since this set does not contain any other this set does not contain any other values that's it suppose if we have values that's it suppose if we have three if we also have three here I'll three if we also have three here I'll check if three is present in this or not check if three is present in this or not this is not the three this is a this is not the three this is a bracket uh this three is not present in bracket uh this three is not present in this right so I will not add this and I this right so I will not add this and I cannot also add one suppose what if cannot also add one suppose what if there is also one one I'll check one is there is also one one I'll check one is present in this or not one is present present in this or not one is present right so this is the answer so like this right so this is the answer so like this we're going to solve this what is the we're going to solve this what is the time and space complexity the time time and space complexity the time complexity will be you know we will be complexity will be you know we will be traversing through the whole first will traversing through the whole first will which will be let's say uh which will be let's say uh the let's say the length of the first the let's say the length of the first array is M and the length of the second array is M and the length of the second AR is n so it will be order of M plus AR is n so it will be order of M plus we'll also Traverse the entire secondary we'll also Traverse the entire secondary right order of n plus and we again right order of n plus and we again Traverse the Traverse the set two right Traverse the Traverse the set two right so the set two in the wor case can be so the set two in the wor case can be order of n right so this will be our order of n right so this will be our time complexity and what is the space time complexity and what is the space complexity we're using a set for the complexity we're using a set for the first shr so at most there can be M first shr so at most there can be M elements right and in the second set elements right and in the second set there can be at most n elements right so there can be at most n elements right so this this is our space this this is our space complexity and in the interview the 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 array can sort the array can sort the array and array and use two pointers 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 4 comma 8 comma 9 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 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 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 do initially what I do is I'll take a do initially what I do is I'll take a set [Music] as so as I have already said I'll Sol the I'll Sol both the 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 length and J less than 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 nums I can also nums I can also add I'm of J as well but I'll always add add I'm of J as well but I'll always add the first one uh and else if my nums one the first one uh and else if my nums one of I less than nums of then I'll move my of I less than nums of then I'll move my I pointer this is very similar to the I pointer this is very similar to the thing that we did yesterday right next thing that we did yesterday right next is array the size of the array the size of the set and for every result again here oh when we are uh when we are here oh when we are uh when we are adding both the elements we just need adding both the elements we just need to increment both the to increment both the pointers forgot to do 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
2024-03-24 11:13:06
349
https://i.ytimg.com/vi/_…axresdefault.jpg
Leetcode 349 || Intersection of two arrays || HashSet || Two Pointers
pMtGhGFflPw
hello everyone so let's talk about a redundant connection so you are giving redundant connection so you are giving the um direct graph right and then you the um direct graph right and then you are given to the array and which you are given to the array and which you generate on that request so you want to generate on that request so you want to return the edge that is removable so if return the edge that is removable so if you want to remove two or three you want to remove two or three uh the graphics still connect right if uh the graphics still connect right if you want to remove one two it's still you want to remove one two it's still from there one three so command the from there one three so command the problem is you want to remove the edges problem is you want to remove the edges from the last right so um from the last right so um this is going to be pretty this is going to be pretty straightforward so uh which is what straightforward so uh which is what you're starting from the beginning and you're starting from the beginning and then you probably just connect just keep then you probably just connect just keep connecting and then we want to just connecting and then we want to just connect two and three right you just connect two and three right you just have to make sure have to make sure do you have a connection between what do you have a connection between what two and three beforehand right so in two and three beforehand right so in this uh in this question you can use the this uh in this question you can use the union fine union fine so union point is pretty straightforward so union point is pretty straightforward and and if you don't know you can just figure it if you don't know you can just figure it out right so pause the second just look out right so pause the second just look for the unit fine and if you finish the for the unit fine and if you finish the video then i'll probably just come back video then i'll probably just come back to the solution so i'm going to just to the solution so i'm going to just create a class for unit 1 create a class for unit 1 and then and then i'm going to have a parent array so for i'm going to have a parent array so for everything don't know everything don't know for every single note right if i if i for every single note right if i if i come here one one two two right so for come here one one two two right so for my one parent is actually equal to two my one parent is actually equal to two so this is how i connect so this is how i connect but by default right you are going to but by default right you are going to connect u connect u uh you to yourself so which is what uh you to yourself so which is what i initialize right so union fine and i initialize right so union fine and i've been passing on you play the cycle i've been passing on you play the cycle of the note right of the note right and then i'm going to just initialize my and then i'm going to just initialize my paragraph paragraph and i'm going to okay so the problem is and i'm going to okay so the problem is what what uh our index doesn't stop from zero uh our index doesn't stop from zero right on the cell phone one so i need to right on the cell phone one so i need to give the extra space 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 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 one or two right so one into passing to the union so if if they are connected together i'm going to so so uh so let me just give a little comment uh so let me just give a little comment so so check if they connect check if they connect or not right or not right so um and then if they didn't comment and and should constantly try should constantly try and and this is going to be pretty much it right this is going to be pretty much it right so so so beforehand i need to what i need to so beforehand i need to what i need to know how do i actually find my know how do i actually find my uh find my uh uh find my uh connector beyond so which is parent connector beyond so which is parent beyond right so i'm going to say fine beyond right so i'm going to say fine since i'm using the in in the ring i'm since i'm using the in in the ring i'm going to return the image going to return the image so i'm going to pass more fasteners so i'm going to pass more fasteners right right so i'm going to say well no uh so i'm going to say well no uh well apparently so you are going to find well apparently so you are going to find a parent right a parent right and while parenting is not able to know and while parenting is not able to know so so basically you want to just keep going up basically you want to just keep going up right so this is what this is uh right so this is what this is uh basically you by default you're pointing basically you by default you're pointing yourself but once you're union you'll yourself but once you're union you'll connect to others connect to others so uh just making sure like if they are so uh just making sure like if they are another thing if they are all the same another thing if they are all the same with me you are just basically finding with me you are just basically finding your answer right so you will just your answer right so you will just return very wrong here so i'm going to return very wrong here so i'm going to just keep updating updating my parent just keep updating updating my parent not equal to what not equal to what able to parents parents able to parents parents you know so which is what finding your you know so which is what finding your grandparents right then you just keep grandparents right then you just keep update your parents update your parents uh uh pointer so uh once i have it i'm to say pointer so uh once i have it i'm to say well i'm use the well i'm use the h root f equal to one h root f equal to one x x two square it will define what two square it will define what right and then keep traversing so i'm right and then keep traversing so i'm just making sure uh if root x if root x just making sure uh if root x if root x is not equal to u y is not equal to u y if they are not the same so which means if they are not the same so which means they are not connecting together right they are not connecting together right triangular loop x 2 triangular loop x 2 y y and i will return true and i will return true so so i'm making sure they connect right i'm making sure they connect right so if loop so if loop if if they are not the same they are not if if they are not the same they are not the same then making sure they come and the same then making sure they come and that will change right over here so if that will change right over here so if they are already connecting together i'm they are already connecting together i'm going to switch and pause going to switch and pause all right all right if you know the logic then come back to if you know the logic then come back to the solution so main function the solution so main function union fine union fine i'm gonna put uf instead right i'm gonna put uf instead right and then new and then new union font union font and then the size is going to be y the and then the size is going to be y the age of 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 and i'm talking about zero formal equals and i'm talking about zero formal equals one right so what does this mean by in the two two two input which is age one and two and i'm gonna connect together if they if they do not have the same pattern right and making sure they 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 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 by one union for every single node right so in this case it is all of e right for the time for the time this is prime right this is all of e as well because drivers the land of the edges and you 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
2024-03-20 16:08:08
684
https://i.ytimg.com/vi/p…Pw/sddefault.jpg
LeetCode 684 | Redundant Connection | Union Find | Java
UWlnLw3a6MI
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 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
2024-03-22 12:31:12
442
https://i.ytimg.com/vi_w…xresdefault.webp
Leetcode #442 - Find All Duplicates in an Array | Full Python Solution in 10 Minutes or Less!
VOgt3NuGU5Y
hello everyone today we are going to cover cover arithmetic slices so we are given an arithmetic slices so we are given an input of an input of an integer array and we have to return the integer array and we have to return the number of number of arithmetic slices in given array so what arithmetic slices in given array so what is arithmetic slice is arithmetic slice a sequence of number is called a sequence of number is called arithmetic arithmetic if it consists of at least three if it consists of at least three elements elements and if the difference between any two and if the difference between any two consecutive element consecutive element is the same so there must be a sequence is the same so there must be a sequence inside the given array whose inside the given array whose difference should be same and the difference should be same and the sequence must be sequence must be at least three elements now let's see at least three elements now let's see this with an example this with an example here is a given example array so now here is a given example array so now let's start checking the difference let's start checking the difference between the first element and second between the first element and second element the difference is one element the difference is one and the second element and the third and the second element and the third element the difference is one again element the difference is one again so one two three forms a sequence that so one two three forms a sequence that is called arithmetic slice is called arithmetic slice so so far the arithmetic slice we found so so far the arithmetic slice we found is one is one so now it is said that the arithmetic so now it is said that the arithmetic slice slice can be at least of three elements or can be at least of three elements or more than three elements more than three elements in this case we already found one one in this case we already found one one two three as an two three as an as one arithmetic slice and further as one arithmetic slice and further moving and checking what is the moving and checking what is the reference reference so between three and four the difference so between three and four the difference is one is one and between four and five again the and between four and five again the differences differences one so now the whole one two three four one so now the whole one two three four five can form an arithmetic sequence so five can form an arithmetic sequence so that is a second sequence that is a second sequence in between if you see one two three in between if you see one two three four alone forms another sequence so now four alone forms another sequence so now the the sequence total sequence is three the sequence total sequence is three the possible sequence from the given possible sequence from the given array is one two three array is one two three one two three four one two three four one two three four five one two three four five and it can be two three four or three and it can be two three four or three four four five or two three four five or two three four five so we can form five so we can form six sequence from the given array so six sequence from the given array so let's see how are we going to solve this let's see how are we going to solve this this problem can be solved by you five this problem can be solved by you five different approaches different approaches and in this video we are going to cover and in this video we are going to cover few approaches of them few approaches of them so obviously our first approach is going so obviously our first approach is going to be brute force to be brute force so now in brute force as usual we'll be so now in brute force as usual we'll be having two pointers i having two pointers i and j i points at the initial element and j i points at the initial element and j and j point is the next element and j moves point is the next element and j moves all the way all the way till the end and scan every possible sub till the end and scan every possible sub array array and calculates its consecutive and calculates its consecutive difference difference and if the difference matches then it and if the difference matches then it gonna count gonna count every time we found a summary that every time we found a summary that matches matches all the consecutive differences same so all the consecutive differences same so this is pretty simple this is pretty simple straightforward algorithm we use for straightforward algorithm we use for every array every array programs and the time complexity of this programs and the time complexity of this is going to be big o of n cube and is going to be big o of n cube and further if you further if you scrutinize it it is going to be big o of scrutinize it it is going to be big o of n square n square but we want this algorithm to run in but we want this algorithm to run in linear time linear time so how do we do it we gonna use dynamic so how do we do it we gonna use dynamic programming programming so here we are going to arrive at the so here we are going to arrive at the solution for solution for every sub problem step by step and every sub problem step by step and finally finally gonna get into our optimal global gonna get into our optimal global solution for the given problem solution for the given problem so our dynamic programming is going to so our dynamic programming is going to have a dp array 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 we found one slice so we are going to update here to one one and now one and now moving on to our third element six moving on to our third element six so now we are going to ask us a question so now we are going to ask us a question that whether we can start a new slice that whether we can start a new slice from this element from this element or we can append with our previous slice or we can append with our previous slice in this case find the difference the in this case find the difference the difference is again two difference is again two so you can append this to a new series so you can append this to a new series so so far we found one so by adding this so so far we found one so by adding this one one it is going to become completely a it is going to become completely a second second sequence or slice one three five is the sequence or slice one three five is the first first slice we found so by adding six slice we found so by adding six it can be one three 5 6. it can be one three 5 6. so we are going to add 1 plus 1 here so 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 so this is this can be one sequence by so this is this can be one sequence by using using six you can form two sequences that is six you can form two sequences that is one three five six and one three five six and three five six that is why we have three five six that is why we have updated here updated here at this position two so now our sum is at this position two so now our sum is gonna become 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 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 and it adds to the sum and the sum and it adds to the sum and the sum becomes seven becomes seven as you don't have any more elements left as you don't have any more elements left next to 30 next to 30 and the sequence should have minimum of and the sequence should have minimum of three three elements it stays zero and the final elements it stays zero and the final result is going to be seven result is going to be seven so this algorithm actually works in big so this algorithm actually works in big o o of n time complexity and big o of of n time complexity and big o of n space complexity so let's see how are 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 of size given array so i'm gonna start my array from so i'm gonna start my array from third element because it should have at third element because it should have at least least three numbers in a slice three numbers in a slice since the index starts from zero i'm since the index starts from zero i'm gonna send it to two 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 previous elements difference is equal to equal to if that is the case we are going to if that is the case we are going to update our tv value in previous index and we're gonna update our sum every and finally we'll return sum 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 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 if it breaks the chain of consecutive differences so now let's yes it is accepted it again works with yes it is accepted it again works with the same time complexity but the same time complexity but we just changed it to constant space we just changed it to constant space so thanks for watching if you do like so thanks for watching if you do like the explanation the explanation hit like and subscribe thank you
2024-03-22 10:52:13
413
https://i.ytimg.com/vi/V…axresdefault.jpg
Arithmetic Slices | LeetCode 413 | Coders Camp
hODRAHL4sE0
Hua Hai The Kid Number 101 Title Se Is Account Number Kid Number 101 Title Se Is Account Number Accident Distic And The Problem Accident Distic And The Problem Description Yagya Ministerial Out In The Description Yagya Ministerial Out In The River Systems And Don't Stop This Problem River Systems And Don't Stop This Problem Virvar Problem Subscribe And Subscribe Virvar Problem Subscribe And Subscribe The Picture And Subscribe To Feed Subscribe Chhindwara To Middle One Playlist Voice In Which is the In Which is the In Which is the Longest River in Middle Age Subscribe Now to Longest River in Middle Age Subscribe Now to the Subscribe I have subscribed this problem do the Subscribe I have subscribed this problem do do do do do do do do do and tell that police character of birth to order unique love letter to president on this page for all [Music] [Music] Kar do Kar do ki Vivek Disayla Distributor Test ki Vivek Disayla Distributor Test Deposit All put all the best All characters Deposit All put all the best All characters set ki Nagaur ki past The individual string of words past The individual string of words is on Music] Music] Ajay ko Ajay ko do Ajay ko ab to Considered Considered Considered 120 During 120 During A Balance Merchant Request To Apology A Balance Merchant Request To Apology Letter Gifts And Checking Point In Letter Gifts And Checking Point In Different Forms And Avatars Subscribe Different Forms And Avatars Subscribe This Video Not 9th This Video Not 9th A Consistent Latest Updates Not True A Consistent Latest Updates Not True Any1 Preventing Ka Answer To Answer Wisdom This Any1 Preventing Ka Answer To Answer Wisdom This Point Of View Account Subscribe Not Point Of View Account Subscribe Not Attend A Meeting On Attend A Meeting On So one more thing later come Neetu Saturday So one more thing later come Neetu Saturday Nunihal which Bigg Boss gift banister gifting fruit and all the best wishes for these string first method then return pressure yourself now first method then return pressure yourself now dish notification come and that his nature irritable loot that his nature irritable loot [Music] 202 Aadat Sudhar Top This Problem To Like Positive Pass Turn On The 55572 Printer To The Amazing 2.1 President Mirwaiz More
2024-03-20 12:13:16
1,684
https://i.ytimg.com/vi_w…0/sddefault.webp
Leetcode Problem - 1684 | Java | Solution Explanation
LLqBECCOBCQ
Loot hello everyone welcome to my channel today is the last day of miding challenge and is the last day of miding challenge and problems but search to sleep very famous problems but search to sleep very famous problem in the interview problem given problem in the interview problem given alms from all must be constructed from subscribe alms from all must be constructed from subscribe and subscribe to and subscribe to that beer given a list of birds like and that beer given a list of birds like and and and and Channel and subscribe the world will be lit and tried to explain in detail to your show Lakshmi increase font size or your show Lakshmi increase font size or fennel birds fennel birds laugh so much laugh so much that the show let's pick one word like to veg dishes that the show let's pick one word like to veg dishes from dictionary word from dictionary The Channel subscribe The The Channel subscribe The The Channel subscribe The Channel and subscribe the Video then Channel and subscribe the Video then [Music] [Music] subscribe to A Similar ES Look for Being A This Weekend Seervi Seervi Chief York City Video [ Music] Subscribe Now We Are the subscribe for More videos Study and Nurses and You Will Give To To To [Music] [Music] That And Start Processing Word Character That And Start Processing Word Character Director And Look For Director Retired Director And Look For Director Retired And Old Effective Work And You Will Then Its And Old Effective Work And You Will Then Its Existence After Birth And Always Existence After Birth And Always Till Twelve Thursday Subscribe To The Page Loot And Similarly Another For You Which Will Go From 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 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 Problem Solve Thursday Family English to a small Family English to a small Family English to a small character morning user of 600 person node character morning user of 600 person node was the state champion use the 6 characters of was the state champion use the 6 characters of but that but that try note sadswini report in this try note sadswini report in this explanation powder I will form with what we will do explanation powder I will form with what we will do subscribe from roof but subscribe from roof but nothing is the receiver Thursday subscribe and nothing is the receiver Thursday subscribe and after subscribe the world will creative world subscribe the world will creative world only cases will result in the reel only cases will result in the reel that encounter set an other is the prohibition of the same is that encounter set an other is the prohibition of the same is simrely are taking I am so this one simrely are taking I am so this one try try 200 what we can live with considerable 200 what we can live with considerable Tribes End Will Start From The Body And Tribes End Will Start From The Body And Look For The Character First Character And Call Bhi Dad Check Weather It's Not End Of The And Call Bhi Dad Check Weather It's Not End Of The World In Your Cities End Of The World Will World In Your Cities End Of The World Will Update You Are Not No Witch Will Start From Update You Are Not No Witch Will Start From Drut The Current Month Drut The Current Month Witch Witch Witch 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 subscribe from all over the country in subscribe from all over the country in That Young Bullet Bike That Young Bullet Bike United States North End Speed ​​Because United States North End Speed ​​Because Minute You Subscribe Mode Of Are Of Minute You Subscribe Mode Of Are Of Midnight Children That Children Which Is Midnight Children That Children Which Is New Line Mode Of New Line Mode Of Sciences String Cheese Word Okay So No Need To Build Right Method Sciences String Cheese Word Okay So No Need To Build Right Method And Will Return Subscribe Will Describe The Calling All Will subscribe appointed nodal key and will Will subscribe appointed nodal key and will Will subscribe appointed nodal key and will scan from all the words 100w scan from all the words 100w in words and create account one way current in words and create account one way current track point to the root of the world in more track point to the root of the world in more in all the w and in all the w and have oh have oh if ever met attract all the character and if ever met attract all the character and reduce subscribe share reduce subscribe share reduce subscribe share Who Is Not Not Updated On Who Is Not Not Updated On This Video Channel Bellini Slice The This Video Channel Bellini Slice The Current Dot Children Of Ideal To New Current Dot Children Of Ideal To New Note Note In Hindi Will Update Our Current Next In Hindi Will Update Our Current Next David Question You Can Not Familiar With The David Question You Can Not Familiar With The Dare Devil Children Dare Devil Children That You In1 Switch Debit That You In1 Switch Debit That You In1 Switch Debit updater and current wave in Indian villages in the subscribe to that subscribe to that encounter dad be lit the board inter encounter dad be lit the board inter result 2018 youtu.be hai android plus plus and after that again 10 board of zero 10 board of zero 10 board of zero different method like share and subscribe and which excess dry fruit fruit and private type subscribe this Hair private type subscribe this Hair that in tie in DJ and within that rose against that in tie in DJ and within that rose against British rule in the list of British rule in the list of strings paints strings paints side member Martin side member Martin side member Martin first pick subscribe star channel subscribe 9 subscribe star channel subscribe 9 that all will change it's there is already children 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 Equal To Know Which Mins Of Wave The Equal To Know Which Mins Of Wave The Equal To Know Which Mins Of Wave The 15-minute Bieber And Swift We Will 15-minute Bieber And Swift We Will Update Blocked Vikas Vihar The Pirates Rubaru Thoughts Children Update Blocked Vikas Vihar The Pirates Rubaru Thoughts Children Of - Withdrawal David Results And No To Do Do Do Do Do Do Do Do Meghwal subscribe in this Meghwal subscribe in this Meghwal subscribe in this great content on website board 921 great content on website board 921 subscribe And subscribe The Amazing side subscribe And subscribe The Amazing side 220f clean board IJ - 1m and roots oil 220f clean board IJ - 1m and roots oil result result that similar when check this is loaded on that similar when check this is loaded on board land minus one which will call the board land minus one which will call the download note members download note members download note members 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 Of logic Of logic Of logic plus one guava result picture volume plus one guava result picture volume is all the phone calls and direction call me will is all the phone calls and direction call me will be stretched be ours and in impatient be stretched be ours and in impatient tractors pe this is the back track sedan tractors pe this is the back track sedan app solutions app solutions member jhawar courier member jhawar courier hai so let's scum pilot 133 compile and expected result 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 Dictionary But Number Of Columns Of Power Grid Is So For Every Word Chief Guest Calling In Directions on this will v40 power Directions on this will v40 power Directions on this will v40 power everyone along in the voice of falling for everyone along in the voice of falling for every bird Video plz subscribe to subscribe and subscribe the Channel Please subscribe and subscribe the Bechain Se Id Total Length Of The World In More The The The Like Button and subscribe To My Channel for Like Button and subscribe To My Channel for The Upcoming July Series Jewelers Lootkand Contest The Upcoming July Series Jewelers Lootkand Contest Problem Idea Share My Problem Idea Share My Videos A
2024-03-22 10:31:48
212
https://i.ytimg.com/vi/L…CQ/sddefault.jpg
word search ii | word search 2 | word search ii leetcode | leetcode 212 | hard
w_XdjlJf0eI
hey everyone today we are going to serve the little question fast missing and the little question fast missing and positive positive and you are given unsorted integer array and you are given unsorted integer array numbers return the smallest missing numbers return the smallest missing positive integer positive integer you must Implement algorithm that runs you must Implement algorithm that runs in o and a time and I use constant extra in o and a time and I use constant extra space so let's see the example so you space so let's see the example so you are given one to zero output E3 because are given one to zero output E3 because the number in the range one twos are all the number in the range one twos are all in the array so we have to return the in the array so we have to return the like the smallest missing positive like the smallest missing positive integer so that means um integer so that means um we always start our Target is always we always start our Target is always start from one so start from one so um but uh we can find the one in in um but uh we can find the one in in delay so next we find the two delay so next we find the two so that's why output is 3 in this case so that's why output is 3 in this case and example two um and example two um you are given like three four minus one you are given like three four minus one and one and the output is two because uh and one and the output is two because uh so the target one is uh here and then so the target one is uh here and then next we need to find the two next we need to find the two but we have like three and four so but we have like three and four so that's why output is 2 in this case that's why output is 2 in this case before I start my explanation so let me before I start my explanation so let me introduce my channel so I create a lot introduce my channel so I create a lot of videos to prepare for technical of videos to prepare for technical interviews I explain all the details of interviews I explain all the details of all questions in the video and you can all questions in the video and you can get a code from GitHub for free so get a code from GitHub for free so please subscribe my channel hit the like please subscribe my channel hit the like button or leave a comment thank you for button or leave a comment thank you for your support your support okay so let me explain with this example okay so let me explain with this example three four minus one and one three four minus one and one and so description set we have to solve and so description set we have to solve this question with like a linear time this question with like a linear time and a constant space but I think I it's and a constant space but I think I it's good good um it's good for you to share your like um it's good for you to share your like a multiple idea and to the interviewer a multiple idea and to the interviewer in their interview so and then explain in their interview so and then explain why you choose that solution why you choose that solution so so um that's why uh let me start with like um that's why uh let me start with like a a um like a analog and solution um like a analog and solution and so to solve this question first of and so to solve this question first of all we have to find the all we have to find the um like a positive number so we don't um like a positive number so we don't need a like a negative number so first need a like a negative number so first step is remove the step is remove the negative numbers so in this case only -1 negative numbers so in this case only -1 so so in the case in the case input array should be 3 4 input array should be 3 4 1 right 1 right and then and then next next we will sort this input array with we will sort this input array with ascending order like a ascending order like a 1 1 3 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 we will have found we have found the smallest missing positive 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 get into the cold okay so let's let's go first of all 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 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 yeah so let me submit it yeah so let me submit it yeah looks good and the time complexity yeah looks good and the time complexity of this solution should be uh order of of this solution should be uh order of analog n because we sorted the input analog n because we sorted the input array and the space complexity is a o1 array and the space complexity is a o1 or on or on um it depends on language um it depends on language because of sorting here because of sorting here yeah next so I'll explain how to solve yeah next so I'll explain how to solve this equation with linear time and the this equation with linear time and the constant time constant time okay so let me explain with this example okay so let me explain with this example so to solve this question with a linear so to solve this question with a linear order I use the three Loops in the first order I use the three Loops in the first loop I remove the value which are less loop I remove the value which are less 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 so after I finish the first Loop so I will get will get 3 4 3 4 1. 1. right right easy easy and then in the second loop I use each and then in the second loop I use each value as a index number so value as a index number so we uh first of all we find the three so we uh first of all we find the three so index number is like a three minus one index number is like a three minus one and which is two so look at the index and which is two so look at the index two and then we find one and if two and then we find one and if this value is greater than zero in the this value is greater than zero in the case convert the positive integer to case convert the positive integer to negative integer so which is a minus one negative integer so which is a minus one in this case in this case and then move next and then move next rewind the four rewind the four four minus one and three so look at four minus one and three so look at index three but that is out of bounds so index three but that is out of bounds so we don't do anything we don't do anything and then move next and then move next and now um actually uh index 2 is not and now um actually uh index 2 is not one actually minus one so how can we get one actually minus one so how can we get uh um index number from minus one so uh um index number from minus one so it's simple uh combat minus one to like it's simple uh combat minus one to like absolute value so in that case uh absolute value so in that case uh absolute value is one right so one so absolute value is one right so one so absolute value minus one is one uh zero absolute value minus one is one uh zero right one minus one zero and look at the right one minus one zero and look at the index 0 and the three is a uh greater index 0 and the three is a uh greater than zero so in that case uh convert than zero so in that case uh convert three to minus three three to minus three then finish so in that case four is a 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 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 and then if we finish the third group in and then if we finish the third group in that case um that case um the smallest positive number should be the smallest positive number should be uh length of input array plus one right uh length of input array plus one right episode just return length of input episode just return length of input array Plus 1. array Plus 1. yeah that's it let me submitted yeah that's it let me submitted yeah looks good but uh yeah this is our yeah looks good but uh yeah this is our own solution own solution um but uh um but uh um I can throw us on the previous one um I can throw us on the previous one like a login version like a login version um I think that's because I think uh um I think that's because I think uh um I try many times um I try many times I hope but definitely uh this is a Time I hope but definitely uh this is a Time complete this solution is like a on complete this solution is like a on solution we just Loops three loops solution we just Loops three loops right this is a fast loop and a second right this is a fast loop and a second Loop and the third group Loop and the third group so yeah time complexity of distortion so yeah time complexity of distortion should be order open and then space should be order open and then space complexity is a one because we don't use complexity is a one because we don't use external data structure just uh uh use external data structure just uh uh use the input input array the input input array yeah so that's why uh space complexity yeah so that's why uh space complexity is o1 is o1 yeah so that's all I have for you today yeah so that's all I have for you today if you like it please subscribe the if you like it please subscribe the channel hit the like button or leave a channel hit the like button or leave a comment I'll see you in the next comment I'll see you in the next question
2024-03-20 09:14:07
41
https://i.ytimg.com/vi_w…xresdefault.webp
First Missing Positive - LeetCode #41 with Python, JavaScript, Java and C++
hAjX129vbRU
what's up youtube today we're going to take a look at legal problem number 1393 take a look at legal problem number 1393 capital gain capital gain loss marked as medium let's get into it loss marked as medium let's get into it now this problem is for all my wall now this problem is for all my wall street badge fanatics that like the street badge fanatics that like the stocks stocks because it's about the stock markets because it's about the stock markets it's also recently being asked by it's also recently being asked by robin hood even though there are some robin hood even though there are some controversies around robin hood right controversies around robin hood right now now anyways we have a table called stocks anyways we have a table called stocks which contains which contains stock name operation which is an enum stock name operation which is an enum that can that can either be buy or sell we have an either be buy or sell we have an operation day operation day and we have a price that this stock has and we have a price that this stock has been been sold or bought for our tasks to write an sold or bought for our tasks to write an sql credit to report sql credit to report the capital gain or loss for each stock the capital gain or loss for each stock capital gain or loss of a stock is a capital gain or loss of a stock is a total gain or loss after buying and total gain or loss after buying and selling the stock selling the stock one or many times turn the result table one or many times turn the result table in any order in any order the query style format should look as the query style format should look as follows we have a stock name and we have follows we have a stock name and we have capital gain loss in here capital gain loss in here which tells us the entire which tells us the entire balance so to say of what balance so to say of what stays after buying and selling that stays after buying and selling that stock so let's go through an example stock so let's go through an example lead code circles bought lead code circles bought at day one for one thousand dollars and at day one for one thousand dollars and was sold at day five for nine thousand was sold at day five for nine thousand dollars dollars capital gain would be nine thousand capital gain would be nine thousand minus one thousand minus one thousand summing up to eight thousand dollars summing up to eight thousand dollars let's take a look at the rows in the let's take a look at the rows in the stocks table we have here we have elite stocks table we have here we have elite code by operation code by operation for 1000 and then a sale operation for 9 for 1000 and then a sale operation for 9 000. so it seems like we just subtract 000. so it seems like we just subtract by from cell in this case we only have by from cell in this case we only have two entries if we would have multiples two entries if we would have multiples would have to make them calculation would have to make them calculation multiple times for example for corona multiple times for example for corona masks we have masks we have six entries in here buy sell buy sell six entries in here buy sell buy sell buy sell it seems like we always have a buy sell it seems like we always have a sale operation for a buy operation so sale operation for a buy operation so these are always complete these are always complete and in the end there are no stocks being and in the end there are no stocks being held anymore held anymore but let's just get into coming up with a but let's just get into coming up with a solution so since our result table solution so since our result table format should contain stock name we're format should contain stock name we're just going to select just going to select that from our stocks table and then we want to take care of this capital gain loss so let's see how we come up with that given the example we just went through we pretty much want to subtract by operation from cell operation and we have a field called operation there that can either be buy or sell we don't have separate columns for that which is a bit annoying and we need to work around that so let's do that so what happens what i usually think of when i have that kind of problem having a certain value being price but that being dependent on a value in another field being operation so i want to do something with the price value depending on the operation value so i'm going to use if here you could also use case when then and another sql dialect or in mysql as well but if it's a bit shorter so this if statement it's going to check for the value of operation and if that operation is buy it's going to be yeah by operation and we add that value to our sum of board stocks so if that condition is true we want to take price and if it's not true we're gonna take zero since that means it's a cell operation i'm also going to do the same for cell so let's put them in separate rows for now just to show you what i'm doing it's gonna become clearer in a bit but let's just call that by will be called cell and i'm going to will be called cell and i'm going to check for cell okay so let's run that to see what it gives us we have lead code in here 1000 as buy and 0 for cell we also have it in here as 0 by and 9 000 cell so that works the way it's supposed to now why did if we use sum on this if we use sum on this operation we will get operation we will get total sum of all stocks being bought and sold so let's do that for buying and selling for buying and selling and call them total buy and total sell and call them total buy and total sell see what that gives us so now we should see what that gives us so now we should only get only get one value per stock if we one value per stock if we group by stock so let's group by stock group by stock so let's group by stock name just forgot to do that and we should get the entire amount of price we we paid to sell and buy these stocks so we bought lead code four thousand sold for nine thousand bought coronal masks stocks worth 2010 and sold them for 11 510 and we bought handbags for 30k and sold it for 7k so now we just need to subtract that again to get the entire capital gain loss because if we take the entire sum of what we got for our stocks which will be the total cell column in here and then subtract what we bought these for we should be left with what we have in the end and the amount of money we made or lost so let's just remove the comma here and the names we came up with for these and we said we're going to subtract buy from cell so let's put cell in front i copied that and we'll paste it here after the minus and then we're going to capital gain loss sorry running that should be an accepted output it is and if we submit that it should also be an accepted solution and that's pretty much it for that problem it's just about handling these buy and sell operation by using if and that is a common pattern you have in many lead code programs there are some about purchases in a certain month so you're going to check the date for being in may and then if that is the case you're going to take the price and otherwise zero so this pattern of having an if and either taking the value of zero is something you should understand and probably apply to other problems as well and it's one of these tools that allow you to solve these types of questions where you have a certain value that decides what you're going to do with another value and that's it for that problem as i said if you want to study some more check out my playlist only called easy medium and hard problems i have on youtube so i have one playlist for each difficulty and videos on problems in there and also make sure to subscribe if you want to see more of these videos and be notified when new ones come out aiming for three videos a week by the way and hope i'll see you on one of these coming
2024-03-21 01:02:41
1,393
https://i.ytimg.com/vi_w…xresdefault.webp
LeetCode 1393: Capital Gain/Loss [SQL]
SnInnZjrOXY
guys today's problem is search search insert position insert position and um and um this is simple search this is simple search question searching question where question searching question where we have an integer array we have an integer array it is uh it is uh sorted sorted so so from um from um from one to six it is um given in sorted from one to six it is um given in sorted array a sorted manner and array a sorted manner and we have one target variable and we need we have one target variable and we need to return to return its its position position right where can we right where can we insert it in this sorted array insert it in this sorted array and and we need to write this algorithm in big o we need to write this algorithm in big o of of log n runtime complexity log n runtime complexity so so this is simple this is simple question of binary search algorithm question of binary search algorithm and binary search is one of the and binary search is one of the algorithm which you should know by heart algorithm which you should know by heart and and it is very helpful it is very helpful in many cases in many cases we'll use binary search algorithm we'll use binary search algorithm and for the binary search algorithm the and for the binary search algorithm the question can be asked in question can be asked in multiple ways multiple ways so this is very helpful algorithm and so this is very helpful algorithm and yeah and yeah and [Music] [Music] whenever we use binary search algorithm whenever we use binary search algorithm the runtime complexity will be b of log 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 we might find five so this is possible uh and 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 okay okay so let's start it so let's start it uh uh so in the binary search so in the binary search we we always uh divide our input in half always uh divide our input in half so that's why we will have one integer so that's why we will have one integer called called then then we will have left we will have left is equal to the starting of the array is equal to the starting of the array and we'll have a right which will be the and we'll have a right which will be the end of 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 algorithm until algorithm until uh uh left and right mids left and right mids okay okay so so let's let's initialize mid initialize mid so for that we need to find the so for that we need to find the the the mid element of the the the mid element of the array so the idea is 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 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 that's the gist of algorithm so first let's find the mid algorithm so first let's find the mid element element which is left plus which is left plus right 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 eight minus five eight minus five divided by divided by two 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 as integer it will take is 1 and the mid will be 6. uh so 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 [Music] then we can return then we can return mid target target is less than numbers of is less than numbers of [Music] [Music] mid mid then then we will just change our right mid minus one mid minus one right pointer to mid minus one right pointer to mid minus one um um [Music] [Music] and else left is equal to mid [Music] one otherwise we will increment our left pointer outside the while loop outside the while loop will return will return left left [Music] [Music] let's try let's try running it running it [Music] okay so it not expected a yeah okay let's try submitting it yeah okay let's try submitting it okay okay so so this is simple binary search algorithm this is simple binary search algorithm there are many other algorithms but i there are many other algorithms but i think this is the famous one think this is the famous one that's that's it for today's that's that's it for today's video video if you have any questions comments if you have any questions comments please put it in the comments if you please put it in the comments if you have better solution or better way to do have better solution or better way to do it let me know
2024-03-20 08:54:55
35
https://i.ytimg.com/vi/S…axresdefault.jpg
LeetCode #35 Search Insert Position - Coding Interview Problem with Java Solution | Binary Search
GUCJOpFS3h4
hey there today we'll solve one of the problem it could merge sorted in problem it could merge sorted in so which means that uh two sorted array so which means that uh two sorted array will be given in the input and the will be given in the input and the number of elements in the number of elements in the array is also given array is also given and the first array will have and the first array will have extra space so that the one will merge extra space so that the one will merge it it now the second area elements now the second area elements can also be tested inside the same can also be tested inside the same okay okay so so the num one the first array length will the num one the first array length will be equal to m plus m be equal to m plus m now to solve that uh there are multiple now to solve that uh there are multiple approaches which you can do uh but i'll approaches which you can do uh but i'll uh today i'll be using a two pointer uh today i'll be using a two pointer approach approach um so 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 now um the sorted elements needs to be now um the sorted elements needs to be uh inserted inside nums one p1 is greater than equal to zero and p1 is greater than equal to zero and nums one nums one p1 p1 equal to if the elements is equal equal to if the elements is equal greater than greater than nums to nums to p2 else what will do so in case if it is the higher than in numbers of index minus minus nums one nums one p1 minus lines so i'm inserting from the p1 minus lines so i'm inserting from the last last and uh and uh in other case i'll in other case i'll just use just use nums nums to to secondary element and the second point secondary element and the second point so every time so every time this is greater uh from the end uh i'll this is greater uh from the end uh i'll insert insert from this array first from this array first and otherwise i'll insert from the array and otherwise i'll insert from the array two two to this index okay to this index okay and i'm decrementing it so from in to and i'm decrementing it so from in to first it will be inserted one by one first it will be inserted one by one um so let's see if this solves the 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 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
2024-03-20 12:50:48
88
https://i.ytimg.com/vi_w…xresdefault.webp
Merge Sorted Array | Leetcode 88 solution in Java