id
int64
1
2k
content
stringlengths
272
88.9k
title
stringlengths
3
77
title_slug
stringlengths
3
79
question_content
stringlengths
230
5k
question_hints
stringclasses
695 values
tag
stringclasses
618 values
level
stringclasses
3 values
similar_question_ids
stringclasses
822 values
76
it has been asked by Facebook Tik Tok Amazon lyt Google yendex Snapchat nagaro Adobe Airbnb LinkedIn Microsoft Apple Spotify Uber we can have let's quickly see what the problem says the problem is simply short and simple saying that we have two strings s and D of length M and N okay respectively uh just one thing in the future code you will see that I represent my string n with length M and string t with the length M there's just a small change here so just remember that and return the minimum Windows substring of s return the again substring is a part of a string window is nothing but same saying okay it's a substring of s such that every character in t including duplicates which means if in T I have duplicate characters let's say a b c a is coming duplicate a is coming twice so in the window of s which I will take my a should also come in twice so okay and including the duplicates is included in the window and again in that window portion which I have I can have a B I can have other characters also d c it's just that in the window all the characters of D should come in that window of s that's the only condition and all such Windows okay all such possible windows I have to minimize the length of that window and return that specific window which means return that minimum length window having all characters of T in that specific window now just says that there will not be any two windows having same so basically cases which are generated the answer is always unique which means there cannot be two windows where the window length is minimum but you have two different strings that's not required that's not uh given and also if it was given that it would have specifically mentioned that you can return any window but yeah uh for example for in this case you will see that this is one of the window in which you have corrector a corrector B Cor C and this is my condition which means all the correctors again duplicates also it should be inside my back window so right now the length is six but I have to minimize my length so I will try to find some other window so some other window is this specific window again I have a b a and c a b c order doesn't matter I just only want to have all these characters inside it now this length is four so okay I can minimize my length this is the minimum length and just return that specific minimum length window that is B A and C is the answer now uh first very basic boot Force approach which comes in our mind is AR and I have to try on for all the possible substrings and in that okay which means we will try on as you can see a substring is okay you will try on for this string then this which means you are trying on for all the possible substrings now number of substrings in a string of length n again remember I said that my string s is of length n and string T is of length M just a small change uh so for sure to just figure out all the possible substrings I will have o of like n Square substrings so o of n Square will for short com in picture now when I have figured out a specific substring now I will have to check if all the characters of p is actually lying inside my that substring or not so one very naive way for this specific check to just check okay all the characters of my t is lying inside my that window that string which I have formed because I know I have n square substrings but yeah one to just have a check okay that specific substring that specific one subring is actually good for me or not and it will be good only when the characters of T is lying all characters of T is lying inside that substring so very na check will be I'll just go on and check okay if that character of T is inside my window or Not That C of is inside my window or not and all that stuff so for sure I will have to iterate on my entire for every of my sub strings so that will be o of n sare into M but you have so far thought of I why have to you go on to every character again and again for T just make sure that you keep track of all the characters of T in a hash map because you know that you have only English alphabets so you will have only 26 characters so now for that specific window just make sure the just make sure that okay you have just 26 characters frequency so just make sure that all these characters which are here for t for T should lie inside that specific substring so I can just simply rather than iterating again and again on the entire string T I can keep track of the count of frequency of the characters of T and then use those characters so I will reduce that to just over 26 time rather thaning on all the characters again and again for the entire and I just for one subring I just have to iterate on the 26 CEST to know what's the Frequency inside my T and would not have to go on the entire T again and again so that can reduce our time a bit but still it is still high it is still o of n squ so right now we have see okay from o of n square into M then o of n square is the complexity which we have seen so far but um why you were finding all the substrings but if you remember that okay you just have to find a substring with the minimum length so if you have found a substring then why can't you expand or drink that substring why you have to go and try to find the subing again and again now again the main two hints in this problem is that you have to go and find a window you have to minimize or maximize that specific window length window and subing both are same window length which means if I have found a specific length then it's good no I will just try to minimize this length that's it so that is where our sliding window comes in picture when you know okay you have a window then you have to just maximize and minimize that window again in sliding window also there are two approaches that the window will either keep on shifting again the window will always keep on shifting but the window will either will only and only expand and that's it window will only expand but they can be Cas Okay window will extend and then expand like as in string expand shing string so there are two variations in which only the shrinking will take place like the size will never ever decrease like much Beyond it or never increase much Beyond it and okay in other case it can be increasing decreasing increasing anyway we'll see uh what and how something can be useful but right now we just know one thing okay if we have again if you don't know that how window and all that work no worries hold on we'll just see everything so let's see if we have seen again R what does this window mean all that stuff I'm new to it no worries uh even if you're you are new and you want to practice just go and watch this arraying playlist in this we have two pointers window very deep questions very deep now let's say you have a window in you will just have to make sure you have to expand that window or Shrink the window again there's a simple rule that if your window is not good for sure try for a bigger window if your window let's say if you want to S outside let's say if you have a home and if you want to take outside if your window is small your main purpose is sneaking outside if your window is small then you will try to expand that window so that you can sneak outside right your main purpose is sneaking outside you expand the window what if the window has become large but okay that's taking a lot of space but you want to minimize the window length so you'll try to shrink it that you will try to shrink it only up to the point that still you can peek outside that's it so I'll do the same thing right now I can not peek outside when I like when I say peek outside I mean okay I have a and b now A and B C is still missing so I should expand my window size so I just simply expand my window size but AR it will keep on expanding no as soon as it will go up till c now I have got all the correctors okay so when I've got all the correctors this is one of my good possible window now when you have got a good possible window just try to shrink the window and see if it is still good or not so I'll just shrink the window now oh as soon as I shrink it became bad now if something becomes bad oh so okay again try expanding it in the future try expanding and so on and so forth so this is the entire concept of sliding window now just remember two points for sliding window that again that's a standard ad hog template for you to always Implement sliding window like this it will be very busy else you will be like me okay just worried okay where the point is going all that stuff just remember these two points that you will have your I and J is moving always ahead at every step my J will move j will move at every step that's it no matter what my J will move at every step J will never stop which is the endp pointer and when I have got a correct window size then which means it matches the condition again the window size logic if the window is correct or not it will depend from question to question right but depending upon if the window is right now correct this I to J window is right now correct then just try shrinking the window and see that if you can minimize the length or not so if the current window it matches with the condition whatever condition can be in this case the condition is to T then you just try keep shrinking your window now shrinking again shrinking only happens J Will for short move as I told you earlier also J will for sure move and it will move at every step but I move when I have a correct window and I want just okay minimize the length now uh we will see that how it will actually happen now the condition okay for J to move at every step it is as simple as that you will have a simple Pointer while J is less than n and simply J will keep on moving at every step no matter what so this is a simple template for J but what about the condition so for the condition it is simple that right now you are at I andj you have this specific window this is was this was your team now I said that if the current window satisfies the condition now the condition is condition to T so the condition right now is that the I toj window size all the characters of T should be inside that window size should be inside that window now to implement this specific logic to implement this condition only we have three possible options again in the beginning we saw two variations of Brute Force itself now for the optimal which means for the sliding window again we have three possible options one is a very naive way that okay you have a window I2 J and you want to know if all the characters again we had seen so far is that we will just keep a track of all the characters of T in a hash map of size 26 which will keep try of all the characters of T so that I don't have to on T again and again I just only itate on my window right now so one naive way to check if all the 26 characters frequencies is corresponding to that window of from I to J is one n way simply trade from I to J and check if all the characters frequencies of T is lying inside my i2j window size so it will take a o of n time because I to J is kind of a string s of length n and space will be o one because of no extra space you are using You're simply trading and the hashmap which you had already made of T you can simply decrease its frequency and find if it becomes zero for all the characters of T then I am good now you can see it taking o of end time and that is for every window now window as in okay J was keep on moving so I know one thing for sure J will keep on moving J will for sure keep on moving so o of n will for sure come in picture and then I will also move so o of 2 into n will be my pointer movements and for every pointer movement I am saying I will take o of n time so it's still L of n Square that's bad now the next smart way is that you have to just know again you have known that the frequency of all the characters int right now you just have to make sure if all these characters are lying inside your I to J that's it so which means ultimately you're also concerned about what are the frequency of characters in the window I toj so when I ask you in the smallest possible time you have to know the frequency of characters basically you have to know the summation in a range of characters of the frequency of characters like frequency okay is it's nothing but the summation of how many times it is occurring if you want to know that simply use a prefix sum so what I will do is I will use the prefix sum to know that I to J what is the frequency of all the characters now if you had not known how we do a prefix sum for these characters so let's say if I have a b c d and e let's say a b c a A and B so I will just keep track of the prefix sum will say a equal to 1 here it will say AAL to 1 b equal to 1 AAL 1 b = will say AAL to 1 b equal to 1 AAL 1 b = will say AAL to 1 b equal to 1 AAL 1 b = 1 Cal 1 a = 2 b = 1 c = 1 a = 2 b = b = 1 Cal 1 a = 2 b = 1 c = 1 a = 2 b = b = 1 Cal 1 a = 2 b = 1 c = 1 a = 2 b = b = 2 Cal 1 now if I ask you what is this specific range frequency so you can just subtract this from this so you will get a = 1 b = 1 from this so you will get a = 1 b = 1 from this so you will get a = 1 b = 1 and Cal to 1 this is a frequency in this range so you sol saw that you just keep track of the 26 characters and length was n so now you know that the time required will be a o of one operation to know a window to know all the characters in that window and when you have got all the Cs in that window then you just have 26 size on which you have to iterate so time will be o of 26 after you have made this which means the precomputation which you will do will take o of n 26 time this is a pre competition which you will do or you can say of end time that's it uh after this pre competition is done then you can simply go and find any window frequency any window cus frequencies and for sure you can see the space required will be n is for this entire length and 26 is for 26 is in the worst possible case so that seems okay that for sure work again this approach will for sure work in this problem because it's a easy the time required is less but we can still optimize the space I don't think we require the space how we know that again now to optimize this space it's actually a bit tricky part how that other ways rather than making the entire new making that because see right now this space is required because I am keeping track of the frequency of s which means all the characters in a range for S I'm trying to find now I'm saying my only concern was if my T if my character like frequency of characters of T is inside my S or not that's it so rather than making s why can't I simply use my T itself which means I can simply decrease or increase the frequency of characters and T so as to manage my window size so what I thought of okay I can simply use the map basically the map of 2 which I made for t i can simply use that map or the frequency of 26 characters of my te which I have made and I simply use that itself to know if my window is right now correct or not and this is actually a tricky thing to optimize the space in this particular problem but many people just directly jump onto it without even knowing that the most intuitive approach is using the perix sum to know the frequency or basically to know the count again in a context if I would have been there I would have used this specific approach but it's more intuitive but still we can optimize the space and we'll only use the T frequency which we have made and thus we will again do it in o one time same was here itself but here you will see again you will see that here the time will be exactly over one like it will not be over 26 like for every step and space will be just as you can see the T the temp so the t uh map which you have made the map for T frequency map which you have made that space is the only space required no space of 26 required and that's how you can simply solve it now this is actually a tricky part now let's see that how we will solve it via actually using the map of T So as we saw that for a specific string T we will simply make the map of him it is T map so I have written my t- map it is not temp it is a written my t- map it is not temp it is a written my t- map it is not temp it is a t- map so this is a t- map which I have t- map so this is a t- map which I have t- map so this is a t- map which I have made now A B C I just keep track of the frequency of those characters as I wanted from the very beginning I will for sure have taken that but now I'm saying I only use this I'll only use this T map to actually trade on and find the window if it is correct or not so for sure in a specific window how you move on okay you have your IJ in the very beginning make sure remember two steps J will always keep on moving I will only move when you have got the correct window now the correct window is all the characters of T should be in that window now uh I seems nice ni um so one thing is for sure to know if I have got all the characters in the window how will I make sure because okay if you are saying that I will use this specific map so for sure as I will as I'm standing on this specific character so I said okay I'll use this character when I say I use the character so what modifications I should do in my existing map because I have I know right now that all the modifications I have to do this existing map only so I'll do all the modifications here itself so one operation I can think of very like naively is I am at a this was my existing map I have to somehow make sure that I have taken my a this is the existing map so I simply reduce the frequency of a one 1 a taken then I'll simply move on but as you have seen that 1 a is taken oh 1 a is taken now how will you make sure if all the characters of T are taken so one thing you can also make sure is keep track of the initial count of characters in your t as soon as you take any character which was inside your T then you can decrease its frequency or decrease its count okay right now the remaining characters which I have not taken in my window are two this represents that and because as you can see a is taken so a is right now in my window remaining characters which are not taken in my window right now are two and this will help us make sure is if I have if in the current window if I have taken all the elements of t or not because as soon as my count becomes zero I have taken all the elements of character I have taken all the characters of T in my window I to J and then I can simply start shrinking my window okay let's see as you can see my J moved forward again simply decrease again the operation is still same but simply decrease the frequency but R and B is not even there no worries at all D is not there simply decrease the frequency d isus one so if I decrease the frequency so shall I decrease the count also n why not because you know that you because you know your D is not even there now AR that is okay D is not even there but how will I figure out if my D was here or not because you just told that okay as soon as you encounter your nums of J simply go in the map and decrease the frequency okay you decrease the frequency but then you also said that okay nums of a when the frequency was decreased but then you also decrease the count how will you make sure that some decreasing which you doing right now is from your like from your T string or not as simple as that how I'll tell you because if you have these T if you have the characters of T by default all of them were actually positive which means more than zero their count by default would have been more than zero so if some count is more than zero which means it was from my string T if it is less than zero or if it is zero or less than zero because T you can see was Zero T's frequency sorry D's frequency was zero so it was not even there in my map so I can just make sure when I'm about or when I'm about to decrease something when I'm about to decrease a frequency if the frequency is positive which means it is for sure from my string T if it is zero H simply decrease it because it is not from my string T so that's how I simply decrease the frequency of D now it became minus one but my count never decreased okay cool no worries move ahead now I am at o again decrease the frequency of O count will still remain same because it is not inside my string T now again increase the frequency again move the I sorry move the J because see you will keep on moving J at every step as you saw J will keep on moving at every step no matter what now uh B oh B I try to decrease the frequency but before decreasing frequency I can see it its frequency is positive which means it was inside my string T so I'll just decrease the count now my count will become a one I'll simply decrease the frequency of b will actually decrease and will become a zero and does I'll simply keep on going so right now you have seen that the standard template was while your J is less than n simply keep on increasing your J but I saw that as I'm currently at the GTH index I will firstly check if my t map of that s of j s ofj was B your this character was a b the T map gives me the frequency of that character at the J index if that is positive which means it is lying inside my string T if it is please simply decrease the count as you can see simply decrease the count now when you have decrease the count no matter what you have done this or not simply for that s ofj in the T map decrease the frequency so as you can see the this will happen no matter what for B for a for d for o for everything it will happen but this thing will only happen when my frequency is more than zero represents that it is inside my string T and what makes this question hard rather than other sliding window problem is this specific optimization of only and only using your this specific T map okay and simply this for a step one operation which means simply keep on moving your J forward always now with the stand template we have seen so far okay simply go on moving your T moving your J okay J will move e was not there simply e frequency again minus one now J again moved so C Okay C is there frequency was one so simply firstly decrease the count becomes a zero decrease the frequency of c frequency will become a zero and then J should move ahead but ah now do you see one thing it's simple that your count has become a zero H that is the case which means you know that this specific window has all the characters of your team this window has all the characters of your team now if that is a case voila great man great um just one thing that firstly put your answer right now my answer is this window of size six again right now my answer was Infinity I have to minimize my window length so I put the answer as six but if your answer would have six just simply minimize the answer okay Infinity by default now it became a six now uh as we saw if the window a condition matches then try to shrink the window so what I will do is I'll now when I like when I say Shing I'll just simply keep on moving my eye now when I say I'll keep on moving my eye I'll simply say that whatsoever eye you have let's say eye you have is here now simply move your eye ahead but as you're moving your eye you have to make sure one thing uh where is this gone as you move your you have to make sure one thing that if I is going so which means I this character should come back to life so a is coming back to life now I simply increase the frequency of K A because it is coming back to life a is coming back to life so as I was moving onto character I was decreasing frequency so if something is coming back I'll increase the frequency now the same thing comes in picture if I if you increase the frequency if it becomes positive which means it is for sure because of it was a line inside your string T and thus if something if the after bringing back to life which means after increasing the frequency of that character a if it becomes positive it was because of it was in this inside my string T and thus please increase the count also now the count becomes one which means now your window is not correct now window is not correct so simply again now keep on moving forward so now we have seen that as soon as we Tred to shrink again we know that we know the condition has matched so first I have to minimize my length so I just make sure I'm just minimizing my answer I just I'm just minimizing my answer now when that specific thing is done my minimization of answer and stuff is done so one thing is for sure that I will now increase try to increase my eye now when I say I will increase my eye I just simply keep on doing it while my window is valid and how is the valid condition window valid is only when the count is zero while my window is valid if my current window length if it is less than my minimum length current window length it is less than my minimum length then simply update the minimum length with the new minimum length and also if you make sure that RM y have taken minimum start because in the answer if you go back if I just show you in the answer you have to return um where is the gone in the answer you have just in the answer yeah in the answer you have to return a b n c which means a string to find the string you need to have the index of the string and the length of the string for to access the actual string which is the substring from the main string you have to know the index and the actual length so one thing we have seen so far is that we will actually make sure that we need both minimum start and the minimum length but if you had been following so far you must have seen a small catch Aran one thing while like you said that if you are at pointer J you will firstly check the pointer J and like as you mentioned before only you will decrease the frequency from s of J and then you will increase the pointer so and you said your J will always increase so your J would have already been increased and this was your I by default in the beginning so for sure your window length will be J minus I only and Not Jus I + 1 so one thing is your Not Jus I + 1 so one thing is your Not Jus I + 1 so one thing is your window length currently is J minus I because your J has moved one step ahead already so that's your window length is J minus I and the same way here window L is J minus I because your J will for sure move ahead one step but as soon as it has moved now it will give a chance to I bro now you will try moving okay the implementation as in the actual implementation will which means the utilization of the specific J movement will be seen in the next step next V Loop but it just says okay my J has moved next step and then again as you can see also your J moves but as soon as the next while loop comes in picture its impact will be seen it's impact will be seen but right now the J has been moved also if you want what you can do is put the condition here itself and move your J in the very end of the code that is one way to do it then you can actually use the same logic of J Min I +1 just make sure that of J Min I +1 just make sure that of J Min I +1 just make sure that pointer think that where you are placing your J I usually make sure thatth where is this gone I usually make sure that if I'm placing my piece of code of checking that window correct logic I usually if I place here then either my J is in the end or I place it after this specific condition if you placing after it which means your J has already moved ahead but the good practice is you can place it here also that's completely simple that's completely easy that's completely okay now as you can see um I'll simply move on my specific because of the window which I have moved on shring my I actually minimize my window length and the same way goes that as you have shring the window which means the S of I tmap frequency will increase if the frequency increase becomes actually more than zero which means it is positive so simply increase the count also and also increase the ey pointer but this V Loop will only keep on going until unless your count is zero as soon as your count becomes more than zero sorry bro um you have got the incorrect window length thus you can simply keep on going forward now if you remember uh you will simply keep moving your J now as soon as your you moved your J okay your o frequency will decrease o frequency will become minus two then simply again the count is still a one uh your you will increase your J again the d will come in picture D frequency will increase to minus 2 like decrease again uh then e will come in picture minus 2 then again B will come in picture okay it will become a one sorry it will become a minus one because B is coming picture no if something is coming in picture it was a zero if something's coming in picture simply do a minus one as simple as that again the count will not decrease because the B by default frequency was not positive then okay I'll simply keep on going on my a was actually a one now I will actually decrease it my actually frequency will decrease it oh if it decreased which means for sure my count should also become zero now bro count becomes a zero if count become a zero then this is my specific window right so I'll just say my window will be Jus I + 1 by default again I'll show you Jus I + 1 by default again I'll show you Jus I + 1 by default again I'll show you both the codes how this Vari like VAR like Vari but if you increase your J right now then you will you can see that the window length is J minus I but yeah if you don't increase the window length right now like J right now so you can say okay in the next Val loop I increase my J now your window length is Jus I + 1 my J now your window length is Jus I + 1 my J now your window length is Jus I + 1 and thus you can simply say that 1 2 3 4 5 6 7 8 9 10 but my by default length was six so it will not be minimized so length will still remain same but now I have opportunity to shrink my window so I'll just simply increase so D frequency will increase become a minus one o frequency will increase become a minus one again move on I keep on moving ey B frequency will increase it will become a zero H again it has not become positive so you can never increase your count okay again um move your i e now it's a e uh decrease the frequency increase the frequency become a one minus one again I C you have got a c ah simply you have got a C increase the frequency now it has become positive simply increase the account also because this is the new window which is valid after this as soon as you will move after as soon as you will move you are done so here right now I have got a window length which is actually valid so 1 2 3 4 5 6 which is already same length so rather I should try minimizing the window length because it was a valid it's a valid window right it's a valid window so I just try to minimize the window length which means I'll go here as soon as I go here which means you saw that I tried to decrease the frequency of C it has become like frequency sorry it has I moved I has moved so for sure my frequency of C will increase count will also increase now kind my count has no longer remain zero so this is no longer a valid window length now if something is no longer valid window L simply keep on increasing your J okay n frequency will become minus one uh n frequency will become minus one now again move on J C frequency will become a zero count will become a zero this is a valid window length now okay I was here so uh increase the frequency of O it will become a zero then D it will become a zero then uh e it will become a zero then B it will become a one it has it now again it has become a one which means now okay now it is actually valid again still it is so far it is valid I'll first try to minimize my length which is j- I + 1 so minimize my length which is j- I + 1 so minimize my length which is j- I + 1 so now my length will become a four again length will become a four now okay when I have minimized my length only then I will update as you have remembered first I'll try to minimize my length only then I will update my temp frequency and stuff so after I have checked off for my length minimize the length only then update it which means it will become a one now count will become a one so now it is no longer valid now simply keep on moving your J forward okay J forward and thus you can simply get the answer cool now uh it's exactly simple as that the code here um I will just show you a quick modification in the code that rather than um again like first I'll show you exact implementation of everything which you have seen so far is as you saw that first we'll keep track of the T map is T is the strin T and the frequency of that is the T map for us now I will have few variables I and J counter is the count which I have taken if you ever remembered by default the counter was the string length right I have those many number of characters for my string uh T minimum start and minimum length is for the final string final most optimal smallest window length I need to have a start for it and the length for it to actually find the substring for it and thus my n is nothing but I have to iterate on my J up till the nend so the simple Loop will while my J is less than n and I'll simply as I explained above also I'll simply try if my frequency of j s of J is more than zero which means this character this s of J is inside my T string T So decrease the frequency decrease the count and also um decrease it everything this everything you will understand by the snippet of code which I have shown you above this entire block I have showed you one at one place this entire block I have showed you at one place which means this is minimizing this is getting a minimum length and then as you move on your eye please revert back all the operations which you have done now the only thing which I was saying is that right now it is J minus I because your J has already moved one step but I also do like that if I put I if I put my J in the Super End which means right now your J will be at that specific Place only then what you can do is your current length will be j- I + 1 is your current length will be j- I + 1 is your current length will be j- I + 1 and the same way it will be J - I + 1 and the same way it will be J - I + 1 and the same way it will be J - I + 1 and that's the only change which you have to do and th if you try to submit it will still work because it was exactly same now coming on back uh this was the portion where you move your J at every step as going to see J at every step because you have already moved your J so it's the reason I have put a j minus I but if you just put your J afterwards which means your J will move only in the end then you can just simply have a check minimize your length and then update move shrink your eye as you have shrinked your eye ultimately in the final answer you will have minimum start and minimum length as the same okay it is a starting length of the window having a minimum size and that is a minimum length for that window this will give me a subst strring if the minimum length is infinity so there is no substring simply an empty string and that's how you can simply Solve IT of n plus M time is to Simply make this specific hash map and N time is to iterate on this entire string of length n okay it's actually a 2 into n because your I and J pointer will move one step I can also in wor case move one step so it is a 2 into n plus M and for sure space is just over 26 this is the most optimal solution which you can have see goodbye take care bye-bye again I specifically went on to bye-bye again I specifically went on to bye-bye again I specifically went on to these all five approaches to actually specify that what all you can tell in an interview cool byebye take care
Minimum Window Substring
minimum-window-substring
Given two strings `s` and `t` of lengths `m` and `n` respectively, return _the **minimum window**_ **_substring_** _of_ `s` _such that every character in_ `t` _(**including duplicates**) is included in the window_. If there is no such substring, return _the empty string_ `" "`. The testcases will be generated such that the answer is **unique**. **Example 1:** **Input:** s = "ADOBECODEBANC ", t = "ABC " **Output:** "BANC " **Explanation:** The minimum window substring "BANC " includes 'A', 'B', and 'C' from string t. **Example 2:** **Input:** s = "a ", t = "a " **Output:** "a " **Explanation:** The entire string s is the minimum window. **Example 3:** **Input:** s = "a ", t = "aa " **Output:** " " **Explanation:** Both 'a's from t must be included in the window. Since the largest window of s only has one 'a', return empty string. **Constraints:** * `m == s.length` * `n == t.length` * `1 <= m, n <= 105` * `s` and `t` consist of uppercase and lowercase English letters. **Follow up:** Could you find an algorithm that runs in `O(m + n)` time?
Use two pointers to create a window of letters in S, which would have all the characters from T. Since you have to find the minimum window in S which has all the characters from T, you need to expand and contract the window using the two pointers and keep checking the window for all the characters. This approach is also called Sliding Window Approach. L ------------------------ R , Suppose this is the window that contains all characters of T         L----------------- R , this is the contracted window. We found a smaller window that still contains all the characters in T When the window is no longer valid, start expanding again using the right pointer.
Hash Table,String,Sliding Window
Hard
30,209,239,567,632,727
1,844
all right let's talk about replace all digits with characters so the idea is that you shift how many times after c so for example fight five times after a you get f and then there's a constraint it's guaranteed let your shift never exist z so the maximum for a is 25 a plus 25 is 26 right but for this is simple a right a plus one is b and then c and d e and f right basically you are taking the previous character plus one but the number could be different like two three four right you just have to worry about your tongue your constraint because for this character you don't have number and then you end up just by itself then we need a stream builder to build okay let's just start looping now i can just do it like this make it easier and no matter what right i have to append a pen see okay so i have to check the character if the character is less than equal to 9 or n sorry n c square equal to 0 which is which should be one right okay one you can say zero but zero doesn't work the minimum number is one right should be one and we have to make sure i mean choosing case the previous character is quite a good view right so index if i'm here i have to make sure this is this index is valid so let's just say new character neutral is equal to uh stock chart at i minus one but since this is the taking the previous character plus the number right and then the number will be c right it's the choice c right c minus zero right we don't want the zero technically so for the ascii value you subtract the subtract 48 and then this since this is char right we just have to cast a chart that will be your answer and you need to append a pin neutral so when we append b right we don't want to append a again because c equal to a right so we continue right so id is pretty much it so i just have to return string for the string builder and check if i have arrow cool all right let's talk about what happened so there's a case for zero right and then we have to worry about zero now checking again cool okay let's talk about timing space for the space is all the fun why because you are storing every single character into the string and for time it's all of them right you're looping every single character inside the screen and a little bit so time and space are all the fun
Replace All Digits with Characters
maximum-number-of-balls-in-a-box
You are given a **0-indexed** string `s` that has lowercase English letters in its **even** indices and digits in its **odd** indices. There is a function `shift(c, x)`, where `c` is a character and `x` is a digit, that returns the `xth` character after `c`. * For example, `shift('a', 5) = 'f'` and `shift('x', 0) = 'x'`. For every **odd** index `i`, you want to replace the digit `s[i]` with `shift(s[i-1], s[i])`. Return `s` _after replacing all digits. It is **guaranteed** that_ `shift(s[i-1], s[i])` _will never exceed_ `'z'`. **Example 1:** **Input:** s = "a1c1e1 " **Output:** "abcdef " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('c',1) = 'd' - s\[5\] -> shift('e',1) = 'f' **Example 2:** **Input:** s = "a1b2c3d4e " **Output:** "abbdcfdhe " **Explanation:** The digits are replaced as follows: - s\[1\] -> shift('a',1) = 'b' - s\[3\] -> shift('b',2) = 'd' - s\[5\] -> shift('c',3) = 'f' - s\[7\] -> shift('d',4) = 'h' **Constraints:** * `1 <= s.length <= 100` * `s` consists only of lowercase English letters and digits. * `shift(s[i-1], s[i]) <= 'z'` for all **odd** indices `i`.
Note that both lowLimit and highLimit are of small constraints so you can iterate on all nubmer between them You can simulate the boxes by counting for each box the number of balls with digit sum equal to that box number
Hash Table,Math,Counting
Easy
null
1,470
hi guys let's talk about a google interview question today the question is lead code 147 or shuffle the array uh it goes something like this given that a number consisting of two n elements in the form x 1 x 2 x 3 until x n y 1 y 2 y 3 so on until y n you have to return the array in the form x 1 y 1 x 2 y 2 x 3 y 3 and so on until x and y n okay so it's a lead code easy problem but it becomes pretty hard to solve if someone asks you to solve it in one space and o in time complexity like it's easy to solve in on space but one space is pretty hard and in a google interview you will be expected to solve it in o in space basically shuffle this array in place so let's look at the input constraints are like n is less than equal to 500 and length of basically n is the half of the size of the array because length of array is 2n and num psi is greater than equal to one less than equal to thousand okay so basically uh all the numbers in the array are positive a pretty important constraint which will help you develop a solution of open space okay and here's our test case as well like nums is two five one three four seven n is three which is half of the size of array and output is two three five four one seven anyways like uh you can solve it in o in space by creating a new array and just copying the elements in the order specified in that new array very easy but let's see how to do it in one space so like i have taken example here original is one two three four five six shuffled array will be one four two five three six okay and here i am denoting the mapping as well of the numbers from their old position to the current position uh basically sorry from the current position to the new position basically the position in the original error and the position the shuffled array okay like blue color is denoting all the numbers uh in the first half of the array and red color is denoting all the numbers in the second half of their basically all the numbers whose index current index is greater than n and blue color current index less than n okay so this mapping actually helps you to visualize and uh like the position of the array in the original and position of the numbers in the original and shuffled array and it also helps you determine a formula to come up with a formula for the uh for the new positions of the elements okay and let's see what that formula is so i have here in violet color i have written the indices of the like the current indices of the elements in the original array and any n as i said is the half of the size of array so the new positions in the shuffled array will be something like this like if current position is less than a new position will be twice of current position else new position equals twice of current position minus n plus one okay and you can also see this formula is correct like uh for two the current position is one its new position will be uh twice of current position which is two and you can see here in the blue color two is here which is at index two and similarly for five like its current position is four is obviously greater than n which is 3 okay so its new position will be twice of 4 minus 3 that is 1 so 2 into 1 plus 1 that is 3 and you can see here in the red color that 5's new position is 3 and this formula also holds for the elements at the first and last position i mean their position remains same in the original and shuffled array like for one uh its new position will be twice of zero which is zero only and for six its new position will be twice of five minus three which is two into two 4 plus 1 5 okay uh now what would be our algorithm so algorithm would be something like this that uh what we will try to do is go in cycles in for each index like what we will do let's take an example for the number two which is at index one i determine the new position of two using this formula it comes out to be two only okay i will replace the number at the index two with the number at position index one basically this two so what i would do instead of placing two here i would place minus two here okay and why i'm placing minus two is because i want to mark that i have actually visited this element and like since i cannot use an extra array for marking that i have visited that particular element i will mark the visited as by keeping that number as a negative number okay and since i already told you in the constraints we are given that all the numbers are positive so that negative will not basically uh but you can say basically destroy our array okay so what i would like i have replaced two with this and then i would similarly determine the position new position for the number which was at index 2 and replaced that number with this particular number at index 2 and i will keep on doing that until i come to a position which was already visited okay in case you did not understand this uh let's actually try to simulate this scenario okay so here i am like my current number is two current position is one uh which is here i determine the new position which is n is as i told you three new position will be twice of uh twice of one which is two and the new number that is the number at new position is three okay so what i would do i would replace this number so here i am i replace the number at index two with minus two okay and i then i swap current and current number and current position with new number and new position so my current number has now become three current position has become two i determine the new position for this which is twice of two which is four and at index four the number is five which is our new number so again i will swap uh basically what i would do is that i would replace the number at index 4 with -3 4 with -3 4 with -3 so that's what i have done here i replaced this with minus 3 now and swapped new number and current number and new position current number is 5 current position is 4 so new position will now become 3 because like 4 is greater than 3 we'll use this formula so it comes out to be 3 the number at index 3 is 4 which is our new number so now what i would do is i would replace the number at index 3 with minus 5 so that's what i did i replace this number with minus 5 and swap new number current number new position current position now our current number is 4 current position is 3 we determine the new position again 3 is not less than n so we did use this formula to determine new position which comes out to be 1 and number at current sorry new position is 2 so now i would replace the number at index 1 with -4 so as you can see here index 1 with -4 so as you can see here index 1 with -4 so as you can see here that's what i did here i've denoted these negative numbers with violet color and as now our current number becomes two current position becomes one i determine the new position which comes out to be two okay so i would replace the number at index 2 with minus 2 so i did that okay and after doing that what would happen is our current number will now become minus 2 and current position is 2 so now since current number has become minus 2 it means that we have already visited this we do not need to you know go further in our cycle here we can stop this our cycle here and we will keep on doing that for each position like this i have only done for one like if you remember here we started with the number at position one but we will do this for each we will repeat do this cyclic thing for each position like for two three four and five okay so this way you can clearly see that we have basically not used any extra space and this will also make sure that we you know transform our original error into the shuffled array now the thing is like what is its time complexity so the time complexity is order n and let me tell you why is that so that is because this visited thing like we are replacing every number with the negative of that number so that makes sure that every index will be visited at most twice okay once uh like it would be visited once when we encounter basically when we are replacing that number that particular index and then there might be a scenario that we might come back to that index again in our cycle but at that moment we'll break out because you know uh we are using this negative as a visited flag so this thing make sure that all the indices are visited at most twice only so we will at most do like two end traversals and sorry to win iterations so uh and let me show you one more thing like this we have done only for the index one then we go to index two so at index two we see that the number is already negative so we do not do anything here current number is already negative we go to index three again current number is already negative minus five we go to an index four current number already negative minus three then at five like uh last this is the last number so last number will remain at its own position and we finally break out of this loop so you can clearly see that this visited flag took care of not repeating our iterations and you can also see that this uh like after doing this what we will do is that we iterate over the array once more we will replace all the numbers with negative numbers with positive value of that particular number and uh finally we will get our original shuffled array basically our expected shuffled array which is one four two five three six and if you remember this was the answer as well one four two five three six so let's look at the code for it uh so here is the code which i had written like this is the api we had to implement and i what i am going to do is that for each index i will try to you know do that cyclic process so that's why i'm iterating here from i equal to 0 to length of the array and initialize current number as num psi current position is i and we only basically do you know iterations in this while loop until this current number is positive until this current number is greater than zero and we figure out the new position based on current position and this is that particular formula and then what we do is that we would replace the number at new position with the negative of the current number and we will then swap the current number and current position with the new number and new position okay and we'll keep on doing that and eventually when uh after this for loop we iterate over the array again and if we see that num size less than zero we replace it with the positive value of that uh number and eventually we return the num array so time complexity o n space complexity oven we have solved a google hard interview question good to move to second round thank you guys for watching please do not forget to like subscribe and comment on this video i'll see you all next time
Shuffle the Array
tweet-counts-per-frequency
Given the array `nums` consisting of `2n` elements in the form `[x1,x2,...,xn,y1,y2,...,yn]`. _Return the array in the form_ `[x1,y1,x2,y2,...,xn,yn]`. **Example 1:** **Input:** nums = \[2,5,1,3,4,7\], n = 3 **Output:** \[2,3,5,4,1,7\] **Explanation:** Since x1\=2, x2\=5, x3\=1, y1\=3, y2\=4, y3\=7 then the answer is \[2,3,5,4,1,7\]. **Example 2:** **Input:** nums = \[1,2,3,4,4,3,2,1\], n = 4 **Output:** \[1,4,2,3,3,2,4,1\] **Example 3:** **Input:** nums = \[1,1,2,2\], n = 2 **Output:** \[1,2,1,2\] **Constraints:** * `1 <= n <= 500` * `nums.length == 2n` * `1 <= nums[i] <= 10^3`
null
Hash Table,Binary Search,Design,Sorting,Ordered Set
Medium
null
489
hey everyone and welcome to another Elite code problem so today we're going to be doing problem number 489 robot room cleaner and it's a backtracking problem it's a hard one it's probably one of the hardest backtracking problems I've done um even if you know like backtracking there's a lot of annoying parts of this problem for sure so I would encourage you if you are learning backtracking it is on the backtracking explore part I would encourage you to try this one for sure um just to test your you know understanding of backtracking and the hard thing about this problem is I'll just tell you is so you have this robot in a grid and you don't know you're not given access to the grid the only thing you're given access to is a couple functions for the robot so you're given a move function that will return true if the robot can make a valid move and then you can turn the robot left and right and it starts off facing up and so yeah the annoying thing is like you don't see the grid you don't really know where the robot is and it's hard to visualize if what your algorithm is doing is correct also the other annoying thing about this backtracking um is like let's say you're in some cell draw a grid here so let's just draw a simple grid three by three grid with no obstacles and let's say here's our robot so Circle it's going to be facing up so The Annoying Thing is how to figure out well how do I actually backtrack like let's say I call move and the robot moves up here it's still so whenever you move you're still facing the same direction but how do I actually backtrack like what's my backtracking algorithm like if I return it's still going to be in the wrong grid so what so how do I even do this and so what you're going to want to do is you can visualize I mean when you go somewhere your end State needs to be your robot needs to turn around right so it needs to face this way and then you need to call move and then you can handle backtrack in one of two ways so you can either move back and then return and then like turn it around in the function right before you return or you could handle it in the actual backtrack function so let's say you just call backtrack right you call backtrack with some you know you move and then you call backtrack then what you can actually do is once the function before returns like let's say this function you can call backtrack the robot's over here and then it's looking the way you want it to let's say for the ending state maybe you want it to look like this I don't know there's a bunch of ways to do it then what you would have to do is well what would you have to do to make this state turn into this state right and this is our original state and to fully complete our backtracking so in this case we'd have to turn left or right twice so we'll just say turn left twice so we can just call that function then we have to go move and then we can turn left again twice so hopefully that makes sense when you have this robot you turn it around so a 180 degree rotation would be left or right twice then you'd call move then it would go here and then you'd turn around again and then that would give you the original state of the robot before it entered this so this is how you would get out now the other annoying thing for so for most backtracking problems well it actually depends but let's say you do have some backtracking algorithm and let's say you're backtracking algorithm just so let's say you try the cell in front of you and then if it doesn't work you just keep turning right and you keep turning right well let's see what would happen so we can't go here so we're gonna turn right okay and we're remember when we go into a cell we Face the same direction that we came in we can't go here we turn right it's going down okay we can go here okay we can't go down here so we turn right okay can't go down here so we turn right here then go here okay well now we can't go here we go here so how do you how do we even know and then we end up here how do we even know we ended like we don't have a grid remember and in this case it worked out but in other cases uh you can try out some other examples but some other examples when you do this when you just keep turning right here so in this case you did end up where you started but in a lot of cases you'll just run into like a loop and how do you even know and then you just hit maximum recursion depth right because you keep looping but you don't even know that you cleaned every room and you can't check that you cleaned every room you don't know how big the grid is you're not giving access to any of that information all you can do is move the robot and so how would we solve that problem and to solve that problem this is also kind of really annoying actually what we're going to do is we're gonna have a visited set and you may ask well how do you have a visited set if you don't even have an index of like where you're starting and so what we actually need to do that makes this problem difficult is you have a visited set and then you need to figure out what index what at least what relative index you're at and so let me show you what that looks like so let's say we let's call this index 0 right so we just say inertial index is zero so we put zero in here and now by the way when we Traverse we're gonna only Traverse if our if the place we're traversing isn't in our visited set because we don't need to visit the same room twice also for this backtracking that makes it different from some other ones like a Sudoku is even if you like once you're on a path and you go to a bunch of rooms when you backtrack to where you started you never have to go back to any of those rooms again because we of we've already cleaned them and we've already went as far as we could from any of those rooms so once we have visited set and we add items we're never going to remove them in a normal backtracking you normally do remove and you kind of check for a Final Solution type of thing you know like for end Queens you would go down all the rows and you have to see is there a final solution and you can you keep removing Queens from the set but in this case once you were in a room once you never have to clean it again because as soon as you go into room we can just hit clean and then it's clean so let's say we're here so what we're actually going to use is we're going to use um to actually use this for a lot of DFS so we're actually going to have an array like this of directions and we're gonna so normally when I have this array of rays for different directions I have like one zero one negative one zero and so on but here the mistake we need to not make is we need to make sure that so we're going to be turning right a lot and now we need to figure out what are the values that you need to go up and then if you turn right we're gonna try to make sure that the value to the right of the current one we're at is the right thing so to go up actually it would be this we are going up a row now if we're going up and we turn right now what is okay now what is this is column plus one and so this is another tricky thing is you have to make sure you arrange these in the right order and for this problem so this is going to be 0 1 okay now down if we go right so down is one zero and then so yeah if you do a normal like stuff they use for other functions you're going to get an error so now we were down now we need to go right or sorry left right so down if we turn right from down it's a left and left is actually 0 minus one and so this is what it's going to look like and all we're going to do when we turn right is we're just going to say let's just go to the next Direction let's go to the next Direction and when we reach the last one we can simply just go back to the first one so let's see what kind of that looks like so we're at zero now we know we're going up so if we're going up that means our row is minus one right so then that would be negative one is zero and so this index I might cut out for a second so this index is going to be negative one zero now we tried to go up we can't we go right so then what is right going to be well right it's going to be negative 1 and so on so you're gonna have these relative indices instead of absolute indices so even though you don't know how big the grid is you have to know which way you're facing and where you started and from there you can figure out what relative index you're at and so we're going to keep adding to our visited set until we can't go anymore and then we are going to like I said when we're facing some Direction so it's going to look like this is what a backtracking would look like for just one particular square right so if we have a square let's say we came from here so we came from here we're in the Square let's say we can't go anywhere so we try to go here can't we turn right try to go here can't and because we can't because it's visited then we turn right again and then we try to go here and we can't and then we turn right I'm gonna double check the code but our ending State wants to be like this so in our after we tried everywhere we want to be here yeah so actually first we don't turn right so we turn right four times total so we try here we can't try here can't and then we turn right one last time until we turn right four times total and if we turn right we make 360 degree and then once we're actually going down here then we simply to go back like I said we turn right twice so then we turn around and we go this way we hit move so then we're back in this cell and then we simply turn right two more times either and you can do this either in either method as long as you do it because even once you're back in the original method you can actually hit move and if it's like an invalid location as soon as you've act as um as long as you've cleaned all the cells it doesn't really matter like if you try to move and you recurse back to the original method it'll be fine okay so let's take a look at the code and we'll explain that so I actually didn't want to code this up on the Fly because there are definitely I would there's yeah there's not a lot of code but there's a ton of Errors you can make here okay and so like I said they said these are the directions so this is representative of up then we have right and we have down then we have left oops and we have a visited set and then we have this backtrack function so first thing we do when we get into a room is we clean the room right so as soon as it doesn't hurt us to clean the room so we might as well do that then we add that room to our visited set and then here's our Loop where we try every single Direction and so to get a new Direction our initial direction is going to be up which is going to be this thing right here and so to get a new direction we're just going to have an i and a range four and then we are going to do Direction plus I mod 4. and what that does is it starts with zero right so the original direction would be this then it'll add this then a lot of this but let's say our Direction our original direction is three maybe so we're on this one then if we add one and mod it by four it'll actually loop back to the beginning of the list so let's make sure we're not out of bounds and then we just loop back to the beginning of the list then recalculate a new row and a new column based on the direction we're at and the current row and column we're in and then remember so this is also another thing you can screw up when you do this check to make sure that your row and column isn't in your visited set and this robot move make sure that you check that the row and column isn't in the visited set before you do this robot move because if you do the robot move now you're going to be in another square and then you're not gonna like this stuff isn't gonna line up so you have to make sure it's a valid place to go before you even try to go there otherwise yeah like even if you can't go there it'll be fine but if you can go there and it is in your business that's going to screw your code okay so now we backtrack to the new uh Direction and new row column then remember when we backtrack this is when we're recursed out so in my code I made it do this 180 right after you leave the back trap Loop you can do this in a bunch of different ways and then we turn right so we turn right four times as I said so really what's going to happen is this is going to be when we return from a square right so let's say we were in this top square we went down right then we returned from a square well the way my code works is when we're returned we're actually going to return facing the other way and so when we return we just need to 180 around to be in the original state we were in before we backtracked and so that's what that does so turn right we check remember we check the next place we can go to and then this is simply what we do before we backtrack out so when we and like I said I could have done I'm pretty sure if I wrote this code uh in here this would have worked too I don't want to test it actually I can do it I can try to test it so let's just see let's say we backtrack out and we literally do it right here instead what happens it might work maybe there's some other thing that I need to think of but okay so it actually does work so that's another way you can backtrack out is so now what I did instead of my original thing is I have something like this and so let's say I'm here and now I would be actually see here so I moved I turned around twice and then I move yeah okay so I believe that the final state is like this of the cell that I backtrack to so what I need to do is I need to turn it around right then I need to move back and then I need to turn it around again and that would make it the same state here so like I said you can put this code in multiple different places but basically yeah you have to make sure you handle this and turn right to Nursery you know you want to turn right as many times as you turn left so the gears on the robot you know don't get rusty you don't want to keep turning right only okay so anyway so yeah so you go back and then this is the initial function call and I just made it pass with one zero because and so what I would encourage you to do by the way if you're getting a lot of Errors is maybe um one thing that helped me is this grid is really big so you can just make a custom grid and you can even try something like this you know where you have a custom grid and this is the custom grid I used where every cell doesn't have anything and then I just made all of these ones one meaning it doesn't have a uh it doesn't have brick so it needs to be cleaned and then I made my starting location this and then I would try to draw out the states of the robot on my grid and then also print like the visited set and where it was in and make sure it matched because that's how you catch a lot of your areas that's what saved me a lot of time for sure um so and then you can also do that by if you don't know in this new lead code version what you can actually do is you can go to test case you can add a test case and so you can say like if you know what it looks like so something like this you can add that in copy that so this would be a three by three array if you wanted to and then you could say yeah like start at you know one and maybe print my visited Saturn row column or whatever it is when you have errors because like if you think about it there's no really way to test for this what makes it really annoying and difficult is there's no really way to test your code like when you have a bug it'll just say all the rooms weren't cleaned and you don't really know where the robot was or where it went because you have no access to the grid so it's a real pain to try to debug it unless you actually draw at the grid yourself and try to follow like is the robot facing the right way is it going in the right order by checking where the visited set is and where the column is and so on and so I do think this is a great problem for backtracking it definitely does get annoying with you have to do a lot of israelization and figure out what things have to look like with limited information so okay so let's do the time in space complexity and actually the time and space complexity for this prom are pretty good compared to a normal backtracking algorithm normally they're very inefficient and so here because we're never actually removing from the visited set we're not visiting a cell more than twice so we are only visiting cells that are ones and not uh so let's say zero is a brick we're only visiting cells that are one so it'd be something like count ones mine or just be count ones right so if we have whatever many empty cells we only visit them one time we do have to technically go back actually but I think that is not going to add complexity so that's fine okay and as far as the space so what did we do for space so we do have a we do have um this visited set right and so this visited set is going to have every single so this is kind of the same thing it's going to have every single room we visited but we can only visit rooms with cat ones so that's just going to be big of count ones and yeah like I said if we clean a room and we backtrack uh I think that should be constant time to backtrack back or yeah it's actually going to be no it's actually gonna be like Big O of so we do actually have to visit a room and we backtrack back so let's say we go something like this is our path and we have to backtrack back how much does that cost like our maximum call stack does get to like the number of rooms we visited but we're basically just visiting a room and then coming back so it's going to be like Big O of 2N instead of n it's not going to add any more and then once we did visited these rooms and come back we can never go into any of these rooms that we visited ever again because we're never getting Rhythm and they've visited um in the visited set that's what would make things more expensive and that's why most backtracking operations are more expensive because you have to fill in let's say nine different you know problems and then you can have repeated work where you're here you can't once you've visited a room you're done okay so that's all for this problem and if you like the solution app please like And subscribe to the video it helps grow this Channel and I'll be posting more in the future so I'll see you in the next one
Robot Room Cleaner
kth-smallest-instructions
You are controlling a robot that is located somewhere in a room. The room is modeled as an `m x n` binary grid where `0` represents a wall and `1` represents an empty slot. The robot starts at an unknown location in the room that is guaranteed to be empty, and you do not have access to the grid, but you can move the robot using the given API `Robot`. You are tasked to use the robot to clean the entire room (i.e., clean every empty cell in the room). The robot with the four given APIs can move forward, turn left, or turn right. Each turn is `90` degrees. When the robot tries to move into a wall cell, its bumper sensor detects the obstacle, and it stays on the current cell. Design an algorithm to clean the entire room using the following APIs: interface Robot { // returns true if next cell is open and robot moves into the cell. // returns false if next cell is obstacle and robot stays on the current cell. boolean move(); // Robot will stay on the same cell after calling turnLeft/turnRight. // Each turn will be 90 degrees. void turnLeft(); void turnRight(); // Clean the current cell. void clean(); } **Note** that the initial direction of the robot will be facing up. You can assume all four edges of the grid are all surrounded by a wall. **Custom testing:** The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded ". In other words, you must control the robot using only the four mentioned APIs without knowing the room layout and the initial robot's position. **Example 1:** **Input:** room = \[\[1,1,1,1,1,0,1,1\],\[1,1,1,1,1,0,1,1\],\[1,0,1,1,1,1,1,1\],\[0,0,0,1,0,0,0,0\],\[1,1,1,1,1,1,1,1\]\], row = 1, col = 3 **Output:** Robot cleaned all rooms. **Explanation:** All grids in the room are marked by either 0 or 1. 0 means the cell is blocked, while 1 means the cell is accessible. The robot initially starts at the position of row=1, col=3. From the top left corner, its position is one row below and three columns right. **Example 2:** **Input:** room = \[\[1\]\], row = 0, col = 0 **Output:** Robot cleaned all rooms. **Constraints:** * `m == room.length` * `n == room[i].length` * `1 <= m <= 100` * `1 <= n <= 200` * `room[i][j]` is either `0` or `1`. * `0 <= row < m` * `0 <= col < n` * `room[row][col] == 1` * All the empty cells can be visited from the starting position.
There are nCr(row + column, row) possible instructions to reach (row, column). Try building the instructions one step at a time. How many instructions start with "H", and how does this compare with k?
Array,Math,Dynamic Programming,Combinatorics
Hard
null
62
cool 62 unique paths will bite it's located on the top left corner over m-by-n great the robot can only move m-by-n great the robot can only move m-by-n great the robot can only move either down or right at any point in time well by trying to reach the bottom right corner and the grid how many possible unique paths are there ok it's a little so actually I mean this is actually a very straight forward I want to say dynamic pole and well and it's not straight for in a sense that is you know you've come up with it's just very standard in the sense that it's a very possible textbook type album yeah like yeah my only concern and that's I'm missing something it's kind of like what happens if the number gets too big because easily with a man and it's a hundred that's not missing something yeah and that's I'm missing something like you could definitely over for long or and a lot very quickly and actually there's a halving the thing to notice here is that it's actually I mean once again this is a straightforward issue unquote dynamic programming problem which stems from I mean it's very textbook me in a sense once you kind of get it down but the other fun thing about this poem is that it's actually related to how you calculate binomials in a sense that just where I wish I could draw but you know binomial type things and I could we'll try to attempt some ASCII or so bear with me for a second but let's say you have a tough thing oh yeah so the binomial is X and so you have like the top layer and then you have to was a car like 1 plus X 2 man I don't remember my mathematical formulations to be honest but uh but yeah but on the next level it's huh it's 1 plus X and then I know the next level is 1 plus 2x plus x squared oops and so forth I mean you know their expansion for that kind of worries for me love it and you get this so that's kind of like I mean you could keep on drawing this is where is like you learn it in greats not one of the great schools or maybe high school I don't remember anymore and that's just like you know and actually tip yeah that's why I messed up so one in time and then just and then this obviously this corresponds to 1 plus X 2 is 0 this is 1 plus X to the first and then this is 1 plus X to the second and so forth right so then that's the kind of the pattern here and it turns out that this thing also is a way to kind of like it's I think they're called something like generating functions attire there's like a decade of math ago hey back to a follow him strike him trip em but yeah but that's the general thing here and that actually and you could and kind of a standard way to explain it is that and you could I forget what that parameters core I just finger was PI Gnomeo bread scouts tryingo that's what I'm thinking of way and this is a Pascal triangle thing where you know you could think about it as 1 and then 1 2 1 go say the same pattern you Center what I did before and where this node is just the sum of the two entries and you know in the world before and so forth way dot so this is Pascal's triangle which relates to this other thing that I guess I should have started with the Pascal triangle by just blank underneath but anyway so the fun thing about this is that this is if you kind of tilt the board a little bit or like you look at it in a diagonal way now you could see your entries are actually like 1 on the first world 1 in the first column and then 2 3 and so forth and then you told your head a little bit you could get like the diagnosis so this maps to these in the diagonals right I don't even know how George is on ASCII or despair but like diagonal for the first row and or first diagonal and so forth so those are your things right and also it the fun thing is that this is also the number of unique paths because you could look at you should know to be like okay how many ways do I get here well just one way to get to this cell and there's one way to get to this cell so there's two ways to get here and then how do I get to here well there's two ways to get to this cell and there's one way to get to this cell so that did doing ways to get to this cell and so forth and anyway so there's all these math things so anyway there's a very long explanation hopefully it's kind of interesting to you but it's a long way of saying that's how you would solve this problem in the same way and if we left a binomial and Pascal's triangle and all these other fun stuff but one more thing that I will leave you with this problem then is actually another kind of interesting thing is if we sum up the rows of in Pascal's triangle which is also diagonals so this is actually if you sum it up is two to the zero and if you sum this up is two to the one and you could see that easy and then here is two to the two and two to the third and so forth right and you could kind of make this proof the other way very quickly because for each entry in the previous world you're gonna for you to of those paths there'll be two paths outweigh so you always double the paths every time where so I said so on each row the sum is 2 to the K or whatever so that's kind of one interesting thing about it and that also goes back to there's another way to prove this but another way to kind of visualize it with binomials because we're binomial is another way to think about it's like this entry is also the number of ways to choose one given three elements choose one element way this is given three elements true zero do we animal choose to do a true story right and something so like so that's yeah so it's 3 to 0 3 choose 1 3 and then you see somewhere that should be 2 to the K because that's literally the number of possibilities you can have because that's just you know like the in our counting type thing way anyway so that's a very long-winded way of saying that's a very long-winded way of saying that's a very long-winded way of saying but the reason why I kind of brought this up and not just to flex or show off or whatever is that it's something that I think about when I see this form because when m and n will be at most 100 what that means is that so like you know just let's say this is 100 I mean I skip ahead a little bit so I gave this entry here so yeah I am and I forget I guess we should check with you and then like in the corner here is M plus n right and the thing here is that as we talked about before so this is a most going to be M Jews oh sorry M this is M plus and you know what is that well I guess I've always MPUs well that diagonal is ampersand and choose what know the sum of that one is oh I don't remember man I'm mixing myself up it's been a while but the point is that this is dominated by like the sum of that diagonal you will oh yeah oh wait no cuz okay I'm thinking of this tag so I was doing the math with this place where has to be between m and n there's some eggs but if you're doing like diagonal then M plus N is under on this diagonal which is yeah so it's M plus and choose notice M times n times choose M percent I don't know but the point is that this has a bound of like something like 2 to the M plus N and that was what concerned me when I saw that M plus n will be 100 because you got a really big number is my point so and looking up and down my other daughter about it is to see if they have any kind of strange to be like oh hey but it's ok because you know it's between a hundred oh sorry with the answers like the answer will fit in long or 64 bit or 32 bit and debate the other one too it is usually something that they would tell you but anyway so given that or set this is that's why this dynamic programming problem is a way straight for it dynamic program in this sense and then it's just about coating it up so I'm wearing do not yeah okay and there's a easy optimization that I'll talk about but I'm not gonna do yet I did last time so maybe I should do it mmm I've been trying to do it more okay I'll just do the obvious thing first center corner to do the one and then yes it doesn't actually I just found checking and now we just have to return no maybe it's off by one out sometimes I walk by one on these things good oh yeah oops would I get deep oh yeah let's try a real number for kicks oops we're in Python I think I don't have to kill but it's just in other languages a little weird that they don't specify especially in JavaScript for example see there's a very long number and I guess they don't have an expected result because it crashes on it that's why you need to specify your things watch I Mississippi case ok cool yeah so again this is very straightforward but that's how I kind of think about this problem and it these things are kind of fun to kind of think about because it comes up in random places as well oh yeah the other thing that I would say a very common thing is to refactor this is that well this is a dynamic program well obviously of M times n and with all of em times and space as well but the thing is you actually reduced this 200 of min of M or n by noticing that if you look at this away you actually you know which is this array here you essentially pretty much right so now 2 will always look at you know one and this one and so forth and some domed we will go get the 2 and the 1 and sum them and so forth and then now like we go all the way down and then now for some of 4 and 5 say well the thing is at the for you notice that you only add 2/3 the for you notice that you only add 2/3 the for you notice that you only add 2/3 under one way so actually in this entire well let me add some data tots in this entire world you only care about the results from the previous world right so this will only calculate itself in this flow so actually if you kind of take advantage of that you could actually just get rid of all these stuff well not get written I mean maybe get rid of it but you could you don't have to think you don't need that memory to stay around and that's you need to look up stuff for whatever reason in the future but yeah so you notice that then actually you only need to keep track of the last two rows or the current world and the previous well so you can actually do that in linear space as well because yeah it's like you know when this is done then you just keep track of the new one and so forth way anyway so that's good how you solve this was I would say for a dynamic programming problem this is way fun um this is a way one of they were more fundamental ones I should definitely get to get familiar with and I heard that Google was still asked a lot time before grandpa I actually went into Google for a long time but uh but that's what I've heard but you know the way interviews I feel like people have not been asking dynamic programming well so yeah maybe it's a but yeah we've want to go Google I guess you should study timing programming oh yeah that's why I have for this one
Unique Paths
unique-paths
There is a robot on an `m x n` grid. The robot is initially located at the **top-left corner** (i.e., `grid[0][0]`). The robot tries to move to the **bottom-right corner** (i.e., `grid[m - 1][n - 1]`). The robot can only move either down or right at any point in time. Given the two integers `m` and `n`, return _the number of possible unique paths that the robot can take to reach the bottom-right corner_. The test cases are generated so that the answer will be less than or equal to `2 * 109`. **Example 1:** **Input:** m = 3, n = 7 **Output:** 28 **Example 2:** **Input:** m = 3, n = 2 **Output:** 3 **Explanation:** From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down **Constraints:** * `1 <= m, n <= 100`
null
Math,Dynamic Programming,Combinatorics
Medium
63,64,174,2192
1,732
welcome to code map today we are going to discuss daily record challenge find the highest altitude now let's discuss the question there is a biker going on a road trip the road trip consists of n plus one points at different altitudes the biker status strip at point zero with Attitude equal to zero you are given an integer array gain of length n uh where gain I is the net gain in the altitude between point I Plus 1. where I is between 0 and M you have to return the highest altitude of a point let's understand it with a given example test case in this example this case we have given again array which is minus five one five zero minus seven another question it is given that the biker is starting with zero again so at the beginning gain is zero now when the backer will be at the point zero so it's its gain will be 0 minus 5 which is -5 which is minus 5 and here also we can say it is -5 say it is -5 say it is -5 now when the biker will be at point one this gain is 1 so it's so its current gain will be minus 5 plus 1. which is equal to minus 4. and here we can see that it is minus 4. now current we have current gain ah current gain current again as minus 4. now when the marker is when the vehicle will reach 0.2 when the vehicle will reach 0.2 when the vehicle will reach 0.2 0.2 which is 5. 0.2 which is 5. 0.2 which is 5. so current again will become minus 4 plus 5 which is equal to 1 and we can see that here it is 1. now when the biker will move at the point three the gain is 0 so 1 plus 0 equal to 1 so the current gain will be 1 and here we can see that it is one and when the biker will be at the point 4 his gain is -7 so the current gain 4 his gain is -7 so the current gain 4 his gain is -7 so the current gain will be 1 minus 7 which is equal to -6 -6 -6 and we can see that it is minus 6. now let's this is the code uh here I have taken a variable risk which will show the highest among all the altitudes and I have taken a current gain which will restore the current gain and I have run a loop to iterate through the gain array and I have calculated the current gain at every iteration and I have maximized the current again and my result is in the resultant address variable and I have returned that now let's submit this code now we can see that our code has successfully passed all the test cases thank you for watching
Find the Highest Altitude
minimum-one-bit-operations-to-make-integers-zero
There is a biker going on a road trip. The road trip consists of `n + 1` points at different altitudes. The biker starts his trip on point `0` with altitude equal `0`. You are given an integer array `gain` of length `n` where `gain[i]` is the **net gain in altitude** between points `i`​​​​​​ and `i + 1` for all (`0 <= i < n)`. Return _the **highest altitude** of a point._ **Example 1:** **Input:** gain = \[-5,1,5,0,-7\] **Output:** 1 **Explanation:** The altitudes are \[0,-5,-4,1,1,-6\]. The highest is 1. **Example 2:** **Input:** gain = \[-4,-3,-2,-1,4,3,2\] **Output:** 0 **Explanation:** The altitudes are \[0,-4,-7,-9,-10,-6,-3,-1\]. The highest is 0. **Constraints:** * `n == gain.length` * `1 <= n <= 100` * `-100 <= gain[i] <= 100`
The fastest way to convert n to zero is to remove all set bits starting from the leftmost one. Try some simple examples to learn the rule of how many steps are needed to remove one set bit. consider n=2^k case first, then solve for all n.
Dynamic Programming,Bit Manipulation,Memoization
Hard
2119
1,716
hello everyone today we are going to calculate money in lit code bank which is a problem which is a Del quing of today so uh basically what is happening is that you have a certain number of day which is the number of input n and then from that input you are supposed to compute the total amount that has been saved in the bank given that uh the bank is the money is safe given a process that can be described as follow every day you are going to put like $1 day you are going to put like $1 day you are going to put like $1 plus what you put yesterday so if today I put $1 tomorrow I'm going to put two I put $1 tomorrow I'm going to put two I put $1 tomorrow I'm going to put two and after tomorrow I'm going to put three and so on but there's a little trade at the end of the week I'm going to restart that means after 7 I'm not going to put eight but I'm going to put $1 more than what I put in the first the $1 more than what I put in the first the $1 more than what I put in the first the last first week so this is the first week I put $1 here so at the end of this week I put $1 here so at the end of this week I put $1 here so at the end of this week I'm going to put two instead of one so I'm not starting back with one I'm starting back with two so um this is how the thing is actually arranged now the goal is to find out how many uh what is the total amount we are going to have at the end of the process that means at the end of the and days so for you to understand better of what we are doing let's say you have four weeks the first week you are going to put 1 2 3 4 5 6 7 the second week you're going to start back at two that is 1 + 1 and then you are going to have is 1 + 1 and then you are going to have is 1 + 1 and then you are going to have the Siri 2 3 until 8 and so on and at the end of the day you are going to have the total amount of the money you need to keep so um giv this process how are we going to solve it so my Approach of solving this will be as follow I first so my Approach of solving this will be a follow I will go through two approaches the first one will be based on the exact description of what has been said here so I'm going to have a Conta which is going to move from one till 7 and once we are at 7 we are just going to restart our cter but not with zero but with the previous day plus one so that is what I'm going to implement here so uh for me to implement that the first thing I need to do is to have like a result here my result is actually zero I'm going to return the result here and then I need to have a follow up here so I have the number of week uh the number of week starting at zero and I have the days which is starting at one right and then I will say the end of the process is actually the day where the number of day will be equal to n and since I'm going to restart the number of day after each week I need to compute the total number of day a little bit different here so I need to say week * 7 plus d so this is a number of D so * 7 plus d so this is a number of D so * 7 plus d so this is a number of D so while this is actually less or equal to N I will say a day ++ because I'm N I will say a day ++ because I'm N I will say a day ++ because I'm incrementing my number of days and then what I'm going to do here is I'm going to say result plus equal to day plus week so what I'm saying is that after each operation I need to add the number of the value of the number of day to the total sum that means at this step I'm going to say okay my total s will take the prev value that was 0 + 1 at take the prev value that was 0 + 1 at take the prev value that was 0 + 1 at this step it will take the pr Value Plus two and so on but guess what actually I'm doing what I'm doing here is actually the same thing that I'm doing here just that for each of those value I'm adding + one + one + one why value I'm adding + one + one + one why value I'm adding + one + one + one why because we are on the week two so what you can do is that you can see keep adding the number of day but just adding the number of week so you can directly handle the fact that we have different value for different weeks so that's what I'm doing here now the question is how do I take care of the number of day how do I change the value to make sure that it is actually accurate with the process you're going to say okay if D is actually equal to eight that mean is the beginning of a new week you're going to say okay day we take one and week Plus+ so whenever we are Hing the Plus+ so whenever we are Hing the Plus+ so whenever we are Hing the end of or whenever we are starting a new we are saying okay we are going to restart the number of day so we are still going to have 1 2 3 6 7 but we are going to increment the number of week so that is why we are titing the number of day and the number of week here so let us run this and see what it gives everything is green let to submit so uh we have everything green uh so another approach of solving this will be uh based on artic formula we are going to L the fact that the saving process is been performed using a progression and using that we are going to compute the value that has been saved using mathematical formula so what will it look like you're going to use this which is saying that if we want to compute the sum of element following an arithmetical formula we can directly use the first element plus the last element time the number of element divided by two and we are going to have the sum of the element so this is what we are going to use to kind of Leverage The the fact of using arithmetical formula to have this solution so what will it look like this is our things the first thing here is to find out what is the Ser right and then you can see that during full weeks we have uh like static element like this we have 1 2 3 2 7 now the next week we have again the same value 1 2 3 till 7 till 8 this time but we are going to we can transform this into the 1 2 3 until 7 plus 1 one year and for the third week we can transform it into the same year plus 2 two year which will always give you like the 28 for the first week plus Z for the second week 2 with 28 + 7 and 28 + 14 so this week 2 with 28 + 7 and 28 + 14 so this week 2 with 28 + 7 and 28 + 14 so this can be computed with number of week time 28 which is the static value and here we have a Ser which is actually 074 which can be see as a Ser of 7 * 074 which can be see as a Ser of 7 * 074 which can be see as a Ser of 7 * 012 so this is a series now that you able to figure out this so how do we compute this so let me just grab you my solution so uh you have to compute the number of week we need to have the total number of week and then we need to have the remaining days we are going to use it for this one all right so um now to compute the amount save in Full full days we are going to have total full week which is actually the 28 time number of week that is what we said because we have 28 and then now we are going to compute the remaining year by using the formula we just see here that means the first element plus the last element time the number of element ided by two so in this scenario our first element is actually zero our last element is actually the number of we minus one and the number of element is actually equal to the number of we so that's what we are going to use here we have our first element which is zero we have our last element which is actually number of we minus one we have our number of element which is actually number of we that we going to divide by two so this is the formula Computing uh this ser and don't forget that we put seven in Factor here so we just need to reuse this seven here time 7even so this is actually the formula that will have us to compute the total number of week The Total Money Sav during full weeks now we also have a total remaining how do we compete the total remaining so the total remaining here we can see that is actually for this specific case will be 4 + 5 + 7 this specific case will be 4 + 5 + 7 this specific case will be 4 + 5 + 7 which is still kind of 1 + 2 + 3 because which is still kind of 1 + 2 + 3 because which is still kind of 1 + 2 + 3 because that is actually the starting pattern of saving but depending on the week we are going to have a certain amount that has been added so if you have three weeks that means the four week each value are going to be like the normal saving plus the number of week here we are on week four the number of full weeks I mean here we are on week four we had three full weeks that means here this one is going to have the normal one plus three because we had three full weeks and the same year so this is actually the Ser year and for you to have the total value you can just reuse this the first element is one plus the number of week the last element is actually uh the number of full weeks plus the uh the number of week and then the and then uh yeah that's the first element that's the last element so how can you solve this you're going to say the first element is one plus the number of week the last element is uh the remaining days I mean the remaining days is here number of remaining days actually the remaining days plus the number of week and then the number of element is actually the remaining day so we have the first element number of one plus number of week last element number of plus remaining there and the number of element is remaining there divid by two this is the formula so this will actually give you the value of this and now that you have this you just need to return the total full plus the total remaining which is actually this so let us run this and see what it gives so it's working really strange that the I will say um the big of one solution is per performing less better than the big of end solution so yeah this a woring thing so um I hope it was interesting for you going through this I hope you were able to learn something so don't forget to like share and subscribe see you on the next video ciao
Calculate Money in Leetcode Bank
maximum-non-negative-product-in-a-matrix
Hercy wants to save money for his first car. He puts money in the Leetcode bank **every day**. He starts by putting in `$1` on Monday, the first day. Every day from Tuesday to Sunday, he will put in `$1` more than the day before. On every subsequent Monday, he will put in `$1` more than the **previous Monday**. Given `n`, return _the total amount of money he will have in the Leetcode bank at the end of the_ `nth` _day._ **Example 1:** **Input:** n = 4 **Output:** 10 **Explanation:** After the 4th day, the total is 1 + 2 + 3 + 4 = 10. **Example 2:** **Input:** n = 10 **Output:** 37 **Explanation:** After the 10th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4) = 37. Notice that on the 2nd Monday, Hercy only puts in $2. **Example 3:** **Input:** n = 20 **Output:** 96 **Explanation:** After the 20th day, the total is (1 + 2 + 3 + 4 + 5 + 6 + 7) + (2 + 3 + 4 + 5 + 6 + 7 + 8) + (3 + 4 + 5 + 6 + 7 + 8) = 96. **Constraints:** * `1 <= n <= 1000`
Use Dynamic programming. Keep the highest value and lowest value you can achieve up to a point.
Array,Dynamic Programming,Matrix
Medium
null
201
Hello and welcome tool again this is Shaur Awasti and today we will talk about a medium level problem of lead code which is bit wise and of number range so basically what is in it, in this we are given left and right and what is we have to tell that in What will be the end of all, like suppose five and six and sane, what will be the answer of all three, okay, so we cannot do it by putting a normal for loop because that TL will give us okay, so if we want to see a little optimized code, then we have to do this. We can do this with the help of bit manipulation, so if we move towards enter, if we look carefully, one thing that we can see is that brother 2 and f if there is a range and we have If our range is from two to sorry, two and seven, we have written all the elements from two to seven in binary representation. After that, if we look carefully, a pattern follows when we write the binary representations and suppose if we are adjacent. If we keep looking at the elements, if we follow the continuous elements, then a pattern follows i.e. zero then a pattern follows i.e. zero then a pattern follows i.e. zero index P means the one which is the highest, LSB is the least significant bit. If we look at it follows the pattern of one, i.e. alternate one to alternate, significant bit. If we look at it follows the pattern of one, i.e. alternate one to alternate, zero i.e. zero then one then zero i.e. zero then one then zero i.e. zero then one then Zero then one then zero then and so on is fine. Similarly if we look at the second one here then it follows and 00 and then again 00. By doing like this the meaning of saying is that every element is following a pattern meaning. Every number, every bit follows a pattern, depending on which position it is in, so one approach we can think of is that there will be elements between all the ranges here. Will not depend Answer: It all the ranges here. Will not depend Answer: It all the ranges here. Will not depend Answer: It depends only on the first and last number, why did I say this because the first is the smallest, so its MSB i.e. the most significant bit, there are i.e. the most significant bit, there are i.e. the most significant bit, there are chances that it will be at the lowest position, i.e. chances that it will be at the lowest position, i.e. chances that it will be at the lowest position, i.e. look at it is found right here and The most significant bit of our largest element has possibilities that it can be at the last position. You have to set the bit ahead of it, that is, you cannot find the bit set further ahead of this, anywhere above because this is your maximum i.e. largest element and this is i.e. largest element and this is i.e. largest element and this is your minimum. So we Now we have understood that it depends only on the first and last number. Why did I say this because it follows a pattern and if we end each other then everything will be canceled out? Brother, if we look at this then rows and rows will be canceled out, right? 0 will be canceled out. If we look at it like this, it becomes one, then again row is zero, then there is one, then this row will cancel out zero. If even one zero falls in the middle, which is bound to happen, because it follows a pattern of alternation. If he is doing okay, then that zero will become zero, so the maximum dependency, we have taken the example of our dependency from 2, where is it coming from our two i.e. 1 2 where is it coming from our two i.e. 1 2 where is it coming from our two i.e. 1 2 3 4 Let's assume like this, okay 5, 6 and 7. Let's take it in 8 88 bits, this is how I took it, for seven I took 1 2 3 4 and here there will be one more four then three, okay oh sorry, it will be like this okay, this is the representation of seven, so this is our Now if we look at this thing carefully, we can find out on the basis of these two, why did I say this because the most significant bit will be at the lowest position and the one at the most. It is significant that the largest element will be the highest i.e. no middle highest i.e. no middle highest i.e. no middle element will be found in which father one is found ahead or father one is found here ahead i.e. no sorry, no middle element will be i.e. no sorry, no middle element will be i.e. no sorry, no middle element will be found in which the most significant bit is found before it. That means here also zero is present and no other smaller number will come in between it and in this case no bigger number will come in between i.e. it number will come in between i.e. it number will come in between i.e. it cannot go beyond this. Okay, so if we look here then In this, we will keep reducing the elements one by one from the right side, that is, we will keep shifting it to the right, we will keep shifting the left one to the right, that is, the right sen will also be shifted to the right one by one, until we have both left and right equal. As we go, we shifted this element disappeared, this element shifted, okay again this element or element shifted, now we have the remaining left and right i.e. 00, both of them are equal, so we right i.e. 00, both of them are equal, so we right i.e. 00, both of them are equal, so we In the while loop we will write while left is not equal to right, what will we do till then we will keep shifting left to right, ok one by one and also keep shifting right to right one by one until we become similar as soon as our It will be similar and we will come out of the loop, okay and one we will put a counter and as many times as we are shifting, we will take a counter so that we can come back to our position, okay ultimately when both are equal. When both are equal, meaning whether you lift left or right, now the two that are left here, when the right shift is completed and the two that are left at the end, will be equal, then either all the zeros will be zero or all the ones will be one and Either all the forests will be one, take one example and understand the case of one, okay take one more example let's suppose here 1 0 1 and this 1 10 If we see in this then right shift this The one element has disappeared, this row has come here This element has disappeared here, this row has come Okay, this is our left, this is our right, again it is not equal The row zero has disappeared, this row has come here from here again Look again, still not equal Left Right again it disappeared and one more zero came in the right sides means three zeros are totaled. Again not equal. Gaped again one more zero got inserted. Okay so now four zeros have come from here and the next four We have shifted the elements, so now ours becomes left and right, this becomes left, this becomes right, so if we look here, now we have equal brother, left is equal to right, okay, there are four set bits in this, it is at the same position. There are four sets of bits in it, so everything is equal here, so now that it is equal, in this case, if we look carefully, when it is equal, then the elements that are left on our right side, that is, on the left side, which we have not shifted yet. Right, all those are equal, either all va's or all ji's are ok, so what to do in this case when these two come, in this case we can take any one, take left or right, take it at the end, this is what our answer is left. But to bring it back to its position, i.e. the number of times we have taken the count here, the i.e. the number of times we have taken the count here, the i.e. the number of times we have taken the count here, the number of times we are shifting, that is the number of times we are taking the count, after that we will count minus the number of times and the same number of times we have shifted right. With that much time we will shift left or left let us suppose that we picked up the left and from there we shifted it left with that much time i.e. that much time i.e. that much time i.e. all the elements which were there returned to their positions and 0 00 came here 0 00 When we come here, now what was the value of left, four times 0, four times one, then four times 0, four times one, back, how many counters did we have, brother, here one doti cha four, we shifted right, so four times we did this. We will shift left four times. Whatever will come. Okay, so ultimately this will be our answer. Okay, so this thing is clear. Once we will code this thing and see, it will be a little better clear to us. Okay. So first of all, we create a counter in this, okay, after that we write the while loop, while left is not equal to right inside, what will we do, okay inside, till the time our left is not equal to right, then in the left we right shift. Once again we will update the value of right. Right shift is ok. Now this thing is cleared. Then we will keep incrementing our count. After that finally we will answer when left or wide loop will exit only when left. Or right, both will be equal to each other, left and right, then after that keep your left in return or keep right, to bring it back to its position, we will hit left shift again, how many number of times count the number of times, we will return it and see. Does the answer come? OK, here I have missed the semi colon. OK, all three items are passed. Once submitted, it is fine. Thank you so much for watching this video. If you liked the video, then like the video and subscribe to the channel. See you in your next video till then bye
Bitwise AND of Numbers Range
bitwise-and-of-numbers-range
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_. **Example 1:** **Input:** left = 5, right = 7 **Output:** 4 **Example 2:** **Input:** left = 0, right = 0 **Output:** 0 **Example 3:** **Input:** left = 1, right = 2147483647 **Output:** 0 **Constraints:** * `0 <= left <= right <= 231 - 1`
null
Bit Manipulation
Medium
null
1,961
um hello so today we are going to do this problem called check if string is a prefix of array so the problem says we get a string s and then array um of string words and we want to determine whether s is a prefix of strings of orders okay so we get s and then we get an array that is a string of words okay so this is array and this is string s and then i'm going to determine whether s is a prefix of words so s three tricks or four something like this okay what does that mean um so a string s is a prefix string of words if s can be made by concatenating the first k strings in words for some positive k you know larger than the length okay so it seems like what this would mean is that we will get like a something like words that contains um some values like w1 something like this and we can say that s is prefix of words if s is a concatenation of let's say the first case strings in words so words right the first basically we concatenate the first k words and then example here we get a sequel to this and what is equal to that and we want to figure that out so um so what this would mean here is that we get um so if we say so s can be a here is actually it's just like was zero plus word one uh plus words yeah that's pretty much it's okay is equal to the first two words yeah i think we should the problem is whether it's concatenating the first thing you can just check right so here it can be made only by the three last ones but not containing the first one so i think we can just keep checking right and until we reach the end so that would mean something along the line of for cns uh in words right actually we can even do but i think we can just return if s is in join you can just join actually not in it starts with so python string starts with uh yeah i don't think that would work because if a portion of it is in one um one of the array values and not in the not the entire value then we'd have a problem so we can do this so we'd have to say for say w in words let's say this is c this is kind of um okay how can we name this so yeah let's call it c it's just a concatenation right so here we do c plus w and then if s equal to c then return true otherwise it's returned it's a very simple solution here okay so it seems like that one works um what if i try one that kind of has just this right and this should not work it should be false okay so that should work i think okay cool so that works um what if we try something can we do it in a better way um yeah i think we can so we can do actually just uh yeah i know i was thinking of doing maybe joining words like this but that won't really be that i think to do we can't use any here uh because we want to check the accumulation maybe we can use scan i think um because cam gives us the last result okay let's see python uh scan okay i want this functional uh the functional one okay let's call it let's look for reduce um okay so definitely do the juice right so if i do if i take the list of words here that we have so that will be words equal to this and then if we try to do the juice here so for reduce we'll do some need to do something like reduce and then pass a lambda for the function which would be x and y and then what we want is to concatenate them and then we need to press words okay so this groups everything together the problem is i want to somehow be able to compare this but if s is this it should still return false sounds like i need all the concatenation so i need this and i need to check equal so i need all the concatenation up until that point um so how can this so we kind of need to reduce with intermediary results accumulate maybe so accumulate ah okay so i think this is potentially what we want okay so import from error tools you put accumulate okay and then what we need to do is call it and so the ira irritable is words and then the function that we want is this just a plus okay if we turn it into a list just to see the content it's exactly what we want right and then here we can check if any so here any is takes a miracle right so it can take actually this so any uh i need to first define s so s is let's say this right and so what i need at this point is to any um equal to s for w in this variable uh okay seems like there is a okay this so it says true because yes it does i think this should be this should work so something like this okay so that seems like it works let's try to submit but i think so that works cool i think though we can make this i think there is a plus um in python uh python reference plus operator uh okay so i'm not sorry about that so python pass plus function yeah somehow remember but can it be just passed like this so maybe it's what accumulates even does by default yes so um actually accumulate does concatenation by default both strings because if i do this and just show it as a list then i get the same thing so it's even better with just accumulates like this and we'll check if we find any and actually we just need to check if s is in this we don't even need to do any so this is a lot simpler submit and that works so an even simpler solution is just as my weight yeah i think this is good enough cool
Check If String Is a Prefix of Array
maximum-ice-cream-bars
Given a string `s` and an array of strings `words`, determine whether `s` is a **prefix string** of `words`. A string `s` is a **prefix string** of `words` if `s` can be made by concatenating the first `k` strings in `words` for some **positive** `k` no larger than `words.length`. Return `true` _if_ `s` _is a **prefix string** of_ `words`_, or_ `false` _otherwise_. **Example 1:** **Input:** s = "iloveleetcode ", words = \[ "i ", "love ", "leetcode ", "apples "\] **Output:** true **Explanation:** s can be made by concatenating "i ", "love ", and "leetcode " together. **Example 2:** **Input:** s = "iloveleetcode ", words = \[ "apples ", "i ", "love ", "leetcode "\] **Output:** false **Explanation:** It is impossible to make s using a prefix of arr. **Constraints:** * `1 <= words.length <= 100` * `1 <= words[i].length <= 20` * `1 <= s.length <= 1000` * `words[i]` and `s` consist of only lowercase English letters.
It is always optimal to buy the least expensive ice cream bar first. Sort the prices so that the cheapest ice cream bar comes first.
Array,Greedy,Sorting
Medium
null
1,650
hey this is josh from leak dev where we try to explain programming questions as simple and concise as we can today we'll be talking about the lowest common ancestor of a binary tree according to leed code this question has been asked quite frequently by facebook amazon microsoft and just from my own personal experience i was actually asked this question multiple times in screening interviews and actual on-site interviews on-site interviews on-site interviews so being able to know how to work with trees will be a good thing to have in your tool set given a binary tree we want to find the lowest common ancestor of the two given nodes in the tree so what that basically means is for example if we were given p equals five which is right here q equals one which is right here we return three because three is the first common ancestor of five and one in example two we're given five which is right here and four which is right here the first common ancestor of them all is five itself because according to the definition of the lca a node can be a descendant of itself so we return five for example too and then finally in example three we have a tree we don't have a picture of it but we can imagine a tree of one two which probably just like this three and one right here and then we would just return the answer one 1 would be the root node and once again a node can be a descendant of itself one thing to note is that there are several constraints to this problem specifically the important ones to know is that all node values are unique the p-value that we're given are unique the p-value that we're given are unique the p-value that we're given is not the same as our q value and that p and q are guaranteed to exist in tree to solve this problem and all tree problems in general we'll use a recursive solution where we will traverse through the whole tray and find our lowest common ancestor taking a step back and looking at this problem at the high level intuitively it's pretty simple we want to do is we'll recurse our tree we start from one we go through this love child see if it's one of the notes that we're looking for and if it's not we go down look at its left child we find three and we know that it's one of the nodes that we're looking for so return some value back up say true to our two and then we recurse the right tree and see that it is also one of the value that we're looking for q and so we return something back up so maybe another true in this example and then once we're back at 2 and we finish recursing both its left child and its right child we can see both its childs and see that we have found our answer and so we return ideally the problem we want the specific node but in this example let's say we return true and then we go back to one we recurse it's right child and c5 5 isn't what we're looking for so we look at the left node which is null so we return say false and we also look at its right child which also is null so we also return false so because we haven't found the notes we're looking for in five we return back false and then once we go back up to our starting node at one we looked at the left node and we see that we did find our ancestor so we returned some value back up and that would be how we would solve this algorithm of course we can't just return true or false because this problem wants us to return the node that is our least common ancestor so we want to somehow return to in the previous example we bubbled up a true or false value to indicate whether or not we found the nodes and then we bubbled it back up to the top unfortunately that won't work because in this specific problem we want to return the exact node itself that would give us the answer however we can modify our algorithm a bit for example instead of returning a true or false value what if we return the node itself for example once we find the three node we return that node back up and once we find the for node we return that node back up too and then once we're at the least common ancestor and we identify that there are the it is the least common ancestor we can just return that node back up and eventually return that as an answer to be able to accomplish this algorithm i have a six step plan above now first let's clean this up like all three problems we usually iterate through the tree using recursion and we need to do recursion we need to define our base case and our recursive case so what is our base case we have two base cases the first base case is when we reach a null node that means we haven't found anything when that happens we just return null back up the second base case is what happens if we find one of the descendant nodes like three or four when that happens we return that node back up and finally we have a recursive case where we have an identified answer and we want to just continue iterating there's two parts to this first we want to just continuously explore the left and the right subtree of the node that we are currently on and then eventually we will hit those base cases that we talked about and we will return a node back up so three and four now at two while we're processing the left and right subtree if both of them are true we can just propagate the node two back up otherwise if one of them is actually a value and not a null we can just return that one otherwise return null so example in five we would return null because both of its subtree child is null and then we return no back up here and then finally at 1 we'll see that we have 2 and null so we just return 2 which would give us our answer there is one specific case in this algorithm that i didn't address that it handles perfectly though and that's what happens if we have a node that is a descendant of itself so for example if our value p equals two and q equals 4. how this play out in our algorithm because we would actually never process 4. so first let me clean this page up and then we'll do a quick run through right so what happened here is we go to 1 and then we go to two and then two would be one of our base case and then we just return it up however you might just wonder well didn't we just ignore four how do we know if two is actually the ancestor and the reason for that is because of one of the constraints in our problems specifically that p and q must exist at this point if we found one of our nodes and we turn that up that node already is guaranteed to be the common ancestor if we don't find any other nodes in the other sub tree of its parents so in this instance we would return two back up and then everything will play out the same we go to one would then go to its right subtree which end would return null and then finally back at one we compare two and null and then return two because it's the only non-no value two because it's the only non-no value two because it's the only non-no value and we would have our least common ancestor and that's roughly the idea of how this algorithm works let's get to the coding section in recursion problem i like to find define a private helper function because usually you need to pass in different nodes in this instance it's all the same but i'll create one anyways so to reiterate q and p is the nodes that we're looking for and node is the current node that we are at remember for all recursion problems we need to define our base case and our recursive case our base case is either if we hit a null node which means we haven't found anything or if we found one of the nodes and then when that happens we just return the current node that we're at otherwise in our recursive case when we are iterating through our node we have to go all the way to the left child and see if there's a common node and the right child to see if that's a common node and if both left and right is a common node that means our current node is the ancestor otherwise we just return the node back up and that's all for this algorithm very straightforward to code but not so easy to think about and actually implement however just like what we always do let's walk through our problem so first we start with our helper function and we pass in basically everything we were given so current value node is one is not null nor is it any of the descendants that we're looking for so we enter a recursive case to do that we just explore our node.left and we just explore our node.left and we just explore our node.left and we just pass in p and q that brings us to node two also does not hit the base case so we enter our recursive case we check our left node which once again is now three actually is our base case so we just returned three back up back at two our left is now three but we're not done recursing yet the next thing we need to do is we need to recurse through our right node so we go to four and we find that four is one of our base cases it's actually equal to q so we turn four back up so we're back at two and our left node is 3 and our red node is 4. now we are at line 21. if both the left and the right node is not null that means we found the common ancestor and we can just return our node we return two back up to our one node so we exit our left recursive case so in this instance let me just erase everything we are at two for our left node now we still need to explore our right node so we go down there and we enter our recursive case here 5 is not null nor is it any of our descendants so enter a recursive case and just to reiterate where we are i'll use blue to say this is the left and right value of our word node and i'll use green to say this is the left and right value of our five node so r5 and we enter a recursive case we go to left subtree which is null which is our base case and then we turn null back up so that says null and then we do the same with our right subtree which is also null and because both of our nodes are null we don't enter our if statement and so we go to our else case in this code we said that if left is not equal and null we return left otherwise we turn right in this instance because they're both null it doesn't really matter and we just return no back up so null goes back up here and we're back up here and now in our one node we have our calculated node write subtree value which is null and then we follow the same exact logic because both of them are not equal to something we don't return the current node we're at so instead we check if the left node or the is null and then we want to check if one of our nodes is not null and then return that in this instance our left is not null in fact it's actually our ancestor so we want to return that node back up and so we just return two which one will give us the answer to this question now let's submit our code pop this back up and there you go this is how you solve the least common ancestor problem the code itself once we look at it isn't horrible to write but once again this the thought process and reasoning involved to get to it takes a quite a bit of a leap key to these tree prom is that we always want to explore all the nodes go to our base case or usually the bottom of our tree and then bubble our answers back up to the root node now if you consider this video helpful please consider hitting like button and maybe even hitting the sub button to get notified whenever we make daily updates otherwise i'll see you in the next video and have a great day
Lowest Common Ancestor of a Binary Tree III
find-root-of-n-ary-tree
Given two nodes of a binary tree `p` and `q`, return _their lowest common ancestor (LCA)_. Each node will have a reference to its parent node. The definition for `Node` is below: class Node { public int val; public Node left; public Node right; public Node parent; } According to the **[definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/Lowest_common_ancestor)**: "The lowest common ancestor of two nodes p and q in a tree T is the lowest node that has both p and q as descendants (where we allow **a node to be a descendant of itself**). " **Example 1:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 1 **Output:** 3 **Explanation:** The LCA of nodes 5 and 1 is 3. **Example 2:** **Input:** root = \[3,5,1,6,2,0,8,null,null,7,4\], p = 5, q = 4 **Output:** 5 **Explanation:** The LCA of nodes 5 and 4 is 5 since a node can be a descendant of itself according to the LCA definition. **Example 3:** **Input:** root = \[1,2\], p = 1, q = 2 **Output:** 1 **Constraints:** * The number of nodes in the tree is in the range `[2, 105]`. * `-109 <= Node.val <= 109` * All `Node.val` are **unique**. * `p != q` * `p` and `q` exist in the tree.
Node with indegree 0 is the root
Hash Table,Bit Manipulation,Tree,Depth-First Search
Medium
1655
103
hello everyone welcome to coding decoded my name isja I'm working at sd5 at Adobe and after a very long time I have come on to creating a new video because uh all the questions in the month of February seems like an easy question and most of them were already solved by me already and for those who were not I believe that you guys are capable enough to solve those questions because the land up an easy category and today since it was a medium question that I haven't solved in the past so I thought let's create a video and it will give me an opportunity to interact with you so welcome guys welcome to day 19th of January lead Cod Challenge uh it's ex wait now it's 19th yeah day 19th of February sorry February lead Cod Challenge and the problem that we have in today is binary tree zigzag level order reversal the question says you need to perform the zigzag level order reversal of a binary tree and what does it mean it means that whenever you are moving from one level onto another uh the direction in which the BFS reveral has to be performed will change for example here you will be moving from left to right here you will be moving from right to left here you will be moving from left to right and the answer correspond that first is left to right then it's right to left then it's left to right so without further Ado let's quickly move on to the presentation and let's quickly get hold of the algorithm lead code 103 binary tree zigzag level on the traversal this question is a medium level question on lead code but the subscribers of coding decoded would feel that this is an easy question and for those who are new to coding decoded this video is primarily for them also in case if you have any doubt understanding this problem upart if you want to ask anything from me in general with respect to job opportunities internships placement please feel free to drop a message on the telegram group of coding decoded we have 2,000 developers working decoded we have 2,000 developers working decoded we have 2,000 developers working from all top notches in this group and we openly discuss problems that we face in day-to-day activity what's new in day-to-day activity what's new in day-to-day activity what's new happening in the industry Char GTP AIML stuff referrals layoffs and what not looking forward to seeing all of you there now let's get back to the problem I have taken a slightly longer example so that you guys get a good hold of the concept and here the root of the binary T that is given to us is 10 so the question says you need to perform the zigzag level order traversal moving ahead let's start the iteration and at the zeroth level we will move from left to right direction in the level order reversal in the next level which is level one we will move from right to left then we will move from left to right and then we will move from right to left so definitely we will need a variable that will help us identify whether we are moving from right to left or left to right and the answer corresponding to this binary tree would be the first one would be 10 then we would be then we would have 0a 40 then we will have 7A 2A 1112 followed by 34A 78 and now comes the question how can we algorithmization in which you're doing the movement at any particular level so let's create a level a variable named left to right l t and let's initialize it to true because at the zeroth level we are moving from left to right let's start the iteration and as the basics of level order reversal what do we need a queue so let's get started and let's go ahead and create a queue what we're going to do we'll add root into the Q what is the root element happens to be 10 and we will initialize the left to right element to default value of true now we are done with the level order traversal L zeroth node the next thing that we are going to do is to pull this element out so this element is gone and uh what is the value of left to right happens to be true so we will simply build a new array and we will add 10 onto it awesome the first ele element of our answer is done let's move ahead and since we are removing this element what do we need to make an insertion of all its children into the Q so 40 and0 will be added onto the Q and remember we'll be adding the left element first followed by the right one so 40 get started followed by zero and this forms the boundary of the first level of the BFS reversal this is level zero of BFS reversal let's contining the process and remember since we are done with level zero of the BFS reversal what we going to do we'll be flipping this value up left to right now let's set it to false we are basically toggling this up and let's continue the process the next element that we have happens to be 40 gets extracted and it's time to build the second element of our answer and what do we see that the left to right element happens to be false so we'll simply make an insertion since it's the first element for 40 so 40 gets started and again since 40 is getting removed we will have to make an insertion for its children into the BFS Q so the BFS Q will get 7 comma 2 so 7 gets added followed by two so this is level two of the BFS reversal and let's continue the process now comes the important part where we will need the left to right variable the next element that we have happens to be zero and since 4 is gone let's delete it the next element that we have happens to be zero and since left to right element is false what we are going to do we'll make an insertion into our answer array at the starting node 0 gets added at the starting node instead of adding zero to the ending position we will be adding this zero to the starting node and this is the Crux of the problem U since we are removing Zero from the first level of our BFS traversal we should be adding its children into the BFS Q what element do we have as it children 112 So 112 gets added over here and this element is gone now let's continue the process and since we are moving to the next level we will be toggling the value of the left to right variable so now again it gets set to true and we are done with the second element of our answer which is 0 comma 40 so let's proceed ahead and it's time to create the third element of for answer uh the second level has three elements in it 1 2 and 7 so let's pull out the topmost element from it seven gets extracted and uh since seven gets extracted it doesn't have any children so no insertion is made into the Q and let's add seven as part of our answer now let's continue the process the next element that we have happens to be two so two gets extracted and does it have any children yes it has one child which is 78 so let's write 78 over here and since left to right variable happens to be true we will be making an insertion into an answer array at the end so two gets added at the end had it been the case where left to right variable would have been false we would have made an insertion at the start let's proceed ahead the next element that we have is 112 So 112 gets pulled out and it has 34 at its child so let's add 34 over here and let's add 1112 at the end of our answered element so in total we have three elements 7 2 1 2 and those are present in this particular order which is moving from left to right we are done with the third element of our answer and let's proceed ahead the next level would be three and since we are moving on to the next level let's set the left to right variable to false let's continue the process the first element that gets extracted happens to be 78 let's create the fourth element let's add 78 over here and it doesn't have any child so no insertion is made the next element that we have is 34 it also doesn't have any child so this element would be inserted at the starting point of our answer result why at the starting point because our left to right variable happens to be false so let's write 34 at the start with this we have successfully iterated over all the elements that are present in our binary tree and in total the answer corresponds to 10 040 72112 3478 and this is what the question expected us to return so without further Ado let's quickly transform this algorithm into code and I'll exactly follow the same steps as I just talked here the first thing that I've have done here is to create a list of integers that will help me return the answer result in case my root is null I simply abought the process and return the ANS otherwise I go ahead and create a BFS Q I add my root onto it I create a variable named left to right and initialize it to true the typical we of lighting any BFS reversal Q dot is not Q is not empty I extract the size while size minus is greater than zero I extract the topmost element and here I have created another subl list that will help me create the answer at that particular level if my left to right happens to be true what do I make an insertion towards the end of the subl list in case my left to right variable happens to be false I make the insertion at the starting point of my subl list and this is again typical way of writing the BFS reversal if my head dot left is not null I add it into the cube my head dot right is not null I add it into the cube and once I've done with iterating over a particular level in my BFS reversal I add my sublist on onto the result and I toggle the value of left to right once I'm out of the while loop outer while loop I simply return the result so let's go ahead and submit this up guys in case you haven't still learned this BFS reversal template it's high time you do it because this is same template that is used in all the BFS questions also it really helps in the graph problems so I would urge you guys to learn this as a temp template and you will be using it everywhere apart from this if you're interested in solving more questions of the tree concept then you can check out coding decoded SD preparation sheet here it includes all the important questions from interview's perspective so if you have an important interview plann very soon and you want to go through the entire revision process then this sheet would act as your Bible so go ahead and select trees for the BFS traversal concept and here you will see the questions that are mared with double sign as a must do before an interview and you can try all these questions using the BFS technique also in case you get stuck in any of the question then here is the video solution attaching it Link in the description below so do check this out with this let's wrap up today's session I hope you thoroughly enjoyed it if you didn't please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and I'll see you tomorrow with another fresh question but till then goodbye
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
119
welcome to august leeco challenge today's problem is pascal's triangle two given the non-negative index k we turn given the non-negative index k we turn given the non-negative index k we turn the kth index of a pascal's triangle is represented nicely in this graphic where every row has one more cell than its previous row and the numbers within are going to be the summation of the two cells above it notice how all the cells on the borders are always going to be one so it's only the ones in the middle that we need to calculate so let's think about how we could represent this in a programming language like python and we'll probably use a list of lists if we went straight forward we could think of what would we need to do to calculate the last row here this will be the row three and whatever row we want to move forward we need to calculate the ones before that iteratively in order to get the next row and so on and so forth so just like the graphic indicates all we care about is the ones in the middle right and we need to add up the two on top so if we represent like this like we can see that visually but how about what would that look like in uh in a programming language to make it easier try to instead of making a triangle just look at it like this um i guess it's still a right triangle but you can see all we care about is the numbers in the middle right we see that the one row before it we just want to add up the same index number as well as the index number before it here so 2 is going to be the sum of the previous row same index as well as the index minus one here in three we can see that we need to add up one and two three is going to be out of two and one and everything else at the edges we don't care about those are always going to be ones so our approach then would be to go through each row create a temporary array and calculate the ones in the middle and then add that to our output and continue this loop until we are finished and then return the last list in that array all right so let's see what that might look like so first things first we want to start off with i'm going to call it pass this is going to be our pascal's triangle and since we know the very top row is going to have just a 1 we can just begin with that now we want to do this for however many rows that we're given so 4i in range of row index and we're going to have to do a plus one because this is 0 indexed and we want to start at the second row which is going to be 1 here because we already have row 0 that's already got a 1. so the first thing we want to do is start off by initializing our temporary rate and we'll just say make this a list of ones for in range of what i guess it would be in range of the row index that we're on right row index that we're on plus one range of plus or months so plus one yes all right so after that we now we know that it's going to be like 1 at this point and we'll say this isn't a very good example because we want to save it's like the third second third row here we only want to care about the one the middle right so what we'll do is since the ones at the edges are already ones we'll just say for j in range of one to the length of our temporary ray minus one so that way we're only going to care about the ones in the middle and at that point we're just going to make our temporary index array the index point equal to our pascal's triangle whatever the previous row is the last row that we've added on as well as j plus pascals minus one uh j minus one so that's going to equal two on top of here so once we're finished with this since this updates to two now we could just add that to our pascal's triangle we'll append our pascal strangle with temporary array and then just continue the loop after we're finished with that let me just delete that here and we will return our last list on our pascal's triangle so let's see if i've messed anything up certainly might have okay looks like it's right let's go and submit that and there we go accept it okay so this works but they have a follow-up works but they have a follow-up works but they have a follow-up can you optimize our array to only use k extra space so basically just a list with k indexes indicating like our last row hmm so that's a little complicated right because don't we need to have our previous rows to calculate the next row this is like a dynamic programming solution right but if you think about it carefully let's just think about that last row here one two one we want to get to one three one right could we use this array to get to this array doing the exact same thing that we're doing here well uh the problem is uh first we might want to append a cell right so we'll say that we add one here at the very end now we just care about the ones in the middle so how about we just add up the ones from before and get that three but if we do it left to right you can see immediately we update this so now this one doesn't work because we've changed this we need that too but what about the other way well because this one is new and that's never going to change you can see that here if we just add the previous one we're kind of going uh i guess bottom up we'll add 2 to our 1 here that's 3 but we'll be keeping this 2 and i'd keep bringing the 1 here and now we've gone to this point and this is still using the same list we just appended 1 and that's going to allow us to only use k extra space so the algorithm is still the same all it is we're going to get rid of our temporary array that we're creating and instead use the same list okay so start with initializing our output it's not going to be a list of lists it's just going to be a list and we'll still go through this same thing but instead of just creating this temporary array what we'll do is append to our output 1 and the same thing here this would be the same except we want to move backwards right so how will we do that length of output minus 1 but we want to go minus 2 because we don't care about the very last one we're going to go to not negative one we're going to go to zero and we'll still decrease by negative one finally instead of having our temporary list we will say i'll put just add the one previous to it so plus equal output of j minus one we don't need to append anything now all we need to do is return the output at the very end okay so let's see if that works okay it looks like it worked let's go ahead and submit that and there we go so the time complexity is the same and we are only using k space so that's it pascal's triangle is a good one i would definitely look into it and solve variations of this problem thanks for watching my channel and remember do not trust me i know nothing
Pascal's Triangle II
pascals-triangle-ii
Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: **Example 1:** **Input:** rowIndex = 3 **Output:** \[1,3,3,1\] **Example 2:** **Input:** rowIndex = 0 **Output:** \[1\] **Example 3:** **Input:** rowIndex = 1 **Output:** \[1,1\] **Constraints:** * `0 <= rowIndex <= 33` **Follow up:** Could you optimize your algorithm to use only `O(rowIndex)` extra space?
null
Array,Dynamic Programming
Easy
118,2324
438
Hello Hi Everyone Jasmine Chakraborty And Today Will Be Discussing Problem Number 1434 Let Code Find All Programs In History 109 This Is A Problem Dentist In Bittu Of Every Day I Am Not Challenge In Its Food Should You To Problem Avoid Yesterday I Want From You Can Be Sent out from Play List to Play List Soe Hind is the problem giving such things S&amp;P S&amp;P S&amp;P that hand they have to find all exams page in this handy tool returned starting index of all 20 grams of words and from Android browser water for five years in the Letter of different water friends typically used oil generator set you want to and from physical representations of a lukewarm spring plate in software approach bring a b c all it's an order comes with baby force will be included in bsc bca editor-in-chief that RCB Ad SSC Board Result Research Adams Of ABC Okay Something Clear Soe Na How To Approach Typical Problem Take Care Due To Speed ​​And It's Okay Fennel Will Have To Subscribe One Will Not Familiar With Lots Of Year Was Doing What Is That We Can Do The Giver size the insights and distributes prices for history for grand set n alarm of birth the same size adds patients can not be a great and fearless and fear to be considered for window size three layer and facilities and akram have descended from which produced som one shiv They know how difficult use fluid you check 1000 soon listed 80 used s monitor of booty dude video to share I currently handsfree consists of life become online country ok so wear considering all the characters and notification like share with all they know what this Chief subscribe Video subscribe window installed after computers for villagers painted advantage of this will be seen in the 11th that soegi vacancy this to is obscene equal handed over validation of from itunes store the answer has starting date for a number of years will shift window 98 ki bread cod don't see soapy mode 150 g in account and lag department z9 Vivo considers is not present in this he should withdraw it and remove all the window that airtel ko 280 b off but as they all records acid 100 comes a row That hand ac being can be included bbi was not dare previous letter this is the doctor away from studio but welcome one ko shampoo difficult and renewable 2009 will continue shifting to window like this is the anil bhai ji tentative dates year will continue for the valuable And give them but it's there in which year will have battery saver mode on the year open the acid which is singh sentence me 120 gms scene of peer 120 respectively 6 on one so normal that Ravana optimization what we can do share this and institute After taking any attachment to account for this what we can do it is decrement account declared like they never define cid comment voyager-1 voyager-1 voyager-1 middle aged department 1000 and find every day the moment when one sheet in exam in 2017 this completely hero sprint with vinod sign up Indians Devi Point Sequence Print Show Video November Of Nowhere Is Described In Later Years From The Back I Increment Annual Victory Awards And Utilize Get Here Sw0 This And Welcomes One OK And A Slack Made It Clear That Comes Forward Bases Painted Sunth Department And So Vid Ooo will again welcome involved in this included and share it well and decrement by one leg is so when we reached near this whole thing but with vidmate s well so ifin singh vikram zero day will include six years in the problems let me to go to the Code Year Celebration of Morality in this Function is Hey What So Any Significant and Mrs Pain Person's This Condition Life in First Time Bigg Boss This Condition Aa Vriksha Ek Plate Idhar Size Penal Sainik Us After Death Sentence subscribe The Channel and subscribe the Channel and in Frequency of all characters page subscribe channel subscribe now to which sliding window is initially e do not moving til servi moving that til size pet checking cba because in this element window size se zoom 12 benefit for industry don't want for this is the time building Window Plate Midnight Fever OK Hum Building's Vendor Teller m&amp;m OK Hum Building's Vendor Teller m&amp;m OK Hum Building's Vendor Teller m&amp;m Exercise You OK So M Taking a Character and Thinking in This Present in the House Map and Implement One Developed Is Not Present Leaders Were Not Pregnant So I Do n't Need to Avoid It Simply Introduce Gift I Is Presented It's Present In Amazon Sub Screen Definitely That Is Not Done From 100 Ki Idea Comments It's Present In The Juice Of His And His Mouth And Noted That If She Gives Functions Check Map Of Facts And Figures Responsibly Started Now Desk Does It Check weather all is the value side and not going to later dated check all the best starting from this side start from - 30 - 30 - 30 - - 121 on that your and share later android gear shifting the window Uttar Pradesh Sliding Window 10 in this building Sliding Window And Take You Can and Should Avoid - Subscribe White on the table subscribe Video Use Two Years Boys and Boys Payment Festivals But They Don't Need Not a Single Bill Sent Content Science and Technology Department and the Initial Typing Position Gold Behind Give New Cars Present in disgusting discriminatory topic director is presented the investment and implemented by one key and share will sell on chat function and after this incident in this time which is a war has time field with jio fei this day in the year digit heading initial position of the soft to Much of the credit for this is the fool solution ok 109 left side this dual sim not interested and want to avoid you will be amazed and subscribe if someone has flowers smack and sacrifice everything is a row of any harm the middle end False evidence of wave's time complexity of all programs of nd24 loop control maximum of with 6 times ok should you go from 02351 subscribe le prince from nothing acid latin characters for divya and you will take time to paint a time when placid is near problem Problem The Best To Do Subscribe My Channel Video That And You Will See You In Next Video
Find All Anagrams in a String
find-all-anagrams-in-a-string
Given two strings `s` and `p`, return _an array of all the start indices of_ `p`_'s anagrams in_ `s`. You may return the answer in **any order**. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Example 1:** **Input:** s = "cbaebabacd ", p = "abc " **Output:** \[0,6\] **Explanation:** The substring with start index = 0 is "cba ", which is an anagram of "abc ". The substring with start index = 6 is "bac ", which is an anagram of "abc ". **Example 2:** **Input:** s = "abab ", p = "ab " **Output:** \[0,1,2\] **Explanation:** The substring with start index = 0 is "ab ", which is an anagram of "ab ". The substring with start index = 1 is "ba ", which is an anagram of "ab ". The substring with start index = 2 is "ab ", which is an anagram of "ab ". **Constraints:** * `1 <= s.length, p.length <= 3 * 104` * `s` and `p` consist of lowercase English letters.
null
Hash Table,String,Sliding Window
Medium
242,567
103
hey everyone welcome back to the channel i hope you guys are doing extremely well so today we will be discussing the zigzag traversal from the frika tree series now what does this traversal means so in the previous traversal that is the level order traversal you saw that the traversal was like one two three then a four five six now this is zig zag as the name suggests so first it'll be one then you'll go across like this that's three two then you'll go across like this four five six so that's the traversal zigzag traversal like first like this then like this so kind of this and if there were any other levels it'd be like this then it would have been like this so that's what a zigzag traversal is all about so we're going to follow the same technique as we did in the level order traversal so initially we will be taking a cue data structure so let's take initially a queue data structure and i'm going to store the root of the tree there's no doubt in that we're going to store the root of the tree in the queue data structure also we're going to take a vector of vector or a list for that reason that's the data structure where we will be storing the zigzag traversal and we'll be returning this as our answer so what we will do different is we are seeing one thing that the first traversal is from left to right then it's like this right from right to left then again from left to right then from right to left so we're gonna introduce a flag kind of a variable okay so let's introduce a flag variable which is gonna say us if you're moving from left to right or you're moving from right to left so probably we can keep a flag variable uh initially let's assign it to be zero or one you can do it as you wish so let's start the iteration of the cube so in the iteration of the queue first time when i check out the queue there's only one element so we will take it out okay and now what we will do is if there is a left there is so we will insert it into the queue if there is a right there is we will insert that into the queue once i've done that once i've inserted all the bottom notes left and right i will take this guy and i'll insert it in the same order like i took it out that's one the flag is zero very important to the flag is zero so flag zero says us that the direction is from left to right and the value one says us that the direction is from right to left in our traversal so we are done with one so once you've inserted one into your data structure please make sure you turn the flag to be one because you're going to the next iteration of the queue right and you'll get the next level notes that's two and three so let's get the next level notes to entry now you're gonna check for twos left that's four so kindly insert that into the queue you're going to check for 2's right that's 5 insert that into the queue so 2 is done next for 3 is left there is nothing 3 is right there's a 6. insert it so i can say i've done for 2 and 3 so these elements are also done now since the value of flag is one what you will do is instead of inserting it like two and three you will make sure they are inserted in the reverse order that's three and two that's why i said a flag is one it's right to left so flag one told us that it's right to left now while you move to the next level please make sure you turn flag back to zero so every time you're switching on levels you turn flag zero one right and the next you get something as four five six and it's time to check if they have left and right four doesn't have a left four doesn't have a right five doesn't have a left five doesn't have a right similarly with six doesn't have a left doesn't have a right so can i say the traversal for four five six has been completed and the flag value is zero and if it is zero i will simply take four five six and insert it into my data structure without reversing it so i've inserted that into the data structure now can i say if i look back at the queue my queue is indeed empty now hence we have traversed all the nodes and right after the traversal can i say my data structure is having the zigzag traversal that i was asked to print and i can return this data structure and this is going to be my answer so the difference that i did from the previous question was i just maintained a flag variable which was like 0 1 0 every time i went on to the next level i just converted zero to one to zero and vice versa that is what i did so again we're going to discuss the c plus and the java code so you can see the c plus code on the left and the java people can definitely follow their code that's on the right them they're mostly identical so you can definitely catch up so initially we are given the root of the tree and we declare our data structure that's result and the tree is empty we're going to return the data structure which will never have any uh zigzag traversal right after that i declare the queue and i initially push the route right and we have a flag which is initially marked as true so basically over here what i'm done is true means left to right and the opposite will mean uh right to left that is what i have been doing over here right after that i travis in the queue so you know uh always we take all the notes of that level so let's take all the notes of that level and what i do is i run a for loop okay i'm running a for loop on all the notes of that level and what i'm doing is i'm basically taking it popping it out so if your cue for an example has 2 3 i will iterate on 2 and i'll iterate on 3 using this for loop got it right after that i check what i check is left to right true if that's the case like this 2 that i'm taking out i'll put it in the front of my data structure and after that i'll put 3 if the flag is true if it is not what i've done is i've smartly made sure that two will come at back then three will come right depending on this flag i'll either insert it uh from the front or i'll either insert it from the back simple enough right simple enough constructive and the rest thing remains the same i insert that into our vector or list and right after that i check left and right and i push it once i've done this entire iteration right i can always switch on the flags and i'll keep on the data structure whatever is on the row that's three two whatever is it i'll keep on the data structure once that is done i can definitely return my result so the thing that i did different from the previous uh level order traversal is this one flag and this while storing in a array or a vector whatever you can call it what i made sure is i made sure i either push it from the front or from the back that's that is the logical thing that i did in order to get the zigzag order traversal so what will be the time complexity again the time complexity is going to be big o of n similar to level order and what will be the space complexity that's going to be bigger of n similar to the level order traversal so i hope you've understood the entire explanation as well as the code just in case you did please make sure you like this video because it took a lot of efforts to make this entire tree series also if you wish you can definitely drop in a comment that will keep motivating me to make such further series also if you're new to the channel please do consider subscribing because i'm going to bring in such more series in the upcoming future as well with this uh let's wrap up this video let's speed in the next lecture bye take care whenever your heart is
Binary Tree Zigzag Level Order Traversal
binary-tree-zigzag-level-order-traversal
Given the `root` of a binary tree, return _the zigzag level order traversal of its nodes' values_. (i.e., from left to right, then right to left for the next level and alternate between). **Example 1:** **Input:** root = \[3,9,20,null,null,15,7\] **Output:** \[\[3\],\[20,9\],\[15,7\]\] **Example 2:** **Input:** root = \[1\] **Output:** \[\[1\]\] **Example 3:** **Input:** root = \[\] **Output:** \[\] **Constraints:** * The number of nodes in the tree is in the range `[0, 2000]`. * `-100 <= Node.val <= 100`
null
Tree,Breadth-First Search,Binary Tree
Medium
102
1,812
hello guys my name is Ursula and welcome back to my channel and today we are going to solve a new lead code question that is determined color of a chessboard Square we will be solving this question with the help of python the question said you are given coordinates a string that represents the coordinates of a square of the chessboard below is the chessboard for your reference return true if the square is white and false if the square is black so we have to return a Boolean value corresponding value with the byte is uh 2 and for black is false so the coordinate always the coordinate Will Always represent a valid a square bot chessboard Chase Port Square the coordinate would always have the letter first and the number second Okay so we will be given a string for example in question number one for example number one uh for example we have given a string and then we will be always given a string a character followed by a number and we have to determine whether it's a black one or a white square so if it's a black then we have to return false if it's white we have written true oh so how are we gonna follow how we are going to solve this question what will be our approach I will tell it to you so just before starting solving this question guys do subscribe to the channel hit the like button press the Bell icon button and bookmark the playlist so that you can get the updates from the channel so let's start so I will say that e C uh AC and first of all I will Target these four so why I am targeting these four so I will I'm explaining it to you that uh you see that on a c e and G they have all the means they if you see on A2 A4 A6 and A8 C2 C4 C6 C8 E2 E4 E6 E8 G2 G4 368 are all white so we will return by uh we will return true for these so let's do that and return true for this and else we will return false for these four values how we are gonna Target this I will say that if coordinates 0 so they are saying the coordinate always start with the letter first so we will Target later first so we can use this here because it will always start with a letter so if I say that if a letter is e or a letter is these so let's copy this to save our time copy and paste it four times or so let's change this to c change this to E and change this to G so we have targeted are these four values now we will see that again our nested if else condition here that if coordinates so the second condition they are seeing here is that it will be always the number second so we can Target a number here coordinate one and you will see that mod 2 is equals to zero because see these are all two multiple of 2 4 6 8 are all multiple of two so if we can uh use this for so we have to use it as an integer because it will not divide if it's a string so we have to convert this only thing here that is our coordinate one into integer so that we can see the modulus of 2 that's its mean even or not if it even then return true else return false so now we have targeted our R4 the four of these values so I will say that uh other the other than these values will be our else value so instead of this I will be targeting with values b d f h so b t e f h would be if I will write the same condition here that if int and coordinates again one uh is divisible by 2 means if it's divisible by 2 means this value h d f h so B2 D2 F2 S2 and so on I will say that return false just the opposite of that and else return true so that's all in the question hope you have understood it let's run the code and check the validity of our answer so we have quarter answer here thank you guys for watching the video if you have any doubt ask in the comment section
Determine Color of a Chessboard Square
reformat-phone-number
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have the letter first, and the number second. **Example 1:** **Input:** coordinates = "a1 " **Output:** false **Explanation:** From the chessboard above, the square with coordinates "a1 " is black, so return false. **Example 2:** **Input:** coordinates = "h3 " **Output:** true **Explanation:** From the chessboard above, the square with coordinates "h3 " is white, so return true. **Example 3:** **Input:** coordinates = "c7 " **Output:** false **Constraints:** * `coordinates.length == 2` * `'a' <= coordinates[0] <= 'h'` * `'1' <= coordinates[1] <= '8'`
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
String
Easy
null
374
hello everyone welcome to kodus camp we are 12th day of october lead code challenge and the problem we are going to cover in this video is guess number higher or lower it is again a easy category problems the input given here is an integer value n and we have to return the number we picked so the problem statement has a predefined api call the method named guess and this is going to return three possible values the numbers are going to be from 1 to n and if the number we sent to this method is exactly matching the same number then it is going to return 0 if it is less than the number then it is going to return minus 1 if it is greater than the number it is going to return 1. so we have to use minimum number of guess calls and guess the number the system has picked or we picked so let's understand this problem with an example so here is the given example the n is equal to 8 which means the numbers are from 1 to 8 and pick is not actually an input the system randomly picks a number and we have to find exactly which number the system has picked by using the guess call so what would guess written is 0 1 or minus 1 for example if we if the system picked the number 5 and we have to pass possible numbers to the guess method and find which number the system has picked for example if we are passing the number seven first the possible outputs will be zero minus one and one so it is definitely not zero because uh the number system picked this five and b cent is seven so if the number is less than the number the system has picked then it is gonna return minus one so obviously 7 is greater than 5 so it is going to return 1 so which means we can figure out 7 is greater than 5 so we have to search for the number which is less than 7 so we can put our search before 7 and look for the numbers for example if we send 3 as the second guess so the guess method we are passing 3 is not 5 so it is not going to return 0 but 3 is less than 5 so it is going to return minus 1 so in this case we can figure out the value is after 3 so how are we going to approach this the straight away brute force method would be calling the guess method from the number 1 to n that is 8 here and for every method it will be a number return for example minus 1 till 4 and guess of 5 would have 0 and then plus 1 till 8. so in this case whichever guess is having 0 that is the number the system has picked and we should return it this is a straight call and i try to brute force method that is going to take because n time complexity but how do we solve it in a better way clearly the input values are from 1 to n and they are in ascending order so this gives us a very clear clue that we can approach this problem using binary search so simply we are going to divide the input by half as usual and gonna find the mid so here the mid is going to be 4 and we are going to pass this mid value to our guess and based on the result of our guess method we are going to fix our search space so let's first fix the mid to 4 and try sending 4 to our guess method so as i said 5 is the number our program has been picked so we are going to first pass guess of 4 and guess of 4 would actually return us minus 1 which means our value is actually less than the value that the system has picked so clearly we have to fix our search space after 4. so we are going to move our left value to 5 because 4 is not our value we are searching for and right value stays the same so now our search space is between 5 and eight now again it's time to fix the mid value and pass it on to the guess method so here the mid value is going to be six we are going to pass guess of six so this is going to return one because 6 is clearly greater than 5 which means our search space must be before 6 so we are going to move our right pointer towards before 6. now our left pointer and right pointer point at the same number five which means we have reached the point where our guess is going to be zero so for confirmation let us send our guess back with five and that returns zero which confirms phi is going to be a number so 5 is going to be an output so the previous solution is much easier than this algorithm is going to work and big o of log in time complexity because of the binary search rule and we go of one space complexity so hope you're understanding the solution let's get back to the code so as i said let's fix our limits left and right to one and yeah and calculate our mid so every time we are going to call our guess method and store the result in the integer variables since we don't have to call it again and again at every if loop conditions so based on the result we are going to check if our result is equal to 0 then mid is the number we are looking for or the number that the system has picked if not we have to check so yes based on the result if the result is less than zero which is minus one then we are going to fix our search space before the minute if not we fix our uh left bound to after the bit if not we did not find the number at all then we are going to return -1 so yes that's it let's run and try okay let's submit yes a solution is accepted and we have done with our today's problem and the solution runs 100 faster of all java solutions thanks for watching the video hope you like this video if you like this video hit like subscribe and let me know in comments thank you
Guess Number Higher or Lower
guess-number-higher-or-lower
We are playing the Guess Game. The game is as follows: I pick a number from `1` to `n`. You have to guess which number I picked. Every time you guess wrong, I will tell you whether the number I picked is higher or lower than your guess. You call a pre-defined API `int guess(int num)`, which returns three possible results: * `-1`: Your guess is higher than the number I picked (i.e. `num > pick`). * `1`: Your guess is lower than the number I picked (i.e. `num < pick`). * `0`: your guess is equal to the number I picked (i.e. `num == pick`). Return _the number that I picked_. **Example 1:** **Input:** n = 10, pick = 6 **Output:** 6 **Example 2:** **Input:** n = 1, pick = 1 **Output:** 1 **Example 3:** **Input:** n = 2, pick = 1 **Output:** 1 **Constraints:** * `1 <= n <= 231 - 1` * `1 <= pick <= n`
null
Binary Search,Interactive
Easy
278,375,658
1,799
hey everyone welcome back and let's write some more neat code today so today let's solve the problem maximize score after n operations this one is pretty hard but it's not as crazy as you might think and if you're not super familiar with bit masks this is an opportunity to learn a bit about them no pun intended but we are given an array of positive integers and the fact that they're positive integers is only significant because we are going to be running the gcd operation the greatest common divider aka the greatest common factor if you don't remember what that is consider two numbers six and nine what's the greatest factor between them I think it is three because we can take six divided by three and it equals two we can take nine and divide it by three and it equals three so we get an integer in both cases and we can't really get a larger integer that will divide them and in this case they say the size of the array is actually two times n that's significant because we're told that we're going to be doing n operations where we are going to be choosing two elements from the array and basically removing them to calculate a score therefore we can only do about n operations until we run out of elements from the array because it's of length two times n so suppose we have an array that looks kind of like this how many operations would we do in this case three of course because let's say we're going to be removing two each time and we do that again and then we're out of elements but what we're going to be doing every time we remove two elements is calculating the gcd between them and I'm just going to tell you right now that we're not going to get super into that this is a math function and in the scope of this problem we're just allowed to call math.gcd because I think this problem is math.gcd because I think this problem is math.gcd because I think this problem is hard enough and in a real interview hopefully your interviewer would tell you that or you could just ask them but given those two numbers that we removed we would call gcd on them one and two find the greatest common divider which I believe in this case is one and as we'd make these n Opera operations we're going to keep track of how many operations we've made so if this is our first operation we're going to take the score or rather the gcd of the two numbers and multiply it by one because this is our first operation so far our score would be equal to one suppose we take two more elements three and four calculate the gcd between them three and four I believe it is also one in this case but this time we would take one and multiply it by two because this is the second time we are doing that operation and then we would take this two and add it to the score which would get us to a total of three so far and then at the end we would do that again and pretty much repeat that operation but the complicated thing here is that we have flexibility on how we want to calculate these gcds so we don't have to do it the way I showed we actually have choices we could start with one and six we could start with one and four we could start with three and four it doesn't matter we have a lot of flexibility but we want to find the way that maximizes the score so we want to find the max score we could possibly get doing it this way which is definitely not going to be easy I mean right off the bat you might think okay let's just try like The Brute Force way trying every single combination but you might think is there room for optimization here like is there some kind of math pattern behind it could we maybe sort the array or maybe numbers that are close together going to have a greatest common divider that's larger because that's probably what we want to maximize the score well once you start going down that train of thinking you kind of realize that even if there is a solution like that you must need like a math dissertation to figure it out so probably there isn't going to be some kind of crazy math solution and again if there is you probably just wouldn't be able to figure it out so then you might go back to the brute force and think if you can somehow try to optimize this but before we even optimize it let's just understand stand how we could even solve this in a Brute Force way because it's not trivial that's for sure okay so starting at the root of our decision tree because we are going to solve this recursively let's try to enumerate all possibilities how would that be like what's our first choice well we can choose any pair of values we could choose these two values we could choose this and this we could choose one and four etc how do we even enumerate those well we're going to need a couple nested for Loops right and doing that we realize that at the first layer of our decision tree we have about N squared choices that is not going to be very efficient right and when I'm saying n in this case let's say n is actually the length of the array even though in the context of this problem it means something else but I think it's more simple to just think about it in terms of n so we have N squared choices how many choices are we going to have well if we remove two elements on each choice and the length of our array is n the height of the tree is probably going to be n divided by two so overall here the time complexity is going to be N squared to the power of n divided by 2 which I think would be n to the power of 2 times n because I think this multiplies with this well I guess the divided by 2 cancels out the 2 here so this would actually just be roughly n to the power of n but clearly that's not super efficient that's even a lot worse than 2 to the power of n so this is not very efficient but there is something we can do to speed this up and the idea is caching yes this is a dynamic programming problem but it's not a traditional one we're gonna need a bit mask but first let me tell you why we can use a bit mask in the first place there is a constraint on this problem which is not shown here but it tells us that the length of this array is at most going to be 14. that's not a very large number at all now it's not enough to pass on leak code if you have a solution that's n to the power of n that's going to be a pretty big number but using this we can apply caching notice something about our decision tree here well instead of drawing out that entire tree I'm actually just going to show you on the arrays it'll be a lot simpler trust me let's say for one of the branches over here we chose one and two as our first choice and then maybe on our second choice we chose three and four that's one possibility let's say on another possibility though we chose one and three then on the second choice we chose two and four so even though we made different decisions in our tree we ended up at the same sub problem now the way we calculated the score when we took these elements and we took these elements definitely could be different I'm not saying the score is the same I'm saying after we make those choices the sub problem is the same so when we have to solve this sub problem why should we ever have to solve it again that's the idea that we can apply caching to because we see there's repeated work going on now how do we even Define this sub problem we can't just keep track of it in a single integer can we because here clearly we have an array so what should we do maybe we should use an array as the key of our cache and what that array would represent is for each element have we already used it or is it available to us so in this case we have six positions and we say for the first four they've already been used and for the second two and for the last two they are still available to us so that's kind of the information we need and yes you actually can use an array if you want to or maybe you could convert that array into some kind of a string if you want to that's like delimited by commas but the most common approach here is to use a bit mask because actually we can represent all of this information in a single integer and we can do it in an integer that's 32-bit because the integer that's 32-bit because the integer that's 32-bit because the constraint here is that the max size of the array is going to be 14. so we only need 14 bits 32 bits should be plenty for us so instead of using the array to Mark whether our value has been used or not we're going to have an integer that might look like this well it'll have more bits but we just care about the first six of them and when we use an integer like for example when we use these four we would take these and turn them into ones like this and this would evaluate to some integer I don't know what it is off the top of my head but it can be used as the key for our cache in my case I'm going to use a hash map but you could also use a array a one-dimensional array now lastly what one-dimensional array now lastly what one-dimensional array now lastly what are the parameters that we're going to keep track of as we make our recursive calls because remember not only do we have to keep track of which elements we've already used we have to keep track of what operation and we are currently on because that plays into the calculation we have to remember take that operation number and then multiply it by the gcd that we end up calculating each time so at that point you might think as we go down this decision tree we're keeping track of our bit mask but we're also keeping track of the operation number which at first might be one then on the second level might be two etc should we also use this as a key in our hashmap well think about it for a second and I'll tell you right now the answer is no because actually this operation number represents redundant information we don't need to use that as a key in our cache I mean technically you could if you want to I'm pretty sure your solution would pass the same as mine but it's redundant information let me tell you why going back to the example maybe on one branch I choose these two elements first on another Branch I choose one and three then for the second decision Maybe I choose three and four on one branch on the other Branch I choose two and four we ended up at the same sub problem this is what our bit masks would look like they would be identical and not only that the operation number would also be identical operation would be two here and it would be 2 over here because we have to choose two elements at a time if the sub problems are the exact same therefore we must have made the same number of operations here as we did over here so the operation number is redundant information we are going to keep track of it for the calculation but we don't need to use it as a key in our cache okay so knowing all of that what are the total number of possibilities that our key value could be well let's say this array is of size n and for each value we could either include it or not include it so we get roughly 2 to the power of n possible values that our bit mask could be so this is the number of sub problems and remember each time we make a choice we're making N squared choices on each level of the tree so we take that and we multiply this by N squared and that's how we get the overall Big O time complexity well technically we also have to compute the gcd which I believe is going to be log of the max number in the array so max of nums let's say but I think this has already deep enough for the Big O time complexity I would be surprised if you ever had to know things this in depth in a real interview so overall we would take this term and multiply it by this logarithm term but I think that's enough so now let's actually code this up so I usually start these DP problems with my depth first search and we know we're gonna have two parameters one is going to be the mask which is going to tell us which numbers are available and the second is going to be the operation number I'm going to call it op for short and the main base case believe it or not in this case is just going to be if this mask has already been computed meaning this is in our DP cache well let me just call it the cache because that's a bit more descriptive and I'm going to create that cache up above in my case I'm going to create a hashmap because it makes things more simple you don't have to know off the top of your head how many possible values we are actually going to be using as the key but like I said it's going to be roughly 2 to the power of the length of nums so if you wanted to create an array instead of a hashmap that would be the size of your array maybe a plus one to that but I'll keep things simple and use a hash map and if we have computed this subproblem before let's just go ahead and return the result that we ended up storing if not then we actually have to calculate it and we do that by enumerating all possible choices with a couple nested for Loops so for I in range length of nums and for J in range length of nums but remember there's a bit of a bug here we don't want to have to necessarily count the duplicate pairs so we should start our second pointer right after her the first pointer at I plus one and now's the part where we want to do our recursive call right but we can only do the recursive call for numbers that have not already been chosen how do we know if the number at index I has already been used how do we know if the number at index I and the number at index J have both not been used before well that's what our bit mask is for if the ith bit is one then that value has already been used before how do we figure that out well basically we take one shift it to the left by I and we take this value and we bit wise and it with the mask value so for example if our mask looked something like this zero and we wanted to know if maybe this value had already been used before we would take our one digit which is over here shift it to the left by two so like to put it in this position and then we would and these together bit wise and them together and we would get a one if both of them are one and we would get a zero if this is a zero so it works pretty much like you would expect it to so let's check if this has been used and let's also check if the other one has been used so one shifted to the left by J bit wise or it or bitwise and it with the mask and if either of those have been used before then we can't use both of them so therefore we're just going to continue to the next iteration of the loop okay but if they haven't been used before what should we do we probably want to make our recursive call and we probably want to pass in the new mask after we have marked both of them as being used so let's actually create a new mask after we have marked each of those positions which we can do like this mask logic or with one shifted to the left by I and then bitwise or that with one shifted to the left by J the difference between the bitwise and the bitwise or is that and is basically us reading the value when we bit wise or we're pretty much overwriting the value at that location now that we have the new mask we can pass that in as a parameter and for the second parameter we probably want to pass in the current operation number plus one but what exactly are we going to do with this recursive call what were we trying to do in the first place remember we were trying to calculate the score of the two values that we just chose how do we calculate the score of them well that's the part where we just use math.gcd and python because this use math.gcd and python because this use math.gcd and python because this problem is hard enough and we don't want to get super into the math so we're just going to call gcd on the two numbers that we are currently choosing and we say that's our score but remember we actually want to multiply this by the operation number as well it's easy to forget so try not to and then using that score we want to take that and add it with the return value of our DFS over here but this is just one possibility we are enumerating all the possibilities and trying to determine the maximum so what we're going to say here is the cash for this mask value is going to be the max of itself cash with mask as the key and whatever value we ended up calculating here let me clean this up a tiny bit so this is the recursive step where we try to find the maximum there's a tiny bug here though what happens if we try to access this value if we haven't already inserted mask as a key well we're going to get an exception throne and an easy way to fix that would be before we even start the loop Just Say Cash mask is equal to zero just initialize it to some value like zero but in even simpler way at least in Python would be just to make this a dictionary carry this hash map a default dict like this collections.default dict like this collections.default dict like this collections.default dict where the default value is going to be an integer so this will basically do what I talked about previously this will evaluate to zero if the key hasn't already been inserted yet now after this Loop has terminated we will have the max stored so let's go ahead and return it out here and finally now that we've wrapped up the DFS let's go ahead and actually call the DFS and return the return value our mask initially we don't even need to create a variable for this remember it's just an integer we can just pass in zero like this now for the operation number we're not starting at zero we're starting at one and then incrementing it each time that we call the DFS so this is the entire code Remember the Time complexity was roughly N squared for the for loops and the number of times we're going to be solving the sub problem and caching it is going to be 2 to the power of n and to actually calculate the gcd each time in the nested for Loops is going to be log M where let's say m is the max integer in our number array now let's run this to make sure that it works now as you can see yes it does and it's pretty efficient if you found this helpful please like And subscribe if you're preparing for coding interviews check out neat code.io it has a ton of check out neat code.io it has a ton of check out neat code.io it has a ton of free resources to help you prepare thanks for watching and I'll see you soon
Maximize Score After N Operations
minimum-incompatibility
You are given `nums`, an array of positive integers of size `2 * n`. You must perform `n` operations on this array. In the `ith` operation **(1-indexed)**, you will: * Choose two elements, `x` and `y`. * Receive a score of `i * gcd(x, y)`. * Remove `x` and `y` from `nums`. Return _the maximum score you can receive after performing_ `n` _operations._ The function `gcd(x, y)` is the greatest common divisor of `x` and `y`. **Example 1:** **Input:** nums = \[1,2\] **Output:** 1 **Explanation:** The optimal choice of operations is: (1 \* gcd(1, 2)) = 1 **Example 2:** **Input:** nums = \[3,4,6,8\] **Output:** 11 **Explanation:** The optimal choice of operations is: (1 \* gcd(3, 6)) + (2 \* gcd(4, 8)) = 3 + 8 = 11 **Example 3:** **Input:** nums = \[1,2,3,4,5,6\] **Output:** 14 **Explanation:** The optimal choice of operations is: (1 \* gcd(1, 5)) + (2 \* gcd(2, 4)) + (3 \* gcd(3, 6)) = 1 + 4 + 9 = 14 **Constraints:** * `1 <= n <= 7` * `nums.length == 2 * n` * `1 <= nums[i] <= 106`
The constraints are small enough for a backtrack solution but not any backtrack solution If we use a naive n^k don't you think it can be optimized
Array,Dynamic Programming,Bit Manipulation,Bitmask
Hard
null

LeetCode Information & YouTube Captions

Original data -> LimYeri/leetcode_with_youtube_captions

The original ['cc_content'] column had many repeated sentences, making the data too long.

To remove the repetitions, we used precise regular expressions to eliminate the repeated sentences. -> new column ['content']

Additionally, we also removed unnecessary strings (e.g., '[Music]').

Downloads last month
60