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 |
---|---|---|---|---|---|---|---|---|
54 |
That Aapke Ajay Ko Hua Hai Hello Everyone Welcome to New Video India Going to Discuss Another Problem Solving Its Problems Spiral Matrix Let's Get to the Problem Statement Problems and Write All Elements of Matrix in Spiral What Said We a Given the matrix and what we have to do is to make a spiral by retaining all its elements like if something melts like this then let's subscribe here and this is our Ghagra and put the subscribe event in an array and it has to return Let's take this example, a slightly larger example, if on our other side, 560 km 3 1415 66 Now if we give a spiral order for this, what will happen, first of all we will go to the right at the top, so what will it be 159 3538 and then here We from the right side because we will just assign 1111 after that here and after that we are going to go up but it's the word of already so we will do one here and it will be ours whatever the answer is so this Approach us by type, first of all, if we see what we have to do, first of all we go to the right side of the form, meaning first ride, then bottom left subscribe button, laptop, subscribe, then how do we try this question, first of all, we go to our potatoes. Unmute to minute question, when out of all the elements we have, how many if that element comes in ours, now we will cut it, okay if we take it, for this we will first have to form a government till one village here. Play list will be created from the beginning. Interior type is ok. Equal to new religions. Is this our New Year lace? Before that we will have to name it, then we would have given the address. Its name is ok. Now our list has been made, what do we have to do now? How many limits will we reach in our list till now * * * How many limits will we reach in our list till now * * * That as long as our mintu end is bigger or bigger than this, as long as our admin trend has increased, whatever is our answer list from that side. Till then we will run it, now what we have to do inside it, so first of all what we have to do is left-to-right, so before that, what will we left-to-right, so before that, what will we left-to-right, so before that, what will we do before declaring, here we do four more if If we see, what do we do to make rice in our village, so first of all, we do to make one, we do - on do - on do - on one here, after that, what do we have to do, now this is our left and right because we have and Now we will make one for the top and bottom, where will the top be ours, then ours will always be there, initially at zero, where will the top and bottom be, where will the water be ours - where will the top and bottom be, where will the water be ours - where will the top and bottom be, where will the water be ours - 151 - Now we will make some of our people last as long as we do this This disgusting oil which is our number of elements subscribe this is our ghagra on the side dots after that inside this we first of all we have to take this for 200 grams first class so see our concept here will be our stop content which is our center If there is a change, what will we do, if we keep it, then how will our collar work? Is equal to where from left side till subscribe liquid and this is our every update and inside this we have our which is our matric name laptop of our topic here. We will put in it like villages will be destroyed, set here there will be a white column about yourself, so here if we look here, our column will be SIM, for this stop, which slave will die from our column, the condition of the one on the right is that our It is changing every day and from where to where we will bring it, we will run it I request to where I request to top plus one stop plus one peel till it goes till this is ours it will run till ours which is ours till Our great daily want to, till then this is ours, we will update it every time and what will we do inside this, what will we add to it, what will we do this time, what is our change and here is our Who was I, what will happen to us here? Our matrix of whatever disease is ours, if it is changing, it will come here and if the column is our love, then which column will remain, whatever will be our light, then it will come right here. Okay, no issues, after that, what do we have to do, they will be like two fruits, so where will we reach, let me write clearly, yes, I have covered so far, we came from here to here and from here to here. Now where do we have to go from here, where do we have to take from here, so what will we do, now we will follow ours, from where we will follow ours, is equal to where I requested to right minus one will do if we go in this case See for this, the disease will be stopped here and from where to where, this drought will last - where to where, this drought will last - where to where, this drought will last - Dainik's left and right click, what will we do inside it, daughter, if our channel subscribe button is on, then we will add my matrix at the bottom. So let's add the matrix and the bottom as my, okay after that as it happens to us, what will we do here and here we have to keep one thing in mind that before wearing this, see if our left and right are equal. If it is not equal then we will run this but if it is equal then we will not cancel it. Here we will put our direct this if our send this also is our right that is not difficult in closed loop condition again this neck from this here we What will we do here, now we will start from where the top is going from, if we see the bottom was ours then we will go from the bottom minus one to where we will go from the bottom minus one we will go to these greater than the top why because if our topic was this then We will go to a bigger injection than that. If this is the injection we are going then from where to where we will go till our Gautam - 110 top. We will check here our Gautam - 110 top. We will check here our Gautam - 110 top. We will check here whether our topic is there or not then we will put it here. That if our top to bottom then what are we going to do then we will run our again from where to where 06 2012 - One 2012 - One 2012 - One Minus One that they got too much raw type butter problem what will we do we will run from bottom minus one to where till where will we run now We'll run this as long as we have this lucid end top, then go back to our eye lashes desktop, okay sorry, is greater than topper, and what we'll do is we'll decrement it by one every time, what we'll see inside this is that Our cry and problem is, who is our friend and which column is this left Olympian stand, what is ours is continuously changing, so what is our answer, what will we add to the answer dad, we will add matrix, add left. Which is our content three, our this is changing, so our I Komal, now we will add, so I Ko Majloom, okay, like you, this will be our end volume, what is ours to do, now if we share the value of these four, then what will we do, let's move the left to the right. We will do one right i.e. increase the left by one, after that, if we i.e. increase the left by one, after that, if we i.e. increase the left by one, after that, if we move one cigarette to the right, then we will increase it by one and remove the problem by one and till this our follow video viral ends, we will not get the answer as the value ends, that is our head. We will get it and we will attend it, so this was the approach, what do we have to do, we have to go left to right, then we have to go from top to bottom, then we have to take the right, then the border, we will do this continuously and every time tell us to reduce it by one. Will it go or will it increase depending on the situation? So let's go, first of all let's see its time complexity. If you talk about time complexity, how long will it last? If we see this is going on every time, Adam's Star and Letters and Answer Dot. Size, this is our order loopback and these people, how long is the loop running? Ours is running from high school onwards. Electronic means here, if you are on MS Word, then what will be our time complexity? Ignore of MSD R-N or you Ignore of MSD R-N or you Ignore of MSD R-N or you can call it soak off. Capital is which will be the number of elements, if we talk about its space complexity, what will it be? Now we are making a hair which will have how many elements and space complexity will also be there. If you are rough then I hope you understand this solution, how we If we will prostate this question, then let's go to your editor and quote this problem, then you are done, first of all, what are we going to do on our liter, first of all we have to return, then after seeing that, we will decide to return. Friends, if you are an international type then subscribe to us and we will do it properly on the internet. You must create it by name. This is a to-do list and we will not specify its size. Now we will create two variables. First, these people are our number off form. This trick to get is daughter and that is our number 90 a okay now what we have to do is here we got these two variables now we have to make 14 more which ones are left right top bottom so our left tilted in left this Whose is this giant which will be ours we will be the last one - 151 - top which subscribe bottom work below this - - work below this - - work below this - - verb - one now we will continue this till our number of element is more than ours then the answer is ok or no Issues: Now what do we have to do within this? or no Issues: Now what do we have to do within this? or no Issues: Now what do we have to do within this? Within this, first of all we have to travel for the crops. Okay, first of all, when we will be the drivers, then what will happen to us, there will be stoppages and problems, meaning if we see this slogan for the crops. What is there will remain constant, how if this is our matrix, if we are going right in the offices, then if we set our zero first time, then our stop will remain on top, that will be ours, so where will we go from where to where will Shyam run, where will the sexual path village be ours The pass will last for so many days and we will update it because we will have a spiral subscribe that in the war and in it we will add whatever will be our element where will be the matriculation of which will be our center jogi top and will our column come so this is our we We will keep adding, this from village to village, subscribe to our channel, so now we are here, even in the mean, our and our, where from where, our top plus one officer house, subscribe from Friday, I have copied this. Click on how far will we go or electronic want to bottom because now inside this we mean our so now what will we do now we on ourselves means where have we reached if we then now we here means here if I this now we See this here, this meaning will take - - - - that's why subscribe even take - - - - that's why subscribe even take - - - - that's why subscribe even today, this time we will come, so this time what will happen to us this time again our disease will remain the content, who is we in the bottom row Will go and our problem is change and from where to where right - right - right - I have presented this point to right - - right - - right - - Dr. Shyam, how far will it last until our channel is subscribed and what will we do? Subscribe to our channel and this is ours. Now as soon as this is over for you, where have we come? Ours is also over, this is also over and this is also over. This is also over. But before putting this mark, we will have to put one somewhere at the top and bottom, so there is no need for any formal form, it will be like this, if we copy and paste our Gautam, our festival is now within the above tip condition. From where to where do we have to go, whatever is our left soul, we have to go in waves from bottom minus one to Greater Noida, because if this element has become then it has been taken to a greater record - and - and - and now we have been appointed from above this - now we have been appointed from above this - and we have Before that, before that, top to bottom here, we have subscribed to here that here we have to go left-to-right, so we have to go left-to-right, so we have to go left-to-right, so we will put six here and next here but copying the same but do not do much modification, we will come here and Presenting it here, what do we have to do inside it, till the time our top 10 is not equal to the bottom - 151 - 110 has already been covered and we are ours, our villages. Subscribe to top - - Subscribe So this is the solution, let's run it now and see if there is any other hair like this Roy in it. A here written statement missing written statement If we have not retained then we will cut If we return the answer, then outside here we are our body, they should not be any other than this is ours, here is ours, twice, ours is that, let's see our first here, this is ours. Do n't forget to subscribe because ours will change. So this is our repeat subscribe and there should be no mistake should be accused for subscribe or the result comes 16 still this is our one element extra has come here 1234 8057 this is our subscribe see but if we see the president subscribe here Subscribe to your face, keep in mind that ours should be Gautam and on the bottom left and here we have seen this is our top and bottom part, they fragrance, the center has changed, let's present it that we cut it from the circle and There should be no doubt here when we press 'Now Thing Defined' should be no doubt here when we press 'Now Thing Defined' should be no doubt here when we press 'Now Thing Defined' because if we see when we go to left, right or then we go to Ghaghra, both AIIMS, this and this, then we are going to compare top-to-bottom top compare top-to-bottom top compare top-to-bottom top toe. We have to see whether our column on the left is not equal to the one on the right because if this column has been done once then we do not want this one to happen again then this is a mistake of our newly appointed Vice Chancellor - 110 appointed Vice Chancellor - 110 appointed Vice Chancellor - 110 Top Subscribe to our channel, don't want to subscribe, yes, this is our successful gift, whose runtime is one minute and short and which is fast, Amazon uses more space, so I hope you must have understood how we are working. Apart from how we are travelling, if you still have any doubt then you can comment in the comment section below. Thank you for watching
|
Spiral Matrix
|
spiral-matrix
|
Given an `m x n` `matrix`, return _all elements of the_ `matrix` _in spiral order_.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,2,3,6,9,8,7,4,5\]
**Example 2:**
**Input:** matrix = \[\[1,2,3,4\],\[5,6,7,8\],\[9,10,11,12\]\]
**Output:** \[1,2,3,4,8,12,11,10,9,5,6,7\]
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 10`
* `-100 <= matrix[i][j] <= 100`
|
Well for some problems, the best way really is to come up with some algorithms for simulation. Basically, you need to simulate what the problem asks us to do. We go boundary by boundary and move inwards. That is the essential operation. First row, last column, last row, first column and then we move inwards by 1 and then repeat. That's all, that is all the simulation that we need. Think about when you want to switch the progress on one of the indexes. If you progress on i out of [i, j], you'd be shifting in the same column. Similarly, by changing values for j, you'd be shifting in the same row.
Also, keep track of the end of a boundary so that you can move inwards and then keep repeating. It's always best to run the simulation on edge cases like a single column or a single row to see if anything breaks or not.
|
Array,Matrix,Simulation
|
Medium
|
59,921
|
49 |
welcome to august leco challenge today's problem is group anagrams given an array strings strs group the anagrams together you can 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 that's the definition essentially we want to see make sure that the number of letters that occur are exactly the same inside the word and then group together inside of a list and return it here with the list of words like this we group together bat nat and tan these two are anagrams and a e t these three are endograms and we can return these in any order so the key thing here is to figure out how do we know if two letters are an anagram or not now at first i thought i'll probably have to use a counter object and we can certainly go that route you can do that doing um you can do that and square it pretty easily but the problem is we want to do this as optimized as possible could we do this all in one pass the problem with using a counter object is it's not hashable we can try to use it but there's no way to hash it we can't hash list either because those things aren't hashable the only thing we can really hash are in this case strings or perhaps a tuple so let's start off how can we do this by creating a key that's going to represent every word well what if we just sort it one of the things you'll notice is well if we sort it in order it doesn't matter how it's arranged the sorted order is going to be the same for all of these right it's going to be a e t a t so let's go with that route first what we'll do is create a lookup or a default dictionary we'll have a list as our value and we'll move through our list 4s and sdrs we'll just sort our word so we'll do is say sorted and this will return a list so we're going to do is a string join and this will be our key this will be the key that checks to see if inside if it's inside our dictionary or not so we'll just use this put into our dictionary and depend whatever the word is and finally all we need to do is return then all the values inside of our dictionary so this should return a list uh all grouped together you can see it's all grouped together like this it's a different order than our expected answer but that shouldn't matter so let's go ahead and submit that and there you go so that works um time complexity is going to be n times k plus log of k because of this sorted right so can we do any better than that well really depends on what you mean by better this is good enough but we could also create a list okay with each index number representing the alphabet uh number so a is going to be 0 all the way to z which is going to be 25 right so what we'll do is create this array here and we'll just say 0 times 26 for every character and we'll have to move through every single character in our words so for letter in s what we'll do is just update the index number we'll just add one here and how do we get the index number we'll just use the ordinal function we'll take our letter and we'll subtract ord of a and this is going to give us if it's a it's going to be 0 if it's b it's going to be 1 so on and so forth once we have that we can just convert this to a tuple because remember tuples are actual not this so i'll convert this into a tuple and do the same thing append it like this so this would also work this would be n times k plus 26 to n uh for this array function and this also gets accepted it does seem a little bit faster so i suppose this might be the better way but it really depends on what you find more um i guess understandable but both work fine yeah so that's it uh one thing i'll uh one announcement i'll say is some of you might have noticed i've been a little inconsistent with my videos lately i've been going back into the office and uh just there's only so much time in the day that i haven't been able to prioritize this um i'll do my best to continue to be consistent maybe i'll make videos at the office eventually but until then please stay patient with me uh just thanks for watching my channel and remember do not trust me i know nothing
|
Group Anagrams
|
group-anagrams
|
Given an array of strings `strs`, group **the anagrams** together. You can 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:** strs = \["eat","tea","tan","ate","nat","bat"\]
**Output:** \[\["bat"\],\["nat","tan"\],\["ate","eat","tea"\]\]
**Example 2:**
**Input:** strs = \[""\]
**Output:** \[\[""\]\]
**Example 3:**
**Input:** strs = \["a"\]
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= strs.length <= 104`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.
| null |
Hash Table,String,Sorting
|
Medium
|
242,249
|
1,819 |
hey everybody this is larry this is me going over q4 of the weekly contest 285 a very hard problem for me anyway number of different subsequent gcds so this one there's actually a little bit of a thing as well i took a long time to solve this in general but i got two wrong answers be or too long two time limited uh exceeded answer in python uh for a reason that i actually wasn't paying attention until i switched to java um so and we'll go over that but this is a tricky problem but the idea is the sif of um uh i never know how to say it correctly but to see if i would ever start how do you spell it um okay everything's yeah okay but yeah this is what i would google on uh you're having trouble with this problem in general and just getting over um just understanding what this farm entails um but yeah um but basically the idea is that okay um it's just counting for each number um you know how many different pairings are there for a given i right um so for a given i how many gcds are there of i right how many subsets idea with a gcd of i um and that's basically the way that i did it um and this is roughly analog again given where n is 200 000 or maybe u log u if you want to call it that where that is the domain um so first of all we set off uh the frequency table but basically we count you know uh how many subsets there are with gcdfi and this is almost like um you know count together right um yeah so the cam we start with f sub i which is just the numbers that uh that we see but we also want to see how many numbers have um how many numbers have a um a divisor that is i right and here we start with two for example we go okay you know let's say i 0 10 um then we know that you know numbers that have a gcd of 10 would be you know with 10 would be 10 you know for because gcd of 10 and 20 is equal to 10 uh gcd of 10 of 30 as you go to 10 uh and so forth dot so that's basically what this does here um we count the number of counts and then we also count the number of overlaps that we already did um and of course we have to well we'll talk about the margin in a second but basically here we count the number of overlaps and what that does is that we don't double count numbers um so that if um if we you know do five later um here this is going to be five um and but the number of sets here we want to subtract you know we want to um this is just basically going to be um actually you know gc of 5 and 10 is 5 but we also want to subtract the you know the ones that are in 20 because then they overlap in that way and that because we already counted them and we don't want to double count um and then at the very end people are cheering near me i don't know why maybe it's because they just finished the contest as well uh anyway so then at the very end after we go for all of this after we go through max um then the number of overlaps of i so that we save it for the future is well this is just the number of subsets which are going to be used for the overlaps um but yeah and that's just number of count and this number of count is just the number of counts that are um of these numbers in array so f is the frequency table of all the numbers in the array so yeah that's just the numbers so now it counts all the numbers that have this number um as the gcd and for that as you can tell because for example if there are eight numbers then you can imagine that any um if there are eight numbers then you know you choose what um i is one of the numbers and then all the other numbers oh hmm i think actually another way i could optimize was making sure that this is greater than zero but um but that wasn't gonna be fast enough anyway um but yeah if you have eight numbers that contribute to this process then there's gonna be two of two to the eight minus one number of subsets because you have eight numbers and every number could be in the subset or not in the subset and then you minus one for subtracting out the case but then no numbers because that doesn't make any sense so basically you get this and then your minus overlap um and yeah and if this number is greater than zero we add the total because that means that uh there's a distinct i uh which is give you know the question asked an answer uh the answer asked in a question and then you just return the number of total um so this is roughly n log n this is uh i'm not going to go over that and that's just that much because this is something that's in the sif of uh sif say uh so you log you say and yeah and it's just something that kind of you just have to know it i know it but i'm not able to kind of explain in a quick way um short answer is the sum of the series sums to you like you um but you can you know for further research just google that out um but the tricky part is that if you do two to the count however count could be a really big number count could be say count you know count could be i don't know ten thousand right so if you have two to the ten thousand this is gonna be a really big number you're gonna use a big integer and that's when it times out um and so to get around this time out we added a mod um so that we added a mod so that um we bound the number of digits by a you know not as big of a number you bound it by smaller number um however you do have the risk of um getting a wrong or like a force positive um but you know they're raised around it i got lucky choosing a constant that didn't have any force positive but if i did then maybe i would have to do it in two places or something like that um but the idea is you know just like you know same thing with hashes and stuff like that and if there you go to zero then probabilistically the two numbers are equal and so forth um so yeah uh but you need this mod to kind of speed it up and yeah and this is why i have a python uh this is going to be n log n and of n space or of u space maybe because u is the maximum number that's in the list um and for my java friends i did support i did submit this problem in java so you know check it out here and this is actually i didn't think about this until i did it in java the mod thing this is why i did in java um because i was like oh this can overflow in java so then i actually wrote my own modpot uh my pow um to support it and yeah um and you could see me try to mostly copy and paste for my python solution um but yeah so if you're in java you know check out this solution um and if you want to check out the mod part is here but this is more standard so yeah um so the surf is the answer for this one let me know what you think i took me a long time was quite a i played around with a lot of different algorithms including um just like playing without around the devices trying to figure out different ways of doing brute forces in a smart way um but i guess i always knew it was gonna be the surf but it took me a long time to really figure out how to do it with the sif and going backwards and double counting and stuff um and you can watch me solve it live in the contest next thank you uh yeah one more uh thing because i wanted to go over um just looking over co-reviews and i saw just looking over co-reviews and i saw just looking over co-reviews and i saw some very clean solutions that were way easier than mine and actually to be honest that this is kind of what i was trying to think about how to do but i couldn't do it correctly um during the contest so that's why i got a really confusing answer so hope you stayed until now because the earliest thing um but yeah but looking good review just going right here this is again the sif um same algorithm that we talked about but this is the other way um where again the loop on the outer loop asks okay for an answer x what is the you know how um is there a way to get x as the answer um for some sequence of gcd and then basically here we just go through all the possible um multiples of x and go you know for if it's two you go four two four six eight and you look at all of them and then you gc them all of them together because if you gc more and more it would only give you possibility of seeing x um and that's basically the idea really um is that if uh because the minimum of this g would be x or zero i guess if it's not used but yeah but in this case but uh but yeah let's say you know g can has a minimum of x because all these numbers are multiple of x and if there is such two numbers such that they the gcd of two of them is equal to x or two or more of them is equal to x we increment and that's pretty much it now that's a really cool answer this is n log n of course as in uh um the sif or you log you in the same notation um definitely try to understand this one uh i even me i didn't do it during the contest right so you know don't feel so bad but definitely um yeah um because basically what this is saying is that okay for all multiples of two for example with x is two all multiples of two is there a gcd of you know some of or all of them because if all your mo because the more numbers that you add to a gcd the lower the gcd is but because your gcd will be at least two because there all multiples of x by definition where x is two um you know if you add if you see the all of them you'll get either two or none um so that's a two or a bigger number i guess that's what i mean to say and if there is an existence of them such that if you go to two then you increment um and that it's a really yeah i mean it's a really nice solution i wish i thought of it um because i did some crazy things and i even got two wrong answers and i do and stuff like that because i did it kind of inverse problem of this which is really confusing but um but yeah i think this is a very clear answer so yeah let me know what you think this is basically just a way of brute forcing or n square solution um kind of in a way by taking advantage of the um the time complexity of the sif which again i implore you to kind of look it up um yeah that's all i have and you can watch me solve it live during the contest next ah silly huh okay no mods on this one remember the match can't believe i forget too much um so uh don't have any idea yet don't tell me someone already got it this get seven from this what's up instead right i guess so i don't know if this is right so let's see do so ready that was my second attempt come on let me just print something okay no that's eight did i mess up something i guess so that's maybe just luck i don't believe this i don't think this is right i messed up on my assumption let's see how many people have gotten this so far oh people have gotten it already the mods suck that would have been like top ten oh well i think this is just luck to be honest but this is right for these answers this isn't even right but this is 5 10 this is 5 and 10 so that's also wrong do follow me all the answers are is it sufficient to look at every two pairs it's too enhancing no i don't think so yeah no actually this should be 40 and 2m stool so we could just remove this i guess two is an answer three is an answer five is an answer what are the other answers oh it's 15 40 and six and one hmm what if this was 10 now what if this was 12 then 2 would not be an answer then it'll be four so do what's the maximizer so is that too slow maybe i should have done it locally 17 so 17. no that's not what i want to do i said the number of devices that's just the number of unique points so what i want is 160 times 10 to the fifth 16 million should be okay maybe no i don't think that's right i mean that's right but i don't think that helps enough because but because at that point we're just hmm right so if only i didn't make those two mistakes i would be happier because this may be a hard one so sorry if this is a five then this has 10 disaster between so you can't really separate them so in this case it's not two so how do we take out the two so do divide and conquer well it's intersection of two numbers so three numbers will never make it a better answer so you're always looking look only looking for pairs of twos hmm so what i say the biggest number was 116. well now it could possibly give you a distinct number so if you have someone like this and then this then 2 times 5 is an answer foreign let me check on it so far a lot of people got it so i guess i'm just the only one stuck those two long answers are killing me so yes so oh just lost today also the two things not true allowing this and the answer is two times five which is three but it doesn't appear on only two of anything oh that's not true is it don't know i have an album but i don't think it's i don't know if it's right also just because you have this doesn't mean that this is not a correct answer for two i'm a furious heart so uh hmm that's not right whoops should be fast enough but it's twice as fast come on uh is that the same case maybe nope i mean it seems fast enough but i need to do one more optimization i guess hmm why is this that slow and this shouldn't be that slow this is this is mostly zero so i have to optimize this a little bit 22 minutes optimizing everything is such a terrible penalty hmm uh if this is right it should be okay so oh pretty fast but not correct unfortunately oh i forgot to fold up it's just the right answer it's pretty fast but um this is gonna overflow so i need to be smarter about it that's probably why it uh time's up in python ultimate yeah this is definitely wrong as a result um really fast so okay standard easy mod powering travel other than picking that's annoying so do oh um that's not right unfortunately why is this too slow 0.31264 0.31264 0.31264 missing four yellow that was a hard one for me i don't know a lot of people got this one so yeah thanks for watching hit the like button to subscribe and join me in discord hope you had a good contest i had i did okay i was q4 was a little bit tricky for me but yeah let me know if you have any questions draw me on discord and i hope you have a great rest of the week rest of the month take care of yourself take care of others stay good stay healthy to good mental health and i will see you next problem bye
|
Number of Different Subsequences GCDs
|
construct-the-lexicographically-largest-valid-sequence
|
You are given an array `nums` that consists of positive integers.
The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly.
* For example, the GCD of the sequence `[4,6,16]` is `2`.
A **subsequence** of an array is a sequence that can be formed by removing some elements (possibly none) of the array.
* For example, `[2,5,10]` is a subsequence of `[1,2,1,**2**,4,1,**5**,**10**]`.
Return _the **number** of **different** GCDs among all **non-empty** subsequences of_ `nums`.
**Example 1:**
**Input:** nums = \[6,10,3\]
**Output:** 5
**Explanation:** The figure shows all the non-empty subsequences and their GCDs.
The different GCDs are 6, 10, 3, 2, and 1.
**Example 2:**
**Input:** nums = \[5,15,40,5,6\]
**Output:** 7
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= nums[i] <= 2 * 105`
|
Heuristic algorithm may work.
|
Array,Backtracking
|
Medium
| null |
109 |
foreign so before starting the video what I want to tell the main motive of this video is to solve this question to approach this question in a very simple manner video okay so what is the main mode I am able to solve this question the way I approach this I want to deliver that part only in a very simple and Innovative manner okay so let's try to understand the question given the head of a link singly linked list where elements are sorted in ascending order okay convert it to a height balance binary search tree okay let me write my observations are very important for every question okay so linked list New Year linked list binary search stream okay reverse okay and sorted in manner of ascending order these are my observation till now let me give you an explanation of what is a height balance binary string so what is a height balance biology so this definition is given by lead code only a height whereas binary tree is a binary tree in which the depth of two sub trees of every node never Divorce by more than one okay so if I take a tree one two I am simply taking a binary to explain you three four five so for every node I will try and check the depth of every two subfreeze if those if the difference of those that are greater than one so that is not a high balance trees okay so yeah zero difference zero minus zero is zero okay right now okay uh foreign okay four foreign where the height of left sub tree and right subtree the absolute difference of them is greater than or greater than one okay equal to one half valid less than one valid so we need to create a tree in this manner like the tree the resulted tree uh should be a height balance tree okay so let's see this example okay so linked list okay observation observed what I observed from this example okay and what I observed is a mid area that become my root of the tree node okay so observation mid is equal to root foreign so what I did what I approached I given an input to lead code only and at the beginning I return null from my code so lead code provided me an output for this even length Okay so this is the input I given to lead code okay minus one okay these are the elements of my uh linked list and for even length the mid will come let me six by two will become 3. okay so as per me if I go to above observation for even then the mid should be the root of the BST should be 4 okay but when I try it with liquid the leak could give me an output of six okay so this thing we need to try ourselves okay that as per question requirement we need to make the root as a second mid element so 3 plus 1 element okay so 6 by 2 is 3 and I need the second mid this is my first mid let me remove this and this is my second mid okay so three plus one is more four kubernetes okay so now we need to discuss how we will find the okay before finding out the mid first I want to tell as part of this question if the question you are approaching is of type of trees okay try to approach the quotient in uh in the manner of recursion to minimize the number of or to minimize the lines of code you will return and recursion will simply create a tree for you so if the question you are solving is related to tree or something try to solve that kind of question try to think in manner see how I can write the code recursively okay this is tips now okay so what I observed from this is foreign contain the greater value than root element left subtree will always contain smaller than root right sub trees will always contain greater than root okay left May equal to values either choose left either choose right as per you if you are comfortable okay choose any part either left either right okay six elements either minus one two four foreign this one two four minutes left that is minus one ll2 okay which was eight and ten in even case what we seen what we observed here the second mid is my root value the second mid die guys got 10. simply 10 okay elements are left side okay left side elements foreign so let me try to observe this with my final answer okay J1 over 6 210 minus 1 4 here sorry okay you can try it yourself like putting this question into your lead code okay so yeah okay let me uh give a try to the above example as well above examples minus 10 minus three zero five nine minus 10 minus 3 0 5 9 okay ll1 or LL 2 my divided minus ten comma minus 3 these are simply my observations okay how I can approach this question okay I simply return I created to link list five and nine left me ll1 right now foreign exactly what we created okay now the question came here is how to find out mid night okay minus okay let me copy this only okay so we know about fast and slow pointer so if I need what I need 6 here 6 as my mid but if I uh if mid is 6 how I can find this link list now ll1 or LL 2 May divide English foreign this is my right sub tree this is my left subtree now as this is a single linguished I cannot go back so I need to stop here I can do this node dot next is my mid and this dot next door next is my ll2 this I observed key if I want to find mid and I want to break it into ll1 and nl2 I can know store here because I cannot go back so I need to stop here and after that I can find out my menu okay so these are my observations so if I now I try to use fast and slow pointer to calculate the mean so fast here slow here okay fast will go two step side so first time here slow came here fast name here slow game here now fast is pointing to null slope came here slow is finding two six do I want this 6 as my slow pointer to return as mid no I want four so over to overcome this ah problem I can maintain a previous pointer previous will store the previous value of slope first it will store null then this low pointer value then this reference and then this reference when stop when slow gets stopped previous value stored the previous value of slope so I can return simply previous in this case so in this case now I am able to know how to find mid okay I know how to find mid then I know how to divide ll1 and ll2 simply and then I will generate the binary search tree recursively that's it that is what I need to do let me show you a code once so you get an idea if you do not want to see the code you can stop the video here and try to write out the code by yourself if you get stuck continue the video okay let me give you a walkthrough of the code so this is my given definition of the like this function I need to return from this function only sorted list to BHD simple base case I created a function generate BST here I simply written a base case if head dot next is equal to null then I need to if my linked list contains only single element so this sorry let me create in this manner this is my linked list that's it the next is null so if it contains a single element I will return this only one so if head dot next is equal to null so return new tree node where I put it the head dot value that's it okay I found out the mid using get mid function let me give you a walkthrough first of get mid function so what does get mid is doing if head is null this is my base case simply return null I created fast pointer I created slow pointer I created a previous but this previous Loop previous will store the previous reference of slow so when fast is not equal to null and fast was equal to null I will jump my first two pointers two steps ahead slow one step ahead and previous will store the previous reference of slow I will return previously that's it my get made function is done now I came again okay so root what I told you in case of one two and three this is if this is my link finished one two three get mid will return this okay now I need this as my mid because mid is equal to root as we observe so what I did I created a tree no root new tree node where mid dot next dot value is my root this is my mid as per get made function as per get mid function this came as my mid but I want this as my root value so mid dot next okay I created rule Now list node right and let's not left I need to create ll1 and ll2 what we observed about we need to create that ll1 and ll2 ll1 is nothing from head to previous okay if my linked list is nothing 1 2 3 4. and 5. in this case previous will come at this from get made function this is my mid from previous dot next okay now this is my head of the linked list so ll1 become okay so how I can do this so to create ll1 and llt how I can create ll2 I need to break connection with previous one so ll2 is nothing previous dot next and list note right is equal to .next now this will become my ll2 .next now this will become my ll2 .next now this will become my ll2 now how I can create ll1 I need to break connection till here so previous dot next I can create null so mid dot next consider this mid as I am saying previous because here I written the previous dot next is equal to none okay then I am doing the recursive pull here and here root dot left is equal to generate BST where I sending ll1 and here I am sending ll2 that's it at end I will return the root here thank you very much for watching this video If this video helped you please like And subscribe okay thank you very much
|
Convert Sorted List to Binary Search Tree
|
convert-sorted-list-to-binary-search-tree
|
Given the `head` of a singly linked list where elements are sorted in **ascending order**, convert _it to a_ **_height-balanced_** _binary search tree_.
**Example 1:**
**Input:** head = \[-10,-3,0,5,9\]
**Output:** \[0,-3,9,-10,null,5\]
**Explanation:** One possible answer is \[0,-3,9,-10,null,5\], which represents the shown height balanced BST.
**Example 2:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in `head` is in the range `[0, 2 * 104]`.
* `-105 <= Node.val <= 105`
| null |
Linked List,Divide and Conquer,Tree,Binary Search Tree,Binary Tree
|
Medium
|
108,2306
|
15 |
for some reason this problem is asked in a lot of coding interviews and I believe that is primarily because it is an extension of the problem too firm which is already a very famous problem if you know about it so what is so special about it let's find it out Hello friends welcome back to my Channel first I will explain you the problem statement and if you look at some sample test cases going forward we will see how this problem is similar to the two sum problem and how can we come up with an efficient solution just by a very small modification after that we will also do a try and of the code so that you can understand and raise your life how all of this is actually working in action without further Ado let's get started first of all let's make sure that we are understanding the problem statement correctly in this problem you are given an array of integers and you have to find out all the unique triplets such that their sum is equal to 0 correct and there is one more condition you cannot choose the same index twice right so it simply means that if you have chosen an index then you cannot use it again to find the total sum as 0 so given all of these conditions you have to find out all of the possible triplets so let us look at our sample test cases in our first test case you can see that I have this array right now what are some of the triplets that when summed will give you the total sum as 0 first of all I can find a triplet as minus 1 and 2. if you add all of them you will get the sum 0 correct and similarly you can get one more triplet that will be 0 1 and -1 and -1 and -1 this particular array will have two unique triplets by which you can form the total sum as 0 right so for this particular test case these two triplets will be your answer in your next test case you have three elements that is 0 1 and 1. so this is the only triplet right and if you sum all of these elements the sum will not be zero right so for this particular test case an empty list will be your answer correct now let us look at our third test case you can see that once again you have an array and all of its elements are zero right now I know that it says that these elements cannot be duplicated but if you notice we are not duplicating the indices correct only the element is duplicated so even if two elements have the same value and they are at different indices you can pick them so one such triplet that can be formed will be 0 and 0 right if you add them all up you get the total sum as 0. so for this particular test gift only this triplet will be your answer if you feel that now you understand the problem statement even better first feel free to try the problem on your own otherwise let us dive into the solution before we begin to solve this problem I want to let you know that this problem is based on a similar problem to some where you are given an array and you have to find out two integers whose sum equal to a Target value and once again that is also a very important interview question it is asked by almost every company out there so if you're new to that just stop this video right over here and try to First understand that problem because on that efficient solution we will come up with an efficient solution to this problem as well anyways we will also go over that slightly even in this video as well but if you're new to it just watch that video first so coming back to this problem you are given a sample array right and to find the triplet what is the most naiveic or The Brute Force way that you can think about it so the most naive way would be that okay you pick up two elements and then you will try to add them and then pick a third element so first of all you pick one then you will try to pick two then minus 1 and then minus 4. so these are all the possible triplets and then you are gonna sum them and see if the sum is 0 right if yes cool you found a triplet then what will you do instead of picking 0 this time you will pick one and then once again you will start to find out all the possible triplets right and certainly this will give you all the possible combinations and ultimately you will be able to find out the possible triplets but this approach will have a Time complexity of order of n Cube and certainly that is not desired right we want to find a better approach to solve this problem so what can we do about it this is where I want you to take a recap and realize what did we do problem our original and what did we do we spotted this array correct and as soon as you sort it you get your array something like this right and let us say you have to find out two values which when summed up give you the target value of -3 correct so what was target value of -3 correct so what was target value of -3 correct so what was the approach over here you sort the array and then what did we do we took two pointers first in the beginning and then at the very end then we sum both of these values so my current sum will be minus 4 plus 2 and that is minus 2 right now since this target value this is smaller than my sum right that means we have to pick a smaller number correct and how did we pick a smaller number we moved our right pointer one space backwards right and that is how now you will try to get the sum as minus 4 plus 1 and that will be -3 for viola you 1 and that will be -3 for viola you 1 and that will be -3 for viola you found your pair right if you add up minus four and one you will get your answer and this solution worked in an order of end time complexity right so you can see that using two pointers you can find the pair in order of n time correct so just try to keep this in mind and based upon this we will build an efficient solution to our actual problem threefa so once again I have a sample array and what did we do first of all we sorted it as soon as we fought the array your array will look something like this correct and now we have to convert this problem to the twosome problem right so here is something that we can do what we can do is we can pick our first element to be minus four right so out of the triplet we get one value or we fix one value that one of my values will be minus four right and I make a condition so one of my value is -4 right value is -4 right value is -4 right and what if the array that I'm remaining with this entire array right now notice what your problem has reduced to using this array you can once again take a left pointer and a right pointer correct and you have one value that is fixed for now instead of finding the pair you have to find that pair plus this fixed value and your total sum should be 0 right so you will apply the same approach as your to some question and what we're gonna do we will take the minor 4 value and then try to find a triplet such that when I add these three values my total sum should be 0 correct just wait for a little while and all of this will start making sense for this particular condition when you are choosing your first value as minus four you will not find any fetch triplet correct so this part is done now try to understand you took care of all the triplets that could start with minus four right now you have to move ahead so what do you do this time you are gonna choose minus one as your fixed value right that is the value at the first index correct so I fix my value -1 and then what is so I fix my value -1 and then what is so I fix my value -1 and then what is the array that I'm remaining with I am remaining with only this array now right so I have my array over here correct so once again your problem changes now the fixed value is -1 and once again now the fixed value is -1 and once again now the fixed value is -1 and once again you will take two pointers left and right and then you will try to come up with a pair plus this minus 1 value and the sum should be 0. so this should give you some triplets right so you have a value minus 1 and then what can you do you can try to find a triplet minus one and two that will be 0 and then if you move ahead you will find one more triplet minus 1 plus 0 and then 1. that is once again equal to 0 correct so you found two triplets that one added give you the sum as 0 correct I hope it has started to making a little bit sense so let us keep moving ahead so this time I'm done with this minus 1 again and if you see I have one more minus one for this time I'm gonna fix this value as my constant value and what is the area that I'm remaining with I am remaining with 0 1 and 2. so once again my problem reduces to 0 1 and 2 and I will take a left pointer and a right pointer and this is my fixed value so once again I will try to find a pair along with the sixth value and try to get the total reward as 0. this time I will get one more triplet that is minus 1 plus 0 plus 1 and that is equal to 0. just keep moving ahead now so now I will fix my next value that is 0 so I fix it and what are the remaining values 1 and 2 so this is my new use case that I have to work with and if you realize this will once again not give me any triplets so while going through all of this how many triplets did you find you found this and this so there are three triplets right since the problem asks you for Unique triplets you can add all of these triplets to a hash fit in a hash fit all the duplicate values will just go away right you cannot have duplicates element in a hash fit so once you add all of these elements to a hash fit this duplicate triplet will just go away right and what are you left with you are left with your answer and these will be your unique triplets for now try to realize what is the time complexity of this problem right so you know that the time complexity of two sum approach is order of n right where you're starting with the left pointer and a right pointer and along with that what are you doing every time you are fixing one particular value right so that multiplies it by n as well correct so what you can say is the time complexity of this problem will change to order of M Square so let us quickly do a drawing of this code and see how it works in action and you will be able to see the time complexity being order of n Square as well on the left side of your screen you have the actual code to implement the solution and on the right I have my sample array once again that is passed in as an input parameter to the function threesome oh and by the way this complete code and its test cases are also available in my GitHub profile you can find the link in the description below moving ahead with a dry run first of all we do some sanitary checks that if the array length is less than three certainly you won't find any triplets so just return an empty lift correct now what is the first thing that we do first of all we sort our array right so when I fought it my array starts to look something like this and then we are gonna create a revert fit that is a hash fit and it will store all of my triplets now try to look at this for Loop and try to remember what we're doing we fixed one value at a time correct so we'll run this loop from 0 and go all the way to length minus 2 that is because you have to pick three values at Max right to form a triplet so first of all you will fix this value then you will fix minus 1 then minus 1 again and then 0 and that is where you stop because to have a triplet you need at least three values if you fix minus one then you cannot achieve a triplet once again so you have to stop just before that and that is where you only go to Every length minus 2 right for now try to focus on this for Loop and see what is happening we fixed our first value as minus four okay so that now you need your two pointer so first of all you have your left pointer that is pointing at I Plus 1. and then you have a right pointer that is pointing at area length minus one right so what just happened you converted your problem to a two sum approach right where you fix the element minus 4 and then you have an array with the left and right pointer after this it is very easy you start a while loop and in this while loop you will try to sum all of these three elements if the sum is zero well and good you add all of these three elements to your result list otherwise if the sum is less than zero that means you have to increase your value right so you do a left plus else you will do a right minus this is the basic approach to finding a pair that equals a Target value correct for now once this Loop goes on happening you will get all your triplets values over here and since this is a hash fit this won't have any duplicates right and as this Loop ends what you do you return this result as an error list which is actually required by your function definition right now if you notice the time complexity of this solution if order of n square and the space complexity of this solution is order of n because you are not taking any extra space to arrive at a solution I hope I will be able to simplify the problem and its solution for you as per my final thoughts I just want to say that this is one of those problems where the best time complexity you can get will be order of n square and I know that when you see a Time complexity of n Square you think that hey maybe I can improve it a little bit so that is where your key Concepts come in very handy you realize right how we built a solution on top of the two sum approach correct so that is how you can be sure that order of n square is the best and complexity you can get for this particular problem and also note that this problem can be asked in a lot of different variations instead of finding the triplets that equal the value 0 you could be also asked to find triplets that come to the closest of a certain Target value and I think that the next video I will be covering would be on that problem itself but until then did you face any problems while going throughout the video or have you found any other such problems which work on the same concept or which extend the functionality of the two film problem so tell us all of that in the comment section below and it would be helpful for all of us as a reminder if you found this video helpful please do consider subscribing to my channel and share this video with your friends this motivates me to make more and more such videos where I can simplify programming for you also let me know what do you want me to follow next until then see ya
|
3Sum
|
3sum
|
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`.
Notice that the solution set must not contain duplicate triplets.
**Example 1:**
**Input:** nums = \[-1,0,1,2,-1,-4\]
**Output:** \[\[-1,-1,2\],\[-1,0,1\]\]
**Explanation:**
nums\[0\] + nums\[1\] + nums\[2\] = (-1) + 0 + 1 = 0.
nums\[1\] + nums\[2\] + nums\[4\] = 0 + 1 + (-1) = 0.
nums\[0\] + nums\[3\] + nums\[4\] = (-1) + 2 + (-1) = 0.
The distinct triplets are \[-1,0,1\] and \[-1,-1,2\].
Notice that the order of the output and the order of the triplets does not matter.
**Example 2:**
**Input:** nums = \[0,1,1\]
**Output:** \[\]
**Explanation:** The only possible triplet does not sum up to 0.
**Example 3:**
**Input:** nums = \[0,0,0\]
**Output:** \[\[0,0,0\]\]
**Explanation:** The only possible triplet sums up to 0.
**Constraints:**
* `3 <= nums.length <= 3000`
* `-105 <= nums[i] <= 105`
|
So, we essentially need to find three numbers x, y, and z such that they add up to the given value. If we fix one of the numbers say x, we are left with the two-sum problem at hand! For the two-sum problem, if we fix one of the numbers, say x, we have to scan the entire array to find the next numbery which is value - x where value is the input parameter. Can we change our array somehow so that this search becomes faster? The second train of thought for two-sum is, without changing the array, can we use additional space somehow? Like maybe a hash map to speed up the search?
|
Array,Two Pointers,Sorting
|
Medium
|
1,16,18,259
|
759 |
hey what's up guys John here today let's talk about another leader called problem number 759 employee free time and it's its markets hard yeah I think I don't know if it's a really hard problem where it's like I need to meet you like a more like medium to hard problem since the I mean the thinking process is pretty straightforward I'm gonna go give it my own like your upload so I think it's as long as you understand the problem I think it's not that hard to come up with a correct solution right so basically you are given like a list of array I'm sorry list what am I saying a list of schedule it's a schedule and a list of the in interval object right so each element will be the like a list of the intervals basically each employees right so each element in the schedule is for each employee for a particular employee and that element inside there'll be another list of different intervals for that employee that's gonna be hit like working intervals right and you need to find the common positive Lance common positive like free intervals for all the employees so what does that mean right so let's take an example here this is for employee white right this is very employee to be for employees three okay so this employee one and two for employee one the free for employee one is from time three to four right and how about the how about a 1 and a 3 right so 1 3 it's there's no free time here there's there is free time from 3 the free time from here for free employee to will be from 3 to 2 to the end right to the end and for employee for the 44d sorry for employee 3 the free time is like it's from 1 to 3 right and we need to find the common area so basically the common time that all the employees are free all right so how do you think about how do we think about this problem right you know I think this one is very similar I see at emerge intervals other merging intervals problem so all we need to do is we sort basically we sort out intervals it doesn't really matter how many employees right because with even with the same employees the advance for the different intervals they cannot be overlap to each other so I just as if there's another like employee with dislike employees so it doesn't really matter how many intervals for per employee all we need is all the intervals interval pairs and then we do what we do sort restored other two pairs by the first by the start time basically by the start time and then we just start from the first element right in every time and every time if - if the current element if the time if - if the current element if the time if - if the current element start time if the current doubt start time it's greater right it's greater than then the end then at the end time so we'll be maintaining the end time right if it is then we know we have a gap right for order for all the employees because we restored everything right we sort everything and we know the next one um the next one will be the earliest one right for all the employees and then we know we will find a gap for all the employees then we just add this like this.what so the gap will be what the this.what so the gap will be what the this.what so the gap will be what the gap will be a with anytime right to this current time right to this current dot start time right and we just keep we keep traversing all the intervals and in the end we'll have the our answer right for the intervals here and see no notice here right let's see here well there's like return the list of a finite intervals representing so here this one finite right as we said so for the intervals right so what does that mean it means that for a number for the let's say for employee three right the free time for the employee 3 is 1 2 3 + 1 + 10 to for the employee 3 is 1 2 3 + 1 + 10 to for the employee 3 is 1 2 3 + 1 + 10 to the max to the into the infinite the to the max to the into the infinite right to infinite time and we'll be discarding this hope this will be discarding this infinite time because all we need is the invite in infinite time so that makes sure we can only all we need to do is just consider the intervals which we can just ignore the others right okay so let's try to code this thing right and first like what we discussed will be sorting the all the intervals based on the start time right and since we're using Python here or its we can use this right interval for schedule is for each schedule right and for like each interval in the schedule right we do what we always sort right with your key so lambda right them that we do a axe to what axe start right start that's because each of the adamant here will be a interval object and which you start to sort right and then okay so first we're gonna create the hamster right answer will be like a array half list and then we'll be maintaining an end time here right so what is the end so we'll be starting at the end time so the end time will be starting at the first interval right because we know that's our first end time right so it'll be intervals 0 right dot and right so that will be the starting point of the end and since we already have the first because we need to start from the second intervals otherwise there won't be any finite free intervals right free time intervals so for I in range a length of intervals right we just start from that intervals and will be starting from one basically rights since the zero is ready we should start from one and then I'll be doing your intervals right then I right so basically all we need to do is here is if right if the current interval start time right the start time is greater than the then at the end time right then we know okay we find a gap right if we simply append the okay since we're returning like a list of intervals so we're going to append a new intervals object here so this start time will be the end right and the anti will be the start interval star so that's the interval basically right and then every time when we find a new intervals will be we'll be maintaining the end time right basically we'll do a two what we do a max right Max and current end and the interval tau n right and then in the end which to return the answer that's route to it so why we're doing this right because let's say there's a like a interval here right this is like interval starting from 1 2 to 10 right that's the first let's say that's the first intervals since we're starting from that right and then the second time let's say this we have another second another intervals from 2 to 5 right because right yeah sorry I'd say this is for employee one right this is were employed too because for one employees there cannot be two intervals that got overlapped right so it's for employee 1 is 10 and 12 2 to 15 like for employee to let's say it's 2 to 5 and something else right and then since we're sorting by the start time so the first one will be we've got would be executing is the this interval 1 to 10 right and then when we see this interval 2 here we see ok so is that is the end so first we see that the start time is it's not it's smaller than n so see so which means the way there won't be any intervals right a three time intervals and in the end we'll be maintaining this end here basically so in this case right in this case the number one and from 1 to 10 in this case 2 to 5 we see ok the farm is not bigger than later than 10 so at the end time for after finishing this interval is still 10 right but let's assume you know the if this interval is 5 2 to 2 I'd say if you seen The Voice two to four eleven here right so what does that mean it means that okay so once we are seeing this interval this like job here right it's like interval two job we see oh so for this one to be finished we have to wait until eleven right in this case the end time after seeing this interval will become whoever is bigger all right and then the next one three will be based on this end time that's how we can get the in the result right basically we start we restored by the start time and then each time we see a end we check okay if this we first we'll check the final with if there's a like free time interval second we are every time we see like a new intervals we just updating this end time so that the next one can be presented the correct end time to check the other intervals right and oh we haven't run it yet let's see and there's a oh yeah sorry so here should be sorted okay sorted this here yeah sorta that's that yeah all right cool yeah work so past basically the idea here is that we have to basically flatten all the intervals regardless of whose which employee it belongs to which is sorted all the intervals by the start time right and then since we have all sorted in the intervals we'll be processing that one by one and every time we'll be would be up keeping the what's the end time we have been we have seen right and then basically what's the last end time and then if the current schedule has a gap between the start and the this the previous the end time the previously end time then we know the there's a like announcer yeah I think that's everything I think for this problem I hope I explained it clear enough for you guys to understand it and yeah let me know if you guys have any question or suggestions thank you so much for watching the video and I'll see you guys soon bye
|
Employee Free Time
|
set-intersection-size-at-least-two
|
We are given a list `schedule` of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order.
Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted order.
(Even though we are representing `Intervals` in the form `[x, y]`, the objects inside are `Intervals`, not lists or arrays. For example, `schedule[0][0].start = 1`, `schedule[0][0].end = 2`, and `schedule[0][0][0]` is not defined). Also, we wouldn't include intervals like \[5, 5\] in our answer, as they have zero length.
**Example 1:**
**Input:** schedule = \[\[\[1,2\],\[5,6\]\],\[\[1,3\]\],\[\[4,10\]\]\]
**Output:** \[\[3,4\]\]
**Explanation:** There are a total of three employees, and all common
free time intervals would be \[-inf, 1\], \[3, 4\], \[10, inf\].
We discard any intervals that contain inf as they aren't finite.
**Example 2:**
**Input:** schedule = \[\[\[1,3\],\[6,7\]\],\[\[2,4\]\],\[\[2,5\],\[9,12\]\]\]
**Output:** \[\[5,6\],\[7,9\]\]
**Constraints:**
* `1 <= schedule.length , schedule[i].length <= 50`
* `0 <= schedule[i].start < schedule[i].end <= 10^8`
| null |
Array,Greedy,Sorting
|
Hard
| null |
1,007 |
hello everyone Alico today our question is minimum dominos rotations for equal row this is a very popular Google interview question as we can see Google has asked this question a lot of times over the past half year so that's directly look into the question essentially this question is about to a race but in the settings of Domino's so in a row of dominoes AI and bi represent the top and bottom half of the dice Domino and we try to rotate the ice Domino so that AI and bu I swap their values and then we try to make all the values in a are the same or all the values in B are the same and then we return the minimum number of rotations so let's look at the two examples here for example in the first one a is 2 1 2 4 2 and B is 5 2 6 2 3 2 so if we rotate the let's look at the array a so if we rotate this one and this one then that means the second element and this and the first element in a will watch wrote or swapped value with the new element in B which is exactly 2 so in that case if we rotate twice that will make all the elements in a equal to 2 right so that's why the output is 2 and for the second example a is 3 5 1 2 3 and B is 3 6 3 4 so for the first element it's same so we both a and B are 3 so we don't have to make any rotations but 4 5 and 6 right no matter how we rotate them equal to three that's why we all put - equal to three that's why we all put - equal to three that's why we all put - what that means we cannot be it cannot be done right so actually let's think about this question um so actually when after we look at the first element of a and B the problem is already fixed right so that's it for this example a is 8 0 is 2 and B 0 is 5 so the goal is one of the following cases either we do some rotations to make all the map elements in a equal to 2 or 5 or we can also try to make all the elements in B equal to 2 or 5 right so that's a basic idea and if we cannot never make it then we return minus 1 with this idea let's look into the code this is kind of actually the implementation is very straight forward for this question so the input for our function minimum dominoe rotation is 2 arrays a and B which represent the top and bottom halves of the ice terminal and then because we need to finally we want to return the minimum counter right the number of rotations so we are we make four counters to record the number of rotations and then try to find the minimum as we just discussed we have actually four cases right so the first case we want to make all the elements in 8 equal to a zero and the second case is make all the element in a equal to B 0 it's the same for make all the elements for in B equal to B 0 or make all elements in B equal to a 0 that's why we have fokin counter counters here so let's look at one of the cases because actually the case is almost is very similar so if we want to make elements in a equal to a 0 so we iterate through all the elements in a and if AR is not a zero and at the same time VI is equal to a zero right in that case we if we rotate the ice element then all the element then like all the elements before I should be all equal to a 0 and if else if AI is not a zero and also bi is also not a zero in that case we can't we cannot make this case happen right because in that means no matter we are rotate or not rotate the ice element in AI and I we cannot make all the elements in a equal to a 0 so in that case we will break and also make the corresponding counter to be a infinite number so you have to be careful we cannot directly return -1 here right cannot directly return -1 here right cannot directly return -1 here right because we cannot make all the elements in a equal to a 0 doesn't mean we cannot do to others right so maybe you cannot do that but maybe you can do this it's the same you but you can make like all elements in a equal to be 0 that's why we first if we encounter some cases like this we make the counter to be infinite and it's the same for if we want to make all elements in a equal to be 0 right so after we calculate those four counters because those four counter will include all the cases possible so we just return the minimum of those 4 if it's not infinite right if the minimum of the 4 is in finite that means all or all of them are being finite and that means it's impossible so in that case we will return -1 um for the that case we will return -1 um for the that case we will return -1 um for the time complexity because we have like for parallel force here and so the time complexity is basically Oh Big O it's a linear time right um for the space complexity it's a 1 because we only have four counters here so when we if we look at this the this solution right it's uh it's very tedious and it's like we have four cases here and actually the format is very similar for all those four cases right and we then we can think of its this is a bad coding style and we can think of can we make it like more concise of course yes right so if we have if we can see a lot of redundancy in our code basically what we do is we try to make a function right to abstract the format so let's to get then we are with that idea we define a function called X to Y basically it's with the previous format we can see if you want to make all the elements in X I Y X equal to 0 y 0 then we can directly use this function to calculate the corresponding minimum value and all the other things are the same right so in that case the time complexity is still linear and space complexity is constant that's it for this question if you think this video helps please like and subscribe my channel thanks for watching
|
Minimum Domino Rotations For Equal Row
|
numbers-with-same-consecutive-differences
|
In a row of dominoes, `tops[i]` and `bottoms[i]` represent the top and bottom halves of the `ith` domino. (A domino is a tile with two numbers from 1 to 6 - one on each half of the tile.)
We may rotate the `ith` domino, so that `tops[i]` and `bottoms[i]` swap values.
Return the minimum number of rotations so that all the values in `tops` are the same, or all the values in `bottoms` are the same.
If it cannot be done, return `-1`.
**Example 1:**
**Input:** tops = \[2,1,2,4,2,2\], bottoms = \[5,2,6,2,3,2\]
**Output:** 2
**Explanation:**
The first figure represents the dominoes as given by tops and bottoms: before we do any rotations.
If we rotate the second and fourth dominoes, we can make every value in the top row equal to 2, as indicated by the second figure.
**Example 2:**
**Input:** tops = \[3,5,1,2,3\], bottoms = \[3,6,3,3,4\]
**Output:** -1
**Explanation:**
In this case, it is not possible to rotate the dominoes to make one row of values equal.
**Constraints:**
* `2 <= tops.length <= 2 * 104`
* `bottoms.length == tops.length`
* `1 <= tops[i], bottoms[i] <= 6`
| null |
Backtracking,Breadth-First Search
|
Medium
| null |
606 |
Challenge and so far again we haven't missed even a single day for all those who tried searching for daily lead Cod problems on coding decoded channel would have got the solutions and for all those who didn't please guys check out you'll definitely find the solution if it is not there then I'm there to create the video up as happened today after a very long time I'm creating the video and I'm super excited about it the question that we have in today is construct string from binary tree so the in this question we are given a binary tree and we need to create one string containing parenthesis and integer values from the binary tree such that the elements in the binary tree are traversed in pre-order fashion and we need to return pre-order fashion and we need to return pre-order fashion and we need to return that string up so here they have provided us as an example so if you carefully observe then this is a tree that is given to us and the output of this tree should be the traversal in a pre-order fashion when I say pre-order pre-order fashion when I say pre-order pre-order fashion when I say pre-order fashion what does it signify it signifies info left right I L R so let's walk through an example here we are at one and so one came up then we'll be moving towards the left child and as soon as we are moving towards the left child we should create a parenthesis and this is what we have created so this contributes to the left child and this contributes to the right child and if you carefully observe then we have recursively done the same thing over here as well I'll be talking more about it by the presentation even before jumping on to this I want to tell you two test cases is that I could think of that makes this problem slightly more difficult the first test case is this one so let's write 13 null so let me just run this code and the output of this is something like this so let me just open the tree visualizer and this is the tree that is given to us we have the root of the Tre as one we have only one element in it but is a left child of that root and the value here is three so this is the tree and its output turns out to be something like this so the null value is absolutely ignored over here we have the output as one bracket followed by 3 closing bracket and let's walk through another test case we have the elements as 1 null followed by 3 and this time uh the left child is null however the right child has an element three over here so let run this up and the output turns something like this the first element that we have is one followed by an opening bracket and a closing bracket this element signifies null Leaf node which is the left side so this is very important that in whenever we see a node which has its left child as null however the right child is present we have to appropriately build the response take taking care that null values are entertained and as I talked about in the question itself uh there are two test cases that we need to think of U the first one is this one when you have the root of the tree and it only has the right side this is what is the expected response and when you have the root of the tree something like this and it doesn't have the left child which is this one so this should be the expected response remember here we have explicitly mentioned that the F child is null by adding an empty parenthesis there's no value inside it so this is a take away remember these two things and then rest of the problem is very simple and straightforward so what we are going to do we'll need to iterate in the pre-order fashion so let's start from pre-order fashion so let's start from pre-order fashion so let's start from the root and we see the root uh it has value one so the string gets updated to one now what we will be doing we'll be moving towards the left Direction remember as you're moving towards the left Direction what should be the first step start an opening bracket so you start an opening bracket and now two will be acting as a current roote again so we see the root value as two we are going to append it up so two gets added onto the string again what do we see that we have a left child present so since we are moving in the left pre-order fashion so let me just write pre-order fashion so let me just write pre-order fashion so let me just write the formula for it info left right so we'll be applying this over all the nodes since it has a left node we will be moving towards the leftmost direction as we moving towards the leftmost direction what should be doing we should be creating an opening bracket and we have created the opening bracket now the current node under concentration becomes this one which is four so let's add four over here and as soon as you reach this particular node what do you see that you have reached the leaf node you the process there and then itself and this completes the left traversal across this path now we will be moving backwards so let's move backward words now what do we see that a two doesn't have a right child it is null so whenever you see such a case that then the null value should not be appended in the final result remember this test case so remember null value should not be added in the final result now let's move ahead and um since we are moving backwards what we are doing we'll be closing this bracket up so we are moving backwards and we are closing this bracket up again since we have moved two times backwards so we should be adding two brackets up two closing brackets up as soon as we move backwards don't forget to add the closing bracket now what we'll be doing we'll be moving towards the right side of the root which is one so we have successfully iterated over these two nodes info and left with respect to root being uh the node under consideration and it's time to iterate toward its right side since you iterating toward its right side what you should be doing you should be creating an open opening bracket so opening bracket gets added and now the element under consideration happens to be three so since we have three we'll be adding to the um string and three gets added and what do you see that this is also a leaf node as soon as you see a leaf node you have to avoid the process and return back so you return back use the closing bracket and now you are done so we have successfully completed the entire iteration and this is the string that we have generated this is sync with our expectation and now let's quickly move on to the coding section and I'll exactly follow the same steps as I've just talked over here the first thing that I have done is here is to create a string Builder object and then I have created a helper method that accepts two parameters the current node under consideration and your string Builder which will help you build the entire string I haven't used string class because strings are immutable and this will help us in better space complexity so let's proceed ahead and let's walk through the core algorithm if my current node happens to be null I have bought the process if it is not null that means I'm at line number 30 and I add it to my current string and moving ahead I check if I have reached the terminal State what is the terminal state I'm at the leaf node if my current node happens to be the leaf node it doesn't make any sense to move further Beyond and I return back from there and then itself at line number 35 what do I check if my current dot left has any nonnull value that means it has the left side if it has a left side I simply create an opening bracket appended to my SDR string I move in a pre-order fashion and string I move in a pre-order fashion and string I move in a pre-order fashion and I pass in current do left comma SDR and once I'm done with this I append a closing bracket afterwards and I do a similar kind of thing for my right child as well there's one corner case that we should think of while uh building the complete algorithm is when we are in the right side we should always check if current do left is null or not in case it is null then we should be appending an empty complete opening and closing bracket onto it so this is an important statement people often tend to miss this out and that was the reason I talked about this particular case at the start of the question so let's time uh to submit the solution the time complexity of this approach is order of n the space complexity of this approach happens to be log n uh why it is order of in because you're traversing each and every node only once and by space complexity is login because you are using a recursive uh algorithm and in those recursive algorithm the maximum uh depth that would be built would be equal to the height of the binary tree I think this answers all the question that the interviewer may ask and with this let's wrap up today's session I hope you enjoyed it if you did then please don't forget to like share and subscribe to the channel thanks for viewing it have a great day ahead and stay tuned for more updat from coding decoded I'll see you tomorrow with another fresh question but till then goodbye
|
Construct String from Binary Tree
|
construct-string-from-binary-tree
|
Given the `root` of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
**Example 1:**
**Input:** root = \[1,2,3,4\]
**Output:** "1(2(4))(3) "
**Explanation:** Originally, it needs to be "1(2(4)())(3()()) ", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3) "
**Example 2:**
**Input:** root = \[1,2,3,null,4\]
**Output:** "1(2()(4))(3) "
**Explanation:** Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 104]`.
* `-1000 <= Node.val <= 1000`
| null |
String,Tree,Depth-First Search,Binary Tree
|
Easy
|
536,652
|
145 |
today we have the binary tree but like it's similar to the last problem but it's instead of a pre-order it's uh post it's instead of a pre-order it's uh post it's instead of a pre-order it's uh post order so basically I have a binary tree that I should return in post order so it will be three to one so uh what basically that means first let's just talk about the pre-order again pre-order again pre-order again in the pre-order we start in the pre-order we start in the pre-order we start from the node okay and it was told and after that we store the left and after that we store the right okay and this is a pre-order and uh post and this is a pre-order and uh post and this is a pre-order and uh post order we store the left and we stole the right and after that store the root or the hit and yeah that's it physically so let's just um not just uh I mean that the code directly and we will use recursions also uh just um okay so uh let's just um a second uh no that's it um lit or equals enter array and return uh or okay and um I'll say the um const DFS equals a function it will be the first basically it will equal the function that takes node I'll call the function on the root it's the same as this previous problem but I tell you what was the difference so basically I would say that first as always if you have a recursion function we should put a base case if we're not node if not node return and I will say uh first okay post order Left Right node so basically it will be div is node.lift and the if is not the right and no um array no array the push um I guess this one will work yeah okay so let's just have how this works actually if we had if you are working at pre-order and the pre in working at pre-order and the pre in working at pre-order and the pre in the pre-order we left and it's the pre-order we left and it's the pre-order we left and it's stored node Left Right post order it just we just put we start left right and go to the actual node so basically what happened here first of all we call this function on the root is one supposedly node equals one and R equals empty array and we go to the left first note dot left okay and basically uh one has known on the left so basically when we call DFS again and notice and also if no direct return null so basically this is written nothing and we run this one not the right so basically we have node.right have node.right have node.right and when we have not the right not right now it will equals to so I will say okay I'll run DF is not the left okay so we uh we um not right now it would equals three and I'm saying if not equals nothing no not equal three so okay so uh run uh node.if is uh D if it's not the left so node.if is uh D if it's not the left so node.if is uh D if it's not the left so basically um it will be null so it will do nothing and also div is not the right it will be null because actually we want to reach until the deepest point and after that we push because both of these things are returned when in when node equals three and I'll push the value so basically the value will equals three okay and if you remember this two this function was waiting so basically the functions right side this node will this we finish the lift uh the left side of the two so we start with the right is null so D is written on this is written nothing and we add the value so it will be two and basically when we finish this when we finish the right thing the right of two it's time to go to one back so basically we finish the left to finish to the right and we add the one so yeah it's like that and this is it basically and um hope my description was goes quite good if you like my description make sure to subscribe and hit the notification Bell so you will never miss a video and yeah that's it and see you in future Pro
|
Binary Tree Postorder Traversal
|
binary-tree-postorder-traversal
|
Given the `root` of a binary tree, return _the postorder traversal of its nodes' values_.
**Example 1:**
**Input:** root = \[1,null,2,3\]
**Output:** \[3,2,1\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Example 3:**
**Input:** root = \[1\]
**Output:** \[1\]
**Constraints:**
* The number of the nodes in the tree is in the range `[0, 100]`.
* `-100 <= Node.val <= 100`
**Follow up:** Recursive solution is trivial, could you do it iteratively?
| null |
Stack,Tree,Depth-First Search,Binary Tree
|
Easy
|
94,776
|
56 |
Shruti Hello friends welcome to Tech's new video your blind 725 and dead chal raha hai hamara jo that is seventeenth Tomar Jain travels watch zoom game we had seen last day ok hai tu mar in trouble question very nice I liked it As soon as you see it, you will understand that he is giving an interview and he is merging us. Okay, you have one to three, then two to six, Jatin, and if we overlap, it will go to 16. Okay, it is something like this, if we have such a thing. Is dropping as if four are coming in both then one will reach written that it is a simple question and is saying that it should not have been a native layer, so first let me explain it to you once on the copy. Then let us code, so if something comes up that we have given this interval, it is okay, keep all the interpolations, then what will be the problem, we will have to soften them, here we have given 153, this time will be given in the class after that. And the situation is that this question is easy, I will suggest you to do it like this. Create a number length. It is said that if there is no negative value then start from zero and get 50 questions. So far, you have been able to visualize this hole. Try making it from one to three lifts, it will be here, three here somewhere, AP's village done, from eight to that is this that in talking and from 15 to 18, let's say this is from 2 to 62162, this is and 65 is a little bit. Next, see the question again, just this, if our input is getting it, then you will be debited, if the other one is in the pot, then it will remain in our output. Education is going to come from forest that if it is cleared in Tibet, then we will give it 50 grams, our A is significant, how much will it cost, we will add the link of login starting, its hydration, everything is fine, it is a small thing, fold it and understand, okay let's code. It is said that we have to do the shot inside the basis of this post person tube 1218 15 According to this the shot will be done Ramesh what to do a little bit I take intuition in this and give logic what is it that it is from one to three taking the second If there is something like that then tell us Chetak by taking one, what if it is from 1 to four and from two is the article, from 2 to three then go to loot, if from 10 to three then what happened here from the end What will happen from one to four Vedas to all three? If all exclusive comes within the same, then ultimately what we have to check is that we have to check that as soon as there are two, this is three, I give you the starting value. Its which end is jewelery na its starting value gets reduced 2 is smaller than 3 saugandh in and question is equal to quick na so if it happens that I told you this app around four wala na so that 1445 So 158 A meeting with another is smaller than 3, you one thing, coordination is going on that there is overlapping going on here, then we have to check which one is bigger than the three, we will not increase it, okay, so 1316, let's fold it and see that one. So let's start the code, we have kept the intervals. Okay, so I take the intervals as palaces. These are also there. So the interviewer has already asked what is the interview and what is the condition. Is the value Mandvo ok so that it is easy to write? Then see. We know that the value has to be adjusted, I must tell you, then it is done in the beginning by softening it and doing the shopping in such a way that you know, I take it so that there is no confusion again and again, that is, there is no need to edit the screen, okay, I What do you need in this, how to do shopping in such a list within the list, okay, I have told you to do it on the basis of post valley, so to find out what have to be given, I was in the land, that I am ILO Anant. After what is zero, do your answer in the film, let's assume that master will become our interval play list, that this is all for disturbance, isn't it, my voice is coming, please friend, the answer is no, if it is an interview, then what is it? Zero is there, it will be there with um, do n't do it, after softening it, if you feel like math first then do that and put 153 in the answer list. Okay, why am I doing this so that how can I avoid this? Now we have the address where we want to travel on the interval, from where will we take zero, we already know the time because we have put it in the beginning, not in the answer, so from here we take the first and second. Now the travel is going on in between. So we know that we have to last, this becomes its second body, so let's take L2, tap and hold to schedule it for late, okay, so what does it know, understand, you are coming here and saying that right now I am minus one. And see what happened in our starting, what was inside it, turn off the torch in the setting inside the answer, show it to Minister Ajay, I mean bread, you are going to come to New Delhi, you commercials do something strange, I am going to insert in it, apart from me, answer in it. I am not telling you, Mithu, that when we learn values, in 9th, I have accepted that the part after the interval is the next part from 1 onwards, how is this that is this and if the teacher is bringing in it, then this is our Other will go and to yours will go ok your edit will be ok that is the answer's minus one day inside the answer now miles behind which is the last time na his post element Jatin I what entered you right from here dating site and not Shruti 's alto became equal to three. Sorry friend, for the buffalo 's alto became equal to three. Sorry friend, for the buffalo 's alto became equal to three. Sorry friend, for the buffalo from behind, that doesn't happen when I do 60 and the construction continues. This is the story of every house, so if you, if it is our duty that Muslim boy, second of equal to last is that our posted is two that this is the one who is entering it, then most of all you are the one who is entering our element, so the first one is our two that I change the alphabet, is two small, one is big smooth. Request to last second is less than 3, it is equal, if neither is smaller, then what will we do in this, the answer is destroyed, mine is - - - 1413, our second will change the maximum. In 2009, it was told that you have come out of the team, tell me, activate. We will take any of these maximum, if such an officer points us then we have to do a verification, if nothing happens then we will pay in the answer whether the posters were on second, I was taking the first web address ever, I am this Post and two will be fine, now I will check half liter no answer, is that Ghaghra good, fine, is it effective, 200 no, yes, Ranbir, it is fine, I did it for the app first, made it two for second. Okay, I should have written one to two, I was thinking, okay, this is a small thing, so we will paint like this and our dough will go, okay then this was the question for today and just keep doing like this, blend code. The file is now our day will reach 7903, you drive through the goal
|
Merge Intervals
|
merge-intervals
|
Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_.
**Example 1:**
**Input:** intervals = \[\[1,3\],\[2,6\],\[8,10\],\[15,18\]\]
**Output:** \[\[1,6\],\[8,10\],\[15,18\]\]
**Explanation:** Since intervals \[1,3\] and \[2,6\] overlap, merge them into \[1,6\].
**Example 2:**
**Input:** intervals = \[\[1,4\],\[4,5\]\]
**Output:** \[\[1,5\]\]
**Explanation:** Intervals \[1,4\] and \[4,5\] are considered overlapping.
**Constraints:**
* `1 <= intervals.length <= 104`
* `intervals[i].length == 2`
* `0 <= starti <= endi <= 104`
| null |
Array,Sorting
|
Medium
|
57,252,253,495,616,715,761,768,1028,2297,2319
|
1,833 |
Hey gas welcome back tu de new video you guys watching in this video today's daily lead challenge name is maximum ice cream baras so there is a boy he wants ice cream in summer season ok so whatever is it what is the price of it so Ice cream outside these points, so basically you have been given this, like 13241, so what is your like, what is this van telling, this van is telling what will be the cost of your zero ice cream bar, if you talk in terms of index, then like this FIRST ICE CREAM [MUSIC] OR BROTHER WITH COINS OK SO WHAT HE SAID MAXIMUM SO SEE MAXIMUM HOW MANY ICE CREAM BARS HE CAN TAKE OK 132 HOW MUCH IS IT 6 AND 1 7 OK SO WHAT SHOULD WE DO SO WE FIND OUT THIS Let's find out how many ice cream bars he can take with one coin. Okay, so we have sorted it out. So, this guy has become something like this, it is okay, he has become something like this, it is okay, as you know in Giridih's questions. Here, I will understand the greedy approach because we have to find some maximum and minimum in it, okay, there is a question of such n chocolates, in that also we are doing something like this, okay, we have to find the maximum chocolates in it, okay so now I How to mine the maximum number of ice creams i.e. the initial coins, I will i.e. the initial coins, I will i.e. the initial coins, I will mine the first one, the cost of the first ice cream bar, so it becomes six, now what will I mine from the six, what is the cost of the current cream bar, the course van of the current cream bar, okay? So it becomes five, okay and similarly, I will keep increasing the counter. He is not asking what is the counter for, right? If you can take maximum number of ice creams, then its correspondence will also have to be kept in the counter, so just for that we will What are people doing? They are keeping counters. Okay, now five are left. Now what will I do out of 5? 2 - I will go to zero, then what will I return? Now I will make my return on the counter, so let's see what they do. First of all, what did we do? First of all, we have shorted this one, who has the science cost and what have I done, I have done the through loop cost, first of all you will have to mentalize the counter, right, we will make the counter together, okay, so what are we doing The Coins What are I mining? The coin is equal to zero. Okay, so I will return it. Okay, and I think that a code work is done, it should mean that it is our mistake, so if you follow the example I just explained, then you will see that this is the condition. What have we written, if it is wrong, then what will come in its place? If you support me, take this case, if you are okay with this, then what will become of 6 7 8 10, but if the element of every area in this is bigger than your coin, then what are you five? There are points and I have given you only the price, so what should I take now, people, if you will not be able to take anything, then what will I have to return, I will have to return the count and what is mine, initially it is zero, so this simple condition, I have done it wrong, but no problem. No friend, it means mistakes keep happening, only then we learn, so run the time complexity once and see whether it is running or not, submit it and see. Okay, so time complexity because it is getting inbuilt sorting. Okay, so its time. there will be complexity
|
Maximum Ice Cream Bars
|
find-the-highest-altitude
|
It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are `n` ice cream bars. You are given an array `costs` of length `n`, where `costs[i]` is the price of the `ith` ice cream bar in coins. The boy initially has `coins` coins to spend, and he wants to buy as many ice cream bars as possible.
**Note:** The boy can buy the ice cream bars in any order.
Return _the **maximum** number of ice cream bars the boy can buy with_ `coins` _coins._
You must solve the problem by counting sort.
**Example 1:**
**Input:** costs = \[1,3,2,4,1\], coins = 7
**Output:** 4
**Explanation:** The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
**Example 2:**
**Input:** costs = \[10,6,8,7,7,8\], coins = 5
**Output:** 0
**Explanation:** The boy cannot afford any of the ice cream bars.
**Example 3:**
**Input:** costs = \[1,6,3,1,2,5\], coins = 20
**Output:** 6
**Explanation:** The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
**Constraints:**
* `costs.length == n`
* `1 <= n <= 105`
* `1 <= costs[i] <= 105`
* `1 <= coins <= 108`
|
Let's note that the altitude of an element is the sum of gains of all the elements behind it Getting the altitudes can be done by getting the prefix sum array of the given array
|
Array,Prefix Sum
|
Easy
| null |
138 |
hey hello there so today I'm talking about this question 138 copy lista with Brendon pointer we have a linked list the thing that's a special about this link list is that the nodes inside this linked list contains not only a next pointer which points to obviously the next two node in the sequence but also a random pointer that could point to potentially any node inside this list or it could be a null pointer now go for this question you still create a deep copy of this list and return the head node to the you know often copied linked list so as a simple example we could have a linked list always maybe like three nodes and the links I'm currently drawing are the next appointees and maybe just one of the note here note to you might contain a random pointer that's pointing to a node one inside this linked list just kind of notice a surrended for the other two notes in my they might have some random pointer so i guess for the sake of this example we can just treat them as just imagine that they there wrentham pointer is null pointer so i'm not really showing that out so the whole goal is to make a copy of this linked list with random pointer so obviously if we traverse through this nick list using only the next pointer we can very easily make a copy of this then maybe the second round we can try to establish this random pointers so to do that we can generate over this two linked lists simultaneously at the same speed so you know when we look at the first node in the original linked list we also have another pointer that's pointing to the same correspondent node inside this new linked list then we if we have a render I'm sure that we'll find the node in the original or linked list has a random pointer that means for the new linked list we want to have a establish we ran the random pointer pointing to the corresponding node for the new linked list so for that reason we would want to have a mapping from the old node to the correspondent new node so I'm just gonna note down here it's gonna be to pass the first pass is to create a copy Wis correct next links also create mapping from o to new to long put into two like so after that the you know the new linked list will look like something like this the second step is to second passes to the first is to list lists after the same pace when we see a random pointer we set new node wreden to be this mapping oh yeah so just look at where this random pointer points to in the old linked list and then look up the corresponding node inside the new linked list and have that points to over there so yeah after this to pass we'll have a deep copy of this original linked list with random pointer so that's the very straightforward way of solving this it will be linear time and linear space linear time being that we do to pass the linear space is that we maintain a code node to new node kind of Association so that map will require n space so that's the that's pretty much sure the first way of solving this I'm gonna talk about another constant space solution which is a little bit tricky but here's the very straightforward one we're gonna code up first so obviously the first thing is to first possibly create a copy we're just correct next second pass is to fix the random the pointers yeah so beyond this we also need a map that's keep track of the a pointer map it's okay that we put the pointers as the key and values if we put the object as the key and values to this unordered map it will be required actually the node to implement some kind of hash function and I'm just doesn't seem to be the case here so that's why I'm just putting a pointer yeah over to you let's just call this and we're gonna have our sentinel node that which is just a dummy node that have a next link points to the you know the head node of the new copy so that's going to be dummy with whatever value I don't care and just gonna have a copy that's pointing to this dummy in the beginning and the statement mention how many nodes is guaranteed there to be there you only have an upper bond there's no lower bond maybe just catch that here so yeah let's do the first pass so we're gonna make a copy and we're gonna tell you take there take the value from the original from the node in the original linked list and use that value to create a new node have the copy you know the traversal kind of a pointer for the copy the link lists next to the points to that and then just gonna advance this to be this newly created a node then what we're gonna do is to advance the old pointer as well but before that we can we're gonna insert this associate relationship into this map here so it's the old to new then we advance also in the Olynyk list so that's the first pass then the second pass is to iterate over them at the same time and when we see a random pointer in the old linked list in the notes that from the ODE linked list we will try to establish a finish fixed random pointer in the new one so we just move this Traverso pointer back to the head and move the copy back to the beginning as well then what are we gonna do is to iterate over them at the same time with the same speed obviously some code we can quickly what opera here is to advance the amount of the same time at the same pace if the node in the linked list have a random pointer then we gonna do is to have the copy random pointer points to the we look up at that new note associate a corresponding new node inside this new linked list so yeah so that's pretty much it return the Sentinel notes next which is going to be the head node hello to the new newly copied link list not working not much in constructor initialization for the node so okay so it does take a house to take at least our value so let's just put a zero there okay looks good so yeah this is the most straightforward way of solving this we do to pass the first pass is to create a copy where's the next link that's correct and also maintain a map from the old news to the new note then in the second pass we when we see a random pointer in the old linked list we will try to do the same in the new one so after that we should be able to have the complete deep copy of the old linked list with random pointed so that's the solution number one was linear space and linear time so I'm going to talk about another approach gonna borrow this as well another approach that requires only constant space obviously we wouldn't maintain this mapping from the old to new so that the way we do that is just to put the new node temporarily in between the old and it's next so it will look like something like this I'm using Prai 2 indicating this is actually a copy node we can very easily insert this one you know when we iterate over the new code original linked list for every node we just create you know copy of that node immediately after that so we need to basically insert that between the original node and it's next so in the first pass we can do this and obviously we only have this random point our correctly working for the original no not the copy one because the copied one in the first pass we're not going to be able to figure out that yet because if you have a node that's pointing to some other node after that we first create the copy there's no way you can pointing that to the you know copy correspondent copy so that's a first class so just kind of summary this the second pass we're going to make sure that the newly created node also points to the you know it's the we're gonna fix the Wrentham pointer so it's similar to that the first one we just only able to get that next to working you can see that if we just want the original link list what we need to do is to instead of off to the usual way to go to the next we go to the next if we just hop to step at time at a time from the handle of the original linked list we would basically only traverse the original note if we start with hit on next you know from the same node of the copied link list and we also do two hops at that time we would just only be traversing the newly created a copy so for that reason it's easy to separate those two after we fix them the random pointer for the particular let's say that we're looking at node two we can follow the random pointer to go to its associated node inside the original linked list but the door next here note that the door next a there is its associated along the node in this for the new linked list so we're just gonna have this note stop next to two prime points to its random pointers next so yeah so that's going to be the middle iteration understand no to talk here whoop yeah just gonna summarize this around quickly it's getting quite late so yeah first iteration first to pass insert the coffee between owed and next the second pass for a note with random pointer we're gonna set node on next I'm just gonna call this ode on next which is gonna be its copy in the new linked list all random equal to o Renton so next do you know a case in our example here - its know a case in our example here - its know a case in our example here - its next it's gonna be to prime two primes next is gonna be to surrender which is gonna be you know just I'm just gonna using brackets here to indicate that the twos Brendan is one and the Nexus One prime yeah maybe just that one and one prime so yeah so that's pretty much just say setting to Prime's rent a link to one prime so after this second product second pass we establish that the correct random pointer in the new linked list then it's just split the split to the linked list you know the also on the offs notes the old one even the number of nodes are the new one so yes it's going to be a three paths and it's going to be constant space because you know we don't have that mapping and mapping the in social job of the mapping is been captured by the next link so in the original in the first solution we have to use this map to keep track of node 1 is this new one prior no - it's mirroring it's prior no - it's mirroring it's prior no - it's mirroring it's going to be 2 prime right here the copy notes is immediately after the origin now so we don't for that reason we don't need this linear space mapping but we do have to do this in one more pass so you see that this is a three pass for that one it's two paths so even though that the time complexity is going to be dropping the constant multiplier it's going to be the same order of M but this one does take a little bit longer so you know we start time you're just going to cut this up that's not supposed to happen anyway so we're gonna have the note so traversing the oat one and we going to have a copy and also a note indicating the friend note of the newly copied one we're gonna use this to start collecting notes you know even in the odds later on so the first pass my first copy is going to be a new note with the nose value old notes body and we're gonna set this note next to be the original own notes next so that we inserted it in here to have it points to two and after that we can have the old one points to this so that's this so with this we should be able to advance we have to hop this two by two steps or we can just pop it to the copy nurse next so that's one path to insert a copy of the own notes so the second pass to fix the random pointer we move this back to the head and we're just going to set my next which is going to be the new note and have its random points too if I do have a Rendon which is not a null pointer if that's the case I'm gonna set it to set this thing - yep I'm gonna set it to set this thing - yep I'm gonna set it to set this thing - yep it's a little bit too long I mean let me actually put a if statement otherwise it would just be the default which is going to be in null pointer so after that I can traverse to step at a time so yeah because if I Traverse to step at time I'm only looking at the original notes inside this sort of fuse the linked list so that's the second pass and the surpass is - it's exactly pass and the surpass is - it's exactly pass and the surpass is - it's exactly the other questions on link Lee code is the even order this in - even all the is the even order this in - even all the is the even order this in - even all the lists so the all the list is going to be all the number of notes you know node 1 node 3 node 5 it's gonna be the old linked list the even number notes here no too new for node 6 is going to be forming the new linked list there copy the link list yes sir move this back so we're gonna pop this to step up I actually know actually just gonna be one step at time we're gonna fix the link so that we only need to jump once here it's just got to remove that to make sure the link works okay and the copies next are this is more readable I think so yeah so we are even when we jump hop two hop sometime the only difference is that the copy' is the only difference is that the copy' is the only difference is that the copy' is actually when we Traverse at the same time that's going to actually one step ahead in the you know fuse the link list so it's a the even though we advance them at the same pace the copy is kind of likely to hit no pointer before this traversal so for that reason we need to do a condition check here to make sure that the copy dot next is not null pointer if that's not pointer then this will be undefined you know you couldn't call the next pointer or no pointer so that's why this looks slightly different yeah so after that we just returned the new head which is going to be the initial notes for the copy the linked list so this is a three pass and constant space let's see if it works okay all right so slightly faster I'm not really yeah not really right so yeah that's the that's this question two solutions one straightforward to pass with some mapping the other one is the three pass with constant space it's not too difficult to think about this you have to find some way to replace the job of this mapping you know that map's the owner to its correspondent a new node and to do so the only thing that you can really rely on are the two pointers obviously you don't want to mess up at the random pointer so the only way to utilize the next pointer to keep track of you know to function both first it has to steal functionally as the pointers you can rely on to correctly traverse inside through the linked list in the correct order the second thing you has to also keep track of the relationship between the own node and the new node so the way to do so is just to you know insert the new node in between so that if we you want the origin or traversal although you're just hop to step at that time if you want to find the mapping you just look at the immediately next all right hope you can make sense yeah that's it for today
|
Copy List with Random Pointer
|
copy-list-with-random-pointer
|
A linked list of length `n` is given such that each node contains an additional random pointer, which could point to any node in the list, or `null`.
Construct a [**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly `n` **brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the `next` and `random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. **None of the pointers in the new list should point to nodes in the original list**.
For example, if there are two nodes `X` and `Y` in the original list, where `X.random --> Y`, then for the corresponding two nodes `x` and `y` in the copied list, `x.random --> y`.
Return _the head of the copied linked list_.
The linked list is represented in the input/output as a list of `n` nodes. Each node is represented as a pair of `[val, random_index]` where:
* `val`: an integer representing `Node.val`
* `random_index`: the index of the node (range from `0` to `n-1`) that the `random` pointer points to, or `null` if it does not point to any node.
Your code will **only** be given the `head` of the original linked list.
**Example 1:**
**Input:** head = \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Output:** \[\[7,null\],\[13,0\],\[11,4\],\[10,2\],\[1,0\]\]
**Example 2:**
**Input:** head = \[\[1,1\],\[2,1\]\]
**Output:** \[\[1,1\],\[2,1\]\]
**Example 3:**
**Input:** head = \[\[3,null\],\[3,0\],\[3,null\]\]
**Output:** \[\[3,null\],\[3,0\],\[3,null\]\]
**Constraints:**
* `0 <= n <= 1000`
* `-104 <= Node.val <= 104`
* `Node.random` is `null` or is pointing to some node in the linked list.
|
Just iterate the linked list and create copies of the nodes on the go. Since a node can be referenced from multiple nodes due to the random pointers, make sure you are not making multiple copies of the same node. You may want to use extra space to keep old node ---> new node mapping to prevent creating multiples copies of same node. We can avoid using extra space for old node ---> new node mapping, by tweaking the original linked list. Simply interweave the nodes of the old and copied list.
For e.g.
Old List: A --> B --> C --> D
InterWeaved List: A --> A' --> B --> B' --> C --> C' --> D --> D' The interweaving is done using next pointers and we can make use of interweaved structure to get the correct reference nodes for random pointers.
|
Hash Table,Linked List
|
Medium
|
133,1624,1634
|
278 |
hey alex here and today we'll be going over the problem called the first bad version it's a number 278 on lead code and it's an easy so essentially we're a product manager and we're currently leading a team to develop a new product unfortunately the latest version of our product fails the quality check since each version is developed based on the previous version all the versions after a bad version are also bad so suppose we have n versions starting at 1 up through n and we want to find out the first bad one which causes all the following ones to be bad so we're given an api called isbad version which returns whether a version is bad or not so we want to implement a function to find the first bad version we should minimize the number of calls to the api so you might think well seems pretty straightforward why don't we just implement the very straightforward intuitive solution so we could say let i equals one because we know that we're going to have at least one version at the very least and we can just say while is that version i so we'll just continue looping until we reach our first to bad version and then we reach our first bad version we'll just return i seems pretty easy pretty straightforward let's run it looks good so far let's submit it time limit exceeded so just give a brief rundown as far as time complexity this uh this little for loop here or this while loop is running in an o of n time complexity and in terms of space it's ob1 so for time um it's of n because let's say that we have an input of one million let's say that we have one million versions and the first bad version happens to be it version number nine hundred thousand so that means that we're going to be iterating literally through 900 000 versions until we finally get to that first bad version not very efficient and it's all one space because we're not really saving or increasing the size of a data structure as we continue to iterate through doesn't matter if it's 10 versions or 1 million versions we're going to be using the same amount of space but going back to the time oh then time it just isn't fast enough for this problem so we're going to need to find and implement an algorithm that operates an o log of n time instead of o of n time and we're going to get into that right now so here's the approach so we're going to focus on this we're not even going to use numbers and we're just going to break this down visually so first thing or rather we're going to use the bare minimum of numbers uh that we need so we're going to initialize a left pointer at 1 because we can always assume that we're going to have at least one version whether it be good or bad we're also going to initialize a right pointer which is going to be initialized to n which is the total number of versions that we have in total and we're also going to initial initialize a middle pointer which is going to be math.floor l which is going to be math.floor l which is going to be math.floor l plus r divided by 2. so this is going to give us our average or our middle value between l and r so now we can come over here and we're going to draw this out so these are all of our versions and we're going to say let's say that from here onwards these are bad versions so first things first we're going to calculate uh left plus r um and then we're going to divide that by 2 and we're going to math.floor it by 2 and we're going to math.floor it by 2 and we're going to math.floor it so that's going to give us a whole number and that's going to give us our middle point so first thing we can put a left actually it's good if we do it like this so we can put the left over there we can put a right over here and let's put middle let's say middle's right over here cool so we're going to first check middle and we're going to see that it is a good version so we're going to check directly to the right of it and we see that directly to the right of middle we're going to pretend that uh that we have like a few we have a few versions over here right we can assume that so since the version directly after the middle version is also a good version we're going to continue with our operations we're going to go to the next iteration of our search here so we can essentially eliminate the entire left side of our data set so say goodbye to this so now we can move the left pointer to where middle is and now we can say l is over here r is still at the end and we're also going to say that we still have these bad versions so now we're going to split this down the middle again and now we can see that we're in a bad version territory so we see that this middle pointer is now on a bad version we're going to check this and now we're going to check um directly to the left of this middle bad version and we're going to see that's also a bad version so we can eliminate the right side of our data so now we can see kind of little by little we're just breaking down our data set in half each time now here's our middle pointer again so we can just keep on going down until we just keep reducing our data size smaller and smaller we're going to see again that our middle pointer is pointing to a bad version so we're going to check directly to the left of it and we're going to see that's also a bad version so we're going to cut that out and our data set just keeps on getting smaller and we're going to split this down the middle again so now finally let's say that we're on our final iteration here so we're going to check if the middle pointer is a good version or a bad version we see that it is a good version and now we're going to check directly to the right of it and let's say that this happens to be the very next version right here so we're going to see that is a bad version so since the middle was a good version and the version directly um following that middle version is a bad version it's safe to assume that the middle pointer that the middle version is the last good version and that m plus one is our first bad version so this is our answer here so now if we code this out we're pretty much going to go through the same steps that we went through during our sort of visual breakdown so first thing is we want to initialize our two variables or rather our two pointers um we want to let l equals 1 because we know that we're always going to have at least one version at the very minimum and we also want to initialize r as n which is the total number of versions that we have so after we have those two initial pointers um we can get into a while loop here so to say while l is less than or equal to r at this point we can initialize our middle pointer so we can say let m equals math.floor l plus math.floor l plus math.floor l plus r divided by 2. so every time that we iterate through our while loop we're going to be recalculating our middle point so after we've calculated that we can now check if is bad version m but notice that we put a bang here so if this statement returns true then it pretty much means that the middle version is actually a good version and not a bad version so if it's a good version we're going to check if m 1 the version directly after it we're going to check if the version directly after the good middle version is a bad version and if that is a bad version then we'll just return m plus one because we can come to the conclusion that um m is a good version and n plus one is the first bad version so we'll just return that and if m plus 1 is also a good version then we'll simply say that l is now equal to m now on the other hand if m is actually a bad version then we're going to go into this else clause here and we'll say that if is bad version m minus one so we'll check the previous version instead then we'll return m because this will mean that m was a bad version and the version previous to m is a good version so that means that m would in fact be the first bad version and if that inner if statement is you know also isn't true then we'll just set r to m so essentially this is all that we're going to need for this solution here so if we go ahead and run this code it's going to give us a nice run time and a nice memory usage if you run it a few times depending on the test case get different results but uh for this solution this is um as far as a time complexity it's o of log n because we're dividing our input in half each time that we iterate through this while loop and as far as space it's o of one because we're only using a few pointers and we're not really saving or increasing like a data structure as we iterate through so we're just using pointers and those pointers are going to be the same regardless of if we have an input of 1 million or an input of 10 so it's like that so there is actually one more solution i mean there are a few ways you can solve this but there's another solution it also is o of log n and o of one space but if you notice we're actually checking if is bad version we're checking twice on each while loop so here we're checking first and then we're possibly checking on line 28 or line 33 and based on the directions we want to minimize the number of calls to the api so here we can uh actually we can maybe we can yeah we can just copy and paste this solution is it's a little simpler depending on how you look at it except for this if uh if the um overflow error is new to you then this may not make sense at first but you can definitely read up more about that but yeah this solution is also o log of n time complexity because we are splitting it we are splitting our data input in half each iteration and it's also one space complexity because we're not saving or incrementing the size we're not increasing the size of a data structure as we continuously leak through and yeah if we run this solution you'll see that this works as well sometimes gets you a good run time sometimes it doesn't but yeah so yeah that does it for today make sure to tune in and subscribe for some more algorithm breakdowns and see you later you
|
First Bad Version
|
first-bad-version
|
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have `n` versions `[1, 2, ..., n]` and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API `bool isBadVersion(version)` which returns whether `version` is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
**Example 1:**
**Input:** n = 5, bad = 4
**Output:** 4
**Explanation:**
call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.
**Example 2:**
**Input:** n = 1, bad = 1
**Output:** 1
**Constraints:**
* `1 <= bad <= n <= 231 - 1`
| null |
Binary Search,Interactive
|
Easy
|
34,35,374
|
78 |
hi everyone my name is sakshi and in this video we are going to solve a very common interview problem subsets this is the problem number 78 only code let us first look at the problem statement given an integer array nouns of unique elements return all possible subsets that is the power set of the integer the solution set must not contain duplicate subsets and we can return the solution in any order we are going to solve this problem in three simple steps firstly we will look at the recursion tree for this problem after that we will implement our algorithm and after that we will analyze the time complexity and the space complexity of our algorithm now let's first jump to the step one here i have drawn the recursion tree for this particular example 1 comma 2 comma 3 here the left branch indicates that we do not include a particular element into the subset and the right one indicates that we include that element now that particular element depends on the index so we start from index 0 that is the element 1. we do not include 1 we get an empty subset and if we include it we get 1. similarly we do it for 2. here we get an empty substitute we get two not including two we get one here and including it we get one comma two for three we get an empty subset three two this becomes 2 comma 3 this remains 1 this becomes 1 comma 3 and this remains 1 comma 2 and this becomes 1 comma 2 comma 3. now all the leaf nodes represent the subsets which we need as solution right how do we count the number of uh subsets which uh we are going to generate look at this recursion tree for and for an array of unique elements of size n we are going to generate 2 to power n subsets how for every element we have 2 possibilities either we include that element or we exclude that element from the subset since we have two possibilities for every element and there are n elements um we will generate two to power n subsets of a particular array of size n also we can derive this from the number of leaf nodes of this recursion tree which is 2 to power m now we have done part 1 of our process we will jump to part 2 which is the implementation of our algorithm we'll do it in c plus we will write a recursive function i'm naming it recurs now look at the inputs which i am providing this to this function nums which is the given array integer n which is the size of the given array index is the current index i am taking a temporary vector in which i'll be storing the elements and uh finally i'll push the temporary vector into our final vector of vectors which is the our output vector and that output on that output vector i am considering it to be rad we will write this algorithm according to our recursion tree only so uh first thing we do not include that element if we are not including that element we'll just pass on to the next index that is i'll call this function for next index everything else remains the same if i include that element that means i am pushing that element into temp and after that i am calling recurse for index plus one also i will do pop back here now why i am doing pop back because look at this let's see temp is here the temp is the empty subset now we go to one now temp is 1 now if we go to 1 here and after that we go to 1 comma 3 now we push temp equal to 1 comma 3 into rad now we want to push another 1 comma 2 and 1 comma 2 comma 3 as well now uh so we need to pop three out to go to one and uh after that we'll go to one we are not popping out one here because uh it is the case of not including 2 here right so we go to 1 and after that we include 2 and we do the same process so this we do for all the branches of this tree here i'll return now one thing which is left in this function is when will i push temp into the ret vector so this we know when we reach the leaf nodes we'll push temp into the ret vector and when do we reach the leaf node when index is equal to okay then we reach the leaf node and we'll push temp here and we'll just return now to call this function i will get the size of my array i'll define a vector temp another output vector rdt i'll call the above function using nums and i'll start from the index 0 index will be 0 temp and rad and i'll return now let's check so for one two three it is giving the correct output and ah you can see that this is the order in which we have our nodes since we have written this algorithm based on our regression tree only so this has to be the same right now let's submit this we are good to go so we have completed the part two now let's come to part three let's uh complete the easy part first the space complexity we are using an extra vector temp here and the maximum value or maximum size of temp can be n if we have all the elements right so that means the maximum space complexity of this algorithm can be n so the space complexity is order n and we are not considering the space used by this vector because this is the output vector and to find the time complexity so how to find the time complexity of a recursive algorithm we find the number of recursive calls and then we multiply it by the time complexity of one recursive call now how to find how do we find the number of recursive calls look at this we have one call here two calls here four calls here eight calls here that means it is going in the manner two to the power zero two to power one two to power two and two to power 3 because there are three elements here it goes till 2 to power 3 now if we have n elements it will go till 2 to power n so uh total number of recursive calls will be 1 plus 2 plus and so on up to 2 to power n which is a gp and the sum of it will be 2 to power n plus 1 minus 1 order of 2 to the power n so the number of recursive calls are 2 to the power m and what is the time complexity of one recursive call this the time complexity of this is order one this is also order one this is order n why because um the time complexity of pushing a vector into a vector of vectors is the uh is the number of elements in the uh in the temp vector right so here the number of elements in the temp vector can be maximum n so the time complexity of this if condition will be order n so the total time complexity is n into root power n um which is the number of recursive calls into the time complexity of one call so this is the complete solution along with the time complexity of this problem if you like this video please like share and subscribe and if you have any doubts or comments please leave them in the comment section below and that's it for today see you in the next video bye
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
1,563 |
hey everybody this is larry this is me going with stone game five uh the reason q4 hard problem with the leeco contest uh hit the like button hit the subscribe button join me on discord uh so one thing i'm a little bit sad about is that uh i feel a little bit bad that i keep on doing this um where i actually don't know the proof of this problem uh it feels like so i'm gonna go over it and you'll see what i mean by a second so as to be honest so i end up taking about 17 minutes on this problem uh to be honest i spent about like 14 minutes or something like that you could watch the live video afterwards um just trying to figure out uh and something that's n square or n log n or sorry n squared like n or something like that something that's faster than n cube and why do we need to be faster than n cubed because n is 500 but to be honest um i think there's some sort of um a lot of these states are not may not be reachable uh so because of that it is not it's probably not a n cube uh i don't know how to ex you know do the tougher battle on this uh my guess is that it ends up being uh roughly n squared like n just because you remove half the um half of the possibilities every time so half the states at every level um don't get caught uh it's a little bit hand wavy uh and because this is a hard problem to analyze and like i said this is why i spent 14 minutes uh doing it and i spent three minutes just kind of yolo implementing the end cube solution and then submitted and it worked i don't have a great explanation uh for that um but let's go over to the recurrence real quick uh so the request is actually pretty naive and i really wish that to be honest um this is some of those problems that i consider not that great because especially in python i'm pretty sure i have to take a look later but i'm pretty sure that my code is very close to the time limit exceeded uh where in other languages it might not be uh but some of it is like maybe you should believe in yourselves i don't know i because like i said don't it took me about three four minutes to implement this uh maybe a little bit longer because i think i'd work a bit but a lot of time just trying to figure out the n square solution and i only tried to end cube quote-unquote solution quote-unquote solution quote-unquote solution because i couldn't figure anything out uh so i was like yeah okay i may just try but the first thing i do is i said prefix sum uh but the recurrence is basically you divide this is a classic um uh subdivision uh dynamic programming and then for each subdivision you just try all possibilities of the things in the middle um so yeah so basically i start you know if left is equal to right then is you have one note in the left then it's zero and one thing to remind you is that um you know this is um uh this is inclusive left and right so sometimes you have to figure out what your left and rights are rather than crucial exclusive otherwise you're gonna run into a lot of work by once um but yeah but and i actually messed this one up because i knew i had to do it but i was just worried about running time so i didn't really worry about the correctness um but yeah but basically this is the code uh the recurrence is that you know given a function of the left and the right boundary um we just prove first what's in the middle um maybe i'll figure out the recurrence after this actually um but yeah basically you keep track of the sum of the left and then the sum of the right and then for every stone that you kind of pause you just kind of move them over from the right to the left and then this is just in the problem description which is that if the left sum is bigger than the right sum you do this thing if the left sum is smaller than the right sum you take the left uh and then if the equal you just take the best of these two so this is going to be the most expensive one but because uh the stone value cannot be zero uh this cannot be called more than once per thing so that's probably okay so okay i know that hand wave a little bit because this is actually a pretty straightforward dynamic programming if you do have trouble understanding how to come up with this um definitely practice more dynamic programming problems uh but the hard part for this one particularly is try to figure out the recurrence and the math which is what i struggled with a long time right so how many possible inputs are here right um so the possible number of inputs are n squared right uh left right is n choose two but roughly right number of possible inputs right uh and then so this is also going to be also the space complexity for obvious reason of well those are the possible input you store one value for each input right and then the question is how much does this take right so this is o n because you do a linear loop um but so the naive interpretation of this algorithm is n cubed and that's probably what stumped a lot of the top or maybe not top but uh but the mid people because this well a lot of like this should um because honestly if n is equal to like a hundred or two hundred uh i bet you that a lot of people would have gotten it within five minutes including myself i think um and then i don't know maybe it's not the best problem though but um but as a result it the question is this true are there n square possibilities right um and that's going to be a homework for you at home but i believe that this these are the number of possible inputs but not all of them are reachable and what i mean by that is that there are a lot of possible inputs that are just not possible for example in this input um like there's no possible way to go from uh zero to four like this will never be an input because if you divide it along those lines uh you have to choose the right so there's some like some almost like um so you have a recurrence of oh uh kind of something like this um where you know uh of n plus someone like that so that's kind i mean i'm hand-wavy a little bit i mean i'm hand-wavy a little bit i mean i'm hand-wavy a little bit because uh it's a tricky recurrence um but that's kind of the math and i think that's why it becomes um oh and actually i messed this up and if you do the math i guess it ends up being uh um and square log n i want to guess uh those of you with the master film uh let me know in the uh come up with the recurrence let me know what you think about the complexity but yeah but to be honest at the end i just kind of implement the naive ish dynamic programming um and it i mean it took a long time but if you look at watch me live afterwards a lot of it was just thinking and as soon as i got this like yeah i had enough by one here and there but yeah anyway that's right for this problem watch me solve this live next okay well a little lucky than good this so hmm do my research so that's in sketch binary search i prove it do we always want to put the m cube on this obvious fit and cube is too slow for 500. it's so well people got this one really well but i'm missing the recurrence a little bit i'll bottom up hmm just trying to see how fast people solve it for maybe inspiration uh people something pretty quickly so that's not it must be an obvious recurrence that i'm not seeing i'm gonna just type it up so oh maybe uh no do i do all right i can say the same anyway that's not what that's not that it's twenty-five so that's a little bit too slow though maybe not hey everybody thanks for watching me self just uh explain these problems uh i have a video for before the con for this contest for the screencast let me know what you think hit the like button hit the subscribe button and join me on discord ask questions have fun and i will see y'all next contest bye
|
Stone Game V
|
maximum-number-of-darts-inside-of-a-circular-dartboard
|
There are several stones **arranged in a row**, and each stone has an associated value which is an integer given in the array `stoneValue`.
In each round of the game, Alice divides the row into **two non-empty rows** (i.e. left row and right row), then Bob calculates the value of each row which is the sum of the values of all the stones in this row. Bob throws away the row which has the maximum value, and Alice's score increases by the value of the remaining row. If the value of the two rows are equal, Bob lets Alice decide which row will be thrown away. The next round starts with the remaining row.
The game ends when there is only **one stone remaining**. Alice's is initially **zero**.
Return _the maximum score that Alice can obtain_.
**Example 1:**
**Input:** stoneValue = \[6,2,3,4,5,5\]
**Output:** 18
**Explanation:** In the first round, Alice divides the row to \[6,2,3\], \[4,5,5\]. The left row has the value 11 and the right row has value 14. Bob throws away the right row and Alice's score is now 11.
In the second round Alice divides the row to \[6\], \[2,3\]. This time Bob throws away the left row and Alice's score becomes 16 (11 + 5).
The last round Alice has only one choice to divide the row which is \[2\], \[3\]. Bob throws away the right row and Alice's score is now 18 (16 + 2). The game ends because only one stone is remaining in the row.
**Example 2:**
**Input:** stoneValue = \[7,7,7,7,7,7,7\]
**Output:** 28
**Example 3:**
**Input:** stoneValue = \[4\]
**Output:** 0
**Constraints:**
* `1 <= stoneValue.length <= 500`
* `1 <= stoneValue[i] <= 106`
|
If there is an optimal solution, you can always move the circle so that two points lie on the boundary of the circle. When the radius is fixed, you can find either 0 or 1 or 2 circles that pass two given points at the same time. Loop for each pair of points and find the center of the circle, after that count the number of points inside the circle.
|
Array,Math,Geometry
|
Hard
| null |
1,504 |
A [MUSIC] [MUSIC] [MUSIC] RIVER IN THE QUESTION HAS ACCOUNT WAS AMAZED WITH ALL ONE CHAPTER QUESTION SEE THIS AND SOME MORE TO SAY SCHEME AND CROSS AND TRICKS 540 HOW MANY SQUARE SUB LEADERS HAVE ALWAYS MEANS WE KEEP EMBROIDERY MYSELF I JUST 1GHZ What do we know that when Meghnad that we can subscribe anything that all this school 0111 421 arrow 105 in a friend is okay then what is the meaning of all that like it happens that it was continuously that this is the same submit juice this is also submit There is juice, this is also a spoon of juice, this is also a submit, okay, this is all my submit, this means continuously appointed thing, everything is okay, now what is meant by telling us the WhatsApp message is that its size can be increased from this onwards. If it is there, then friends, there is a need for more on the side of this, the second is that the advocate can get it from coat 3, this means that the length from here, things should be within the limit only, okay and after this. He has said that the status of matter should contain all once submit, there should be one in it, if I talk about it that once submit juice is there but it also has zero here then it will not work, okay there should not be and in every whole. If you want, okay, then this is one or two sizes of submit rickshaw square review and everything is made in it. Okay, now by exercising, this can be done while sleeping, in which only a bun is made. Okay, so if we have to fall in the total, then in this What will be the total? Taking the rate of excise. Is it correct? 123456789 10 11 21 Subscribe Now this is this one, 10 is also coming in it, so it is not this one, it is this one, so one is found, then that one. After this one i do if get then this one then get this one then this one is 42 43 size first then this second one how many total subscribers in this is ok then its answer is A see how half of its size 2012, we have done very quickly here, okay, now let's talk about every mind, which meter square review of every forest is, which part is being made for this one, its own part is being made for this and it is not water. This one is becoming a point, this one is becoming someone's partner, this one is becoming a ribbon, it is my own bond, just a square review part of my excise, this is also this one, now this one is my own lesson. It is important to remain together, here we are talking about the bottom right corner in the parts that this is the partner, this part of this is being made, make up to four together, if we talk about the bottom right corner, bike agricultural waste, we will see that bottom right. Talk about the corner, this one is the one is its own bottom right corner, loot is fine and after that, this is the word for these days also, so this is its bottom right corner from two square meters, bottom right corner of Talking, okay, now after that, this one is also this one, the time of this lineage, its bottom right corner is that this one, so this one is its bottom right corner, and this one is this one, how much time is this one, so this one For this one for your own one for whom one for your this big one for this one for the two size ones and one how many one and one more square is part of time tracks whose size is 38 its bottom right corner this is so once added to this Let's get this bottom right corner converted, which one is it? Okay, got it converted, look, zero is nobody's once, this time is our own, our festival is also alone after water, this is one, this is its, it is written, make yourself. As for someone else's water, we will add this one to the score of two, its bottom right corner was Khusro, one of its own is fine, one of its own and one of this big one is fine, this one is also similar, this one of arrows, this one is the same. of own cave this one cheat and this one we saw this is three square meter bottom right corner which 31 so this one itself this one and this one this is the big one okay so here I have placed it here We kept two and this one was 3's lesson needed okay so I will do something from here if you do then now school 1230 50000 so now we that actually this is but this just by itself If it had happened here, if it would have taken a partner in this, then it would not have happened otherwise. So or here, then this is because of the arrival of this lineage, in 20 minutes, I am one myself and he was here due to which 11212 subscribe so subscribe because of this because in this The first arghya due to which one is subscribed, the second one is the one which was second, the thing which has been received for the top 10 years is clear. If there was a giver here then it would have made no difference, but if there is a zero here then it is one here it is one. So due to this, a square sub matrix is being formed, the new one which is at the matrix is being formed, the new one which is at the matrix is being formed, the new one which is at the bottom right corner, due to this, a cosmetic hunter, one to you, Vasudev, in the race for one forest, open excise, but I am a forest and there are forests on three sides of me, here on the left. Above and definitely I am on the laptop, so because of this, I noticed that while making the dress, wow, this is also helping in making the Dahab matrix, each one, so it has developed it, that the lectures organized on each index, how many matters help in making it. Are you doing and ping how many are good okay here if not that here two that one then I am taking the time to make it myself tips and one on top death side one is placed one then one I am reaching here similarly here But look here, this 300 would have been given here, otherwise nothing would have been made, neither would I have made it myself, but here is the fruit, now because of this lineage, how could three be made, that one is fine here and Come for a total, okay, so because of this it falls to three, so this is the size that we saw, this is the bottom right corner, we saw that for how long are Swarag able to become like hell, then they are coming with help, at how many places are there families. Now the more people are helping in solving this, the more it is becoming a WhatsApp message, because of this, what have we lost, we have made a cab which is telling me that there is excise on every index but this even How many sports matrix is he keeping? How many sports matrix is he keeping? How many sports matrix is he keeping? Okay, okay, now see how to make this dress, how to make it is 90 and what is this Vansh 210, okay, now I have seen what is happening in it, help care, how. Now we get to know about this thing, tell me that because of this size, where is the size coming from, look, this one was the one who would have become a big ass, submit sometime. I was able to make a part but how much bigger is this book than this? There is only one book on its side. It has a wet side on its side. Its sides are different. So all three of these are on all three sides of this. Is this the bottom right corner? Because of coming once, time is becoming a trick and this is the second health. Firstly, I am myself, secondly, time helps in making tricks, but how many sizes of juice are mixed together to make how many sizes, if there are three sizes, then three. By the time Shankar Raghavendra saw that it was of the same size as the one made above, okay now look here, only the excise was there was the excise here too, so when there was excise from three sides, he added it in his Excise Aditya that will I be able to make two cups or will I make it like this Dream of three types of excise Similarly where was the excise kept here Salman here two sentences are kept that one here is this one point this one which is made one There is such a square review part which is the cosmetic shop bottom right corner which was of two sizes, here it was of two sizes but here it was of same size and here also it was of excise, so the minimum of all three was 1431 plus month. Also added that If I had been of two sizes here too, then I would have been made a little bigger, which we see here, the building is zero here, on all three sides, the head has dropped to the minimum, the footwall is broken here and there, two here, full from here, and closed from here, all three. I mean, I get the bottom right corner. In any rally, whoever makes the question A, I get the bottom right corner. Okay, so the thing kept here, the upper left one there, and the left one on the upper left side, because of these three, these days. Whatever size you are making, I have added a corner in it was not there, I had something like this kept, now this one is in the middle, it could be a part of something bigger, it could be a part of someone from somewhere like this. Tell me if I am suffering from any disease, since my arrival I have completed a square, now I do n't know how big a star I have completed, I have updated this award till now, well, how will you know this, there are two things kept on my three sides, they are minimum. Whose part is it? If there is no line here, then not every line is there, then if it is being made only by the insider, then the partner is like, should I be a part of it now or who knows, am I completing the lesson of someone bigger? How will I know the things, someone else will play a part by making things, now how will I know this, I will know from these three bottom right corners that these three will also be the bottom right corners of some other square, is n't this symbol when someone And when will you have to hit the button, out of which three, their minimum, who knows, there is nothing above here, there is nothing above you, it would be like this, only these two are part of some big Bieber, this is someone's part, neither above, when zero is defensible. Let's see how things will be done, let's see with a big example, I said that friend, this one who keeps four forests here is also a reminder from me, it's okay, now look here, this one is this one. The point is this is the bottom right corner of four size square meter deep. Now see what they do here, apply 300 ml here, I have taken only three cups of sugar from here, this is the bottom right corner of this one, so I am the minimum of these three plus one. Okay, so the chart of these three on minimum balance, now this thing could not send a message that after seeing this one, see the policeman, this one is the one, I said to this one, friend, you should have locked him in lines once like this. This is SS Rana, he is coming, this is his part, okay, now this one, the one inside, is the one, I told him, let's show the women, this is his part, road and this fast inch, this is the one whose part is three, so is it okay? Now, will this one clear the trees of these three? Now what could have been made of any cloth? Either one could have been made by returning it. Tell me, this one could have been made once. Is it of two sizes or not? On the journey, only one inside would have been made, it depends. Will do on these three that the drunkards of these three brothers, this is the part of any three sizes, then it is of some 337 that if the party and I myself are also one, then after this, friends, already it is the part of death, then here there are three sizes, above also 30. So here means there are three sizes of tomatoes here, this means there are three types of tomatoes placed on this side and keep 20111 from this also find one by keeping one, here also both the sides are kept one, here I saw, there are also here also both the sides are kept one, here I saw, there are four types placed all around here but only looked at the top. So, only three sides are kept, so I can go up to only three sides. If I can go up to only three, but only one is kept, and if I see for myself, I have come up as a plus, then I can become like this. After that, after that, its could have been made. Friends, its could have been made. had happened and could have been made of its. Three sizes of biscuits were made here. Film Party Accident. Made this. I am yours. What thing are you looking at? I picked it up. This one picked it up. I picked it up. This one picked up one border, picked up one of its borders and from here also there were 3, so from here there is only one weight, the inner part, here the partner picked up the entire four borders, the frustration is that there were zeros here and there, so if this one is four, then that is the whole war. It is okay, so this generation has given us that why do we have to look at all three sides and why do we have to take the minimum share, I have to take them because who knows from here, if there is zero above, this minimum is telling you how far I can go up and become special. How much fun could I go to this event, because of me, which chest size time, his semester is beautiful and which size is being made, he is making it in the Swat semester system, right. So, what do we have to do, we have to make a share, how will it become now, you are on the intense minimum of size, right, okay, look at the code, the intention is equal to me, tricks, Bluetooth matrix and length, and inter music volume and tricks. OK, let's make one for our DP RX100. A DP has been made for these questions. OK, loot it and we will talk about this DP on Friday. Size and how many sizes are there for help. In the bottom right corner, what are they made of? It's okay, now from zero till now, from 50 till now plus app is good, if it comes to zero, if I get the ID in the matrix, then it is of no use to me, so I am on some work, isn't it okay if I get it? The above part is done, it is nothing, if only one can make it, then J0, if no one can make it, then only one can make it, minimize it and I am the statement of DGP of GDP of IJ Minor and DPO A Minor girl is fine and this thing has to be done for a proposal, now I have got the answer to how to make it where I swear subscribe to that the film was individual Dhananjay Plus app Ajay to give an answer plus is equal to prepare for Eyes on, it's okay and the hearts come out, let's run the designated place, turn on, there was a lesson, time is going on, a lot is going on, which we have also made in Android evening, if we get zero, then it is not its white bun. Can he himself become a partner sometime? If you don't get zero, if you condition it into zero and two, then you don't get zero. Hot here, I tell you, there is fear in my eyes, but what are we doing? We are doing this by getting the minimum removed, if 204 Stroman. So there is no problem, then it is the same, if we are in the first column too, then there is no problem, then I can become Dwivedi's part, otherwise I went to both the sides and saw how much part you are able to become. When I asked him, he said, You have to read the lesson that if its side part is able to be made, then whose part is it made of, then who am I am a bottom right corner, so how many will I be able to fit, whoever among the three of you will be able to get it, its juice is fine and it will take time, friend. Bhindi Main Hindi MP3 Jhaal Yes friend, it's gone today, let's do this, whatever I run, one is going on, submit a lot and now we put some plate in it, this we have done, now tell me if a big I is in some position. When I go, do I see the one in which I am coming again? If I did not use this DP and got it updated in the matrix itself, then it would make some difference. Hmm, Deepika doesn't even put space. Whatever we had in the space was used. If you do this once, it makes some difference, it is a blessing that if I apply moisturizer once or twice on any ID, then it is a blessing, then I am not even spoiling my table, right, I am here to the minimum, Deepika is in her place. I will change it and check it, and if I have to share it in the sea, then sex meeting cannot be held, then work would have been fine here even without DP, if I had just updated the matrix, what would I have to do, this problem has been removed in the board. If Matrix is I, problem has been removed in the board. If Matrix is I, problem has been removed in the board. If Matrix is I, then please continue. If it is there, then one must have been kept there, it must have been made there, it is already made on the table and I heard that Shankar's people were with me while doing it here, there is a need to do something here and There are innumerable things that have already been made there is a need to do something here also and it is okay, here I have to get the minimum removed from the side for a few days, Mirwaiz back side minus one more - 6a, there is a side minus one more - 6a, there is a side minus one more - 6a, there is a trick in place of DP here. Update it in OK and it is outside, get your answer guna plate right here, meditate here till the time you get the cleaning done, the people below do not join, came out from here and termed it a stunt, answer penance, write a good dance, write a trick, flowing in one Big answer A, how to run it, let's submit it for the scientist, okay, what have we seen here, what is the observation, what is the media reservation? The bottom right corner of Jodhi's is a fixed one, who is able to become a part of whom from here. Let's show whose part is being played. You see, friends, it is right, he was the part of the person who will become the size of juice and whose lesson will help him in it. If he is a part of 300 meters, then I have become three, like Romeo, three are becoming. We have subscribed, Aaliya, that's all I had to do, okay, thank you.
|
Count Submatrices With All Ones
|
get-the-second-most-recent-activity
|
Given an `m x n` binary matrix `mat`, _return the number of **submatrices** that have all ones_.
**Example 1:**
**Input:** mat = \[\[1,0,1\],\[1,1,0\],\[1,1,0\]\]
**Output:** 13
**Explanation:**
There are 6 rectangles of side 1x1.
There are 2 rectangles of side 1x2.
There are 3 rectangles of side 2x1.
There is 1 rectangle of side 2x2.
There is 1 rectangle of side 3x1.
Total number of rectangles = 6 + 2 + 3 + 1 + 1 = 13.
**Example 2:**
**Input:** mat = \[\[0,1,1,0\],\[0,1,1,1\],\[1,1,1,0\]\]
**Output:** 24
**Explanation:**
There are 8 rectangles of side 1x1.
There are 5 rectangles of side 1x2.
There are 2 rectangles of side 1x3.
There are 4 rectangles of side 2x1.
There are 2 rectangles of side 2x2.
There are 2 rectangles of side 3x1.
There is 1 rectangle of side 3x2.
Total number of rectangles = 8 + 5 + 2 + 4 + 2 + 2 + 1 = 24.
**Constraints:**
* `1 <= m, n <= 150`
* `mat[i][j]` is either `0` or `1`.
| null |
Database
|
Hard
| null |
345 |
number 345 reverse vowels of a string go write a function that takes a string as input and reverses oh there goes the grammar again only the vowels of a string example one hello you reverse the o and the e whoops now elite code you reverse all the vowels are there the vowels does not include the letter y the grammar does not include good grammar y is not a vowel so why put that and let's go so this is just some sort of string manipulation exercise that's what they want you to learn they don't want you to learn their bad grammar they don't really want you to do anything else it's an easy problem however you just have to manipulate things as you can the first thing we're going to do here is come up with unordered set of cars and this is our little improvement which we're going to call my vowels instead of having some sort of what is it if statement all over the place we could just set everything here i o u and we could just search this um this unordered set an o of one time because it's a hash map it's a hash table um and that will tell us whether it's a vowel or not whether we're looking at a vowel or not so they also want the capital letters okay next our plan is to iterate through this word we're going to have a left pointer and a right pointer and while left is smaller than right we're going to increment the left pointer until it finds a vowel and we're going to decrement the right pointer until it finds a vowel as soon as they're both on vowels we swap then we increment again until we find the next vowel and decrement again until we find the next vowel while left is smaller than right and that's it so that's how we plan to do it so let's begin so into left equals zero inch right equals side s dot size minus one while left smaller than right it almost looks like a binary search um okay so while left is smaller than right um we're gonna increment left so while left is um smaller than s dot size and okay now we're going to search through the vowels my vowels dot find s dot left equals my vowels dot end if you're not familiar with um what we're doing here is incrementing the word if we if it's not a vowel and if you're not familiar with this nomenclature you should look up containers at your dearest uh at your dearest um kind of reference book or website i recommend c so we're going to do the so we're going to do the so we're going to do the same thing over here with the right just copy that while right and or just a slightly different condition is bigger equal to zero um and we're searching for the character we're searching to see whether the character at position right is a vowel and if it's not we decrement then uh oh yeah well we also want a swap function so this should be almost second nature to swap two characters or two integers or whatever so first we come up with attempt character then we say a equals b and b equals temp done when we increment incremented left and we found a vowel and we decremented right and we found a vowel we still want to check if left smaller than right because it could be that while it was doing this they kind of passed each other or if you already reversed vowels that you kind of crossed each other and you went back um and it does this at dossier so it keeps on replacing the vowels that it already replaced every single time so when that's true you swap the two so s dot left and s dot right and after you're done you increment left and you decrement right and at the end of all this you return s and again i'm not sure why they don't just pass this by reference but nobody asked me my opinion let's see if this works and it looks like it did we run it and let's just run that again see if our um so it just ran a lot faster 10 seconds ago with the same code i'm not sure what's going on thanks a lot everyone let's run it again see now it worked faster have a good day everyone
|
Reverse Vowels of a String
|
reverse-vowels-of-a-string
|
Given a string `s`, reverse only all the vowels in the string and return it.
The vowels are `'a'`, `'e'`, `'i'`, `'o'`, and `'u'`, and they can appear in both lower and upper cases, more than once.
**Example 1:**
**Input:** s = "hello"
**Output:** "holle"
**Example 2:**
**Input:** s = "leetcode"
**Output:** "leotcede"
**Constraints:**
* `1 <= s.length <= 3 * 105`
* `s` consist of **printable ASCII** characters.
| null |
Two Pointers,String
|
Easy
|
344,1089
|
1,425 |
Table Today They Are Going To Discuss Elite Problem Tasty Maximum Subject Some Governor Content Ashok Tanwar Na Important Terms And Example Se 021 To Take Medicine From This Subscribe And Numbers In All Soon Subscribe Button More That Where Is Take Jin-Jin Swadesh That Where Is Take Jin-Jin Swadesh That Where Is Take Jin-Jin Swadesh Ki A Definition In Taxes Where Two Elements Can Not Be More Than Sacrifice Of Taking 1000 To - And Quote You Sacrifice Of Taking 1000 To - And Quote You Sacrifice Of Taking 1000 To - And Quote You But They Can Take 500 And Want To Get Maximum Sum Of The Subject Possible All Subjects Are Listed Here With Elements With 12345 Android Subjects In Orange And Solution 2076 Acidity Problem Solve This Problem With The Stars Subscribe And Quid Maximum And Milk But Lets Tattoo Is Tomato Play List Tuesday Programming Kal Subah Guddu Is We Want To You Sir Dynamic Programming Even Tuesday Results Of All Problem Understanding Size And Problems Size - 1929 Result of Problems Size - 1929 Result of Problems Size - 1929 Result of problems to get the results of the jhal sukh how can achieve this software 12512 create maximum which stores maximum value for its element a vendor particular element included sale wants to get currency given maximum 100 is active and passive waste macro value with which you will be This is just this value added end and tenth of this volume Wilson Previous solution Sentence Wikinews only elements within which lie Indore range K Sunil Used in maximum The results of previous maxims from the - 121 - K Suggestion Means this Wikinews - 121 - K Suggestion Means this Wikinews - 121 - K Suggestion Means this Wikinews element only if you are lost end - K element only if you are lost end - K element only if you are lost end - K last sorry last k maxims arya and last k elements of units viewers maximum only from others and gives body system morning and evening these elements and with default maximum last k elements and see what is election 2012 maximum of the element is that we laddu with The help of example for equal to zero and maximum forces stand against injustice element dozens of previous elements for this and made them stand and result date final match stand now max m1 is later to and read this element plus maximum last me subscribe 1000 2000 to two to The maximum to is the maximum of these elements - 0 and this element plus elements - 0 and this element plus elements - 0 and this element plus blouse to so much someone maximum one is the 1200 stranded no damage to minus plus minus 1032 bill-2013 low 10 minus plus minus 1032 bill-2013 low 10 minus plus minus 1032 bill-2013 low 10 C-17 Dravid result hua tha C-17 Dravid result hua tha MP3 ki awadhi r c plus co dot the earth is particular dynamic programming algorithm witnesses said the result in the and determine which lies maximum wishes for b id elements button click justin.tv servi divya 2012 news se withdraw from one to two elements of elements and 100 days and half Person Maximum The Independence Day Result Facebook And Secure At The Time Complexity Of This Is Chief Justice Of Waterloo Times Of Date In Ullu Sentence Of Indies Complexities That And For The Number Of Elements Decision San Hua Tha So Ek Suno Bichuvva Seervi Doing The Times To Krishna But Will Need A Maximum Of The Last Day Of Attacks On Celebs Towards Tomorrow Morning Window Instituted Of Using Maximum As We User That Europe's Element School Of Why Interviews And Work Hard Match Them Tube Which Gives Maximum Element Of The K Tune In Different Flash lights front so and whenever they remove elements from different of the why they want to update and mix recording facility women in the front of the guru will check reduce stomach elements ms chief macaroni why front s well with distinctive s against Element from different of the match Solitude and insert a new element of witnesses and they want to incident increasing order fashion maximum element width element last element quantity 1000000000 quantity Note 3 business inside the last element in the back-up element in the back-up element in the back-up a message disease maximum element of the current Which cute in different of the match soldiers let's directly selection had happened so let's do take which example we and deposit also included in this life equal initially French twist you will have two elements very element definitely and make sure you will have been maximum 3000 years In English Test for All 60040 Kal Mexico City Mexico of this element id am id to give some time instituted of calculating maximum Video then subscribe to the Page if you liked The Video then your settlement max of two and tubeless max Planck Institute Front Special ten plus two result twelfth activity deposit you two different objects and activist rule and addition to the accomplishment British administration show the volume two button president Sudhir Vinod 1000000000 subscribe Video co entertainment vacancy for is equal to three layer maze pe 10 sentences into and finally Loot 3737 व्यति jio4gvoice is ab school 40th slice 100 end activity elements and subscribe to this feed modi why attributes of smaller continue element in this case which is the local max and ruby confirm element in the local max and ruby confirm element in the local max and ruby confirm element in the back and also indicate why against element from different Subjects with this element Why video for this video
|
Constrained Subsequence Sum
|
weather-type-in-each-country
|
Given an integer array `nums` and an integer `k`, return the maximum sum of a **non-empty** subsequence of that array such that for every two **consecutive** integers in the subsequence, `nums[i]` and `nums[j]`, where `i < j`, the condition `j - i <= k` is satisfied.
A _subsequence_ of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order.
**Example 1:**
**Input:** nums = \[10,2,-10,5,20\], k = 2
**Output:** 37
**Explanation:** The subsequence is \[10, 2, 5, 20\].
**Example 2:**
**Input:** nums = \[-1,-2,-3\], k = 1
**Output:** -1
**Explanation:** The subsequence must be non-empty, so we choose the largest number.
**Example 3:**
**Input:** nums = \[10,-2,-10,-5,20\], k = 2
**Output:** 23
**Explanation:** The subsequence is \[10, -2, -5, 20\].
**Constraints:**
* `1 <= k <= nums.length <= 105`
* `-104 <= nums[i] <= 104`
| null |
Database
|
Easy
| null |
1,957 |
hello welcome back today let's try to solve another lyrical problem 1957 the lead characters to make fancy stream so it's really easy to understand a first history is a stream we are no three consecutive characters are equal so for example the lead code for this e there are three characters so it's a fancy actually we need to reduce the three E's to two e's it will be just after lead code yeah as you can see and as you can read from the title or the descriptions it's basically a list group problem because it's always about consecutive characters if the consecutive calculus are three years you just need to reduce it to two yeah and for every list group problem we just need to record the index the start index and the eye index yeah and then you just need to get the result let me write the template code if you need to check the details of why we are going to use list groups template to solve the problem you can track my videos or delete code problem 228 by also analyze why the temp time complexity is a software yeah that's exactly the result it is s equals to 10 to the power of 5 and it means you must use o n to pass for the lead code or you can use all unlocked but for this program basically it is the First on now let me write the template so I'm going to prepare a result so the result will be my final return so and the iporter will start as a zero and the L will be equal to the length of the string so the result will be at empty three and iporter will be zero and will be length of the string now I'm going to use the two while loop so while I less than n and the outer loop the inner loop so while I less than -1 and I'm going to exactly conditions -1 and I'm going to exactly conditions -1 and I'm going to exactly conditions the condition is the problem we just need to check the consecutive unique characters so it will be the same as other similar problems like before with I solved a lot of similar problems now it will be numbers I equal to nums I plus one and here we're gonna use double equal and from the after the outer loop we're gonna have a record of the start pointer equal to I and inside the while loop inside the inner while loop we're gonna update it the eye pointer should be updated by one now we are going to check the result so if the lens I mean the length of the start to I minuses start plus 1 if this lens is more than three basically we're going to update it because 3 is not the result we just need to let it become too ease if it is less than three we first need to put it into our results yeah so here we just need to have a f tag let me put a temporary variable answers for the normal case so for the normal case it will be just from the string of start to I plus 1 because in Python for the add index for of the supplies it is not included now we just need the two tag if I minus start plus 1 is less than and equal to 3 we just need to update the answers so the answers should be equal to S with the start and start plus 2 because if it is a more length or equal to 3 we just need to make it two characters if there are three is we need to make it two e's now we just need to update the result so the plus equal to the answer and the pointer should be plus one and now we just need to return the result now let me run it to attack if it really works um yeah there is some type typo let me delete that of the Norms it is 3 is not announced let me put it to a stream as you can see it works now let me submit it after that I optimize a little bit of the code but really it doesn't matter because you are just learning the patterns it's a list groups patterns you are not learning to make your python code so fastly I mean the pricing code has already been so fancy you need maybe you need to yeah write a little bit fancier than that you can yeah you can see the speed it's a nearly 42 percent of all python series submissions but it doesn't matter because it's just their own algorithm and for here for this three lines basically you can make it to one line yeah because in Priceless or other language it's possible to make it like that so for other without uh let me put it for the answers we just need to use one line vocal one line of code it will be like this so the answers will be equal to start with the minimum of start plus 2 with the minimum of here is I Plus 1. yeah you just need to tag yeah because even it is more than three or less sweet but the end point should be bounded to the minimum of stat plus 2 or I plus 1 it means it will always be less than and equal to 2 so this admissions the answer can never be more than or equal to three now let me submit it to that if it really works yeah as you can see it works and with us to reduce the two lines of code but it doesn't matter because we are learning the patterns we are not learning about to making the python code so fancy thank you for watching see you next time
|
Delete Characters to Make Fancy String
|
closest-room
|
A **fancy string** is a string where no **three** **consecutive** characters are equal.
Given a string `s`, delete the **minimum** possible number of characters from `s` to make it **fancy**.
Return _the final string after the deletion_. It can be shown that the answer will always be **unique**.
**Example 1:**
**Input:** s = "leeetcode "
**Output:** "leetcode "
**Explanation:**
Remove an 'e' from the first group of 'e's to create "leetcode ".
No three consecutive characters are equal, so return "leetcode ".
**Example 2:**
**Input:** s = "aaabaaaa "
**Output:** "aabaa "
**Explanation:**
Remove an 'a' from the first group of 'a's to create "aabaaaa ".
Remove two 'a's from the second group of 'a's to create "aabaa ".
No three consecutive characters are equal, so return "aabaa ".
**Example 3:**
**Input:** s = "aab "
**Output:** "aab "
**Explanation:** No three consecutive characters are equal, so return "aab ".
**Constraints:**
* `1 <= s.length <= 105`
* `s` consists only of lowercase English letters.
|
Is there a way to sort the queries so it's easier to search the closest room larger than the size? Use binary search to speed up the search time.
|
Array,Binary Search,Sorting
|
Hard
|
2179
|
146 |
hello friends welcome to joy of life so today we are going to look at another medium level problem from leadput the problem number is 146. so it's a lru cache so design a data structure that follows the constraint of which recently used or lru dash so implement the learning cache class so you have to implement this entire class over here right so it has a constructor lru cache in capacity so it takes the capacity of the cache initialize the variable cache with positive capacity so you have to give some numbers like 1 2 3 before it should be positive it should be greater than 0 and then we have a get function to get anything from the cache we need the g right so it takes a parameter which is the key of the value that we should be returning return the value of the key if the key exists otherwise we done a minus one right so if the key doesn't exist then we need to return a minus one the other important function in our cache is a two right very neat password the key and the value so we'll be getting the key and the value update the value of the key if the key exists otherwise add key value pair to the cache right so if the number of key exits the capacity from the um from this operation i make the least recently used item right and also there is a follow-up to it and also there is a follow-up to it and also there is a follow-up to it could you do it in um could you do both the get and put in body of one that means a constant time complexity right so we are going to look at that and we are going to see and understand everything is much more details so if you are new to cash this video is absolutely for you if you know what a cache is and you wanted to know how it operates and how we can solve data in order for order of one complexity to time complexity how we set the data how we put and get the data in autograph on time complexity then also this video is absolutely for you and uh if you know what the cache is then you have some idea then do it in the paper under pen at least try to solve how the cache works what would be the data structure that you'd be using and how you would be using in order to design a lru cache right so let's head over to the board and understand the solution or understand our cache work in much more details so cache is nothing but a key value store wherein we have the key and the value we use the key in order to retrieve the item right so cash is often used for locally storing some data and which can be accessed very fast so that's why you perhaps seen in the problem that they have asked for a constant run time everywhere because we need a very fast access of the data and for that we basically use the cache so whenever you make a network call again and again for the same request and for a particular request and you uh anticipate that the response is not going to be changed it's going to remain the same in those scenarios you mostly use the cache right so let's uh see some example over here and understand how the same is used right i have an application let's try to understand the usage of a cache i'm going to give you a very nice scenario wherein we can use the cache so suppose you have your application over here and what you probably do over here is like you store the ssn number the social security number for the user or for indians it will be easy to understand with your other number so every time you give me your ssn number or your other number or any number over here i go to the database to query using the other number or the ssl number and i get your first name last name and your address for example for the need of our application or it might also happen that either we have a database or i'll put an order over here or you might call another application which is not yours maybe which is a government hosted application wherein you're authorized to get the details for the user so you pass him the ssl number and it gives you the details so you pass in the ssn or the other number and what you receive from him is nothing but the first name last name and address right there could be several applications where we might have a need like this right so what is the problem with this the basic problem with this is that it requires time right the database is not in your own server right so you have to make some io calls it will go to the database you are going to query it and then you are going to get the result and then you are going to process the result and so on there are uh there is some network traffic involved in it same for the third party applications you are going to get the details and let's say that you have a number which is xyz a number other number or a ssn number how often these things are going to change how likely this data is going to change it's very rare that you are going to change this right it's going to be more or less the same thing right so what we can do is we can have a cache of our own so what we can do is we can say that once i will vary you and once i get your data i will have a cash over here this is basically a cash so what i can say is that i can make use of a cash so i make a query to the database and when i get a response i am also going to store them in the caches object there are various strategies of storing i am not going into that so as asum when i am getting the response from this guy over here i am going to use the response and i am going to put it in my cache so next time when you ask me what i do is i have stored the entry in my cache that this is my key xyz and this is his first name last name and address so when i next time get a query for this user to get all these data what i'll do basically is i'll go and check if xyz key exists in my cache i see that yet yes it exists i'm going to return this rather than going to the database or the third party application again and again right what it makes is you tend to serve your request really fast right and similarly you can keep on adding and entries like this so what happens when you store a lot of records is your stats for cash starts growing right and you can't store everything that you have right there could be billions of people in your country and you cannot store for each one of them so what you're going to basically do is you're going to say that okay ehy has been used maybe 10 days a whole right this was used seven days ago this was used five days ago this was used 10 seconds ago so i can say that this is my least recently used entry in my cash right so i am going to throw him out when my cash is full so i say that i am going to store only four records so i have four records and i get a new request to store mno right and i have to throw one of them out so which one i will throw out i will definitely throw out the least recently used so here a xy is the least recently used right so i am going to throw him away and put mno and this is called evicting the data from your cache or clearing the data from your cache there are multiple strategies to do that but we are going to check on lru so this was a little understanding of how your cache works and then now what we are going to do is we are going to see which data structure will help us to do the get and put in order of one right we need fast we need to serve data fast we need to store data fast suppose this was taking 15 milliseconds so the expectation is that my cash will return much faster than this number over here so here we are going to see how we are using multiple data structure in order to come up with the solution and we serve the data in constant time so here let's understand how we are going to implement get input and our sla is order of one or constant time so we need to complete both this operation in constant time so let's put there are some common operations right here are the two common operations that we need to address one is the addiction so when we say eviction we have something called our cash size or capacity we can say and we need to evict after that so let's say the number is 5 just for the simplicity of understanding and also we have to uh take care of the least recently item right so let's say i have one two three four and five right these are my keys and each one of them had associated values stored with them right and how do we do the get operation in constant time so i have a key i need to get the object and i need to return the object in order of one time so which status structure comes to your mind when we hear that so for me i'll say it is nothing but the hashmap data structure that comes to mind so the map stores a key value pair like our cache and hash map which ensures that i can return the element in a constant time so let's put down the operation over here get the element from the map using the key and we know that hash map ensure the order of one since the keys are unique and we are using the hashing technique we will get the element in order of one and one stand time right so now let's consider this example over here we have one two three four and five these are my keys right and say five is the least recently used and four then three then two and one is the most recently used right so how we are going to store that so now if i get a key over here new element 6 i see that my cache is full i need to edit and i need to evict out 5 so how we are going to deal with that how do we know that we have to evict five right which data structure are we going to use in this scenario right so what comes to my mind over here is to maintain an order right we have to maintain the order and when we have ordered kind of things what comes to my mind is a list right in list we can have the elements in right order right and if i create a list wherein i have nodes we'll come to it in detail so let's say we have multiple nodes in this list like this right so i have a list like this let's say so this is this looks like a link is right why i chose an english because i don't know the elements that's going to come and i have to put that element lot of things is associated with that so what does this list have so what is the order of this list right we can keep things in order so what i can say is that this is the head which will have the most recently used and this guy over here will have least recently used so whenever i access a element from here i'm just going to take that element and put that in the front of the list right so if you see here that this list and this map over here is storing the same reference right and what we are going to do is we have to move william shuffle elements in between in the list right so for that what i feel shoots best is a doubly interest and we will see why we are choosing a doubly linked list over here so let's create this link list with one two three four and five these data and see how why we are choosing a doubly linen list so these are the nodes and as you know in a doubly linked list what happens is we have two pointers right one is a forward pointer what we call is a next and we have a prep pointer so we can come back so in a normal linked list or a singly linked list what happens is when you go to two you cannot come back to one when you come to three you cannot come back to two you cannot come back right and we will see why we need to come back shortly and so we'll let's establish the double pointer over here let's say we have two nodes over here one is the head and we have a marker to the table right so now when you tell me that you want to put a 6 over here in this situation that a new node has to be entered and our list is full right or our cache is filled what i am going to do is i am going to remove this node the tail node now you think that had it been a sinclair linked list how would i update the pointer on the note 4 right it's not possible for me to update the pointer on note 4 i have to come from the beginning or i have to maintain the mapping of all my previous notes which is again cost will cost me an extra memory right so we are going to have a marker to the head and to the tail right and what happens as we know from the statement that this is the most recently used and this is the least recently used right so when you tell me to that you are going to put a new node and my cache is fun how i am going to handle this i am just going to update this node over here the last but one node in the list and set it to null so 5 is moving off basically which is the least recently used node so how we can reach innocently ling list this pointer either we have to store additional mapping or we have to traverse all over again to reach the node right but in this case what i can simply say is that i can do a tail dot prev which will take me to this node and i will set its next and i am going to set it to now right and that's it i am done over here right so this is the reason why we chose a double influence right and we see that least recent eviction is something is that is taken care of right so i'm fine now what about the least recently used how it's going to help me in the least recently this case so this eviction that you have just seen right what we are doing are we iterating over the list if there is a million items in the list i am going to go over all of them no we are not we know the tale and we are going to just modify that portion only so this eviction is also going to cost me order of one right and keep in mind we have both head and tail marker and we will be updating them now let's see this is the condition of our list so we have seen how we are going to take the insertion into account right now let's understand how we are going to deal with the list recently used so you wanted to get the element with the value with the key three so i will get it from the map and i will let's say this is my node over here right so you have accessed it i have returned you back but now i have to update the same into my map right so what i am going to say is basically node.red which means this node over here node.red which means this node over here node.red which means this node over here dot next is equals to node dot next so basically what i am doing is i am cutting off this link over here and instead i am putting this link over here right that's how i can take care and also node dot next prev right so i'm talking about this link over here this also i need to descend it and i need to put it to node.trap so basically this link is being associated over here right and what we are going to do is we are going to take this node up and now what we are going to do is we are going to set node dot next is equals to head right so that means this node over here now this is my node over here which is of the value 3 and what i am going to do next is i am going to put note dot next is equal to head means node dot next is now pointing to this and what i am going to say is at dot prev is pointing to back to the node do keep in mind this is my node and the next statement over here i am going to say my head my new head is my node so basically that will ensure that i am getting this head thing over here and i am making it point to the same node over here so all these operations over here is responsible for this least recently used updation right so all these operations if you see that we are not iterating over the list right we are just manipulating what we have so all this operation could be complete in order of one right there was no iteration involved and that is how our eviction as well as our least recently used has been taken care in the problem here so this is the entire algorithm all about so what we are going to do is we are going to quickly check the code and understand so let's understand this um lre cache from the code perspective so the first thing that we needed is the class the custom class that we have talked about so here is our class for node so as mentioned that we are going to store the key and the value as integer and we need couple of pointers for the w links list implementation that is the priv and the next one and here we have a default constructor as well for this node just right and now let's move over to see what are the instance member variable for this class that we require so here's what we need the map which is going to be a hash map implementation for the cache where we have the integer the written value is an integer but we are storing a node so that we can keep the instance of this class right we need so we need to have instance number variable for the count so count basically denotes the number of elements that you currently have in your catch right so that we can compare with the capacity and we can work on our eviction capacity is something that's constant and that's what we receive in our constructor over here and so we need to this is the upper cap for the key value that we are going to store inside our map right and then we have the head and the tail for the doubling right so let's look at the constructors we'll initialize all these variables that we have declared so the cache is a hash map implementation of integer node with the capacity given count is zero since we have no elements capacity is something that we have received and since there is no list yet we have the head and tail pointing to null right then we have the get method so the get method returns again so we'll be returning a hint and also we need to return a minus one in case the element is not there right so over here what we are going to do is we are going to use the key and look into our map and retrieve the node from the map if there is a null if the key is not there what we are going to do is we are going to return a minus one right and this node over here since it has been accessed it has to come to the front of the interface right so that's why we have this method with move to front so this load should come to the front of the lenses and at the end we are going to return the value which is nothing but the integer this integer over here to our caller right so let's look at this function get node to the front but this function what it does it's when you pass a node it gets it to the front right so if it is already in the front that means you are accessing the most recently used not only which is already in the front we don't need to do anything that's why we are checking for know this equals to it then we don't need to do anything right and uh if you try to access the least recently used node which is at the tail of the node what happens in that case we get the node from that position to the front of the list right and what happens because of that is the tail of the list changes the tail shift point to the previous node to the table right because that tail node has been gone to the front so that's what we have done over here and then also the pointer manipulation that we have already seen in the board over here so we are going to do that so previous nodes next point you should point to the next note and then next nodes previous pointer next nodes previous point this should point to the previous element over here right and also uh since we are creating this node to the front of the list so it does not have a previous and the heads previous that's the current head that we have that's where we should point to them to this node and this node's next should point to the head so we are re-establishing head so we are re-establishing head so we are re-establishing this map in this part of the mapping and we are going to update the head of the linked list to the node that has came to the front right so that's all about the state node to the front part and then the last method that we have is a put method so what we do is basically in this method is uh first we check in the map that if the key is already there in that case we just need to update the value right so in that case we are going to fetch the value from the map and if it is not null or minus one or something like that we are going to update the value to the past value and get this node to the front again so we basically leverage the same method right and then if that's not the case that means it's a new entry to the map it's no more updation so in that case what we do is we implement our account and if our account has exceeded the capacity we have to get the data out from the 10 right so if the head is equal to the tail that means there is only one item so i'll make that null right otherwise what we do we remove the item pointed by the pin so tail dot pref dot next so tails previous pointer is the second last node in the list i point is next to null that means i release the tail and i make the tail point to tails previous right so tail should also come to this node right so this is all about the election part when our memory is when our count is more than the capacity otherwise so once we have taken care of that space we are going to do this for both the cases once we make the space or we have the space we are going to create a new node with this key and the value and if head is not equal to null so initially the head is null right in that case what we are going to do we are going to put this new node in the front of the linked list so head dot prep is pointing to this new data and new data dot next is my head right and also if the tail is also when not established if tail is not i'm going to say that tail is my new data that's again just one note right and then i'm going to reset my head to the new data or the new node that i've just created right and then i put the key and the value so i know the key and the value i put them back into the cache right i think there's one extra space so yeah this is the solution all about let's run this code and see how it goes it will be fine because i published it so let's uh submit and check how's the performance so it took 30 milliseconds which is better than 82 percent of the submission we are pretty good in terms of memory as well based on all the submissions so once again here the main purpose is to give you the idea on how this cache interaction work right so it is one of one such problems where we leverage multiple data structure in order to ensure that we are giving a constant runtime for all our use cases right so for this one over here for eviction for least recently used forget for good again putting in the map is also our form operation so i hope you got the solution over here you got the concept behind how cash works how hilario or the least recently used thing in a cash works how the eviction is being handled how the least recently used item is maintained and how it's been erected when our cash reaches its capacity so do let me know what you think about this solution i hope you got the solution though it was pretty complex in part but concept-wise it is pretty in part but concept-wise it is pretty in part but concept-wise it is pretty clean and simple the mechanism how it works is pretty simple so do let me know it would be a pleasure to hear back from you guys and also if you have any question with any parts of the solution that we have discussed behind then just let me know so yeah i'll keep this video short over here i think we have already been overshooted a lot so yeah stay home stay safe it's just been terrible seeing 20 000 cases in bangalore in a single day so i request you all to stay home stay safe take care of yourself and your family and yeah hope to see you very soon again bye
|
LRU Cache
|
lru-cache
|
Design a data structure that follows the constraints of a **[Least Recently Used (LRU) cache](https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU)**.
Implement the `LRUCache` class:
* `LRUCache(int capacity)` Initialize the LRU cache with **positive** size `capacity`.
* `int get(int key)` Return the value of the `key` if the key exists, otherwise return `-1`.
* `void put(int key, int value)` Update the value of the `key` if the `key` exists. Otherwise, add the `key-value` pair to the cache. If the number of keys exceeds the `capacity` from this operation, **evict** the least recently used key.
The functions `get` and `put` must each run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "LRUCache ", "put ", "put ", "get ", "put ", "get ", "put ", "get ", "get ", "get "\]
\[\[2\], \[1, 1\], \[2, 2\], \[1\], \[3, 3\], \[2\], \[4, 4\], \[1\], \[3\], \[4\]\]
**Output**
\[null, null, null, 1, null, -1, null, -1, 3, 4\]
**Explanation**
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1); // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2); // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1); // return -1 (not found)
lRUCache.get(3); // return 3
lRUCache.get(4); // return 4
**Constraints:**
* `1 <= capacity <= 3000`
* `0 <= key <= 104`
* `0 <= value <= 105`
* At most `2 * 105` calls will be made to `get` and `put`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Medium
|
460,588,604,1903
|
520 |
Hello Guys Welcome Back To Decades And This Video Will See The State Capital Problem Wishes From List To Dog Assailant Conscience Planning You To Approach In Order To Solve This Problem Solve Latest Read Problem No Problem Gives What You Need To Judge Weather Or Not Define The Uses of the following is The First President of USA Cash Withdrawal subscribe and subscribe the Video then subscribe to the Page if you liked The Video then subscribe to the Standing Boat in the Example 80 Patience for Kids Were All the Latest Capital in the World subscribe The Channel Please subscribe and subscirbe Subscribe The Worst Position Otherwise Letter This Is Not The Return Of The Day Status Look At The Rules For The First Toolset Award Can Have All The Perks And All The Lower Case Letters Se Control System Word Can Start With One Capital Letter For Loved By All The Lower Case Latest Saugandh Combination Monday Ki Delhi Noida Subscribe Must The Capital Letters Where Is The Capital Of The Worst Position Only One Capital Letter Subscribe Position This Is The Capital Letter Subscribe Button Thursday Quiz Correct Vikas The Capital Letter His Only Years The Worst Position Situated in the Last Words to Also Validates INS Wear Heavy Capital Letters and All the Positions of the Story The Rule 90 Approach to Solve This Problem for the Worst When Invented by Covering All The Water Subscribe And Small Number Of Cases Without You Totally Free With The PS Gill Sick Dress Invalid Latest Se 10 Vwe Capital Nandish Vikram Invalid Record Only One Capital Letters Business Boxing In the worst position will be falling in this is very simple to cover all the subscribe and subscribe the Channel Please subscribe and subscribe the capital letters in the capital letters no what is equal to what is the subscribe which is the capital letters Jai Hind is case which will not hold to know the second one is that is account is lineage and difficulties of workers in this and account is lineage and first character is so this is matching discus 100 will be retold improve work now let us look at the second Example with the second example with passing this trend and account of capital letters will be coming to which is this are you will again request the person to subscribe and subscribe This is to The Amazing 2019 This is the best all small letters 2009 ka birthday se also Not True And Singh Of This Show The Final Of Country This Is For Invalid Strings Notice And Account Dr To The Point Will Not Fall In Your This Cases And So Will Have To Return For Cigarette Decision Invalid Of This Handed Understood District's Approach Which Is Just Doing setting of the capital letters OK no latest look at the code for this approach 19 This is the code of the first approach This is the function which gives the giver characters' function which gives the giver characters' function which gives the giver characters' server not the capital use function will give what will be the size of The World Channel Subscribe Is Din Will Return True And Give All The Character Notifications Let Me Show You Okay Night All The Character President Rule According To The Character Of The Return Gift All Subscribe By Subscribing The subscribe to the Video then subscribe to the number of letters subscribe number of setting on main socha hai domination wide is letter sari chords to end that mince all the latest r capital ok doctor capital and evil returns through adverse effects account is zero this is the best all the Latest Small and all the letters for wealth will be written to improve otherwise Ephesus letter is capital that is it is polling in the range of A to Z Swift letters capital and tarf account discretion to improve like this one OK otherwise fostering is not falling in all cases Will Also Give A Code To Do Subscribe Like Share And Subscribe
|
Detect Capital
|
detect-capital
|
We define the usage of capitals in a word to be right when one of the following cases holds:
* All letters in this word are capitals, like `"USA "`.
* All letters in this word are not capitals, like `"leetcode "`.
* Only the first letter in this word is capital, like `"Google "`.
Given a string `word`, return `true` if the usage of capitals in it is right.
**Example 1:**
**Input:** word = "USA"
**Output:** true
**Example 2:**
**Input:** word = "FlaG"
**Output:** false
**Constraints:**
* `1 <= word.length <= 100`
* `word` consists of lowercase and uppercase English letters.
| null |
String
|
Easy
|
2235
|
1,764 |
200 Welcome to my channel So in this video I am for those who are migrating survey surfers, it is a very simple problem so first of all in the video I will discuss the problem then we will quote again on that mic you will make you think ok so the problem is basically me I have given a group of address and find me, please find out and tell me one more note, tell me the number of groups in this group, how many RS are there in this group, all of them should be combined in the description box, plus they should not overlap with each other. And these should be in order, okay, so if you want to understand the example, then like one minus one, so he was extracting here and then 13 - extracting here and then 13 - extracting here and then 13 - 2013 presses in this and these two do not overlap each other, plus the first one here. Hare is coming here first, you are also coming at second number and in the second case, like it is 123, so let's adjust here, 343, then it does not unite, chilli flexes, but this is the platform, okay, so this We will solve the problem, now we will divide it into parts, basically the approach has been that first search one thing one minus one, okay - I have one minus one, okay - I have one minus one, okay - I have subscribed one minus, if I find it for this reason then I will do something else. No need to do this, if I install it then like by setting it to 205, the number is three, but the number was not, it means both got it and mine is also there and if you see the case of J, I got 123 in it, okay now I will go to three. Four, if you have given me this condition and I want to get it done in velvet then it is okay, this ironing meaning party smith forex should be done okay, so in this I have to do three practices, so in that case, I will make this point metropolitan and This will send my main function to the hospital, meaning it is ok and what was happening about this, here I went to a third group, they definitely gave me the bag, they also returned it to me and I got my answer through ok, let's quote the rest of it. Let me explain, still there is less and T-shirt, okay, so there is still there is less and T-shirt, okay, so there is still there is less and T-shirt, okay, so there is no problem, first of all, I create two interiors, inch logical 120, intent of 120, so basically this group is intact, meaning which group number is it and where is the index at this point and If everything is fine then now I will create the function Return Solve Husk-Husk Namaskar Jiya Return Solve Husk-Husk Namaskar Jiya Return Solve Husk-Husk Namaskar Jiya wear a garland Ok so let's make a group then liquid use that cream so now forget solve you here Similarities I have to do shopping here Control C Control Ghee Pendant Jiaye Comment Intention Okay now what will I do first of all that writes down from 24 hours first of all so S Jiaye Equal two groups don't size I your group thoughts is generated through physical what is it telling is telling that if number groups complete It means like if you lived with two groups and what was there in the shooting, yes, there is zero in the setting, then group number one will be life and then if you decide, then if you lived two, then the activist group does not accept two, it means that the total number of It is complete in the rate of front, then you will understand that it means that I have got some qualities in the return room. Okay, now what will I do, now I have to point to my more basic roots, I have enough in my name, so I have started. Look, first of all, as I reached the office yesterday, do I need to fit it in this and currently the point in my name is pointing here? Okay, so let's do the height, so first of all, I make it like technia batter. tractor int cheesy is equal to what hussain group-2 cheesy is equal to what hussain group-2 cheesy is equal to what hussain group-2 suicide ok so this is the current group i have stored here and in taekwondo rahna hai in try record hai meaning my current which is intact with the number name there like your Equal above neither toilet nor size is ok. Now inside this we will create a folder which will appoint my group but where is that group in it, President is ok. 100 points equal to news and subscribe. Now here I will match that which is my current If the character who is in the group has sexual intercourse, if he doesn't then it's okay with them, then I will explain it to you understand plus because it is available like I am doing zero to computer, okay then look in I plus, cheesy zero. And number 0 will compare and whatever comes Wally do whatever 2002 subscribe he will go okay 100 if it is so then what should I do of this note 10 - - this notice - - done because 10 - - this notice - - done because 10 - - this notice - - done because sub subscribe to tum kuch match kar raha - match kar It's fine, it's not matching, it's - match kar It's fine, it's not matching, it's - match kar It's fine, it's not matching, it's fine, so it doesn't match here, if it was a minus or plus, then in the comparison, I would start from here, if I can, then this subscribe to, if I get this in the last, somewhere in the middle. If it doesn't match, I will have to do a - - doesn't match, I will have to do a - - doesn't match, I will have to do a - - Okay, so guys Ajay, if you try to combine it, you will understand. Okay, I have written so many parts, then medium if support, touch and touch, like this one is my WhatsApp and global desired color. Okay, this one pot has and - one and - kills are this one pot has and - one and - kills are this one pot has and - one and - kills are matching so if basically this is that James is equal to G dot size - 110, James is equal to G dot size - 110, James is equal to G dot size - 110, that means that my thing, yes, has come up to here, that means that here. Till the characters are matched, my group is matched, okay, so if this happens, what will I do, I will give one to search for the next group, ok, either we will write a new function to search for the next group, solve group-2 csse- 1 Husan Norms ka baje group-2 csse- 1 Husan Norms ka baje group-2 csse- 1 Husan Norms ka baje plus one is ok yes plus time meaning and here I will write hi why I came plus one because here went to DI plus ok so if then basically search for next if black declared If I return two, what will I do? Return raw is ok, it means I have got the next group, ok and if I don't get the next group, what will I do? Return toss, it is just a prop, if you are there then it will work, let's test it and see running. Votes have come, best work ok, there is some problem ok here, sorry, I have to write gruesome a jiyaye and because the current group is 158 100 times, there is still another mistake here, can't write that a hai abe so it's working and increase submit to intercity percent Paas displayed So see, the pimple of the problem can be opened by turning on a divided one, first you get the first part pile, then basically if you get the first one, then you go in search of the next group, if you fall from there then there is no point. It means no and if you get a 2 from there then you spread it from here, it flows okay, so the problem is basically what I did is I found out the group and then went to the next group and if I find the daily form then Then in the next and last, if all the group was finished then I am requesting, so if you have understood the video then please subscribe the channel, like the video, thanks for watching night by.
|
Form Array by Concatenating Subarrays of Another Array
|
maximum-repeating-substring
|
You are given a 2D integer array `groups` of length `n`. You are also given an integer array `nums`.
You are asked if you can choose `n` **disjoint** subarrays from the array `nums` such that the `ith` subarray is equal to `groups[i]` (**0-indexed**), and if `i > 0`, the `(i-1)th` subarray appears **before** the `ith` subarray in `nums` (i.e. the subarrays must be in the same order as `groups`).
Return `true` _if you can do this task, and_ `false` _otherwise_.
Note that the subarrays are **disjoint** if and only if there is no index `k` such that `nums[k]` belongs to more than one subarray. A subarray is a contiguous sequence of elements within an array.
**Example 1:**
**Input:** groups = \[\[1,-1,-1\],\[3,-2,0\]\], nums = \[1,-1,0,1,-1,-1,3,-2,0\]
**Output:** true
**Explanation:** You can choose the 0th subarray as \[1,-1,0,**1,-1,-1**,3,-2,0\] and the 1st one as \[1,-1,0,1,-1,-1,**3,-2,0**\].
These subarrays are disjoint as they share no common nums\[k\] element.
**Example 2:**
**Input:** groups = \[\[10,-2\],\[1,2,3,4\]\], nums = \[1,2,3,4,10,-2\]
**Output:** false
**Explanation:** Note that choosing the subarrays \[**1,2,3,4**,10,-2\] and \[1,2,3,4,**10,-2**\] is incorrect because they are not in the same order as in groups.
\[10,-2\] must come before \[1,2,3,4\].
**Example 3:**
**Input:** groups = \[\[1,2,3\],\[3,4\]\], nums = \[7,7,1,2,3,4,7,7\]
**Output:** false
**Explanation:** Note that choosing the subarrays \[7,7,**1,2,3**,4,7,7\] and \[7,7,1,2,**3,4**,7,7\] is invalid because they are not disjoint.
They share a common elements nums\[4\] (0-indexed).
**Constraints:**
* `groups.length == n`
* `1 <= n <= 103`
* `1 <= groups[i].length, sum(groups[i].length) <= 103`
* `1 <= nums.length <= 103`
* `-107 <= groups[i][j], nums[k] <= 107`
|
The constraints are low enough for a brute force approach. Try every k value from 0 upwards until word is no longer k-repeating.
|
String,String Matching
|
Easy
|
1689
|
55 |
uh so hi guys we have given a question which is called as a jump game it's taken from lead code itself so we have given array of numbers and each index represent a value uh that value means we can go maximum that value from that distance for example here i've taken the test case from lead code itself if i am here at index 0 and i found that value is 2 so maximum i can go from here is two distance from here and i will reach here at index two uh i have a value one so i can maximum go one here so i will go here and add index i found a one again and i will go here so as soon as i reach the uh array length minus one was actually my last index of the array uh i will return it to that i can end of the array so this example for true and we have given another example let's take that consider as well one zero four as well zero one two three four uh minor indexing so i'm initially here and i found that the value return here is three so i can go one i can go to i can go at three but as soon as i get here i found a zero so i avoid this path i don't want to go this part because from zero i cannot go anywhere now so we have to avoid this path so uh we can go maximum three but we can also go between from uh one two three so i will not use the third step path i will try uh path number one which actually is one so from here i can go only one which is actually leading me up to zero only so i will not use that part also and from two uh i will check that if i can go from here i can go maximum two i can go one and i can go to so we can see again we are reaching at zero from here we cannot go anywhere so we will return a false that we cannot cross the uh we cannot get to our target which is length of that array so we got a basic understanding so how do we proceed this question is a task so suppose uh i'm taking this example itself one four and every index represent the value that maximum where we can go so uh we initially at zeroth index we have what uh we have two as our value so we can go either plus 1 like from here to here and plus 2 like here to here so if i go up plus one where we will reach we will test it at index one so that's indexing huh that's indexing so if i take a uh maximum two of path i will just do an indexing of two okay uh recursion goes like this uh left and right um taking the left part first so at one we have a three so we have a three possible uh path to get to the end so from here is one is two and it's a three from if we take a one from uh indexing one we will lose to a two and uh if we take a two path to get twist over three and if we take a three part uh we will restore four directly yes 4 uh actually 4 is our target so we need to reach here so as you can see we can reach your arith index we return a 2 from here we return our true from here so ultimately this will return this to true and it's true there will be further more cause but i am considering only this because we need a answer of true that's for the first example itself let's uh take this approach into our second one example that tensor falls in the test case itself so three two one zero and a four and mark this indexing zero one two and three and a four at zero uh i have three calls for one and two and three if i take a one i will use two or one if i take a two i will disturb two in here three so at one index i have two calls and the two index i have only one column third i have a zero call i cannot reach from here so i've written a false from here written up false from here so we cannot go from here and two i can go to three and it's also we can go from here return or false from one i can go to and two and three and that's turn off also ultimately i will return false from everywhere and this will return also false so that's a recursive approach we have seen so many overlapping sub problems like here we are calculating two three here itself so if trees goes out of very number uh in size number of calls will be a creator and there will include overlapping sub problems at many levels so we need to take into conditional implement dp for that but recursive approach is very important for this question to get the understanding of that so we create a function public boolean call it a jump it will take nums array and ind which stand for indexing from here i will return jump i will pass nums and i will pass index zero because we need to start from a zero or we can start from zero that's up on to us if i nd equals to num start length minus 1 what that means it means we have these to the end so we need to return a true form here after that i need to make some cos i equals to one because uh we are making number of calls starting from one if index contains two so we starting from one and then two so we start from one and we go till terms of ind which is that at what index what is the value of xml numbers we can go now so that's this so i plus here i will check if jump a password equation to nums plus ind so if that's true it will return me a true and i will ultimately if that does not return to i'll return a false from here so let's try to run it and try to get what we get the possibility of that so it's getting me a false what i have done wrong expect it to i write enough false okay i have put these two numbers in because i'm starting from one self syntax mistakes happens guys uh so it probably uh get me at dle because of overlapping sub problem so uh second part is we need to implement a db for that so dp you can implement a memoization path itself which is considered to be very easy so we have to use the boolean array because we need to store the answer for uh last index so we have to get one more for that so i have to pass that dp here and also need to pass that boolean dp here and check if dp of ind tp of ind exist return that is something that inside now uh it's all true we need to written dp of ind itself so before making this we can say that dp of ind plus i equals to jump nums i plus ind comma dp and check if tp of ind plus 1 exist or not ind plus 1 so if nd plus i exist or not if that exists you simply return that if you have ind plus 1 that's it that's our memoration part let's try to run it and check for compilation errors and it's running let's try to submit it and check if it's submitted or not so you can see it's again giving us a dle because it's not optimized that well so what we can do takes up another approach exists for that uh to make it into a very optimized time complexity uh which tends to be big of n and that's approach is 3d approach let's go to the screen we will try to learn what the greedy approach is so i am here this is my array and this is my indexing marker 0 1 2 3 and a 4. so my main goal is to reach here from here i need to be see here but what if we are here and we check if i can reach here or not if i reach here i will shift my pointer from here to here i will check for this guy can reach here to here if this guy can reach to here means it will uh ultimately can reach here so pulling our criteria if this can reach here i will move that here and we will do that continuously let me show a better uh clear example of that two one so my end goal is to reach here i mark it as x and my starting point is here so in recursion i am checking for every possible uh chances of reaching here like one two and from here one two and three and from here one and from here upon i am taking every possible uh causes for that and that's causing a lot of uh time complexity that's we are getting our tle every time we are even we have optimized that using our db but we are getting uh tl again so we need to uh improve our time complexity and to get the results so right now we are here and we need to go from here to uh here actually now so there's a big problem here uh it's actually a bigger leap than that right now we need a shorter problem what is this shorter problem for that could be if i am here i will check if i can go from here to here or not yes i can go is one i can go from here to here that means i can go here so that means i will remove that and now my new goal is this part itself and my eye and my start point will be here and check i can go here to here it will say yes you can go from here to here so i will move my thing from here to here and this thing from here to here is not it is in this manual here is it and here it is my goal i can reach from here to here yes you can reach here i will move that to my origin point and check if i can reach from here to here or not yes you can reach here to here so ultimately i will check if my goal is reached to our uh original starting point if that's the case that means we can restore goal from starting to and you go from here to here or head where it's all the same okay so we need to implement that approach into our question itself so i will erase that and let me write it for you firstly i have to get rid of that so what we have discussed our end goal should be nums dot length minus 1 we create a loop from i equals to nums dot len minus 2 just before our goal i should be greater than equals to zero and i should be uh decrease every time for every iteration and there we will check if our i plus uh nums of i is greater than or equals to our goal or not if it's equal we need to shift our goal to our i we shift our goal to our eye and we perform certain task and last all the iteration happens we check if goal equals to zero or not and if it's yes we return our true else return of false but we don't need to write else we take care of itself so try to run it and see if that works or not so we try to submit that and check for yes guys you can see uh this only method which runs and accepts a lead code as far as i guess and i checked for my for myself this method is known as greedy method so in this video we have discussed three approaches first is recursive to understand the problem better and second is optimization of recursive approach using dp and third is 3d approach which actually satisfy the time constraint given by the problem to us so we have submitted that and thanks for watching
|
Jump Game
|
jump-game
|
You are given an integer array `nums`. You are initially positioned at the array's **first index**, and each element in the array represents your maximum jump length at that position.
Return `true` _if you can reach the last index, or_ `false` _otherwise_.
**Example 1:**
**Input:** nums = \[2,3,1,1,4\]
**Output:** true
**Explanation:** Jump 1 step from index 0 to 1, then 3 steps to the last index.
**Example 2:**
**Input:** nums = \[3,2,1,0,4\]
**Output:** false
**Explanation:** You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
**Constraints:**
* `1 <= nums.length <= 104`
* `0 <= nums[i] <= 105`
| null |
Array,Dynamic Programming,Greedy
|
Medium
|
45,1428,2001
|
214 |
Hai gas welcome back to me youtube channel so today we will be solving a problem from late goal d problem name is shortest plane rom d problem number is 2 and 4 and it is off level heart ok so first let us try to understand what d problem If you are living a string then you can convert it into a palindrome by adding characters in front of it written in the shortest panel ROM you can find while performing this transportation OK so every way they are living a string and they are only allowed to add characters in Front of d string and they have you written d shortest fellow room n date they can find n ok so like they are living there are shortest room on other string from it is a b c a what can be most possible answer in this how n It would be the same Don't be reverse this entire string and add it in the front on D first test how also D most possible answer like there is one possible answer every time and what should it reverse the entire string and add it in the front like in This how a sec and give string it is an possible answers with this a d se answers with this a c with this c and a so this is an room but they have to return d shortest peren rom date they can find what can be d Shortest plain text in this how n it would be if they add every d se answers with this a and this is this with this cc and is this center element in this how what would be the shortest possible answer it would be b c b a b c The it is d shortest possible peren rom today which is the characters from left and right n matching ok so what would be the approach tha they can think so the same don't they find the longest palindromic substring date they can find starting from d zero And let them bill reverse d remaining substring and added in d front par example in this how longest philanthemic substring date they can find from beginning is d to d se match is with this is this with this but this C and this are not matching so d longest far and roaming substring would be this starting from d zero index d remaining string consist of only one character a so they bill reverse it date is d lord is in this how if they find d longest plain row make substring starting from 0 index it Which would be only because there is no other palanpur room date exists starting from zero then next so they bill simply reverse this remaining substring date which became bc given and appended in the starting date which would be answer ok so like same they are finding d longest Palindromic substring starting from zero Thandex only because they are only allowed tu add characters in the front right so date is the same they have tu do ok so no they have seen the approach it consists of two steps first they have tu find the longest fair in economics Subject starting from d zero was next and let them have you reverse d remaining substring and ride it in d beginning so there also spot here hint if you want to solve this problem by yourself you can positive her and give it n to ok so no They are bill c ho they can implement this so on this I am going to use KMP algorithm this is a string matching algorithm n here this is not the whole of it bill only is the LPS part of it which is the longest prefix so let first understand what are prefixes And on suffix this string s what can be possible prefix start from the left so it jump b a ca a and so on and what can be d possible sexis it jump b they start from the right so it jump b a A C A And So On Let's Take One More Example Suppose They Are Life N String A B C D A B C So What Jump B Heart N Possible Prefix De Jump B A B ABC ABCD And So On And Six A Jump B C The c abc the abc and so on so like longest common crefix and six abc every so they are going to use this idea of prefix and six you find d idea of prefix and six you find d idea of prefix and six you find d longest plain romax substring was start from the zero index so let's consider this string if they Form string t which consists of string s and reverse ok ok ok so first let's analyze what is d longest possible palindrome sub string that starts from the zero index in this how is it this c a c ok c match is with c a with a and t is d center element so aa if in this string they can find d longest common prefix and suffix so date would be long is film starting from d zero threes par example in this how d possible prefix richa c and so on And suffix RCS packet another so on so Only so if they are finding a prefix which is also suffix date would give the longest panel roaming substring because a if they consider this and if reverse it give what is the longest common talent room date is the longest common substring date in palenor D longest substance which is in common so this is easily but aa bill also added n has har same has because if i consider this a aaj string so what would b t it would be a i am not entering n has har so In this how are longest common prefix which is also fixed wood be of lens seventh which is color because they want are Answer too be four so if i enter there is every this wood be d prefix which is also travel bill get up correct answer no late s si ho tu implement this ok this is d string makar tu finder answer this si is equal tu a so bill simply move dj painter T is also note equal tu si move d j c note equal tu m of d j ok so no c and a d character is so i and jt index are equal so what they bill do is well co tu this are let sa kal this next lps so i bill ko tu de lps are and bill make lps of k equal tu i +1 yi+1 because this bill store the length of the +1 yi+1 because this bill store the length of the +1 yi+1 because this bill store the length of the longest common prefix and suffix found so for so welcome come the fourth and next and i is zero So IT Bill Make IT One No Way Bill Move I and J So I Was Her It Wood Come Her and K Wood B Her No C and B OK No A and B Are Not Equal So IF They Are Not Equal First Bill Check Weather Zero IT Is note zero so way bill simply move i tu lps i - 1 ok so i ise one right tu lps i - 1 ok so i ise one right tu lps i - 1 ok so i ise one right no bill move tu de zero thunder and de value aate lg ya zero ise zero so i bill be going tu de zero thundex and bill increment ke no C and H are not equal J bill b increment C and B are not equal simply increase k no C and C are equal so further told n alier bill ko tu lpg and make it i + 1 so i zero currently it would lpg and make it i + 1 so i zero currently it would lpg and make it i + 1 so i zero currently it would b one give increment 6 and i both no bill make it tu increment k increment it t and t r equals tu so it bill bi i plus 13 c and c r equals so it would bi+1 date c and c r equals so it would bi+1 date c and c r equals so it would bi+1 date is 5 so this lps n - 1 basically d last index n - 1 basically d last index n - 1 basically d last index Indicators the length of d longest palindromics substring starting from length index ok so r string as c a t c t a c b so 1 2 3 4 5 this is the length of a longest par roaming substring starting from length a starting from index zero this Is Correct So What They Bill Do Is Bill Take De Remaining String Reverse It And Added To The Front And Date Wood Are Answer So I Hope You Who Understand De Approach No Look Come Let's Look At De Cold So I Have Attacked This Code Her So let me explain this code is in what they are going a what you are doing is they are taking t tu b equal tu s let them have a reversing d speed so on example let s consider d se test how c a t a c b So b wood after reversing p wood wickham bca t a no they are making a string a what is a s plus this has plus t this train will come out told you previously and let they are calling this function which bill fool arrange so let move tu de spunk This is D function I told you bill b starting bill b it rating the string a ok let rich d last index and if there is n match what we are doing already we would be steering n coming index like we are making LPS of Equal You I + 1 So making LPS of Equal You I + 1 So making LPS of Equal You I + 1 So They Already Increment I Every And Let They Made LPS G Equal You I Let We Have Increment Both I Or Just So I Have Increment I And Layer Only So No K Is Being Increment OK Aa If There Is No Match Like Both D Characters are note matching first way bill take n test i = 0 because first way bill take n test i = 0 because first way bill take n test i = 0 because note matching what way bill is doing while making i = lps of i - 1 but what if i is zero only way cant i = lps of i - 1 but what if i is zero only way cant i = lps of i - 1 but what if i is zero only way cant move tu -1 else next so way move tu -1 else next so way move tu -1 else next so way bill only increment J adwise they bill make i = lps of i - 1 adwise they bill make i = lps of i - 1 adwise they bill make i = lps of i - 1 so after this function kal color d length of d longest plane roaming substring tha start from zero wood b last element of d lps index and give a per example in this how bill get 5 further R length so aa they bill have you find d substring after this like palindrome so bill find it by taking by using the substring function is dot subsidiary wood gives this b let they would reverse it and give after reversing it would be only because it This is a single character so temp bill b and they are returning dem plus s date is b and catacp so it this was n answer ok thank you per watching
|
Shortest Palindrome
|
shortest-palindrome
|
You are given a string `s`. You can convert `s` to a palindrome by adding characters in front of it.
Return _the shortest palindrome you can find by performing this transformation_.
**Example 1:**
**Input:** s = "aacecaaa"
**Output:** "aaacecaaa"
**Example 2:**
**Input:** s = "abcd"
**Output:** "dcbabcd"
**Constraints:**
* `0 <= s.length <= 5 * 104`
* `s` consists of lowercase English letters only.
| null |
String,Rolling Hash,String Matching,Hash Function
|
Hard
|
5,28,336
|
206 |
A Republic Lift Very Fundamental Concepts of Inner Light of Food Interview You Will Give the Head of Ling Left and You Need to Return Alif in River Water Activist Problem No Problem Statement That You Need to Return the Rebel to the Solution Hello Friends Welcome Back Two players were made to learn the first how to make an appointment what next9news you how you can try to select up state after doing this you can achieve the result of class 10th my latest right to understand problem statement good trade tower sex west point and Its Value and 806 and Ultimately Union Territory of This Completely in River Water Bottles Do Something Like This A That Suzy List Send Another Shift Problem Is Very Similar to Printing List in Reverse Order Book This Cut Problem First Female President Is Latest First Night Fall Key Problem Subscribe elements 800 subscribe and subscribe this Video plz subscribe Channel ko hai to usna belt set in which reduced to bring all of elements who don't see the element S4 and question to take next acid element eight post tag next acid 52615 channel subscribe element 1658 advantage of What Does Not Torch Light Open Element From Estate And Allied Andar Value In My Nude Art Festival UTF-8 Festival UTF-8 Festival UTF-8 Like Pointer Pendant Of Elephant Attacks Confirm I Am Not Making New Left With River Water Repeat This Process To The Time That I Will Ultimately Getman you left winner river water and you can simply return you hate you will tree to avoid you will get the elements in river water pot of water in the next to create a new folder subscribing to the person that in next step travels left you can file U will push statement in these immediately to life easier for head and entered into her daughter next 9 points 88 to again confirmed acid to ultimately must talk to write something like this in one whole channel is up now must read this complaint will forget what does I create New Left Dentist Oil Filter Element In River Water Because If You Stop This System Will Start After - Infinitive This System Will Start After - Infinitive This System Will Start After - Infinitive This That And Create New Point PTR Net Appointing Here A Cooling Tower I Will Run In The Lokpal Will Run Last Came Value Stocks MP English Blue Motu Is Create New Note Next Original Creator You Not Over That A Find Value In Which A Prominent Social Sciences Caught Hidden In Advance The Value Of Point To Next 9 PTR Points 6 This Offer Rungin Ban Sakte Create New Water And Yadav Set This Feeling That BTR Ban Saki nuvwante forward hai main to yun hi itihas how will pop up in element from day take and of later new list that this I will tell created new latest the point refill ponting network first image not right then ultimately what does it return reverse list start next9 my Relative Returned Toe That Boat 10 Minutes On Time Complexity Of Order Of In This Figure Is Creating This Chapter Notes And Editors Plus Complexity Of Water Off On The Topic Of Feeling Fan Notes Day You Need To Create New Start-up Notes Day You Need To Create New Start-up Notes Day You Need To Create New Start-up Turnoff Busy Light How To Connect With Solution If You Don't Want To Take Benefit To-Do List Connectivity Channel Subscribe To-Do List Connectivity Channel Subscribe To-Do List Connectivity Channel Subscribe Ultimately What You Want To Be Next Subscribe Do Something Like This Key And Cheese Dreaming Of Next Of Friction 215 Leaf 1615 And Will Repeat This Process Is Removed This Link And The Next 15.28 Can Also Be Made Can Remove Test For Internet Staff8 10.24 And Ultimately Skin Remove To Staff8 10.24 And Ultimately Skin Remove To Staff8 10.24 And Ultimately Skin Remove To Point From 4th And The Next 14.2 Null Point From 4th And The Next 14.2 Null Point From 4th And The Next 14.2 Null That Such Last Date Water Can Not To Factions Held Every Month From Fear And Points 216 The Water President Who Travels Left Now You Start Some This Dot 10 Person Next 10 Person 600 Next Person Then And Ultimately This To National Politics Has Been Reduced Stress For Using Excel Data Structure To Others Like This My Latest Driver Offers Code To Understand This Context Inside Right Left This Sample End Them Difficult For This Point Vidmate Function Play List To Text In His Life In Its Like Its Medicinal Benefits Eternal Because You Can Not Reversing Effective Original Night Next Check It Contains Liquid Only Have Single Note You Can Not Reversing Last Night And A Specific Not In The Next Personal Life Just Single Mother and Daughter Peeth Subscribe Channel To Next Which Insurance Value Which Important Point To That Point Files Antakarana Motivational Withdrawal Next9 10.2 Antakarana Motivational Withdrawal Next9 10.2 Antakarana Motivational Withdrawal Next9 10.2 Next Off Do That Thursday Gunav Previous No Current Note And Next9 Benefit Point To Certificate In River Water Next Tips Very Carefully I Do A Current Mexico Switch Screen Saver Mode The Order Of The Current Account Deficit And Share 9 Tags Page 10 Note Next Point Of Current Note Subscribe This Channel And Listen That Bigg Boss Note Bill Point At current time that one more step word special notification not show this time the current note will point is next 9 end this continued even alteration open loop but 218 reaction to show what is that our a that a sure startup Matthew Ebdon next month equals to Current Next When Current Notice Pointing 800 To Text Note Point Per Light Image Painter Such Current Next Post Previous Post Rukh Remove Point Of Current And Fail At Current Not Next Equals To Previous Note To That Eventual Making A Report That To England Image Pet Not Equal to Current Dosh Time Previous Not Against to Point This Current Mode on That International Money Current Notification for These Changes Point of Currency Note Bhi Ban Sake Dual Pill Rang and Will Update The Pointer 's Attender File Usage Points Look Like This 's Attender File Usage Points Look Like This 's Attender File Usage Points Look Like This UP The List of Birth Right Thought From 600 800 But And Has Deposit In Four And Without Hat You Can Do Subscribe Must - What Does You Can Do Subscribe Must - What Does You Can Do Subscribe Must - What Does Not Display Updater Valley Of Held From Original Position To New Position And Will Return This New Head Mistress To 1658 And 9th May Advantage Of Deprivation S Complexity Time Complexity Steel Revamp Mod Off In This Because Yaar Kuch Travels Voice Element Heavy Space Complexity Of Dissolution Of Wonders Because You Not Mean That After Years Of Temple Run Subscribe And Destroy You Take Advantage Of The Wrapped One That I Ho Like People To Simplify The Problem And Solution For U For Final Thoughts A Moment Thing About Solution Certificate That Then Original 10 Actresses Me Liberty The Left For Operations In Place To Clarify Subscribe Interview Part 1 Interview Part 2 Parts Problem Subscribe My Channel Video Mein Tu Mera Karma Cipla Programming For you and select friends very problem you want for next under 208
|
Reverse Linked List
|
reverse-linked-list
|
Given the `head` of a singly linked list, reverse the list, and return _the reversed list_.
**Example 1:**
**Input:** head = \[1,2,3,4,5\]
**Output:** \[5,4,3,2,1\]
**Example 2:**
**Input:** head = \[1,2\]
**Output:** \[2,1\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is the range `[0, 5000]`.
* `-5000 <= Node.val <= 5000`
**Follow up:** A linked list can be reversed either iteratively or recursively. Could you implement both?
| null |
Linked List,Recursion
|
Easy
|
92,156,234,2196,2236
|
1,962 |
so hello everyone and welcome to today's lead code daily question that is remove Stone to minimize the total so you have been given an array called piles and uh where each index that is piles of I represent the number of zones in the ith pile and also we have been given an integer k so um and you should apply a certain operation exactly a times so what is that operation you have to choose any of this number given that is any of piles of I and remove floor value of piles I divide by 2 from the from that particular pile so as you can see this example is given to us 549 that is piles zero has four five Stones five the pile at uh first index has four zones and also K is given so our Target is to minimum minimize the number of possible number of total zones So currently the total is nine plus four that is 13 plus 5 so that is 18. we have to minimize this total after we have uh done we have are done a k operations so what is and the operation is to choose any of these files and remove uh piles of divided by two so uh the basic things that which comes into our mind is to Simply take out the maximum number uh do this operation reduce that number by pi divided by 2 and do this operation until K is not equal to 0. so the same thing is there I have taken out the priority queue over here so priority queue by default will give you the smallest number but we want the largest number so I have used corrections.revose order now for I equal corrections.revose order now for I equal corrections.revose order now for I equal to 0 that is I will iterate through the array given to us I will add that element to the priority Queue at the same time I will calculate the sum since sum we have to return at the end so uh so the next one is while K is not equal to zero so uh in the next Loop we will um do the operation K times so um what we will do at each instance at each Loop we will take out the largest element for example nine we will do the operation that is we will store ma this value that is floor of piles are divided by two that is now pile PSI is the highest one so a is there because so a is that particular pile size so we will store a matte dot floor a divided by 2 into the add variable then we will reduce that we add from the sum and then also we will reduce that number from the a what we taken out like for 9 if it we took 9 out so we will do 9 divided by 2 will be in add so it will be 4 9 divided by four or two so it will be 4. so we will reduce sum is equal to sum minus add so uh sum is equal to sum minus 4 that is sum will become uh 18 minus 4 that is 40 and now the a variable that is which was 9 earlier will become 9 minus 4 that is 5 so uh and then at DN we will add that Phi again so as you can see at the end a 5 was added again and then we will do the same operations again and again so now let me do the dry run and explain you how it actually works so okay so I've pasted the code over here and this is the question so K is equal to 3 and this array is four three six seven so uh in the first Loop we will add the sum we will add all this element and stored in the sum and also we will add all the elements of the priority queue so okay so we will add this and uh since it is collections.reverse order so it will be collections.reverse order so it will be collections.reverse order so it will be sorted in reverse order it is decreasing to increasing so it will be 7 then six then four will be stored and then 3 will be sold okay so as a sum will be what it so sum will be 4 plus 3 plus 6 plus 7 that is uh it will be twenty then uh we will move to the this Loop that is while K not equal to zero first we will take out a that is the maximum now A P Q dot remove will uh take out the maximum element since it is corrections.tiverse order it is sorted corrections.tiverse order it is sorted corrections.tiverse order it is sorted in the reverse order so it will take out the maximum element so uh okay so it will take out seven for now seven so now add is equal to integer since a mat dot floor returns a double so we have converted to integer and a divided by 2 so 7 divided by 2 is actually 3.5 so the so 7 divided by 2 is actually 3.5 so the so 7 divided by 2 is actually 3.5 so the floor value of 3.5 is 3 so add will be 3 floor value of 3.5 is 3 so add will be 3 floor value of 3.5 is 3 so add will be 3 so we will subtract sum is equal to sum minus add so sum will become 20 minus 3 that is 17 and a will become a will also be reduced by 3 so it will become 7 minus 3 that is 7 minus 3 is 4 so we add DN we will again add uh a to PQ in this priority Q so again uh instead of um 7 we have a 4 now so 6 comes first now then we have two fours instead of seven we got a four and originally also there was a four and three is was there and the sum is 17. now K is equal to 2 since it is reduced by 1 over here and over here so uh K is equal to 2 then we uh take out the maximum element again 6 will be taken out so 6 and add will be 6 divided by 2 flow value so it is uh 3 itself uh sum will be reduced by again uh 3 since add is 3 so it will be now a 14 and this element so add us a will also be reduced by 3 so it will be 3 we will add that element again so instead of 6 now 3 came so uh now uh it will be 4 three and a three since uh instead of 6 3 came and three was already present so it automatically uh fixes the priority automatically adjusts the value such that we get the maximum element first so um next one now K is equal to one so again we take out the maximum element that is 4 now add will be two and we reduce some uh sum was 14 so it became uh 12 now okay sum is 12 now and also we will reduce 4 8 by 2 so it becomes 2 we will add 2 so now instead of 4 2 came so four three and a two since two is the smallest it will automatically go to the last and now since uh now K was one so K minus so k equal to 0 now k equal to zero so now since K is equal to 0 we will return and at the end a sum we have to return so this sum is equal to 12 will be returned okay so we will return that and uh as you can see the output is 12 for this so we will have to return a sum and let me submit this now so it is getting submitted and um thank you for being with me and if you like the video so do like and subscribe our Channel and uh thank you very much
|
Remove Stones to Minimize the Total
|
single-threaded-cpu
|
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the operation on the **same** pile more than once.
Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_.
`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down).
**Example 1:**
**Input:** piles = \[5,4,9\], k = 2
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[5,4,5\].
- Apply the operation on pile 0. The resulting piles are \[3,4,5\].
The total number of stones in \[3,4,5\] is 12.
**Example 2:**
**Input:** piles = \[4,3,6,7\], k = 3
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[4,3,3,7\].
- Apply the operation on pile 3. The resulting piles are \[4,3,3,4\].
- Apply the operation on pile 0. The resulting piles are \[2,3,3,4\].
The total number of stones in \[2,3,3,4\] is 12.
**Constraints:**
* `1 <= piles.length <= 105`
* `1 <= piles[i] <= 104`
* `1 <= k <= 105`
|
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
|
Array,Sorting,Heap (Priority Queue)
|
Medium
|
2176
|
1,760 |
Hello brother, let's keep today's portion but minimum limit, boss, we have given it back, so we are given one and rectangle index is dedicated to it, how much boil is given, Namaskar, and we have appointed, so this is the maximum, we can do this, any subscribe. We will divide it into two parts like we can divide it into and so we can submit maximum robber like here and do one more operation and divided it into two. Now we can divide element two into three and in this So we people but we people so we people if it is not done then no like and subscribe and now if we like it and subscribe then how do we kill it so let's see the next example like these are four operations so actually we can sit So we guys if you if no one else then you can subscribe to it and if you subscribe that comment moderation we are feeling for making then and operation is smaller than four or school then we guys 4 inches and Let us subscribe to this small, time to wake up to the whole element and now we have that INLO is fixed and hi is there is hope, how can we check, how happy we are to get sleep, so like, subscribe to see this then school, subscribe previous songs Reduce it again, reduce it again by two, the inexhaustible chances of two are small, this eight is the Venus in bringing the body, so these two operations have been done, loot acupressure city, which we know as art, grows in tea, so as if so many one operation has been done, four small, then we are Total one option and you if this operation goes in the operation room then subscribe possible to possible for 123 we now in school subscribe 444 or so again made 12 14 promise 121212 husband this appointment put two to three more and then If we have to make the appointment from above, then we have to make this, then we - this is how much is left, make this, then we - this is how much is left, make this, then we - this is how much is left, then if we reduce this, then we will meet this, whatever this - if we do, then reduce the total quickly, whatever this - if we do, then reduce the total quickly, whatever this - if we do, then reduce the total quickly, then reduce it again. As long as it will remain so happy but we were dividing one - wake up dividing one - wake up dividing one - wake up is because we stop operation one less looks like this four happened till arrow that so this question because it came here so one so this If you are less than yourself, then let's start. So we are called gang minimum. So, we can be minimum one. So, it can be said that what happened in the media is that I am right but Android, what can we do more and more? Scientists can equal to Sangh that Akshay does meat for meat, it is possible that we take out A Hello Hi - No Bittu that Hello Hi - No Bittu that Hello Hi - No Bittu that Aamir Akshay does, it is possible to become rich that how much operation is done for meat, so one point is said for the operation, that's why and All of us are going to check here, now how much current will it take to put it in, so select the account, how much office will you get, then whatever potato will be sealed, yes brother Ameer, it is okay and I have registered this account. This seemed to be an option as if here we all did whatever and I because on one hand, now in the last we will check whether whatever account has been operated as per the list or not, was connected. This is less than an operation, so come on here, now we call it a small village and so if it is not possible then we can take it out like this, how can we do like I have subscribed this channel. So let's accept this, it is matching, please submit, if you are affected and if you have any doubt then you can ask in the comment section. Thank you for watching.
|
Minimum Limit of Balls in a Bag
|
check-array-formation-through-concatenation
|
You are given an integer array `nums` where the `ith` bag contains `nums[i]` balls. You are also given an integer `maxOperations`.
You can perform the following operation at most `maxOperations` times:
* Take any bag of balls and divide it into two new bags with a **positive** number of balls.
* For example, a bag of `5` balls can become two new bags of `1` and `4` balls, or two new bags of `2` and `3` balls.
Your penalty is the **maximum** number of balls in a bag. You want to **minimize** your penalty after the operations.
Return _the minimum possible penalty after performing the operations_.
**Example 1:**
**Input:** nums = \[9\], maxOperations = 2
**Output:** 3
**Explanation:**
- Divide the bag with 9 balls into two bags of sizes 6 and 3. \[**9**\] -> \[6,3\].
- Divide the bag with 6 balls into two bags of sizes 3 and 3. \[**6**,3\] -> \[3,3,3\].
The bag with the most number of balls has 3 balls, so your penalty is 3 and you should return 3.
**Example 2:**
**Input:** nums = \[2,4,8,2\], maxOperations = 4
**Output:** 2
**Explanation:**
- Divide the bag with 8 balls into two bags of sizes 4 and 4. \[2,4,**8**,2\] -> \[2,4,4,4,2\].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,**4**,4,4,2\] -> \[2,2,2,4,4,2\].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,**4**,4,2\] -> \[2,2,2,2,2,4,2\].
- Divide the bag with 4 balls into two bags of sizes 2 and 2. \[2,2,2,2,2,**4**,2\] -> \[2,2,2,2,2,2,2,2\].
The bag with the most number of balls has 2 balls, so your penalty is 2, and you should return 2.
**Constraints:**
* `1 <= nums.length <= 105`
* `1 <= maxOperations, nums[i] <= 109`
|
Note that the distinct part means that every position in the array belongs to only one piece Note that you can get the piece every position belongs to naively
|
Array,Hash Table
|
Easy
| null |
453 |
hey folks welcome to another video today we'll be looking at version 453 minimum number of uh moves to equal array elements so the way we would be approaching this problem is by sorting the entire array and moving from the right let me explain the solution as i implemented the first thing we would do is let's just sort it right and then the next thing we do is we get the length of diary itself so numbs month and then oh what do we have of the alternative result so let's just have the result to be zero so far and then four think and be moving from the back and the reason will become very obvious in a second since we're going from the back you need to get all the elements to the same uh number so the way we can do that is uh incrementing all of the elements in the area to equal the largest element in the area so since after we sorted since the largest element in the area will be the rightmost element you need to get the difference between the last one and the first one nums of zero so basically when you get the difference you're saying hey like all of the elements of from the left right all the way to the left you need to increment that by one time so that you get the first element which is the smallest element to be equal to the biggest element in the array so if you keep doing this for every single one of them till you hit zero the like which is the first element you will be fine um let's just quickly run through an example if that's not very obvious so we have one two and three and this thing is already sorted right so we look at three and we look at uh look at one so the difference between three and one is two so you would increment the value of res as two and then you go to two to one you know the difference is one uh you would increment that again by one so it becomes three and you can use this example for other areas obviously and the solution would work let me quickly run this and see if it's okay ah you were also returning to this okay so it was this particular example and it works for the others as well um i hope that solution was easy to understand let me know if you have any questions in the comments below if there are any other questions that you want to solve in the lead code also let me know in the comments below don't forget to like share and subscribe i'll see you folks in the next video
|
Minimum Moves to Equal Array Elements
|
minimum-moves-to-equal-array-elements
|
Given an integer array `nums` of size `n`, return _the minimum number of moves required to make all array elements equal_.
In one move, you can increment `n - 1` elements of the array by `1`.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** 3
**Explanation:** Only three moves are needed (remember each move increments two elements):
\[1,2,3\] => \[2,3,3\] => \[3,4,3\] => \[4,4,4\]
**Example 2:**
**Input:** nums = \[1,1,1\]
**Output:** 0
**Constraints:**
* `n == nums.length`
* `1 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* The answer is guaranteed to fit in a **32-bit** integer.
| null |
Array,Math
|
Medium
|
462,2263,2273
|
130 |
hello welcome back today's question is 130 surrounded regions we are given a matrix containing X and O's and our job is to find all the O's that are completely surrounded by axes and flip them to X so looking at the example provided you can see the O's here are completely surrounded by Axis or on all sides right so these will be converted to X in the final result notice that the O at the bottom here is not surrounded by X this one it will not be flipped now suppose that instead of an X here this is a o that this region would not be left because you can see that this area is not completely surrounded by X on all sides if that is all then this entire thing will retain as O's they will not be X's okay this question is very simple all we have to do is find the cell star on the edge and all the neighboring cells connecting to those Edge cells we might mark them as some other color and then we flip all the O's that are not marked and then we flip All the ho's regions back to O's so only two iterations okay let's take a look at the call this c-sharp core is provided in call this c-sharp core is provided in call this c-sharp core is provided in the GitHub links below first I will initiate two variables the number of rows and the number of columns on the board so the number of rows are here and the number of columns are here and then I'm going to iterate every cells on the board and find all the edge cells Edge cells are all the cells on the first row last row First Column or the last column for all the edge cells that has a value of O I'm going to call this recursive function Mark cells as y this recursive function block cells as y first checks whether the input parameters I and J are valid being valid means that the I and J values are within the range of the number of columns and the number of rows of the board then it will Mark the Y value as why after that it will make a recursive call four times for the neighboring cells on the top on the bottom on the left and on the right these recursive calls will find all the neighbors adjoining The Edge cells which have a value of O and it will also find all the neighbors and neighbors whose has a value of all each recursive car will pass in a set of new I and J values it is possible that some of these I and J values are beyond the border of the board that is why the is valid cell function is there to check whether that's the case and if it is so then it will not execute the call once all the ho cells and all the adjoining neighboring old cells are marked I would iterate the grid again with a double follow I will find all the holes that are not marked in the previous situation these will be the cells in the middle and they're not connected to the edge cells these I will convert to an X if I find a y that means those cells are connected to an edge cell I will convert got to know and that's all it's very simple let's talk about the runtime complexity we're only entering the cells twice the first time is to find all the edge cells and the connecting cells to the edge cells and the second time we are flipping the inner O's to X and we have fibbling also the force that was labeled as wise to O So the running time complexity is Big all of the size of the grid okay let's take a look and see if it works and it does see you next time
|
Surrounded Regions
|
surrounded-regions
|
Given an `m x n` matrix `board` containing `'X'` and `'O'`, _capture all regions that are 4-directionally surrounded by_ `'X'`.
A region is **captured** by flipping all `'O'`s into `'X'`s in that surrounded region.
**Example 1:**
**Input:** board = \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "O ", "X "\],\[ "X ", "X ", "O ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Output:** \[\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "X ", "X ", "X "\],\[ "X ", "O ", "X ", "X "\]\]
**Explanation:** Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
**Example 2:**
**Input:** board = \[\[ "X "\]\]
**Output:** \[\[ "X "\]\]
**Constraints:**
* `m == board.length`
* `n == board[i].length`
* `1 <= m, n <= 200`
* `board[i][j]` is `'X'` or `'O'`.
| null |
Array,Depth-First Search,Breadth-First Search,Union Find,Matrix
|
Medium
|
200,286
|
899 |
Hi gas welcome and welcome back to my channel so today our problem is what have you given us in the statement here you have given us a sting s and have given us a wait for them okay what do we have to do with this sting first cactus What has to be done by one of the cutters and it has to be appended in the last step? No, for how much time can we do this and what is the time fine? What has to be found out lezikographically? Okay, so let's solve this problem first through the example. Let us understand that the problem is exactly ours, then we will see how we can solve it. Okay, so in the first example, I have given you a string. Okay, in the name S, when is A in the first and what is your cake, van and In the second example, what is your base stick? What is the stick given by you? What do we have to do? One of the first cake actors has to do the thing and attach it to the last one and then see which is the smallest stick that I have made so far. Is that the smallest girl graphical, we have to return it. Okay, so what do you have to do in Ciba, here we have given a pay, we have given a van, we have given a date, now you can choose an actor from the first character, you have only one option. So you can choose only one, which will be C, now what will you do, you will append this to the last, okay, when you append this here, what will become of this, it will become back, okay, now this is created, no matter how many numbers you follow this step. You can do this, then what to do, if you pick it up and mix it here and there, then what will become of ACB, it will become right, then if you pick it up and keep it, you see that Ciba has again become right, then why do it again and again, now these three Which one is the smallest of yours? If it is ACB, then what will be the answer? Your A will be B. Okay, understand this is the string, you have Ba, C, A and K van. Date Mains, what you have to do is pick the first van character and what is behind it. It is okay to append it there and see what is your smallest one, so look here, understand this example also, here it is BA, if you keep it here, then what will ACA become? B is okay, this is C, then what will you do if you pick up A here and put it here, what will it become? If you keep B A, what will it become? Till now, whatever you have made here, which one seems to be the smallest, then what seems to be the smallest of yours, ACB, then the answer will be right, so we have to do this for k1, if yours is more than k1, If it remains more than the van, then we will see what will happen to its condition. Okay, then we will see how we can solve it. Right now I am explaining to you what the problem is. Okay, so look, now we have the solution right here for you. For this example, see, this is your tu, okay, so what do you do now, what becomes your smallest, see what becomes of your smallest, now you have the option to pick any of these two, what do you do, put it here, okay. So what do we do? From here, what do we do by picking B and keeping it in the last, then our CA will be formed as B. Okay, then you have the option, what do you do by picking these two, keep them in the last, then out of these two, you pick If you keep K then C then it becomes ABC which will become the smallest leg graphical string now, so this is your answer, see sorted, you are getting the right one which was before this in this case, what do you get, A C B was found which If you did not get the short trick then it is not necessary that the answer should be fully sorted. It is the smallest which was found earlier, so this was the answer. But in this case, what are you getting, ABC is getting sorted. raha hai right ok ba si a yahaan pe arth ke tu hota apna ok here we see what we get sorted ok sorted what is its sting a b c this is right we see whether we get it in this what Okay, now you have the option to pick any one of these two and keep it last. Okay, now which one will you pick and keep? We suggest you keep one here. Look, you have both the choices. It is not necessary to have one. Now pick one and keep one. Pick up and keep Now you can pick up and keep any of the two, okay so what do we do, if we pick up one here and keep it, then what will happen, it will be BACA, okay then you have the choice between these two. What to do with the pass? Pick up any one letter of the two and keep it behind. Okay, so what is yours here? If you pick up all the letters and keep them together, then it will be BCAA. Okay, now you have a choice between these two. What do you do between these two? If you pick up and keep then what will you do? If you pick up and keep B then CA becomes AAB. Okay, now you have a choice between these two. Do you pick up and keep? If you learn what will become of you? It will go to A.A.B.C. Look, it is sorted, it is A.A.B.C. Look, it is sorted, it is A.A.B.C. Look, it is sorted, it is found here too, OK, can you please find it sorted? Look, you have D and C, OK, so now you can pick up any one of the two and keep it, okay? Suppose here, if we pick up C and keep it, then Ba will be BC. Okay, now we have the choice among these two, we can pick up and keep any one, if we keep Di, then ABC will become D, which is It is sorted, isn't it fully sorted? That's right, you have got ABCD, so whenever you are searching for K2, what is it that you are getting now? You are getting it sorted, so if you have it then you will remain there. So you know that you are getting set string, what is happening is getting sorted, right, if these three remain, then what will be solid, what will obviously happen that if you have three characters, first three characters, you can do things, so what does it mean? Even the first two can be done, right, you can choose even among the first two, you will have no choice but four, it means that you can choose the first floor, you can choose the first three. You can also do first you can also do and you know that 2K was getting its sorted in this, for us it means that for k1 we will have to see separately and if k is greater than wan then it is okay then we will understand. If our string will be sorted then what will we do here, we will sort the string and return it, okay now let us see the case of k1, what will we do in k1, see the first example, what was our string here, when is it okay, let us see for Siba. How can we find here, when will we take it? Okay, this is a string, we will search for it, so what will we do, let's append two strings like this, okay, we will print it in it, okay, what will we do now? Look from here, look, you have it already, okay, what to do now, look from here, Basi, when will the BSC be made, when you will bring C here, this is the smallest, so this is your smallest BSC till now, okay, because how can it be smaller than this, okay? Now what we will do is we will see all this string ACB when will it become ACB when now we will put B here then the number ACB is okay so we will see this substance from here, if we will see this substance then ACB will be found then you will see that the one which is before that is the smallest There was a sting, that was our ba si, what is this, it is even smaller than that, what else will you get even one, okay, so in a way, we have seen till this size here, this is what we have, okay, zero van, okay, what have we done here? Added one more thing, now what will we do, we will see the substance from where to where, we already have it with us, already we will see from here till here, okay, then we will see from here till here, we will see only till that, we will not see beyond that, okay What will happen from this, we will know that if we reverse one string then what will I become? Okay and take another example also, guess what BCDA you have. Okay, so what can be formed in this case, so what will we do here. Okay, what will we do, look, we already have BCD, we already know the address here, now what will we do, we will make substring here, we will take this substring, why will we take this, if you take B back, here then divide this C B C D A B used to be CD. Now Banda, not this banda, now who is the smallest among these two, this is the smallest so far, we will follow this man, okay, this is the smallest till now, then what will we do from here to here, why will we do it because if this If you had brought C here, you would have brought it here, then we would have divided it, E would have been right, this is the smallest till now, okay, then what do we do, we bring D here, we bring B here. So what does ours become? If it becomes A B C D then who is the smallest? Okay, so what will we do in the answer? We will turn it. So now let us also look at the code part. How have we done the code? Ok, we will handle this separately for the van and if there is a gutter, we will separate for that. Okay, if it is 1 second, then what to do in it, I simply have to sort the stick, okay and turn it, see now k1. Let's see in case of k, when we have k1 then what will we do n take the size of s then what will we do we will make a double string s plus s we will do ok then we will take s in the sleeve answer ok then what we will do one by one We will look at subasting, so we will start from van i < n look at subasting, so we will start from van i < n look at subasting, so we will start from van i < n till i < n, okay, what will you do, find the till i < n, okay, what will you do, find the till i < n, okay, what will you do, find the substring and substring, dot substance in double substring from i till n, if you do this, what will it give you substance, then you will see that the first You have a string from, is it the smallest, update it, I have updated it, now finally what will you do, when this fall off will go completely, then what will you do, will you return the answer? Okay, so this will be the case for k1. If if ≥ then we will return OK I hope you have understood. If you liked the video then please like, share and subscribe. Thank you.
|
Orderly Queue
|
binary-gap
|
You are given a string `s` and an integer `k`. You can choose one of the first `k` letters of `s` and append it at the end of the string..
Return _the lexicographically smallest string you could have after applying the mentioned step any number of moves_.
**Example 1:**
**Input:** s = "cba ", k = 1
**Output:** "acb "
**Explanation:**
In the first move, we move the 1st character 'c' to the end, obtaining the string "bac ".
In the second move, we move the 1st character 'b' to the end, obtaining the final result "acb ".
**Example 2:**
**Input:** s = "baaca ", k = 3
**Output:** "aaabc "
**Explanation:**
In the first move, we move the 1st character 'b' to the end, obtaining the string "aacab ".
In the second move, we move the 3rd character 'c' to the end, obtaining the final result "aaabc ".
**Constraints:**
* `1 <= k <= s.length <= 1000`
* `s` consist of lowercase English letters.
| null |
Math,Bit Manipulation
|
Easy
| null |
1,639 |
hey what's up guys this is chung here so today let's take a look at the latest bi-weekly contest problem number 1639 bi-weekly contest problem number 1639 bi-weekly contest problem number 1639 number of ways to form a target stream given a dictionary i mean this is like uh i think it's a standard heart problem so you're given like a list of strings of the same length of words okay so keep in mind so each word has the same length and a string target okay and your task is to form the target string by using the letters in the in this list of words under the following rules so the cut the target should be formed from left to right so this should tell us we can use a index to track the current matched target string right and then second one is the to form the ice characters you can choose any uh any case character of the j strings in the words basically we have words one here right so we have words one word one we have let's say we have a four strings each word has like two four strings four letters okay three right and then so on and so forth so it says that any time when you choose like for example if we choose this one to match our current target string after you're choosing this one anything on the left including this one cannot be true cannot be chosen anymore so it means that once you chose this case index on any of the or any of the word here you can only choose k plus 1 starting from k plus one letters later on to four to form the remaining target strings and repeat the process until you form the string target and then it asks you to find the total numbers of the ways total number of ways you can form this string yeah so by looking at this problem at the first glance right so it's pretty obvious we're going to use it like the top-down dp it like the top-down dp it like the top-down dp right so the top-down dp here the first right so the top-down dp here the first right so the top-down dp here the first parameter is going to be the what the uh obviously we need two parameters the first one is the target index right so we have a we need a target index that's telling us like basically before this target index everything has been matched uh for this target stream and the second one is what is the word index right it's a word index so these things this one tells us from which index we can are the valid strings we can pick right so that's the two parameters we need here and uh but if you just follow if you just use the brutal force way like let's say every time basically every time we have targets index and we have word index we're going to look through all the words right so basically we can look through other words with the same word index if we can if we find a match right and then we just uh we just accumulate that we just do a dp we dp this target plus one and the word index plus one and then we do everything for all the other words here but that's gonna be a waste of time right let's say we have a thousand words here right so and let's say each of the words has the same letter here so which means that we have to loop through every time when we have a when we need to match the target index here we have to loop through the entire words that's going to be a little tle basically because the uh the worst length is 1000 so which means that at each state we need we will loop through make a 1000 times for right so how can we improve that so the improvement is pretty straightforward as you guys can see i mean basically if we have like uh at the sa at the same index here and let's say we are matching the current index is its letter is letter e and let's say we have uh let's say we have four e's on this index here let's say we have one e two e three and four let's say we have four e's here so what does it mean it means that we can at the current index we have four ways to pick the uh the lighters that can match the current e here so which means that we can simply use the count right and then we multiply by the dp that we uh we'll be doing later on because you know anything that's after this one here right basically we have four branches here and each branches will lead to the same of dp here and in total we have four times the dp at this index yeah and then we can just uh that can simply like remove that uh that for loop to loop through all the words we can simply use the count at each of the index here yep basically that's the idea and to do that we can just do a pre-process that we can just do a pre-process that we can just do a pre-process right so we do a pre-process well we right so we do a pre-process well we right so we do a pre-process well we have a count dictionary we have a count of a list of dictionary so at each of the we have account here so the count is the length is the same as the length of each words and of each here and each element is a dictionary right so it stores at each of the index here how the counts for each letters so that later on we can simply use this discount list of dictionary to help us find this four here yep yeah i think that's pretty much the main idea here so let me do uh i'll do the coding here so we have 10 to the power and yeah so in the end it also has to do a modular by this big number okay so 9 plus 7 okay so that's that and since we need two index uh i will be defining the two length first so i have a target the first thing the target length and i'm going to have a target length right so target the length equals the length of target and then we have a word length and word length equals to the length of the words worth zero right because each word has the same length okay now the count index here right the count list here so and each element is the uh so each element is a dictionary so i'm going to do a default dictionary of the index at the integer for range of the word n right because for each of the index here each of the index of the of this word we're going to have like dictionary to count the total numbers and then i'd simply loop through the uh in range of w the word end right so for each of the index we look through all the words in words right and the current letter that's the current letter of the words is the w of c sorry w of i that's the current that's the card the current uh letter right the current character here so and then and the current character is going to be the key okay and the value will be increased by one so this means count so first we find the dictionary at this index here right and the key will be the c right and then we just do a plus one here so that will be the uh the preprocessing for the count and in the end we simply return the dp at zero okay and do a modular right so that's when we need to implement this dp function here so we're gonna have like uh dp of the target the first thing is the target index right and second one is the word index right so that's that and yeah i'll be implementing that uh memory memorization as well so memorizations equals to this right it's going to be a dictionary and if right target word index is in the memorization right i simply return this term memorization uh that's that right and then i'm gonna have the answer is gonna be accumulated uh numbers of the of ways to form this index to form this target so but i'll finish the structure here first i mean this is this one in the end i will be assigning this one answer to this one and then we return the answer okay so that's the uh that's a template or you can use the you can use this right or how are you cash equals to not right that's a basically a shortcut of removing this kind of memorization stuff but for the but to make this code like language agnostic i'll be implementing this one anyway so now we have what we have a the current letter so what's the current letter so we need to match the current the target of the target index letter so that's the current character we need to match right and you know there are like two ways of doing this you know because i was trying to do what you know i was trying to do this i was trying to do a for loop here for the i in the range of the word index right and to the end of the word end i was trying to do this basically i try all the possible index from the starting point to the end and then each at each location i try to do this like the state transition but this turns out to be quite slow because we have four loop here and a better way of doing this is that we should try to avoid doing this for loop here and instead we should just uh you know basically actually did this one it's actually the meaning of this is we're trying to skip right i mean if let's say the i starting from this one to the end right basically it means that you know we could start from the word index or we could start from the word the index or we could start from the word index class one or we start from plus two plus three plus four right so it means that if we start from four it means that we are we're skipping the first three uh indexes here but if we're using this way uh it's t it will be tle because we are actually using a photo here so a better way of doing this is that you know we simply do a what if we decide to skip the current index let's do this we'll just do an answer equals to dp target index and the word index plus one so here we decide we skip current word index that's a better way so that we can just remove this for loop at each of the state that can save us a pretty a significant amount of time here right so that's that and then the knobs next one try to pick try to use current word index right and this one line will basically will take care of skipping all the other index because this once when the next time it comes to here it'll also skip this one right and then skip and then and this will take care of all the skipping cases here we're trying to use the current word index so and here we can simply check right if the c is in what is in the count of the uh of the word index right because we have already have this account for each of the index and here we simply check if the current matching letter exists in this count a dictionary for the current word index right if that's the case and then we know okay there are some potential matches we can find here and then we simply do an answer plus dp of uh target because we have find a match so we'll be increasing this target index by one and of course we'll also increase this word index by one all right so that's the dp state dp transition function here and then like i said well and then we simply can multiply by the count of the word index and then the c because this will give us the numbers of the c that appears at this index right yeah cool i think that's everything yeah let's try to run the code here oh sorry stupid mistake here sorry i totally forgot the base case i'm so sorry the uh okay so the base case is of course the first one is if the target if target index is equal to what equals the target length here it means that we have matched all the uh the targets and here we could of course we need to return one okay because we have find one solution right to match to form the target string here and another one is this right if the word index is equal to the word length it means that if we didn't find it and we have reached the end of the index of this word here that means that there's no match and will return zero yeah so that's the base that's the two basics uh base case here yep and let me run the code again i'll do that oh sorry i think i spelled out a target and the word name sorry target and the word and cool so let's try again all right accept it submit all right cool so it's accepted all right so i mean pretty straightforward and with a bit of tweak here like this pre-calculation of the count pre-calculation of the count pre-calculation of the count at each index right for each letter and so oh yeah the time comes space complexity i think this is pretty straightforward right so the time complexity is the same as the total combination of the of this two right which is the uh let's say this is m oops yeah i don't know what happened to my drawing software sometimes just do uh some weird stuff here so let's say this is m and this is n right so the total state combination is like the what so the time complexity will be the o of m times n right and the space complexity is also o of m times n because of this thing here the same because it will call this number of dp functions here right and here it's just like a pre-calculations right so yeah actually this is also like a uh m time m times in okay yeah but it won't affect the final result cool yeah i think that's it for this problem thank you so much for you guys uh to watch this video and stay tuned see you guys soon bye
|
Number of Ways to Form a Target String Given a Dictionary
|
friendly-movies-streamed-last-month
|
You are given a list of strings of the **same length** `words` and a string `target`.
Your task is to form `target` using the given `words` under the following rules:
* `target` should be formed from left to right.
* To form the `ith` character (**0-indexed**) of `target`, you can choose the `kth` character of the `jth` string in `words` if `target[i] = words[j][k]`.
* Once you use the `kth` character of the `jth` string of `words`, you **can no longer** use the `xth` character of any string in `words` where `x <= k`. In other words, all characters to the left of or at index `k` become unusuable for every string.
* Repeat the process until you form the string `target`.
**Notice** that you can use **multiple characters** from the **same string** in `words` provided the conditions above are met.
Return _the number of ways to form `target` from `words`_. Since the answer may be too large, return it **modulo** `109 + 7`.
**Example 1:**
**Input:** words = \[ "acca ", "bbbb ", "caca "\], target = "aba "
**Output:** 6
**Explanation:** There are 6 ways to form target.
"aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "caca ")
"aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "caca ")
"aba " -> index 0 ( "acca "), index 1 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 0 ( "acca "), index 2 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "acca ")
"aba " -> index 1 ( "caca "), index 2 ( "bbbb "), index 3 ( "caca ")
**Example 2:**
**Input:** words = \[ "abba ", "baab "\], target = "bab "
**Output:** 4
**Explanation:** There are 4 ways to form target.
"bab " -> index 0 ( "baab "), index 1 ( "baab "), index 2 ( "abba ")
"bab " -> index 0 ( "baab "), index 1 ( "baab "), index 3 ( "baab ")
"bab " -> index 0 ( "baab "), index 2 ( "baab "), index 3 ( "baab ")
"bab " -> index 1 ( "abba "), index 2 ( "baab "), index 3 ( "baab ")
**Constraints:**
* `1 <= words.length <= 1000`
* `1 <= words[i].length <= 1000`
* All strings in `words` have the same length.
* `1 <= target.length <= 1000`
* `words[i]` and `target` contain only lowercase English letters.
| null |
Database
|
Easy
| null |
287 |
show you how to solve legal question 287 find the duplicate number giving a array integers nums containing n plus 1 integers where each integer is in the range 1 to n inclusive so pay attention here is one to n not starting from zero and that there is only one repeated number in the nums only one this is also another key point maintain this repeated number you must solve the problem without modifying the array numbers and use only constants actual space and if you look at here the nums that's the output right and then this is two and um here is um is the nums and the output is three is the duplicate it finds and here's some constraints here and all the integer norms appear only once except the for precise one integer appear two or more times and can we prove that at least one duplicate number must exist in nums can you solve the problem in linear runtime complexity so this is our interview question asked by amazon and all these company uh amazon 14 times in the last 14 months what it really tests you is that you need to make sure that you solve this problem in uh con in uh n o n time and also you have to make sure that uh without only use cons uses only constant actual space that means that you can the space complexity cannot be um space complexity cannot be o n because if it's uh space complexity is um o n then the uh space will increase as the input increase right it only use constants extra space that means you kind of wanted to use same amount of space even and increase drastically like you have 10 000 input you still want to use maybe like a 10 size of wherever you store this in the memory so that's what it meant um that's why a lot of regular ways you probably can uh use to solve this problem for me if um i look at this problem first thing i want to do it i will probably put in a set but the problem is that i can't put it in this oh because if i put everything in a set and when i go through the number i look at if the number is already in set if they're in set then i want to retain this number that is the only one duplicates that i'm looking for but for set if you think about it the uh space complexity is still oh and right because it increased as the space grows so you can't use that but there is actually a way that you can do this with uh with using um constants actual space this is how the algorithm works so basically you have nums right and it's one three four two and we look at this example here then you have index here so usually the index is starting from zero let me do this and it's zero right one two three four right but it said that the number is containing n plus one integers where each integer is in the range one two and inclusive so it actually started counting the number one two three four five instead so if we use the index what we're gonna do is that we're gonna continue to just look at because the zero should not have anything mapped to it right after we swap every single number whatever last on in this position should be the duplicate i'll show you how to go through the list here and we are only looking at index zero position so basically one for every single number we're gonna look at we're gonna use this value as an index to look up the number in the nums array and when we find the nums if they're not equal to each other we're going to swap it until they're equal to each other then we're going to return this value that will be the answer that we're looking for example the zero position right now is one right so we're going to compare with index one which is three do they are they equal to each other they're not so what we're gonna do is swap them one three two three one right and then now we're gonna look at a three position three is number two right are they equal they're not so we're gonna swap them and then we'll look at two are they equal to each other they're not so we're gonna repeat the same thing and then we'll look into uh four because we're always looking at the num zero position and then f4 are they equal to each other they're not so we're gonna update it again and is uh two equal to each other yes they are equal to each other yep so we want to return to in this case basically is the nums zero that we're gonna return in the end that's the answer that we're looking for um yep i'm gonna show you how to do this in code here so basically the code is really easy straightforward and you just need to know like this is the method that you can use uh or this one is uh use o one space because it will not um increase as the uh the it will not use any extra space in this case so let's do this so while the while loop condition is that while the num zero does not equals to this numbers index number if that makes sense uh if i write in code you will know what i mean does not equal to nums 0. so if num zero basically two right if two does not equal to index so i'm using two as an index here two index nums two if they are not equal to each other what i'm gonna do is i'm gonna continue to swap nums none with num0 that's what i'm trying to swap here so then i'm gonna say uh nums no num zero because i'm gonna swapping them definitely making sure that you swap you type them in the same line and swap them together that's how you do it in python so that the values will not get overwritten it's important and then you're just going to continue to swap them until they are equal to each other well they are equal to each other all i need to do is just written the num zero right that's exactly what we did in the algorithm here and then that's how you should do it and let's see yep if you think this is helpful please like my video and subscribe to my channel and i'll see you soon with more legal questions bye
|
Find the Duplicate Number
|
find-the-duplicate-number
|
Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive.
There is only **one repeated number** in `nums`, return _this repeated number_.
You must solve the problem **without** modifying the array `nums` and uses only constant extra space.
**Example 1:**
**Input:** nums = \[1,3,4,2,2\]
**Output:** 2
**Example 2:**
**Input:** nums = \[3,1,3,4,2\]
**Output:** 3
**Constraints:**
* `1 <= n <= 105`
* `nums.length == n + 1`
* `1 <= nums[i] <= n`
* All the integers in `nums` appear only **once** except for **precisely one integer** which appears **two or more** times.
**Follow up:**
* How can we prove that at least one duplicate number must exist in `nums`?
* Can you solve the problem in linear runtime complexity?
| null |
Array,Two Pointers,Binary Search,Bit Manipulation
|
Medium
|
41,136,142,268,645
|
1,631 |
hey everyone today we are going to solve the beautiful question pass with minimum effort so you are higher preparing for upcoming hike so you need to return the minimum effort required to travel from top left sale to bottom right cell so from here so this is the start point and the goal is here and then what is our effort so routes a fault is maximum absolute difference in Heights between two consecutive cells of the route so for example um between these two sales so effort should be 2 right so in the between these two cells so efforts should be five right so it's easy and in the end also description said this green pass is the like a minimum effort to reachable so that's because um so this Gooding pass so minimum effort should be two right and looks like this pass is like a minimum effort but um between this pass so we need to like a three effort right so it's a bigger than this green pass so that's why in this case we should return two okay so let me explain with this example so this is example two and the output is one I think there are several ways to solve this question but I use a breast fast charge I think it's a simplest way to solve this question but how can we find the smallest effort for next phrase so do you come up with suitable data structure So my answer is to use Heap so this is a data in Heap so first number is effort and the second number is row and the Thousand number is Chrome and more precisely we use a mean keep and in Python Heap is usually a main Heap so don't worry about that and in the Heap so that these data are sorted with ascending order of effort so if we pop the data from Heap we can easily access the smallest um smallest effort right in the current situation so we can find the next phase very easy so this is a step-by-step algorithm of so this is a step-by-step algorithm of so this is a step-by-step algorithm of pressed for such so wired mean Heap has data so I mean it has data we continue iteration and then first of all take the smallest effort from Heap so that's why we use a hip right so if we pop the data from Heap that is the smallest effort so easy right and then so initialized with so zero so we take this data from here and then calculate the maximum effort encountered so use currently zero right and if we go return the current maximum effort but now we are here so goal is here so that is not true so we Skip and the other visited place to set so now zero so we are the current price like a zero practice and then so check for direction from current place so upper side and the left side is out of one so we have two choice right side and the bottom side and uh yeah first of all check this right side and if we find a new place so zero one is a new place right and then calculates a new effort between a new place and the current price so new place is two and the current price is one so new efforts should be between these two phrases one right so that's why in this case we add like a one effort and a new place is zero one so zero and one right and then um also we check this phrase and uh bottom side is um effort is two right and uh row is one and the column is zero and then we repeat it uh so from step one to five again and but next uh if we take a like a smallest effort from Heap definitely uh we take a this data right because uh this data has smallest effort in the current Heap right now right so that's why uh we I think move right and then checks like a fourth Direction and uh I think uh next time um so we go um this way right because our effort is long and then see yeah we repeated the same process maybe so between oops between uh these places effort is one so we move it down and the same thing down and then delete the goal so and then um one possible maximum effort is not one possible um maximum effort uh for this pass is one and then we check the other path but in the end um we know that so one is like a smallest effort so that's why output is one in this case yeah so that is a basic idea to sort of discussion so let's jump into the code okay so let's write the code first of all if not height oops height and then return zero if not the case calculates uh length of row in the prongs equal ranks or height and the rings of heights and zero and create a mean keep equal and the initial value is zero itself so fast number is airport and second number is wrong and the southern number is from and initialize Max report so equals zero so this is a uh for like a tracking the maximum effort encountered and visit it so in the inside set and then start looping wire mean keep and the first of all pop the smallest absolute effort from Heap so a fold and current role and then current column equal and I mean keep and then calculate the max effort equal Max and Max Airport and the current report current row and the current equals equal and rows minus 1 and the row grams minus one so in that case um we should return Max effort so this if this is true so we need to go and then if not the case um are the current price to visit it so add and so here current row current column right and then so I explore like a four directions so for let's say ER and the problem in like a one zero and uh minus one zero and uh zero one and it asked is minus one zero on let's say a new row and a new column equal current row plus VR and the current plus DC right and then um check if the new position is within the like a grid and not to visit it so if zero greater than equal new row and then less than rows and uh zero is greater than equal and new from and less than chorus and uh neural and a new column note in this date so if this is a true calculator new effort equal so this is our absolute value so obvious and the Heights and the new law mu column minus so let me copy this so current row and the current column and then Heap Q dot Heap push and uh Heap isn't like a new Heap and then value is new effort and a new or a new row and then new column yeah actually that's it after that so here be down Max effort yeah that's it so let me submit it yeah looks good and the time complexity of this solution should be order of low management programs and the marriage Supply Long lows multiply crumbs so the white Loop will run almost all cells in the grid so which is the order of rows multiply columns in the worst case so inside the loop the hip operation pop and push take like order of logical time where K is the number of elements in the Heap so in the worst case all cells could be in the Heap once so in the each operation we could have to perform this heat population for all cells so that's why our time complexity is like this and the space complexity so mean Heap can contain at most all cells in the grid so it can take up to order or lows multiply ground space so visit also can contain all sets in the grid so that's why other overloads merge programs and the other variables like a Max effort rows columns and the loop variables regular Dr DC use constant space and they can be ignored in the bigger analysis so that's why space complexity should be order of rows multiply columns yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Path With Minimum Effort
|
number-of-sub-arrays-with-odd-sum
|
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., **0-indexed**). You can move **up**, **down**, **left**, or **right**, and you wish to find a route that requires the minimum **effort**.
A route's **effort** is the **maximum absolute difference** in heights between two consecutive cells of the route.
Return _the minimum **effort** required to travel from the top-left cell to the bottom-right cell._
**Example 1:**
**Input:** heights = \[\[1,2,2\],\[3,8,2\],\[5,3,5\]\]
**Output:** 2
**Explanation:** The route of \[1,3,5,3,5\] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of \[1,2,2,2,5\], where the maximum absolute difference is 3.
**Example 2:**
**Input:** heights = \[\[1,2,3\],\[3,8,4\],\[5,3,5\]\]
**Output:** 1
**Explanation:** The route of \[1,2,3,4,5\] has a maximum absolute difference of 1 in consecutive cells, which is better than route \[1,3,5,3,5\].
**Example 3:**
**Input:** heights = \[\[1,2,1,1,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,2,1,2,1\],\[1,1,1,2,1\]\]
**Output:** 0
**Explanation:** This route does not require any effort.
**Constraints:**
* `rows == heights.length`
* `columns == heights[i].length`
* `1 <= rows, columns <= 100`
* `1 <= heights[i][j] <= 106`
|
Can we use the accumulative sum to keep track of all the odd-sum sub-arrays ? if the current accu sum is odd, we care only about previous even accu sums and vice versa.
|
Array,Math,Dynamic Programming,Prefix Sum
|
Medium
|
2242
|
352 |
Welcome and welcome back to my channel so today our problem is data steam ahead this joint interval so in this problem what have you given us in the un statement here we have been given a data steam input in which aapke sir kya hoga non negative inteasers ok And what you have to do here is to implement a class by the name of Summary Rangers. So what are you given here, this is your constructed. You will know what is constructed, it is basically used to size the object of any class. Ok and the second function is given by your white addnam which has a value in the arguments, that is, what you have to do is to add this value in your data stream. Ok and the second function of yours is get interval, what do you have to do in it. Here you have to return this array of interests in the stream currently a list of these joint in the world. Start I in I The answer should be sorted by start I. So what do we do? Let's understand this problem through an example. Will we watch the movie? How can you solve this? Okay, so you see what you have given here, what are your constructors, adam function, get interval, okay, so here in the output, you have this because you will know that the constructor. There is no intent type, so here it will be NULL, then wide is given in the name of ad, hence here it will be NN, now it is given in get interval, so look here, the name is given as ad, what is given in the name of ad, WAN. So what you have to do is to add this WAN, you have added your WAN in your data steam, after that there is a gate interval, so in the gate interval, here only you have a WAN, so here get internals here, dan, what do you mean? If there is a van here, then you will understand that it will start from van only and it will end from van only. Okay, this is the value of A, it will start from van, it has to be bricked on van, then if this is your ad name, then what is the ad number given? Three. If you have given then whatever will be your status now, van in the team will be 3, then your getting is doubles. What do you have now, then what will you return? Look in this condition, you are not after van, there are three after you, if there is van here. After you there is three, after you there is three. If we had this, then what do we make an interval from one to three, it means that there is one in it, you are also there is three, but here there is one and there is only three. That is, if you are not here then we will have to keep 1 separate, that is, it is starting from van pe is in, then three piece is starting, three is ending, because you are not in the middle, so we will keep you. Ca n't you consider what does it mean, starting from van, going to three, if you had this, but what do you have here, van and three, van will start from van End will be from three, will start from 3 Ok now here again add name is there so what is the condition of add name which is 7 and whatever output you have to return right which will be first which will start first, you have to do this on the basis of this No, the order is fine, it should be sorted, so what is yours here? If you want to add 7, then what will you have, one will become three, 7 will become right. Now if we have given the pay gate interval here, then what will be the return for us? We will have to see the van. Okay, there is a van, after the van, are you there? If not, then end it at the van itself. Three is okay. After three, there is four. Is n't there four? There is no five, there is not even six, so it will start from three. There will be three trees, 7 is 7, after that it will start from 7, it will end at 7, okay, this is how we will turn it, so you see here, what is one, 113, one, three. Three has been done again here 1 3 7 This is 1137 After that you look here again there is add name so you have given add number so you have to put yourself here like this 1 2 3 7 This What will happen here when we get the interval, look here, after adding you, get interval has been asked, so now you will add the van here, then after the van, you will know that you are also there, okay so from van to van 2 Right, then you come to know that there are three, so we can go from van to three, because we also have you and there are three, so we can go from van to three, then you are consumed. If there were four then we put four here but by taking one we will go till three. Here there is only 7 so it will be 7 and 7. Okay, so look at it this way, the answer here is from one to three, from seven to seven. OK, now what you have to do here is to add six to this data stream, you have to add one, this is three, 7 is 6, you also have to add six, we will take 7 here, we will take it like this, it will remain in the ring, only then we will arrange well. Will we be able to do it or not will we be able to return? That's it, what's the point here? If we start from the van, then after the van, you are also there, okay, we will consider you in the end, but let's see, then what is there, three too, we will take you here. Three then after that there is no four, if there is six, then we will close here from van till three, then we will start further, there is six, after six comes just seven, so here, 67 people, you pay here, then after seven, there is seven. No, it is 8, 9, otherwise you can take an interval from six to 7, so here what do you do like this, when you return, then look at this, the answer is 1367, so this is your problem, whatever you saw is the problem. So how will we solve this problem, look here, look at this data steam, what are we doing here, we will solve the problem in the same way as I told you, look at what you have here. The van is fine, we know that if after this, if we do not get the number continuously, then we will end from where we started, we know this right, but you know that after the van, you come, then here you pay for the van. After you, okay, it's okay, so we will take you from the van, okay, you will take it, then you don't know, the three that happens after you is also present here, okay, so instead of you, we will take three here, that is, from the van. We will make till three, okay then now you will see here that four has come, isn't it four? There is 7 here, so from van till three, you will close here and start from here, 7, then this will be the end, but after the seventh. If there is no number then that means it will end at 7. We don't need to look further, so you return this 77, then in this way you solve the problem, but the data steam you are getting here is add number. I am not getting that in ascending order. Look, here after van, what did you get? After three, you got seven. 7/2 After three, you got. 7/2 After three, you got. 7/2 After three, you got. After six we got it, you did n't get it in the order like this but we do n't want it so what will we do and we have to take care of less lactic also so we will set it or set it because you don't want it. Not only this, it will also give me and will also give unique, okay, so what we will do here is that we will keep adding our add in it, okay whenever we asked to add, it will say like ad name came here, what came here, van came here, so van. Okay, after that there is just get interval, so you know that you have only one value with you, okay, so what you will do here, starting, you take start in any interval, whatever we put together, we will take the initial. I will start both of them from mines van. Okay, what will we do in the initial, we will start from -1 what will we do in the initial, we will start from -1 what will we do in the initial, we will start from -1 because whatever your answer, mine can be from zero to yours, you can be up to 10, you can be up to the power four, so we take negative number. There should not be a negative number, we are just keeping the condition so that we can fulfill it, okay then we have to return it, but you know that there is a van here, okay, so what to do now, here you came to know, what is yours now? Start is mines van, then you will understand that you have just started. Okay, so what do you do, take start also, update the star with this element from van and update these also. You know that there is no number ahead. So we will enter right from where we have started, you know this, we will plate it in this way, after that you are seeing that there is no element ahead, simply. What will we do if our start is not 1, there is no value and we are finished, that means we do not have any value, then what do you do in this, start this and start, you have inserted it here, okay, it is done. So again what will you do now, here your add is finished, now again add namma is gone, your again is 3, so you have added three here, okay and you remove this from here, remove this again because now you Which gate interval you are calling and the second gate interval is OK so here start is - 1 n is - OK so here start is - 1 n is - OK so here start is - 1 n is - 1 ok so now what you have to do is now you have to return the get interval for these here ok so start now what If it is at -1 ok so start now what If it is at -1 ok so start now what If it is at -1 then you take the value at which you are here, separate it with WAN and update these also with WAN. Okay, then you came to know that the next number is also this, so see if this number is yours. Is this your start meaning start from here and these are happening here, is this what is happening after the end, if we do one plus, is it equal to that, but here it is not you, here it is three, that is, see. If here Tu is there instead of Van, then we make an interval from Van to 2, we update these, we do not update the start, hence we will check with these only because we have to update in Indo. And only with these you can continuously check, it will go from here to here, so you will check n + 1 times and n + 1 times and n + 1 times and see whether you are getting that element, not the next element, that is not the next element, then we will understand that this is one van only. Your interval will become one and only interval, now what will you do, you will update it, along with setting it, you will also update it, start three in three, okay, you will update it again, you will finally know that it is over. So what you will do is you will insert three here and turn it okay after that let's check our now for this we will insert 7 137 okay 137 we have added it to the data steam now we for this We will create an interval, we have to call from the gate interval because the gate interval is given ahead, so now we will call for it, then start will be from Remind - 1 and call for it, then start will be from Remind - 1 and call for it, then start will be from Remind - 1 and end will be from -1. Here, if we end will be from -1. Here, if we end will be from -1. Here, if we start from this element, then you got to know. That the start you have is mines van, then what you will do is update the element with that, update them with van, separate these also as vans, then you will see, you will come to this element, you will check whether this is in plus van. What no, this is not in plus van, this is not tu, then you will understand what to do, simply insert this, you have done it and from wherever you are, update the start again, start equals tu three ok. You tu three equals tu three ok. You go to this element, now you check whether it is equal to 3 + 1, that is, it is equal to plus one, equal to 3 + 1, that is, it is equal to plus one, equal to 3 + 1, that is, it is equal to plus one, or not, if it is 7, then simply insert it, you will understand where the end will be at the end, what will happen on this end. It has to be done, it means it has to start, it also has to end, then what will you do, you will start and update them from 7 and you will also update them from 7, okay, then further you come to know that the element is not there, then your finally What will you do, you will insert 7 and insert it in this, okay, this is yours, now you have it, so since it is set, you will come here, after the van, you will come, okay, so this is the set, it takes the lock and end. We will make this 1237 of yours, we have added it, after that we have to call the get interval function because it has been given to us, now we will do it for this, then start, what will happen to us, now you have -1, okay here both now you have -1, okay here both now you have -1, okay here both are mine vanes, so you can use this element. We will separate the van and update both of them, then you will come here, you will check whether these plus van equals, you are this element, what is this element, that is, you are, that is, we will update these, you are ok 1 2 Then when you come to this element, will you come to this element, i.e. is it tu plus one, is it three, ok, this will become i.e. is it tu plus one, is it three, ok, this will become i.e. is it tu plus one, is it three, ok, this will become our three, ok, now we will come to the element, is this our 3+1, is it not come to the element, is this our 3+1, is it not come to the element, is this our 3+1, is it not four, ok, what will we do with this? Here we will insert van three and we will update both start and end on the element we are on i.e. on 7, we are on seven, so on the element we are on i.e. on 7, we are on seven, so on the element we are on i.e. on 7, we are on seven, so we will set it in this and move ahead, otherwise there is no further element, otherwise we will be in the last. If we have already started then we have done it and this is our answer. Okay, if you solve the problem in this way, then what do I do? I will also show the code, so see what we have accepted here. We have taken OK from the set and whenever we will be asked to do the add function, the add number will be called, what will we do, we will insert it, what we will do with this name, we will insert the value, OK and the gate interval given to us here is this. We have given the vector of vector, okay, you have given the vector D, so we will take the broken vector with a result name, we will take a start - 1 and we will a start - 1 and we will a start - 1 and we will take the minus van, okay now we will check each element, we will see the start of our - What is 1, that is, if we are going to start of our - What is 1, that is, if we are going to start of our - What is 1, that is, if we are going to look at the first element, then what will we do, we will weight the start with the element, we will update these with the element, okay, if this condition happens, then if we come in this condition that our element is If it is indirect WAN, that means we will understand that we need to update it, we will apply it equal to end of the element, if it is full in both these conditions, then we will understand what we have to do by setting our start and set these. We have to do this and update it with the elements where we are, it will be okay to start as well as end, this way and when this loop is finished, then what you always do is to insert the last element. Later you would get insulted when you came to know that there is no next element i.e. when this that there is no next element i.e. when this that there is no next element i.e. when this loop of yours ended then if start is not your mine van then it is sure that your last element will not be there then what should you do by inserting it in it. Do these and return the result here, then this function will take total because we will take each element. Okay, so I hope you have understood. If you liked the video, please like, share and subscribe. Thank you.
|
Data Stream as Disjoint Intervals
|
data-stream-as-disjoint-intervals
|
Given a data stream input of non-negative integers `a1, a2, ..., an`, summarize the numbers seen so far as a list of disjoint intervals.
Implement the `SummaryRanges` class:
* `SummaryRanges()` Initializes the object with an empty stream.
* `void addNum(int value)` Adds the integer `value` to the stream.
* `int[][] getIntervals()` Returns a summary of the integers in the stream currently as a list of disjoint intervals `[starti, endi]`. The answer should be sorted by `starti`.
**Example 1:**
**Input**
\[ "SummaryRanges ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals ", "addNum ", "getIntervals "\]
\[\[\], \[1\], \[\], \[3\], \[\], \[7\], \[\], \[2\], \[\], \[6\], \[\]\]
**Output**
\[null, null, \[\[1, 1\]\], null, \[\[1, 1\], \[3, 3\]\], null, \[\[1, 1\], \[3, 3\], \[7, 7\]\], null, \[\[1, 3\], \[7, 7\]\], null, \[\[1, 3\], \[6, 7\]\]\]
**Explanation**
SummaryRanges summaryRanges = new SummaryRanges();
summaryRanges.addNum(1); // arr = \[1\]
summaryRanges.getIntervals(); // return \[\[1, 1\]\]
summaryRanges.addNum(3); // arr = \[1, 3\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\]\]
summaryRanges.addNum(7); // arr = \[1, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 1\], \[3, 3\], \[7, 7\]\]
summaryRanges.addNum(2); // arr = \[1, 2, 3, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[7, 7\]\]
summaryRanges.addNum(6); // arr = \[1, 2, 3, 6, 7\]
summaryRanges.getIntervals(); // return \[\[1, 3\], \[6, 7\]\]
**Constraints:**
* `0 <= value <= 104`
* At most `3 * 104` calls will be made to `addNum` and `getIntervals`.
* At most `102` calls will be made to `getIntervals`.
**Follow up:** What if there are lots of merges and the number of disjoint intervals is small compared to the size of the data stream?
| null |
Binary Search,Design,Ordered Set
|
Hard
|
228,436,715
|
230 |
today we will see how to find kth smallest element in a binary search tree and this k can be any uh fixed number also it can be given like third smallest element fourth smallest element or it can be given a general kth smallest element and here it's not a binary tree it's a binary search tree and we know that in binary search tree or for any node if you look at root you can look at any other node all the elements in the left sub tree are smaller than this root node and all elements in the right subtree are larger than it so here six is larger than five and in the left sub tree we have three two and four so all of them are smaller than five similarly if you look at three you will see that in the left side its 2 if there are more elements these will be smaller than 3 so if it has a left child it will be 1 or it can be smaller so here also its property is valid on the right side it's 4 so this is larger than 3 so how can we find kth smallest element so we know that if we do inorder traversal of a binary search tree then the result that is printed is sorted so what inorder traversal does let's see it on an example first so first we will uh understand in order traversal if we know inorder traversal then this problem should be very trivial so in order traversal for a root means that first do inorder traversal of root dot left this left denotes the root of left sub tree so all the nodes in the left sub tree will be visited first so visit everything here then visit 5 then visit everything here there can be a big tree here also so then after doing this after this call completes this will again call it call for its left and right so once this call terminates it would have printed all three two and four then we print root and then we do in order of root right this is the inorder traversal so after this returns it would be printing two three and four in some order then we will print five then we will print the right subtree which is six so it will call for three so what three will do before printing three to the inorder traversal of left so it will come here left and right are null so left will return empty right then it has to print itself so it will print two then it will do it for right subtree which is null so it will not print anything then it will return to the calling function so 3 hat called this so the call has returned from the left subtree of 3 so it will print 3 now itself the root then it will call it for right subtree which is 4. so 4 will do it for left and right which are null so for left it will do it will be null return then print itself 4 for write its null and then return back here so this all the 3 things i have completed at 3 so this 3 will again return to 5 that i have done my job now you can print yourself so then 5 is printed then it calls in order for its right subtree which is rooted at 6. so what 6 will do it will call for left subtree but it's null so this is done then it will print itself which is 6 then it will do or in order on its right which is also null so it returns and finally everything returns back to the top stack and this is the result so you can see this is sorted due to this binary search property and if we are asked to find third element it will be third from the left in this inorder traversal so one way would be that you do in order to represent complete inorder traversal and then store it in an array and then print the kth element but we can do some optimization here once we have listed three nodes that is once this print is called for three nodes we stop there and return that element we keep track of a count so every time we print this print denotes that we are done with this element i mean we have listed this element this node so whenever we are printing instead of printing here we will not be printing it but we will be just incrementing the count instead of print so when two was about to print we were here so we make count equal to one when it returns we print three so instead of printing three we make count equal to two then it calls for its right subtree and here left is null so we want to print four but instead of printing we make count equal to three so every time we are printing it instead of printing just increment the count and add a check that if count equal to 3 or in general in our case it will be k then return this value this will be the result will be this root dot value which we are which we were printing here and we don't need to proceed further so this will terminate when we come when the count becomes k so if there is a inorder traversal of a tree and it's a big tree and let's say k lies here then once we have printed it we will stop so we will only visit these many nodes so the time complexity will be order n so let's write the code for this first we will write in order traversal then we will modify it the same way not much modification is needed so let's write it in c plus first so they are also telling about this inorder traversal but we will not take this route that is modifying the bst node structure we don't need that so let's write it so we need to keep track of count and result so we will create another function and we need to pass count and result by reference since we will be doing recursive calls and all of those recursive calls should have access to the global value of count and result so we will be passing it my reference so if left is there do this for left k count and result and then here we would be print root dot val this would be the original inorder traversal so instead of that we will just keep track of how many elements we have printed we are not actually printing but just keeping track of the count and if is equal to k then we can stop here result equal to count and also return from here and do the same for right so let's try so it works for this case let's try the second one which is a bigger example case three and it matches the expected answers so let's go ahead and submit and we got a wrong answer okay so this looks a bit funny if count is k then result should not be count it should be root valve the value which we were printing i should have copied this one so let's try to submit and the solution is accepted in c plus sorry for that mistake that was really mistake now let's do the same thing in java so here we will use atomic integer since we need to pass it by reference to get the integer value stored in atomic integer we use get and its return type isn't so we are returning it and result is atomic integer so we will set it result dot set so let's see the count is uh atomic integer not just integer so we can do count dot set equal to in count dot set we can write count dot get plus one but we have a ready-made function ready-made function ready-made function in atomic integer for that so it's get and increment another is increment and get so looks like similar to plus something or like plus count or count plus so we will use this ready-made function here will use this ready-made function here will use this ready-made function here and let's try again and this works as expected so let's submit and the solution is accepted in java as well finally we will do it in python 3. it's nothing but just in order traversal with slight modification and here we will put it in self we don't need count and results since they are present in the self itself so we can get it from there let's submit and the solution is accepted in python as well
|
Kth Smallest Element in a BST
|
kth-smallest-element-in-a-bst
|
Given the `root` of a binary search tree, and an integer `k`, return _the_ `kth` _smallest value (**1-indexed**) of all the values of the nodes in the tree_.
**Example 1:**
**Input:** root = \[3,1,4,null,2\], k = 1
**Output:** 1
**Example 2:**
**Input:** root = \[5,3,6,2,4,null,null,1\], k = 3
**Output:** 3
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= k <= n <= 104`
* `0 <= Node.val <= 104`
**Follow up:** If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?
|
Try to utilize the property of a BST. Try in-order traversal. (Credits to @chan13) What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST).
|
Tree,Depth-First Search,Binary Search Tree,Binary Tree
|
Medium
|
94,671
|
201 |
welcome back to my YouTube channel today's lead Cod DCC question is bitwise and of numbers range so let's read the question given two integer left and right that represents the range from left to right inclusive return the bitwise and of all the numbers in this range so what question is saying so given a left value let's suppose five and a right value let's suppose 7 so what we have to return the bitwise end of five six 7 so we have to return this value so how bitwise and works first let's see that so zero and 0 will give zero if we consider one bit number 0 and 1 it will give zero 1 and zero it will give zero 1 and one it will give one so basically if we consider one bit number and we do a bitwise end of one bit number so if we get any number of time if we get zero any number of times so like this in this we have two times zero in this one time Z so while doing the bitwise operation if we get the zero any number of times then the value will turn out to be zero and if we do a bitwise and of all ones then the value will be one and if any zero any time zero any zeros then the value will be zero so we will use this concept to find out the bitwise and so in our previous example left five and write 7 let's see so first we will write the binary of the numbers five six 7 so what will be the bitwise end of this number five six and seven so if you see the zeroth bid the numbers are 1 0 1 since we have at least one Z in this the value will be zero now we will use the first bit of all the numbers are zero 1 here also we can see we have at least one zero that means the bitwise end of all the numbers for this bit position it will be zero now we see the third bit 1 since all the bit number is one so the value will be one so this value in decimal is four so we have taken this example only we can see the output is four so we will use this concept let's Deep dive into this pattern so let's suppose we have a binary of a number this so we have written the binary of a number from 0 to 21 and we will try to observe some patterns so if we see the zeroth bit so we can see the zth bit in the zeroth bit the values are repeating 0 1 01 that means every two number the pattern is repeating at zeroth bit let's see at first BD so we have two zeros two ones again two Z 2 one again two 0 two ones that means the pattern is repeating after four consecutive number and this the pattern was repeating after two consecutive number let's see for the second bit in this if we can see we have four zeros four ones again four zeros four ones that means for the second bit the pattern is repeating after eight consecutive number like this way we can see for third bit the pattern will repeat after every 16 numbers for the fourth bit the pattern will repeat after every 32 numbers and for the fifth width it will repeat after every 64 number and how the pattern is if the number is repeating after every two number that means half of the number will be zero and half of the number will be one for that bit position suppose if we considered the fourth bit the pattern is repeating after 32 numbers that means first 16 number will be zeros and then ones 16 number will be one again 16 number will be zeros again 16 number will be once like this the pattern will be repeated so can we you use this pattern to solve this question now if we see how bitwise and works so in this pattern so suppose for the fourth bit position so the numbers are repeating after every four numbers 0 1 again 0 1 so can we say at first position if the numbers are repeating if the pattern is repeating after every four consecutive number that means if our range has more if our range is greater than four that means for that bit position for the first bit position our value will always be zero since it the range is greater than four that means we will definitely have two zeros two ones in this pattern in this bit position in the first bit position for example if we considered second bit position for example if we take a number from range uh 3 to 7 so in this we can see the range is greater than four that is the range of this number is five so from 3 to 7 can we see that for the first bit position we will definitely have two Zer two ones see we have 1 0 1 one two zos two ones again if we see any number with range greater than four suppose from 10 to 17 if we take so if we take this range for the first bit position we can see like we have the reputation two zeros two 1es that means pattern is repeated so can we say for the first bit position for the zeroth bit if the range is greater than two that means we will always have the bitwise and zero for the bit one if the range is greater than four that means we will definitely have zero if we do bitwise and for the bit two if the given range is greater than 8 that means the bitwise end of that range and for that bit it will be zero since the number will be repeated as 0 1 that means we will have four zeros 4 ones so let's draw a chart how it is working so if we consider only four any single bit suppose currently we want to see for third bit so for third bit suppose for third bit can we say we have two options either the range is greater than equal to 8 or range is less than equal to 8 and here range is the range of right minus left + one this range I'm talking minus left + one this range I'm talking minus left + one this range I'm talking about right minus left + 1 for the third bit that's why we are considering it for the third bit the pattern sorry for the second bit let's see for the second bit the pattern is repeating for the second bit is four zeros 4 ones that means after eight number the pattern is repeating that's why we are considering range greater than equal to 8 and range less than equal to 8 if the range is greater than equal to8 that means for this bit position for the second bit position the value will always be zero for the second bit in the result if we look at the second bit position the value will always be zero that is confirmed now what is the possibility if the range is less than 8 so let's write the pattern 0 1 0 and zero like this so if the range is less than eight that means we have seven numbers maximum seven numbers so what can be the range of that number either from first zero till 3 ones that means the left and right this bound right will cover some zeros some ones or some zero some ones some zeros someone's or if suppose the range is three then it may happen like the ranges contains only all ones or it contains all zeros or it may happen like it contains ones to zeros something like this that means if it contains all zeros then definitely the value will be zero if it contains some zero some ones then also the value will be Z because any one zeros will result in zero for the bitwise operation and if the range lies in all ones then the value will be one so let's take an example for another bit position so this is zeroth bit so we have looked into second bit now let's suppose we look into first bit suppose we have looking into first bit position so the pattern is repeating after four numbers two of two zeros two ones right that means if the range of the given input is greater than equal to 4 then definitely we will contain two zeros two ones at least in the pattern that means the bitwise and will definitely be zero and if the range contains less than four number either it could be one number two number or three number like if it is 5 to five then it contains only one number if the range is from five to six it contains only two numbers if the range is 5 to 7 then it contains three number like this so let's write the pattern and how it is repeating two zeros two ones again two Zer two ones like this so suppose we have only one number in the range then that one number can either be zero or one suppose we have two numbers in the range so either it contains both zeros or both ones or one 1 like this so if it contains both zeros then the value will be zero if it contains both ones the value will be one if it contains some zeros some ones the value will be zero right so we will use this concept to solve this question let's take an example let's take some big example to solve this question suppose we have a range from 2 to suppose 18 2 to 18 from 2 to 18 so how many numbers we have in this range we have 19 numbers right so if we see we have to check the bits till suppose we check till fifth bit from MSB if we check from zeroth bit one bit second third fourth bit after all after that all the numbers till 31st bit it will be zero right so the value will be anywhere zero so let's check from the fifth BD in fifth BD what will be the range of the pattern which is repeating for the fifth bit it will be 2 to the power 5 + 1 that will be 2 to the power 5 + 1 that will be 2 to the power 5 + 1 that is 64 means after every 64 number our pattern will be repeating and what is our pattern 32 Z and 32 1es and how we are checking so if we see if our range is greater than 64 or less than 64 if it is greater than 64 greater than equal to 64 then that bit Position will definitely be zero else we have to see whether that range lies that whether that range contains some zeros some ones or all zeros or all ones that we have to check so since the range is 19 that means this scenario is not true either of this scenario will be true so our number is from 2 to 18 right and if we see we have 64 right and out of that first 32 number from 0 to 31 it will contain zeros and 32 to 63 it will contain ones since it lies in the range of 0 because 2 is less than 31 18 is also less than 31 that means this range contains all zeros means in the resultant of this bit byse and of this range in the fifth bit position we will get the fifth bid position we will get zero now look at into fourth pit so fourth bit so what is the range after which the pattern is repeating for fourth bit is 2 to the power 4 + 1 that to the power 4 + 1 that to the power 4 + 1 that is 32 that means first 16 number will be zeros and after that remaining 16 number will contain ones and that means 0 to 15 it contains zeros and 16 to 301 it contains ones and our range was 2 to 18 so in the range 2 to 18 we will see since we have completed the operation for the fifth bit we will do one right shift so after doing one right shift for two and 18 we will still be obtaining two and 18 so the range is still 2 to 18 so total numbers in this range is 19 so we will see whether the that 19 is greater than 32 or not it is not greater than 32 that means this range will contain either all zeros all ones or some zeros some ones so since 2 to 18 so 2 to 15 it is zeros and 16 to 18 it is once so we can see from two to 15 is zeros and 16 to 18 it's once that means some zero some once and the bitwise end of this result will be zero that means for the fourth bit also the bitwise end for this bit Position will be zero now after doing this operation we will do a left right left shift of this number that means we will reduce the number by two that means we will ignore this bit now since the operation for fifth bit and four bit is completed now we will are worried about only 3 to one0 bit so if we remove this bit position let's suppose we make it zero to ignore the impact of the fourth bit so the number will be now in the range from 2 to 18 will change to 22 and 18 will change to 2 that means the number turns out to be 222 but the original range will still be same that means we have we will still be having 19 numbers in this range so we will use this so for the next beat now we will see into third bit so our number 2 to 18 changes to 2 to two and two after ignoring the fourth bid but the original range will still be same we will always use this range to check whether it lies in that particular range or not now for the third B bit for the third bit so after how many numbers the pattern will repeat for the third bit it will be 3 + 1 that is after every 16 will be 3 + 1 that is after every 16 will be 3 + 1 that is after every 16 number the pattern is repeating that means first eight numbers will contain zeros eight zeros and then remaining eight number will contain ones now we will see whether this range is greater the 19 or not if the range that means this range is 16 right that means if we considered the numbers 2 to 18 and since the range is of the repeating of the sequence is 16 so 19 is greater than 16 that means any one time we will repeat the sequence of 8 zeros 8 1es so if the range is since 9 19 is greater than 16 our bit value for that position will always be zero that means for third bit also the value is zero now our value after doing the bit operation for three 4 it was 22 now of the value 22 after doing the bit operation third will be since the value was 0 1 0 and 0 1 0 so we will remove this bit now again the value is 2 to2 now we will see for the second bit original value changes to 222 but range is still 19 that will never be changed now for the second bid position two the pattern will repeat after 2 + after 2 + after 2 + 1 that is8 after eight numbers our pattern will repeat that is first phone number will contain zeros and next phone number will contain ones so we will see whether this range is greater than 19 or not so since our range is greater than 19 it will always be zero since 8 is greater than 19 it will always be zero similarly for the first bit if we see our range number will range from 1 + 1 that range number will range from 1 + 1 that range number will range from 1 + 1 that is 4 that means after every four number our pattern will repeat that is first two number will be zeros and then two numbers will be one and since the range is greater than our original range is greater than this range the bitwise end for that number will always be zero that means for the second bit also it is zero for the first bit also it is zero for the zeroth bit also it is zero that means the bitwise end of the number from 2 to 18 it will be zero so let's see whether it's like that or not so we have any one zero that means it will be zero and this also we have one Z that means it will be zero in this also we have 1 zero it is zero in this also we have one Z it is zero in this range also we have 1 Z that is zero in this range also we have at least one zero that is zero that means our bitwise end operation for this number will be zero let's take one more example let's take U for example let's take the range from 4 to 7 or let's take the range from 12 to 15 let's take this range or 12 to 17 let's take this range from 12 to 17 so the numbers total numbers in this range is of six numbers total six numbers are there in this range so let's see so beginning from the fifth bit for the fifth bit our number is the pattern repeats after 2 to 5 + 1 is the pattern repeats after 2 to 5 + 1 is the pattern repeats after 2 to 5 + 1 that is 2 to the power 66 that is after every 64 number a pattern is repeating that means first 32 number will be zeros and next 32 numbers will be one right so our actual range is 16 and this for the fifth bit position the pattern repeats after every 64 numbers that means since 6 is less than 6 before we have to see so it will we can't say whether it will be zero now we will see now that means it may contains all zeros all ones or some zeros and some ones right so for so and the range of zeros will be from 0 to 31 it will contains zero and from 32 to 63 it will contain ones so we will see our range is from 12 to 17 that means it lies in this range 0 to 31 that means all zeros since 12 to 17 the sixth fifth bit position is all zeros the bitwise end of that number will be zero that means for the fifth bid position the resultant bitwise end of this range will be zero now let check for the fourth bit our pattern will repeat from 2 4 + 1 bit our pattern will repeat from 2 4 + 1 bit our pattern will repeat from 2 4 + 1 that is 32 that means first 16 number will be zeros and next 16 number will be ones and it's range from 0 to 15 and this range from 16 to 32 31 and after doing completing the operation for the fifth bit we will remove that fifth bit from this number so after removing fifth bit from the number so it is still after removing fifth bit from the number Still Remains the 12 to 17 right now since the range is 32 and our actual range is six it is less than 32 that means it may contain some zeros some ones or some zero some ones like this let's see so our number lies from 12 to 17 that means for the number 12 to 15 it will be zeros and from 16 to 17 it will be ones that means it lies in this some zero some on so for the so bitwise and for this condition is also zero that means for fourth bit also the resultant will be zero now after completing the operation for the fourth bit we will remove the fourth bit from this number so after removing the fourth bit from this number 12 to 17 we will get 12 to 1 so the number is 12 to 1 now let's see for the third bit so our third bit ranges from 2 to 3 + 1 that is 16 that means first eight + 1 that is 16 that means first eight + 1 that is 16 that means first eight numbers will be zero and next eight number will be ones so it is 16 now actual number range is six so 6 is less than 16 that means it may contain some zeros some ones or some zeros some ones so we will see whether this range contains some zeros or some ones now if we see our number has been changed from 12 to 17 to 12 to one that means it will definitely contain some zero some on since what we are saying our pattern is like this 0 and then ones that means all the zeros will complete and then one will start and since the number is the starting the left number is in itself 12 that is greater than the right number that means the pattern is like some ones and then zeros it lies in this range that means definitely it contains some zeros some ones so it will also be zero for this bit also the value turn outs to be zero so we will remove the third bit from this number so after removing the third bit from this number 12 to 17 the number turns to be 4 to 1 so the number will change to 4 to 1 so if we will see for the second bid the number ranges from 2 to 2 + 1 that is three that is from 2 to 2 + 1 that is three that is from 2 to 2 + 1 that is three that is 8 so our first four number will be zeros and next four number will be eight first four number will be zeros and next four number will be 1 and the actual range is six now our number was 4 and one so left becomes four and right becomes one so we will see our actual range that is six this is still less than 8 that means it still contains some zeros some ones or all zeros all ones or some zero some ones now since after removing the fifth fourth and third bit from this range the number is looking like four and one that is left is greater than one that means it will contain some it will definitely contain some zeros some ones if this why it is so because if the number four contains ones and if it contains all if this range contains all ones then this number should then the right number should definitely be have been greater than this four but since this number is less than four that means it is a pattern like some 0 1 one again 0 that means it lies in certain range like this one and then zeros or some ones like this zero means the left lies in this one part and the right lies in this Zero part so it is also zero that means for the second bit also the number will be zero now since we are done with the second bit operation so we will remove the second bit from the number so after removing the second bit from the number the our number will turn to be zero and one 0o and one so for the first bit now our ranges our pattern will repeat after 2 to 1 that is four that is first two number will be zeros and next two number will be ones since four is less than six that means six is greater than four that means our this pattern two zeros and two ones will definitely be repeated so since it is repeated so the number the bitwise end of this number in this range will be zero so for the first we also our number will be zero so after since we are done with the first bit operation we will remove the first bit from the numbers and number will be after that number will be zero and one so the number becomes zero and one that is our left is zero and right is one now for this zeroth bit for zeroth bit the pattern will repeat after 0 + 1 bit the pattern will repeat after 0 + 1 bit the pattern will repeat after 0 + 1 that is 2 that is first one number will be zero and next one number will be one since this is 2 is less than six that means definitely this pattern has been repeated in this range in this original range that means the bitwise end for this number will be zero so again it is zero since all bits are zero the bitwise end for this number will be zero so I hope we are clear with the solution let's try to code so let's take a variable to keep the answer now we will find the actual range of this number total to or we can say actual range of this number will be right minus left minus one this is the actual range now so what we have seen we will repeat that operation for every bit so from 31 to greater than equal to z i minus so that for that bit position the range will be that means that bit range will be p 2 comma I + 1 so that means after be p 2 comma I + 1 so that means after be p 2 comma I + 1 so that means after this pattern after this number mean that means after this bit range our pattern will repeated now the what is the half of that number we will find the half of this number it will be bit range by minus1 by two so this indicates from 0er to half our number will be 0 so this indicates from 0 to half our number will be 0o and from half + 1 till beit range our number will be ones so we will check that conditions so since we have calculated now we will see if the actual range is greater than if actual range is greater than bit range that means this pattern must have been repeated so in this case our bitwise and operation for that particular bit will be or that particular bit will be zero else if it is not repeated we have to find whether the case Lies We have four case right either all zeros will case all zeros case zeros all zeros will case all zeros case will occur if the left and right both is less than equal to half all ones will arise when left and right both is greater than half some zeros else it will contain some zeros some ones or some zero some ones right or if what we in one scenario we have seen like right left is greater than right in that case also that means our pattern is like for there are some zeros some ones and after that again some zeros that means it is lies in this range still it will contain some zeros some ones so four cases so we will write lse if left is greater than right our answer will be answer into two plus 0 else if our left is greater than half and right is also greater than half that means both that means that range contains all ones in all On's case we will add one else it means it contains either all zeros or some zero some ones in that case also we will write into two plus zero and once we are done with this bit operation we will remove the bit so how we are removing that bit so we will do and operation of that bit with number what we will do the and operation of that for that particular bit will be with zero so we will negate the number and do right shift of one with I so this will negate the number and will do and we'll negate that bit position if the value at that bit position at the ith bit position is for the ith bit position if the value is 0 then 0 and 0 is 0 if it contains ones then also one and Z is zero and for the remaining since we are negating so IOD bit will contain zeros and bit right to the IOD bit it will contain one so this complement of one left shift I so for the remaining bid we are doing the bitwise and with one so it will give if it is zero it will give zero if it is one it will give one like this right and we will make it I and then our bitwise end result will be stored in answer I hope this solution works some see so we have find the actual range and then we are iterating from 31st bit till second bit correct and then we are finding the actual bit range after which the number is repeating that is 2 comma I + 1 correct we are finding the mid way I + 1 correct we are finding the mid way I + 1 correct we are finding the mid way of that pattern that is bit range minus1 by 2 correct now we are checking if actual range is greater than equal to bit range if that is so the answer will be zero else if our number left is greater than right if left is greater than right then also our answer is zero else if left is greater than half and right is also greater than half then it is one else that means both the range lies contains either all zeros or some zeros some ones and then we doing a right left shift of one and doing the and operation left is greater than right since we're doing the same operation here we can merge this two also or we can say like this or left is greater than right and we can remove this and else if left is greater than half and right is greater than half correct half range is bit range suppose I value is three then our bit range will be 2 to the^ 3 + bit range will be 2 to the^ 3 + bit range will be 2 to the^ 3 + 1 it will be 16 now half range will be 16 - 1 15 by 16 now half range will be 16 - 1 15 by 16 now half range will be 16 - 1 15 by 2 that is seven it is correct 0 to 7 and then 8 to 15 correct and if actual range will be right minus left + one sorry will be right minus left + one sorry will be right minus left + one sorry and it will be + one and since our actual range is greater let's try to submit yeah now it is accepted let's try to submit the test cases yeah it is accepted so what is the time complexity of this solution if we see so we are what we are doing this will take o1 operation o1 time so we are running the for loop from 31 to 0 that is 32 times that is O of 32 and for each for Loop what we are doing we are calculating the power that is some mathematical operation half this is some checking and this is some bitwise operation so it is somewhere taking some constant time so can we say we are doing we are taking 0 of 32 into 0 of one time that is 0 of 32 time so can we see our solution is taking more or less constant time so there is one more approach if we see so this solution is taking so doing bit man it will take some constant time or we can do like left if left is four and right is 16 so we can do bit running for loop from 4 to 16 we can do bitwise end of 4 + 5 4 and 16 we can do bitwise end of 4 + 5 4 and 16 we can do bitwise end of 4 + 5 4 and five like this till 16 so this is also one solution but it will take the time complexity of the solution will be o of this range and if we see the range G given is and if we see the range given is 2 ^ 31 - 1 that is it will take maximum of 2 to^ 1 that is it will take maximum of 2 to^ 1 that is it will take maximum of 2 to^ 31 time that is nearly equal to 10 the power 9 so this solution may give tle I hope my solution is understandable and it is taking constant time meet you in the next video thank you
|
Bitwise AND of Numbers Range
|
bitwise-and-of-numbers-range
|
Given two integers `left` and `right` that represent the range `[left, right]`, return _the bitwise AND of all numbers in this range, inclusive_.
**Example 1:**
**Input:** left = 5, right = 7
**Output:** 4
**Example 2:**
**Input:** left = 0, right = 0
**Output:** 0
**Example 3:**
**Input:** left = 1, right = 2147483647
**Output:** 0
**Constraints:**
* `0 <= left <= right <= 231 - 1`
| null |
Bit Manipulation
|
Medium
| null |
907 |
day 25th of November lead code challenge the problem that we have in today is some of subar minimum this question is a medium level question on lead code and I totally feel the same also it is based on the concept of stacks and the question may appear really difficult but it is easy and has a very important underlying concept this is Google's favorite a lot of my friends have been asked this question in Google interview coding rounds and I would urge you guys to understand this question fully they usually transform this underlying concept into various problems and they keep on asking the same concept again and again so guys do watch this video till the very end let's try and understand the problem first here in this question you given an array of integers what do you need to identify all the sub arrays that exist in this array and then moving ahead you need to identify the minimums in each one of them you need to Total that up and finally return that total sum so what I'm trying to say let's apply up to this same array let's create all the subar that are possible 31 2 4 31 1 2 4 312 1 2 4 31 2 4 and this we have done over here we are done with step one now what I'm going to do I'm going to identify the minimum across all these sub ARS so the minimum would be three here one here two here four here the minimum would be one here the minimum would be two here minimum would be one here and now we need to sum these up 1 + 3 + 1 is 4 + 2 is 6 + 4 is up 1 + 3 + 1 is 4 + 2 is 6 + 4 is up 1 + 3 + 1 is 4 + 2 is 6 + 4 is 10 11 12 14 15 16 17 is the answer this is what the question is asking us to return how are we going to solve this up let's walk through the solution now think similar to largest area of histogram this is a base Foundation that will help you arrive at today's solution if you are not aware of this I am again repeating guys this is a base Foundation of this question if you already aware of this then you will be able to understand today's problem so how are we applying this concept over here let's try and understand it so you have to think slightly differently think for up till what range each element will act as the minimum what I'm trying to say just hypothetically assume that the current element under consideration is this one we need to identify up till what range towards the left or towards the right this element is acting as the minimum one so let's go ahead and apply the same concept of stacks that the same one that we apply in largest area of histogram over here and identify the dange up till which this element which is ith at fifth index is acting as the minimum element towards the left when I say towards the left over in this direction so it is acting as the minimum one up till the first index and this is what I have stored over here so we know that this element will act as a minimum one for this entire range so the first one is this subar the next one is this subarray followed by this one similarly what we are going to do we look for the same thing towards the right and we will identify the range up till which the current element will act as a minimum one so this will correspond to up till over here uh 6 is greater than 5 7 is again greater than 5 8 is again greater than 5 at n9th index we see a lower value than this one as a result of which the this element the ith element is acting as the minimum one up to eth index which I'm just highlighted so this is the range so here you can see three sub AR the first one is this one the second one is this one the third one is this one now if I ask you how for how many sub arrays will this element act as a minimum element so you can generate all possibilities it is simple if the count over here is a if the count here is B we going to multiply these two up a into B just think for a second in case there are four elements which are lower than this ith elements towards the left if a is happen happens to be four and B happens to be three then in total how many sub arrays would be there for which this ith element will act as the minimum element it would be nothing but 3 into 4 which is 12 now comes the question how can we identify up the range for which the ith element will act as a minimum element towards the right and that two towards the left how can we do that this is really simple we use the stack based approach for doing that the same one that I have been talking about in the largest area of histogram problems U there are plenty others too I can attach those links as well in the description where I've already explained the underlying concept so guys do give those videos a short and if you have gone through this videos then everything would be crystal clear to conclude this question further let's quickly walk through the coding section the time complexity of this approach is order of N and the space complexity again is of order of n needed for creating and storing the stack in the first score we have created two ARR left Min and right Min left men has been initialized with minus one right men have been initialized with the total number of elements that we have in the input array moving ahead I've created an empty stack then I have built in the right men array using monotonic stack concept if you're not aware of monotonic stacks then coding decoding SD preparation sheet based on the concept of monotonic stacks is there for you check out this sheet and here you will find all the problems that are based on the concept of monotonic stacks in the increasing order of complexity easy medium and hard and these are the questions guys do give them a short it will give you enough confidence to crack any type of question that may come in Google in future so let's go back to the problem and uh this is the same concept that I have written over here similarly we clear the stack and again apply the monotonic stack concept to fill in the left Min array and once we have those indexes one corresponding to the left Min other one corresponding to the right Min we identify the left length and the right length A and B values that I Showcase in the presentation we do an iteration over the entire array and finally what do we consider the current element as the minimum element we identify the length towards the left up till which this element is acting as a minimum element into the length towards the right up till which this element is acting as a minimum element we multiply these two up along with the element itself with this we have considered all the cases wherein each element can act as a probable minimum element and once we are out of the loop whatever value is stored in the result we'll return that up so let's try and submit this up accepted uh over to you guys uh please maintain the consistency and in case you're interested in solving more problems of monotonic snacks or any other underlying concept that are probably as in interview such as DB backt tracking try bit manipulation this SD division sheet is for you do give this sheet a try and this is must do if you have eminent interview planned very soon I'll see you tomorrow with another fresh question I'm attaching this sheet link as well in the description so do check this out
|
Sum of Subarray Minimums
|
koko-eating-bananas
|
Given an array of integers arr, find the sum of `min(b)`, where `b` ranges over every (contiguous) subarray of `arr`. Since the answer may be large, return the answer **modulo** `109 + 7`.
**Example 1:**
**Input:** arr = \[3,1,2,4\]
**Output:** 17
**Explanation:**
Subarrays are \[3\], \[1\], \[2\], \[4\], \[3,1\], \[1,2\], \[2,4\], \[3,1,2\], \[1,2,4\], \[3,1,2,4\].
Minimums are 3, 1, 2, 4, 1, 1, 2, 1, 1, 1.
Sum is 17.
**Example 2:**
**Input:** arr = \[11,81,94,43,3\]
**Output:** 444
**Constraints:**
* `1 <= arr.length <= 3 * 104`
* `1 <= arr[i] <= 3 * 104`
| null |
Array,Binary Search
|
Medium
|
788,1335,2188
|
355 |
hey everyone welcome back and let's write some more neat code today so today let's solve the problem design twitter this is a somewhat challenging problem for a medium and spoiler alert this is actually really similar to another leak code problem which is called merge k sorted lists and that problem is actually a hard problem so it's kind of weird that they make this a medium problem because this problem is actually even harder than the merge case sorted list problem but that's okay so we are told to design a simplified version of twitter and this problem is really about which data structures are we going to use for each of these functions so you really need to have an understanding of trade-offs to make sure that we trade-offs to make sure that we trade-offs to make sure that we implement each of these functions in the most efficient way so there's in total five functions we wanna do one is the constructor so that's where we're really just gonna handle what data structures we wanna use like initializing them and all that and i'm actually gonna start with the implementation for these two functions the follow function and the unfollow function so any user in this case the follower id is the user can follow another user and that's called the follow e id followee a little bit confusing for me but so clearly with this function we need to keep track that this user is following this user right we need a data structure to do that now there's a bunch that we could do the easiest one that you might consider is a map right we want to map this user to another user but of course a user can actually not just follow one person but they could follow multiple people so the simplest idea that you might think of is first okay create a hash map right uh where we're gonna map the user id right just some generic user to whoever they're following right we'll call that the follow eid but it's not just going to be one so let's actually call it list of followee ids right that's just our naive approach that's just the first thing that came to our mind so if each time we get a user and we are told that they follow somebody else we can just keep adding that you know user that they follow to the end of that list that we have right in our hash map this is going to be the key is going to map to a list and we can add a new value to that list and of one time so that's easy but now we're introducing a second operation called unfollow so if a user now wants to unfollow another user how can we implement it with our current data structure well removing from a list is not as easy as adding to the end of that list because we might actually have to search through the entire list to even find that a follower id that we're trying to remove and then removing it is going to be a big-o of end time going to be a big-o of end time going to be a big-o of end time operation is there a more efficient way that we can do this well there is a data structure we know that can add and remove in o of one time do you know what it is well hashmap is one of them but in this case we don't really need a map we just need a set of values right a list or a set but in this case we can use a hash set and that can insert and remove in big o of one time so instead of using a list which was our naive approach we're actually going to map each user id to a hash set of follow eids okay so that's actually pretty easy right so we've already figured out a follow and we've already figured out unfollow and of course we're going to be initializing this data structure inside of our constructor but now for the somewhat difficult part the post tweet and the get news feed function so let's start with post tweet each user can post a tweet and obviously they can post more than one tweet so we need to be able to map a user to their list of tweets right let's just start with a list again and see if it works out for us so again we're gonna have a hash map okay so we're gonna have another hash map mapping each user id to the list of their tweets and each time we post a tweet for a given user we're just going to take that tweet and add it to the end of that list so let's just see if that works for now that's like the most naive approach and in this case i'll just tell you it is going to work for us and you're going to see why so by the way this post tweet if we're just adding to the end of the list each time we can do that in big o of one time so we've basically got all three of these functions running in big o of one time but this get news feed is going to be by far the most complex function so basically for any given user we want to retrieve the 10 most recent tweet ids for that user and the way we're going to get the 10 most recent tweets is from the list of uh followees of the list of people that user follows right and from that list of people that they follow we want the 10 most recent tweets now how do we even get most recent well one anytime a user posts a tweet we're already adding it to the end of the list right so if we create a list of tweets right let's say this is the first tweet then we have the second tweet then we have the third tweet of course the most recent tweet is going to be at the end of the list right for any given user but we don't just have one user right it's possible that we were told okay this user uh you know we're given some user but they maybe follow two people right maybe the second person that they follow has these tweets four five six and let's say these are the actual tweet ids right so we know that this is the most recent tweet from the first person that they follow and this is the most recent tweet from the second person that they follow but these values we can't just compare the tweet ids right because that's what we have right now a list of tweet ids so instead of just having a list of tweet ids how about we also keep track of the time that tweet was posted so in that case we won't just have a list of tweet ids we'll have a list of pairs a list of i'm going to call it count because that's what we're going to be keeping track of for time right we don't actually have a time we have a count of how many total tweets we have and we're actually going to start our count at 0 and then we're going to decrement it to negative 1 then to negative 2 then a negative three and you're gonna see why it basically has to do with us using a heap uh and in python at least there's not really a max heap so we're gonna be using a min heap if you're doing this in java by the way you can just take the count and start at zero and then increment it to one then to two then the three but in this case i'm going to be decrementing it from one to negative two and it'll work out for us this count isn't the most important part of this function okay so once again let's say we're trying to run get newsfeed for some particular user now first thing we want for that user is who do they follow how can we get that well remember we have a hash map for that we can take this user id and get a hash set of all the people that they follow and a hash set in this case is basically equivalent to a list for us because we're just going to iterate through all the people that they follow and then get the tweets of those people right so for each followee id that's a person right that's a user how do we get their list of tweets well conveniently we have a second hash map for that we can take that uh followee id and then convert it into a list of their account and tweets right and that count is really just going to be used to figure out what tweet occurred most recently so suppose we did all that work right we took some user and then got a list of all the people that they follow and their particular tweets let me just draw some example for that let's say we have one three five uh and let's say these are the counts right because we know that list is actually going to have a pair of values count and tweet id uh we do care about the tweet id as well because that's what we're gonna be returning remember we're returning a list of the tweet ids that occurred most recently the 10 tweets that occurred most recently and if there aren't 10 let's say there's only eight tweets from all the people that they follow then we occur however many we have right we don't go over 10 but if there's less than 10 then we'll return however many we have but in this case uh let's say there are less than 10 let's say we have two four and then for the other one let's say we have a six seven so not only do we want at most ten tweets but they need to actually be ordered from most recent to least recent so how do we do that's really the main portion of this algorithm and it's basically exactly like merge k sorted lists the naive way to do this would run in big o of 10 times k where k is basically the number of people that user follows and let me tell you why because of course for each in this case we have three right basically i'm saying k is equal to three because we have three different lists uh if we're trying to get the most recent tweets and order them in that way of course we're gonna start at the end of each list right so we're gonna have a pointer for each list you can call it an index or whatever you want and we're going to compare all of these right which one occurred most recently which one has the smallest value in this case four is the smallest value so what are we going to do well we're gonna take 4 and add it to our list i'm kind of running out of space so let me just create a variable up here sorry if it's messy so result is going to be our list so we found the first value it's 4 so we're going to add 4 to that list and then we're going to take that pointer which was here and then decrement it we're going to shift it to the left so now it's going to be over here and then we're basically going to keep repeating this right we're going to take the minimum of all of these and the reason the time complexity is 10 times k is obviously we have k lists to find the minimum between k values it's a big o of k operation so that's the naive way to do it but if you've solved merge k sorted lists before you know that we don't have to do it in the naive way the slightly more optimal way to do this is actually to take our frontier of all these lists basically frontiers all of the pointers right wherever the pointers are take this and add it to a data structure called the heap in our case we want the min heap because we want the minimum value right we want to know which one of these occurred most uh recently uh and actually that reminds me we remember we were actually going to make these values negative so sorry if this was confusing or remember we were going to start at 0 and then make all these negatives so that doesn't really change the problem at all but it's just how we're going to implement it in the code if you're using java by the way you don't need to make them negative because java has a max heap which you can use but we will be using a min heap and python but the idea is the same right we're going to take these values add them to a heap in our case we're going to be using a min heap and then from this value and this value we're going to find the minimum we're going to do that in log k time and how many times are we going to do that log k operation well of course only at most 10 times right so the time complexity is 10 times log k so that's better than 10 times k which we previously had right well not quite actually and that's kind of the dumb part about this even if you do use them in heap it doesn't really change the overall time complexity let me tell you why because let's say we take each of these k values and we add them to the heap we can add these values in two different ways we can push each of these values which would result in k times log k just to push these values these k values to the min heap or we could run heapify which would be a big o of k time operation so that in addition to our 10 times log k it makes the overall time complexity still big o of k which is what we already originally had so it actually doesn't change the overall time complexity uh but the benefit is if you know if we were running this algorithm in a generic case where we didn't have to actually receive uh 10 uh different tweets maybe we had to receive up to n tweets our algorithm using a heap would be more efficient so i think i've talked enough about the complexity and how we're actually gonna design this now it's actually time to implement the solution and code it up just to save a bit of time i'm just gonna copy and paste a few lines of code so remember we're gonna have three main variables in our constructor we're gonna keep track of the count initially it's gonna be zero uh we're gonna use the count to basically uh it would be better to call this time but it really is just counting our number of tweets so basically we can maintain which tweet was created earlier than another tweet we're also gonna have a tweet map where we map each user to a list of uh that user's tweets as well as the count which is uh gonna be used to figure out which tweet was created uh earlier and of course we want to be able to have a follow map to maintain a user and a set of all the people that they follow so i'm actually going to implement the follow and unfollow first because they're a lot easier so for follow we take our follow map and for a follower id we want to say okay this uh person is now following another person uh with the uh followee id so with the hash set we're gonna add to that hash set this followee id so that's pretty easy now in the unfollow it's basically the reverse of this right a user is now unfollowing someone so instead of adding we're gonna remove but what if this person is actually not even following a different person well let's just add a conditional to make sure that they are following before we actually call the remove function because at least in python i think it will throw like an exception or something so let's just make sure if follow e id is in the set for that follower id so if that is the case only then are we actually going to remove it okay so that was the easy part now let's do post tweet it's the second easiest so for any user uh they just created a tweet so we want to be able to record that so in our tweet map we're gonna say oh and by the way i didn't mention we're using default dicks in this case default dictionaries or hash maps in this case of course we have a list right that's going to be what we're recording and in this one we have a set main reason i'm doing it like this is just to save a couple lines of code if we didn't have default dicks we could have just initialized it to a regular hashmap but in that case each time i'm adding values like see here i'm adding values i would have to initialize it before so i'd have to say follower id is going to equal a list and or in this case a set and then i can add it right first we'd have to create an empty set and then add the values to that set doing it this way just saves a few lines of code i think in most cases your interviewer would probably be fine with it but if they're not you can always just write it out it's pretty easy to do it just saves us a few lines of code in this case so in the tweet map for this user id we want to append to the end of the list the tweet id but actually not just the tweet id remember because we determined that we need to record a pair of values we need to record the count uh that this tweet was created at so that we know which tweet was created before another tweet actually i think we're trying to figure out which tweet was created most recently uh but either way our account will help us for that and then after we've done that we want the next tweet to be uh created at a different count so we're gonna actually decrement this so that we can use this in our min heap in our this function that's i think pretty much it for post tweet so now basically to the main part of this algorithm to get news feed so like i said we're gonna have a result right that's gonna be the list of tweets so it's gonna be ordered starting from the most recent tweets uh for all the people that this person follows and we're also going to be needing a min heap to figure out what the most recent were so initially the min heap is going to be empty we are now going to go through every person that this user follows how can we get that how can we get the followee id of each person that this user follows well remember we have a follower map for that so follower map don't forget to use self in python for this user id so we want to go through each followee id and what do we want to do with that followee id we want the most recent tweet that this person created right our frontier basically first we're going to get the index and that index is basically just going to be the last value of the list so first to even get the list we need the tweet map of this followe id so this will give us a list we want the length of this list minus 1 because that will give us the last index and using that last index we can take that list so this is the list we're going to index it so basically look at this position of the list which will give us the last value and remember this itself is a pair of values the count and the tweet id so count tweet id and this is what's going to be added to our min heap so i'm initially just going to append this to the min heap we don't need to heap push it or anything and then we can heapify this after we've added every value that we want to it so i'm appending to the min heap the first value so it's going to be not just a pair of values but it's actually going to be 4 values and you're going to see why but the first value is what's used as the key as long as there's not a tie and there won't be a tie in this case because count is always going to be unique for every single tweet in this case i'm gonna add that count as the first value because that's what we want to use as the key that's what we want to order our min heap and then the remaining i'm gonna of course need to add the tweet id because that's we're gonna end up adding to the result and i'm also going to be adding the followee id of this person because after we pop this tweet we also want to get the next tweet from this followee id right so we using this followee id we're going to go back to the list and then get the next position at the next index not really the next index but the previous index so really i'm going to decrement this index by one so let's make sure to store that index also in our min heap just so we have it so we can take that index decrement it by one but we're basically saying that this is the next position we're going to look at in our list over here as long as it's greater than or equal to zero basically as long as there are still elements in that list for that followee id okay that's definitely a lot going on here which is why this problem is pretty difficult for a medium and actually one thing i forgot to do is we're not 100 sure that this followee id this person even has any tweets that they created so before we even try to uh you know look at it inside of the tree map before we try to look at some index let's make sure that at least has one tweet so basically if followee id is in self.tweet map if that is the case then self.tweet map if that is the case then self.tweet map if that is the case then they have at least one tweet so that's when we're gonna be actually running this portion okay so we go through every uh person that they follow after we do that let's make sure to actually turn this list because right now it's just a list we want to turn it into a heap a min heap so in python we can do that like this heapq.heapify like this heapq.heapify like this heapq.heapify to that key okay now we actually get into the main portion of the algorithm remember we want to pop at most 10 values we can run a while loop basically saying while the min heap is non-empty and the result or the is non-empty and the result or the is non-empty and the result or the length of the result is less than 10. so basically if we run out of values this is going to stop even if we don't have 10 but right if our min heap is empty it'll stop if we reach 10 values it'll also stop each time though we're going to pop from the min heap we want the most recent tweet that occurred we can do that in python like this heap q dot heap pop from the min heap it's going to pop four values that we defined up here right so i'm just gonna copy and paste that four values we don't need the minus one so these are the values it's gonna give us and of course we want the tweet id that's the most important because that's what we're going to end up adding to the result this is the most recent tweet that happened so we can go ahead and add it to the result now if this followee id this person had any more tweets we want to get that tweet and we can get it at this index let me just actually copy and paste this because we're using the same variable names which makes it convenient for us so let me uh so from the tweet map we're going to get that person and this index which will tell us the next tweet that we can add to our min heap this remember returns a pair of values which we defined up here count and tweet id so let's re-define count and redefine id so let's re-define count and redefine id so let's re-define count and redefine tweet id which we you know used up here that's okay we'll redefine them because this is these two values are what we're now going to be uh pushing to the heap we can do that like this heap q dot heap push to the min heap and we're always adding four values to it the first one is going to be the count next is going to be the tweet id next is going to be the followee id which we have up above and last is going to be the index but remember we always add the index minus 1 because we're adding the next index uh but don't forget we just ran these two lines of code right but we're assuming that the index is going to be valid we're assuming that the index is going to be greater than or equal to zero that person has some more tweets left that we haven't already added to the min heap so let's make sure to have that conditional up above okay and quite a bit of code but luckily that is all of it so after all that is done we have 10 tweets we can go ahead and return the result and of course i do i miss the name so this is follower map but we don't need the er okay and i had one last bug and actually had to do with how we read the problem they actually define the news feed like a user is actually technically following themself basically we want the 10 most recent posts from the people that they follow including themself so before we even run this function what we're actually going to do is to the follow map of that person we're just going to add themselves to it i think that's one of the easiest ways to do this so for that user id we're going to add themselves to it so i think that's kind of dumb if i was doing this in a real interview i think i'd probably miss this detail but it's just one thing you need to do to pass this problem so now let's run it i really hope i don't have any more bugs and luckily it actually does work so you can see on the left yes it works and it's pretty efficient so i really hope that this was helpful if it was please like and subscribe it really supports the channel a lot consider checking out my patreon where you can further support the channel and hopefully i'll see you pretty soon thanks for watching
|
Design Twitter
|
design-twitter
|
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed.
Implement the `Twitter` class:
* `Twitter()` Initializes your twitter object.
* `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`.
* `List getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**.
* `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`.
* `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`.
**Example 1:**
**Input**
\[ "Twitter ", "postTweet ", "getNewsFeed ", "follow ", "postTweet ", "getNewsFeed ", "unfollow ", "getNewsFeed "\]
\[\[\], \[1, 5\], \[1\], \[1, 2\], \[2, 6\], \[1\], \[1, 2\], \[1\]\]
**Output**
\[null, null, \[5\], null, null, \[6, 5\], null, \[5\]\]
**Explanation**
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\]. return \[5\]
twitter.follow(1, 2); // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1); // User 1's news feed should return a list with 2 tweet ids -> \[6, 5\]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2); // User 1 unfollows user 2.
twitter.getNewsFeed(1); // User 1's news feed should return a list with 1 tweet id -> \[5\], since user 1 is no longer following user 2.
**Constraints:**
* `1 <= userId, followerId, followeeId <= 500`
* `0 <= tweetId <= 104`
* All the tweets have **unique** IDs.
* At most `3 * 104` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.
| null |
Hash Table,Linked List,Design,Heap (Priority Queue)
|
Medium
|
1640
|
222 |
Loot Hai Abhi Badi Welcome To My Channel Today Twenty-Three Of June Recording Talent Twenty-Three Of June Recording Talent Twenty-Three Of June Recording Talent And Problem Is Account Complete Cream Notes For Giving A Complete Daddy Free Account Number Of Notice Update Definition Of Complementary From Dar Wikipedia Is Incomplete One Tree Every Level Actor Possibility Last Is Completely failed and all notes in the last level rs and left s possible and can have means 123 notes improves paste level 500 example complete penetration 123 456 likes subscribe and rooted s to a pan use morning loot gang advice will return chapter note plus the number of The Chapter Notes Main Indore Laptop Tree Plus Account Notes In The Types Of Tree One State Here Very Simple 180 Implementation Flex Compile Tower To Dish Compiled And Where Getting Correct Answer Tax Risem Custom Test Cases Where The Paris No Dinner Oo And Even Odd And Even Subscribe for more news Solution This Porn Video Clip From All Over The Country But Not Proper For This Is Solution Little Quiet From Over Funtoosh Amaleshwar Time Complexity Platform Add New Mother Through Which Will Go Into Its Soil Health Related Entries Flexible Complete The Country in Which Every Two Children Only Child Children Internal Govind subscribe and subscribe the Channel As Ud To It Is Always Right Height and Decide Episode 302 376 Phulwa Entry The Number of Death Mystery AB to the Power Minus One Where is the Height of The Mystery Of The Height Of The Day A One-Way Trip Is A One-Way Trip Is A One-Way Trip Is So Here A B C D Death Is Lunch And George From The Current No Dips School Which Means Beach From Receiver Flowers Winery Tree So Effective From Flowers-1 Read And Will Have Number Effective From Flowers-1 Read And Will Have Number Effective From Flowers-1 Read And Will Have Number Of Note To The Power S Minus One Other Vice President Ayub Like Boys Are Not Equal Second K History Is Best When Hair Is Soft Is I Go To Bahraich So Age Will Be Three Layer So BLH Situation Is That Yacht And Rider Pittu From Drut Mod So Ifin Compare This tour notify so that the can not be eliminated full one tree to avoid you can do I will just continued for this is the current mode switch is hair oneplus dandruff absolutely developed bill account for the next describe me aa leke moon pants laptop immediate tree and Continued from the very to absolutely account from the sub media accounts for electric I left sub media and plus continued for the right sub tree on that som will get made internal solve we call the absolutely word is not which is here against S2 from expert in the Left side of this to nh1 leadership quality electronic nh1 beach is 2nd same reservation backward 281 chilli is to in that case also request beach we morning can see in this upper e accept tree from dafna to is the phulwa entry to vacancy hair oneplus one is The previous one encounter previous have to the power htwo minus one notes plus no valid for the right subscribe Free have diabetes 151 so in this dilshan hai year previous entry so the total number of notices to the power line - 150 number of notices to the power line - 150 number of notices to the power line - 150 calculate this is equal to one Plus three plus one so far no dues for media nodes this is the first day of from this and the items will appear in the country and the total number of votes from north east are life and death everyone fold and Sudesh is idea for solving glutes implement support for that so let's reset disc and hair and improvements for implementation word Neetu ko bindh they call them love them cold from Zee TV where is equal to how much will return to power for calculating the power after 6 A times - 121 A times - 121 A times - 121 K advice Will Call In Turn Will Return OnePlus Account Notes From Root Directory Plus Notes From The Day I Will Leave When Death Root Will Simply This Root Via Channel Star Plus Element The Right Method To Computer Root And Same Thing You Which Here Will Always Fall From Like This is to method and development in plates open that such is its compiling and were getting a correct result for ur all the custom how this platform add this British accept this period time complexity of this approach to avoid doing at most calling its chief way all The Time The Face To Subscribe Like Her Only Does Not To Three Do Subscribe My Channel To Ko Ap Absolutely The Settings Polling Account Not How Many Times With Which Have Cottage To Entry Level Of Which Will Have The 0 Times To Be On The Back Burner Video Chat This Level Virver Not Be Special Campaign And Calling Software Calling Only One Times This Resident Hair Calling Two Times One Is Decided In This Site Services Offered Is Arnod This Level Examination Is This Hair Fall In One Time Similarly In Which Year In This Enables This Level Wear Calling To Time Become College Hair And One College Hair Facility C Admit Him Strong Liquid Form The Con Is A Plus To Plus So This Issue Will Come Into Which Is The Fastest Alarms Pe Athletic Performance More Is The Height Of Power Ministry To Complete Ministry Has High Of Nod Will Have High Cheese Law And Software Time Complexities To Of Law Of*And Law Which They Can Give Complexities To Of Law Of*And Law Which They Can Give Complexities To Of Law Of*And Law Which They Can Give Me Please Subscribe My Channel For This Video
|
Count Complete Tree Nodes
|
count-complete-tree-nodes
|
Given the `root` of a **complete** binary tree, return the number of the nodes in the tree.
According to **[Wikipedia](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
Design an algorithm that runs in less than `O(n)` time complexity.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** 6
**Example 2:**
**Input:** root = \[\]
**Output:** 0
**Example 3:**
**Input:** root = \[1\]
**Output:** 1
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5 * 104]`.
* `0 <= Node.val <= 5 * 104`
* The tree is guaranteed to be **complete**.
| null |
Binary Search,Tree,Depth-First Search,Binary Tree
|
Medium
|
270
|
1,762 |
hello guys so in this video we're gonna discuss the second most popular liquid question for um Facebook for the past year which is the buildings with an ocean view so for this question we're gonna be given an array of heights of size n which represents the highs of the building in the line and the ocean is to the right of the building and the building has an ocean view if the building has seed can see the ocean without obstructions okay so basically if all the buildings to the right of the current building is lower has a smaller height and we're gonna return the list of indexes of the buildings that have the ocean view sorted in increasing order so let's look at example one um the ocean will be somewhere here and for the first building four it's taller than all the other buildings to the right of it so index 0 which is the building of four will be in the output and then the second building 2 which is lower than the building to the right of it so the second ability won't be in the output and the third building has a height of 3 which is taller than one so index two will be in the output and the last building it has nothing to the right of it so it has an ocean view as well so this is the output and for the second example so building the first building is taller than all the other buildings to the right of it so it's in the output and a second building is taller than all the other buildings and it's the same in output and the same for the other two buildings and the output has to be in the ascending order so the output indexes has to be sorted so initially the naive logic would be like we can do a double Loop Nest to the loop so we can look on every building and then check all the buildings to the right of it and they fit slower than the current building then we can append to the output append to the index to the output however we can also optimize it because we only need to check like if the building is to the right of it is taller to the current building or not so what do we do the reverse of the loop like we loop from left to right so and then we can keep a maximum height we have so far so in this case if the current building is taller than the maximum height we have right now then this building will have an ocean view and we can update the maximum height to the height of the current building otherwise the building will not have an ocean view and the maximum height remains on okay so let's get started so first of all 10 so this will be the output we're gonna return and we can return this so and we also need to maintain the maximum height we have so far so max height which can be um we can make it like the minimum number for now which is a float of negative infinite now we're gonna look from the left to the right so we can know the total length of the buildings will be in the length of the Heights and we can loop from the last index to the index zero so for I in range foreign so the current height will be um the current height will be uh like the index willing to check if the current height is taller than the maximum height s larger than Max height when we know this building will have uh Ocean View we can just open it now we can we need to update the max height so the max height will be um updated to the current height and also like the output has to be sorted in increasing order so we can just reverse the order of the output because we are appending from the last two um we are planning from the last index first so we just do the reverse this is doing reverse in place so we just do this and we just return the output and let's see how it goes that looks good so for this question so for this solution the um time complexity will be order of n as we are only looping the through the heights one time and there's a space complexity like we just have the output stored in the response which is and the reverse is down in place so it will be order and if we are including the output if we do not include the output then the space extra space we use is like order of what it's a constant foreign
|
Buildings With an Ocean View
|
furthest-building-you-can-reach
|
There are `n` buildings in a line. You are given an integer array `heights` of size `n` that represents the heights of the buildings in the line.
The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a **smaller** height.
Return a list of indices **(0-indexed)** of buildings that have an ocean view, sorted in increasing order.
**Example 1:**
**Input:** heights = \[4,2,3,1\]
**Output:** \[0,2,3\]
**Explanation:** Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
**Example 2:**
**Input:** heights = \[4,3,2,1\]
**Output:** \[0,1,2,3\]
**Explanation:** All the buildings have an ocean view.
**Example 3:**
**Input:** heights = \[1,3,2,4\]
**Output:** \[3\]
**Explanation:** Only building 3 has an ocean view.
**Constraints:**
* `1 <= heights.length <= 105`
* `1 <= heights[i] <= 109`
|
Assume the problem is to check whether you can reach the last building or not. You'll have to do a set of jumps, and choose for each one whether to do it using a ladder or bricks. It's always optimal to use ladders in the largest jumps. Iterate on the buildings, maintaining the largest r jumps and the sum of the remaining ones so far, and stop whenever this sum exceeds b.
|
Array,Greedy,Heap (Priority Queue)
|
Medium
| null |
20 |
I work ethic and Gentlemen I counted lstore Tunisia broke down for instance it recently Come and well furnished somat Android phone and reviews and more with Sweet shops are their work from no understand when you get is strange as containing all there is seeking the pace with printer shita kara brightest Promise to record and other three percent and opening Man And The clothes were at free on uses it takes place Open close Open and close and languages German with industry is well known and when it is the Open products over you were right and high Bright and subscribed Accord indecorous tourists when it is proud and with importance is not responsible to hunt For The First where is Wireless guido westerwelle openings prince innawood Where's my kosta Francis I happen If There were the latest work in progress every Open hard Marine corps of this is one to reconstruct of Sweet Tea or the world of the weight of us will not work force Pika stress Grand opening like is pink girl's day teeth Neville question in to me Cause I need to go on their side with some Oranges and spacious with more excited for example We see Ok opening of aggression and decorate economie norwich unimart opening Black Cat and discover siriport anymore opening careprost Lauren palladino Paladog Dragon Ball Battle of Los Angeles personal Jack welch I can just want something like that she has opened to live and work for inspiration to score in the one and we have opening practice and workers in practice cam astrid the course of peace World jadedness word entries and weather is of great wishes in this course and principle of Bright and Open Project is you now Not reflected Dock and Fall Out The Best Dragon Wars mace live weather in the war is very selfish weather is working as related to the world cup dai Chanel nuestras appealing to people who sold For One Person you ain't seen the best Western openings and speaking score in this Winter weather Open grave of the country is open Kali bogleheads Dielac Grow Dinh plantigrade against them make it is never leave with you are there any I Apologize ever going to make nice flowers and later He is never be applied to your Present the weakest of the boring plan to have to start with and of plenty of any Kind and want to start work with She with enormous either many advantages as well as the morning the world and make clothes in the brighter apple Open plan to Vietnam for using de culturas arabiya Accord trendnet laser disc to massacre at weekend and were Moving from interest rate will inform you come from our lowest rates in out of the way or another of lifting Francis I wish I ate vinafreight Just One Day and we can't move it to end the word which Keep Dreaming not solve the musician and once more inclined to work with the Gray and one Sweet Jumbo Vina Diep cnbui2 MTV Price of giants MV gentleman Nobita motionflow Because we close of the apprentice intumescent Lavigne What We're also noted for arabic arthrozan fastest want and were moved from Beginning of traditional vehicle will Move It is right now Switch explosion crack Ok googel move and gas Paloma vsmart sahuagin before Moving from the end the west stood the pulse width of Star that I had Lost their way to Hold fast to use start their to solve cross pictures are the first floor Apprentice Palace I like the way the Frozen Princess Evil welcome Popin from the all goals in parentheses overcommit to the Mouse to reset open in parentheses and shall have this dream of lifting gentacin contestants Next Switch disk Awards in practice It has winners house not sure How do we know That's When print Asean em euticals this one day well paid subject parapa spring-mass every subject parapa spring-mass every subject parapa spring-mass every question cuenta city tours muscle Black openings anticipatory spacious with Endless Love and chords In Black III Smart array of conduct and because in chorus need to mastery open Courage the way home When She was going of stay swanepoel our Hearts And tricks you really want to How to start a minute echoes in practice in National press to replace with the correct or live show Excel has been more impressed I will go of in two hours as Per Second with Green Fresh tomatoes please open plan to you ok Google best of Voice that decides to top I read articles in Transit doux Sting qmatic weekend for Women or from the grave now the weather in this spring plantigrade mom wants to school Go of the last major for Get Me straight us foreign tourists press Ok ortega Opera that Hurts instead we need DJ question is up Yours sol-ju massacre cross sport is up Yours sol-ju massacre cross sport is up Yours sol-ju massacre cross sport now right person will we Heart goes in practice Ok temperature and track Your Heart map witness this one is one of the best of product uses The Witch and the smarter and movement and now understand now and the Lost age and we have and empty Words We have nothing is what remains of differences in the correct Words and weak and restaurant food outsystem see movie the Third and Wide the Minutes they Go of and Pika Your Hands Together every import care were driving You can't Love Is For You can I think we go of and remember Piccolo sinh stacan be up to say that involved and all that matters all that people Go anycast pokarekare downloadmod your use of stochastic Grand scale to fight for which is also worth reminding the words to open gentleman DJ nha Heart Of the street King Floor Etown improve American take Everything goes in practice with one I'm not to the opening version of Brothers Ana mandara for free take the way because in grade of that to the Open workers and Korean cuisine press to open chorus Adidas JP the wanted to and free a What's what are we doing a first sight and Popin form and the court to occur in the Spotlight first value is this card is growing plantasil Escape and cause to open maps.me utica folk Fantasy and open maps.me utica folk Fantasy and open maps.me utica folk Fantasy and efficient With Me This is every millet av-test oyz correspond to love this av-test oyz correspond to love this av-test oyz correspond to love this record Dinh Francis I want is what makes our doubts That is not and Which is and chords in Plant species and precise and warm as directed towards the thoughts that is the National Open printer show Got To Dance With All show Got To Dance With All show Got To Dance With All Star Trek IV the one with this with all of Which are the act of Master Rising National Open Grand Minutes Walking Dead Bite take out map and inverted Pendulum because inc in shopee my quick recall PCP tree ask for motel Ms. Dinh Courage and earning Harris example with it is suggested that God that means We can fall From A stand and continue her IT necessary world star cabin entidad meal Together for example prince it's gonna save on this page is now i Master plan to have integral to see the short story nhattrung also with notch greatness corinto gfriend Open Project as noted that were transferred to do is win anti contrasted with nice work and rendering Open process with logo Ford has No Promises fastest and its many Awards in your parents want to see what you can stay Together and drop and liked Why is it so sad with etienne the one to Africa the waiting for me what's Yours is Lost art mt6.app not that none Yours is Lost art mt6.app not that none Yours is Lost art mt6.app not that none of the white Wolf and ports this is this Weeks in card printer problems I hope you understand What were you doing and structure she hope that this next and not to school subjects and It Hurts A Perfect world wide Surprise that supports I know well and hopefully suprasentential page ah
|
Valid Parentheses
|
valid-parentheses
|
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
3. Every close bracket has a corresponding open bracket of the same type.
**Example 1:**
**Input:** s = "() "
**Output:** true
**Example 2:**
**Input:** s = "()\[\]{} "
**Output:** true
**Example 3:**
**Input:** s = "(\] "
**Output:** false
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of parentheses only `'()[]{}'`.
|
An interesting property about a valid parenthesis expression is that a sub-expression of a valid expression should also be a valid expression. (Not every sub-expression) e.g.
{ { } [ ] [ [ [ ] ] ] } is VALID expression
[ [ [ ] ] ] is VALID sub-expression
{ } [ ] is VALID sub-expression
Can we exploit this recursive structure somehow? What if whenever we encounter a matching pair of parenthesis in the expression, we simply remove it from the expression? This would keep on shortening the expression. e.g.
{ { ( { } ) } }
|_|
{ { ( ) } }
|______|
{ { } }
|__________|
{ }
|________________|
VALID EXPRESSION! The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.
|
String,Stack
|
Easy
|
22,32,301,1045,2221
|
1,854 |
so hey guys welcome to another video so today we are solving maximum population here so in this question we have given a 2d integer array logs where each of H blocks of I represents birth of I and the death of I so indicates the birth and death years of the I person so if the population of some person some population of sum here x is the number of people alive during that year excess population if x is inclusive range so this is the range of one person's birth and death uh so that person is alive from 1993 to 1998 because this is exclusive we are not going to include this as per this statement okay so note that the person is not counted in the year that they die so return the earliest tier with the maximum population so in this example one person is alive from 1993 to 1999 so and the second uh second person is alive from 19 2010 the 2000 to 2010 so maximum person alive in a particular a time and is one so because they are not overlapping so like it is not like this person born in 1995. if that happens then the value will be changed so on uh so maximum population is 1 and the 1993 as the earliest uh year with this population so secondly we have example like 1950 and 1961. so this person is alive from 1950 to 1960 but at that moment the 90 in 1960 second person born okay second person one uh and uh after the 19 in 1960 the two persons were alive so then after this person died the this was a lie alone and then this is 19 1970 he's alive this person is alive this person born in 1970 so 1960 and 1970 are the two years which has a maximum population is two so it had happened in years 1960 and 1970. so the earliest layer between them is 1916 so the answer is 1916. now let's try to code it in C plus first so we will declare array of 101 size because the difference between the birth and date depth will be 100 years so it will integer ARR of one zero one we will initialize the array using 0 we will Traverse through the logs array integer uh what we will do Auto log of logs so far for integer J equals to log 0 less than log of 1. J plus so in this array we are excluding the depth year so what we will do we will subtract the array 1950 which is the start here foreign equals to 1950 because this is the first year from where they started counting the peoples or integer I equals to zero I showed less than one zero one a plus if Max is less than ARR of I so max equals to error of I and Max here we will get the Year by calculating I Plus we will add that much years in this because why we are adding we have subtract the years here so we will get the index at particular index we will add increment that particular index here and if that index is maximum so we will get the I here so what we will do return maxia let's run this okay it got some accepted let's submit okay it's accepted let's just copy this and I'll nothing much just the array difference I'll code it in JavaScript or JavaScript and code it in Java I'll paste it the code here I'll just change the array integer ARR equals to new integer of one zero one size nothing is changed let's run this okay the auto is not here right integer array okay let's submit okay it got accepted let's try to code it in JavaScript so here as well I'll paste the code so um let our logs in an array we will just change this let I equals to zero I should less than logs dot length I plus J log of I of 0 log of I of 1. um it's logs okay so we will create array we are going to let ARR equals to new array 101 Dot fill for the zero so it is a LED it is also let that set let's run this nothing much changed foreign let's submit okay it's got accepted so that's it for today so you can connect with me on LinkedIn Twitter links are in the description the code for this question is also in the description a code for this question is also in the honor GitHub you can check out the link in the description do to give the star up to the repo and as well as do follow me on GitHub as well thank you
|
Maximum Population Year
|
maximum-population-year
|
You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person.
The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die.
Return _the **earliest** year with the **maximum population**_.
**Example 1:**
**Input:** logs = \[\[1993,1999\],\[2000,2010\]\]
**Output:** 1993
**Explanation:** The maximum population is 1, and 1993 is the earliest year with this population.
**Example 2:**
**Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\]
**Output:** 1960
**Explanation:**
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
**Constraints:**
* `1 <= logs.length <= 100`
* `1950 <= birthi < deathi <= 2050`
| null | null |
Easy
| null |
1,952 |
welcome back everyone we're gonna be solving Lee code 1952 three divisors so we're given an integer and we want to return true if n has exactly three positive divisors otherwise we want to return false and an integer m is a divisor of n if there exists an integer K such that n is equal to K times m so example one and e n is equal to 2 the given output of false with an explanation that 2 has only two divisors one and two while four outputs true because one two and four are all divisors of four okay so we are gonna have a variable called count set equal to zero now we are just simply going to Loop through all of the numbers and the range of one two n plus one inclusive or one to n inclusive and if that number is um if that number modded by n has a remainder of zero then we know that it is in fact a divisor then we can increase our count by one and then at the end of this Loop we can return um if the count is equal to three we can return true otherwise we'll return false so we'll say 4i in range 1 2 N plus one so we can get an inclusive we will say if I modded by n if that is equal to zero we can increment our count by one otherwise do nothing and then at the end we will return count is equal to three so let's run this and we get failing test case 2 y see here output false for Xbox true one ten plus one should be n modded by I that's what it should be so rerun okay we pass both test cases we'll submit and it does run perfect so what is the time and space complexity of this the time complexity is going to be o of n right we are looping through every single number in the range from 1 to n inclusive and then we are checking if it is a divisor so that is going to give us a runtime of all of n the space complexity is going to be o of one right we're not using any data structures here we're just simply having a variable to store our account and I'll do it for lead code 1952.
|
Three Divisors
|
minimum-sideway-jumps
|
Given an integer `n`, return `true` _if_ `n` _has **exactly three positive divisors**. Otherwise, return_ `false`.
An integer `m` is a **divisor** of `n` if there exists an integer `k` such that `n = k * m`.
**Example 1:**
**Input:** n = 2
**Output:** false
**Explantion:** 2 has only two divisors: 1 and 2.
**Example 2:**
**Input:** n = 4
**Output:** true
**Explantion:** 4 has three divisors: 1, 2, and 4.
**Constraints:**
* `1 <= n <= 104`
|
At a given point, there are only 3 possible states for where the frog can be. Check all the ways to move from one point to the next and update the minimum side jumps for each lane.
|
Array,Dynamic Programming,Greedy
|
Medium
|
403
|
116 |
hey guys welcome back to another video and today we're going to be solving the leak code question populating next right pointers in each node all right so let's first try to understand what the question is i think it's a little bit confusing so let's just go through it step by step all right so over here we're going to be given a perfect binary tree so in a perfect binary tree all of the leaves are on the same level and every parent has two children the binary tree has the following definition okay so uh if this is a little bit uh confusing let's just look how it uh see how it looks like in python all right so in python over here uh we have a class called node and each node represents a single node instead of our tree so over there we have a four attributes so we have self.val so we have self.val so we have self.val referring to the value of our tree node then we have left and right which points to the left pointer and the right pointer now the new thing that we have over here which you might not have seen and which is specific to this question is the self.next is the self.next is the self.next attribute so what self.next means is attribute so what self.next means is attribute so what self.next means is basically whatever value is to the immediate right of it so by right i don't mean the right child but instead i mean the exact right so just to kind of show you what i mean is basically in this case the so the dot next attribute so for one the next attribute would be no similarly for two the next attribute would be three and for three the next attribute would be null and finally let's just look at this once more so for four the next attribute will be five for five the next attribute will be six for six it will be seven and for seven it would be null alright so hopefully you understand what the next attribute actually means so in this question what we want to do is we want to populate each next pointer to point to its next right node if there is no next right now the next pointer should be set to null initially all pointers are set to no all right so that's important in the beginning everything is equal to null right so now basically all we're doing um currently let's just look at the very beginning a 2 would be pointing to null right but ideally or in the correct definition two should be pointing to three and three should be pointing to long so uh by the ending of whatever our function does we should end up with something which looks like this okay so hopefully you understood how the question works and what we need to do and now we'll see how we can solve this so to do that um i drew the exact same tree data structure over here and one thing i just want to kind of reiterate is the fact that whatever tree we get it's going to get be a perfect binary tree okay what that means is that every root has two children and the leaves are always going to be on the same level right so we won't have something like this right they're always going to be at the same height or level whatever you call it so we always have a perfect binding tree and that makes it a lot easier for us all right so as with most uh tree based data structures we have two ways to solve it so we could either use a recursive or dfs way a depth first search or we could use a bfs way all right so i'm going to use a breadth first search uh kind of way to solve this question but the other two methods work just as fine right so in a breadth first search approach uh if you don't know how it works let's just go through real quickly we're going to have a queue and i'll just represent a queue using a list over here right so this over here is going to represent our cube so uh real quickly in a breadth first search how it works is we're first gonna go to one then we're gonna go this way so then we go to one then we get two three and then we will go this way right we go but level by level okay so then one two three four five six seven so that's how our breadth first search is going to look like all right so now that we have this like i said the beginning is going to have the root value okay so we're going to have the root uh starting off in our cube so over here we're going to have a variable called current and current is just going to refer to whatever node we are currently on so in this case where how do we know which node we're on so in the very beginning uh it's not going to have a value but we're going to get its value by popping out whatever is at the zeroth index inside of our q so in this case what's in the zeroth index so one is in the zeroth index we're going to pop it out and that is going to be our current value so current is equal to one and just to kind of illustrate it better i'll just write it over here right so current in this case is one right perfect so now we want to make it a next pointer all right so in the very beginning what is one going to be pointing to so the next pointer for one is going to be null right and that is correct right no one is not pointing to the right of anything so that stays as it is so now what's going to happen is we know for a fact every root node is going to have two children right nodes one on the left one on the right so in this case one has a left child of two and a right child of three so since it has a left child and a right child we know that we are not at a leaf yet and since that is the case what we're gonna do is we're gonna make it so that the left child over here which is two so the left child of 1 which is 2 is going to point to the right child of 1. so in simple words 2 is going to point to 3 and that is correct that is exactly what we want and like it said earlier 3 by default is pointing to null or none sorry let me just write them all so it's more consistent and that's what we have so far now one more thing we're going to do is we want to repopulate our cue right we're not done with it yet so to do that what's going to happen is we're going to add first the left child of 1 which is 2 and then we're going to add the right child of 1 which is 3. okay so there is one step over here that is missing but what i want to do is i want to kind of give you a more intuitive understanding of how we can come up with the solution okay so now we have two and three inside of our queue and the current value is now going to be whatever we pop out from the zeroth index of the queue which in this case is well two right so now we're going to have our current value equaling to two so let's just write it down over here and now what's going to happen is the left node so the first thing is we're checking if it has a left or right no it does so that means we're not at a leaf so now what we're going to do is we're going to go to its left node which is 4 and make it point to its right note so four points to five perfect okay so again like i said there is something missing here and i just want you to kind of uh understand or find out what is missing okay so now we need to add uh its children right so its children are four and five and let's just add that to our q so we have four and five okay so i'll just go through this a little bit faster so now we're going to have current uh we're gonna remove this and now it's gonna have a value of three so we have three so now we're going to go to three we're going to go to its left child which is six and six is going to point to seven perfect okay so now we need to add its children which are six and seven but now all these uh values four five six and seven they're all leaves and how do we know that it's because 4 does not have a left child and it does not have a right child both of its left and right children are equal to none that means we have a leave so in that case we can just stop right we don't need to do anything we can just stop after this okay so perfect so uh that would so we would do four then nothing would happen we would do five nothing would happen six and seven all those cases nothing would happen since they are leaf nodes now what exactly is the problem here okay so let's just kind of uh draw this more better so 5 would be pointing to none and 7 will be pointing to none sorry not okay so uh this part is correct this part is also correct um this part over here is also correct but the only kind of mistake here is four points to five but five over here should be pointing to six right so that's a problem why is five not pointing to six and the answer to that is because we didn't actually have any sort of condition to do that so now what i'm going to do is i'm going to introduce a new condition in such a case that now 5 ends up pointing to 6. so let's see what that condition is and what i'm going to do is i'm just going to go back to that step okay so now i went back a few steps to where we have this point over here and now the condition that we're going to be checking for this each time and it basically what we're doing is we're going to check if current.next has some sort of value if current.next has some sort of value if current.next has some sort of value right so we're checking if current.next has a so we're checking if current.next has a so we're checking if current.next has a value so what does it mean if it has a value so in this case when does have a value so when does have a value so when does have a value so let's just go back to the very beginning so when current is equal to 1 in that case does not have a value case does not have a value case does not have a value so in that case we are not going to do anything and we're going to leave it as it is so now in this case when you go to the next step the current value now becomes 2. so over here current.next does have a value here current.next does have a value here current.next does have a value right 2 is pointing to 3 there is some sort of value so now in this case what we're going to be doing is we want to join the nodes between the right child of 2 and the left child of 3 okay and that is exactly what we're going to be doing over here right so what's going to basically happen is we have five and six and since the current node does have a next value we're gonna go to the right node of uh two so the right node of two refers to this and we're going to go to the left node of 3. now one question you might be having is actually the left node of 3 is 6 okay so one question you might be having is how do we know it's the right node of 2 and the left node of 3 and the reason we know that is because we're first adding the left node to our queue and then the right node so kind of following that we can just come up with this okay so the left the right node of whatever current is and the left node of current.next so and the left node of current.next so and the left node of current.next so current.next.left current.next.left current.next.left so we have five and six and now we're gonna make a connection between them so five is now going to be pointing to six so if you still don't understand it i would highly recommend to further uh increase the tree and kind of see how this relationship works it should be a lot more clear but yeah all right so now let's just go on to the code part hopefully you understood how this works and yeah okay so over here we have our code and real quickly this over here like i said earlier is the class node that we're referring to and that's what we're going to be using all right perfect so as with most tree based questions the first thing we're going to take care of a case where the root does not have a value right when we don't even have a tree so to do that we can just do if not root and in that case we can just return the root itself okay so now we took care of that condition and now we can assume that we have some sort of tree right and again remember this is going to be a perfect binary tree so over here we're going to start off with defining our q so for defining our queue like we saw earlier we could just use a list or another thing that we could do is we could use a collections.dq and i would could use a collections.dq and i would could use a collections.dq and i would prefer using that since it does have faster lookup times so to get that we can just do collections uh and you would be importing collections so collections.dq collections so collections.dq collections so collections.dq okay so over here we have our queue defined for us and uh to this queue over here we're gonna be adding the root value in the very beginning to do that we can just directly do q dot append and we're going to be appending the root okay so now that we have our q defined for us and it also has the root element inside of it now we're going to go inside of a while loop so while q and what that basically means is we're going to stay inside of this while loop until our q exists okay so now the first thing we want to do is we're going to pop out whatever is at the zero with index and that is going to be equal to our current element so to do that we have the function top left and that's the same as doing pop zero okay so now we have our current node so now what we're going to check is we're going to check if the current node is a leaf and how do we do that well a simple thing we can do is we can check if it has a left and a right note okay so if current dot left and current dot right and in that case we can just directly actually go into this assuming that it is not a leaf and if you wanted actually you could remove one of these conditions because uh since it is a perfect binary tree if we know that current.left exists then if we know that current.left exists then if we know that current.left exists then for a fact current.right is also going for a fact current.right is also going for a fact current.right is also going to exist okay so let's just leave one of them so if current.left so now we can go inside of current.left so now we can go inside of current.left so now we can go inside of this and what we're going to do is we're going to first dot left dot next to current dot right okay so that is the same as this part over here right pointing the four to five that is what we're doing currently right now okay so to do that current now we're gonna go to its left node and we're going to add it to the next attribute and that is going to be equal to current dot right all right perfect so now over here what we're going to be checking is we need to check for this condition for the 5 pointing to 6. so to do that like i said earlier the first thing we're checking for is we're checking if current.next has a value right so if current.next has a value right so if current.next has a value right so if current.x current.x current.x is next is not equal to none then in that case we're going to go inside of this over here and the check that we're doing over here is basically we're going to go to current dot right dot next and what exactly is that going to point to so current.right.next so current.right so current.right.next so current.right so current.right.next so current.right that is the 5 over here and dot next so that is going to be equal to current dot next dot left so in simple words current dot next so two goes to three and we're taking three's left element which is six okay so that's exactly how we're pointing that and that's it and now all we need to do is we need to add its children to the cube so to do that we're just going to do q dot append and we're going to append current dot left and we're also going to be appending current stock right so q dot append current.right so q dot append current.right so q dot append current.right and that should be it for our solution and obviously at the very end we need to return our root value okay and that should be it so let's submit our solution and let's see what happens okay so as you can see our submission was accepted and there's one small thing you could do i don't know if it's really necessary so over here we're checking if it is not a child right so if something is not a child what we can do is we can actually break out of it because once we find out one thing is not a child that means that everything after that is also going to be a leaf and we know that again because it is a perfect binary tree so over here if that is not the case what i'm going to do is i can just directly return root or instead we could just break out of the while statement so submit this and this should also get accepted so finally thanks a lot for watching guys do let me know if you have any questions and don't forget to like and subscribe thank you
|
Populating Next Right Pointers in Each Node
|
populating-next-right-pointers-in-each-node
|
You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node \*left;
Node \*right;
Node \*next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`.
Initially, all next pointers are set to `NULL`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6,7\]
**Output:** \[1,#,2,3,#,4,5,6,7,#\]
**Explanation:** Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 212 - 1]`.
* `-1000 <= Node.val <= 1000`
**Follow-up:**
* You may only use constant extra space.
* The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.
| null |
Linked List,Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Medium
|
117,199
|
993 |
Jai Hind Is Tutorial Am Going To Discuss A Program In Question Comes Once In Binary Tree Pure Problem Statement Is Given To Value Sucks And Violations How To Write A Code To Take Notes Kar Is Point To Value Action Wires And Note Soiled Not Kar Is Point To 10 Viewers 10 1MB Mode Turn Into This Will Reduce One Switch To Check Weather db2 Notes Of Weight Or Not And Water Due To Notes For Industrial Corridor Nifta Rural Same Dip But Have Different Parents Swift Hybrid SIM The But Different And What Is Dip So Starting From Route Notes for the Dictator's Day Sero Amrit Children of Route Mode One and Children of the Snow Deposit Is Due Point Plus One Which Two Ifin Us Update and Have Different Events Jhal Dr Two Notes68 Victims of Each Rate and All the Values in This Country Are Unique So Let's Understand This All the Values in This Country Are Unique So Let's Understand This All the Values in This Country Are Unique So Let's Understand This Problem Statement To Examples Hindi For Example Given To Values For Inner 310 No Time 10 Notes Values For Inner 310 No Time 10 Notes Values For Inner 310 No Time 10 Notes For The President Of This Is Not As To Independent Of This Notice Vansh-Vridhi Then Independent Of This Notice Vansh-Vridhi Then Independent Of This Notice Vansh-Vridhi Then Different Parents What They Have Different Dates Us Updates Not Seem To Be written for its convenience hotspot of the place for let's move to example2 notes25 0 notes on the subscribe nand specific different parents channel subscribe must notes of versions and group let's move to three examples for any third example common two and three pure values that two In 30 Two Notes Morning Half values that two In 30 Two Notes Morning Half values that two In 30 Two Notes Morning Half Parents There Deputy CM Big Half Prem Paris Adherents Condition Will Return Forms Siddhi Problem Statement And Now Let's Discuss Multiple Approaches To Solve This Problem So Let's Discuss And First Approach And In This Approach I'm Going To Solve This Problem Using Your Details Including Five Words Entry Level Bike Level And Also Of Music Two Hash Map In One House Map I Keep Node Value And Spirit 6 Note Value And Second Hai Smart I Ki Note Value And Its Corresponding Level And Chapter Complete Raw Actually They Are Half Inch Note Value On This They Also Issued Element [ __ ] Level Source On This They Also Issued Element [ __ ] Level Source On This They Also Issued Element [ __ ] Level Source Sampler Check Loot This Condition Students Of Mine Aadhyavadhi Same But Different Parents So It Can Oy Validator Where They Can Satisfy His Condition And Not What We Can Do Is So Let's Start Traversing History Level By Labels Poems For level reversal where using tube saunvi post 10 node in a q white poached eggs value in the ideal upper 10 valuable sy lower desired initial value in this map showing force improved route 010 route did not have any parents what we can do is so let's support 1000 Dildad s0 540 Virender Sehwag Lutz Not MP Sweep And 10 Value Switch Polaris Value And Vivek Left And Right Children 349 Tunnel Simply And Give Them In A Q Subscribe Children Middle Children Not Channel And Also Like This Value To Boys Paint Subscribe It Does Not Mean That This Also Add This Point Se 1000 Years And Similarly For Children Fallout 110 Right Children And Its Present Value And Also Acts Level Hai 360 Similar Code Yaar And Also Bihar And Cute And Not In Next Titration Vihar To Day Cute 10 Value Ravi Poling 10 Value in the same with absolute and children is divine Siddhiyan condition President and Buddhists run his children so lets and food and also put Hindus and spirit will have to similar for boys letter to 9910 and vivid please subscribe and did not have any right Children Sweet 1919 10.53 right Children Sweet 1919 10.53 right Children Sweet 1919 10.53 That Today Also Acts Level Witch S2 Date Side Reaction With A Good Place Value And Where Is Not Left And Right Children For 10 Notes Adult Indian And International Skirt Similarly For The And Not Dare Smooth Left And Right Children And To Daughters Pe Of victims from 1000 how to validate the meanwhile two value note that at this point you two values are the same level solve and values are the same level solve and values are the same level solve and gift for and add 1600 map to maintain levels will give water level of two 9 inches yes de Villiers same so let's check parents with that Front of this not to be two three layer pendants are also not given vent through day-2010 day-2010 day-2010 that I effects of this condition is not satisfied in return for the day to you sir notifications not talk about its time and space complexity shoaib time complexity of a Women were visiting this issue of binary tree and what about space complexities where using your specific benefits which complexities also n sun reduce and next approach in which they tried to solve this problem in constant space play list discuss and next approach and in this approach will solve This problem in by using constant space for the year to take the value of So let's lie and see a greater class in between it into its parent and death and day from this method am falling under cigarette note pendant method for both will also enjoy this method returns different and depth of both the values and also more comparison here And so let's see how this method values and also more comparison here And so let's see how this method values and also more comparison here And so let's see how this method kiss a lips huge events flash lights of the value of Update Road 1200 Days Liquid Is Method And 10 Minute Buddha First Edition Of Roots Null Sampler Tunnel Which Is Not To Indus Valley Is Equal To The Value Of Units Notes In Written Its Apparent Value And Days Of Subscribe Wechat Statement And Calling Subscribe And Share The PS2 Din This Adheen Vihar Fair And Root Notice Vanshdhar Root Mode Of The Day In The Live With A Half The Difference Of The Day Nal WeChat Statement Return Also Give Back 10 Step Remove The Sign Of Good And v5 Subscribe No Right Na Dhan Divya Subscribe And Its Root witch 222 that encounter better again will reach with equal 10 recursively send personal switch address statement and reach at 10 statement and then again will go in right half t tree and within same process and from here all voters will return the value of parent and Apps Buddha Pendant Three Layer Pendant To Fennel In This Way Will With Object Which Consists Of Two Value Simple Three Layer Appear And To For Death And Give Equal This Method For 10 Business Popular Reciprocally Avi Travels Tree And Will Retain Its Parent And Detained For This They written its present which students death which all say that we day also check affidavit same pure desktop first one so let's light clean two so addicts many parents and different so bodhi notes of questions so in this way can solve this problem using this approach And Now Let's Talk About Time And Space Complexity Sweater Time Complexity Is Of N S Complexities Oven Wear Using Condoms And Space Soen Date For This Video Tutorial For More Sach Programming Videos subscribe our YouTube Channel and subscribe dot com in Thanks for Watching This Video Please Don't Forget to like this video
|
Cousins in Binary Tree
|
tallest-billboard
|
Given the `root` of a binary tree with unique values and the values of two different nodes of the tree `x` and `y`, return `true` _if the nodes corresponding to the values_ `x` _and_ `y` _in the tree are **cousins**, or_ `false` _otherwise._
Two nodes of a binary tree are **cousins** if they have the same depth with different parents.
Note that in a binary tree, the root node is at the depth `0`, and children of each depth `k` node are at the depth `k + 1`.
**Example 1:**
**Input:** root = \[1,2,3,4\], x = 4, y = 3
**Output:** false
**Example 2:**
**Input:** root = \[1,2,3,null,4,null,5\], x = 5, y = 4
**Output:** true
**Example 3:**
**Input:** root = \[1,2,3,null,4\], x = 2, y = 3
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[2, 100]`.
* `1 <= Node.val <= 100`
* Each node has a **unique** value.
* `x != y`
* `x` and `y` are exist in the tree.
| null |
Array,Dynamic Programming
|
Hard
|
2162
|
329 |
hello hi everyone welcome back to the channel so today in this video lecture we're going to be solving this problem longest increasing path in a matrix so basically you are given a two dimensional Matrix of Dimensions M cross n it contains integers we want to return the length of the longest increasing path in Matrix so for each cell you can either move in four directions left right up or down you may not move diagonally or move outside the boundary fine so let's take an example so let's see in this example we have a matrix of n cross 3 and here in this Matrix the longest path would be to start from the second cell of the third row now move to move from one to two then from two to six then from six to nine giving me a path of length 4 containing four cells or four nodes and hence the answer is 4. so let's see how we can solve this problem so we want to solve this problem using topological sorting so let's recall the definition of topological sorting basically topological sorting is a linear ordering of the vertices of a graph such that in the ordering if a Vertex a comes if there is an edge bit from vertex a to vertex B then that means a must come before B in the give in the top in the topological ordering that's the concept of topological ordering now how topological ordering can be used to solve this problem let's see that now you can see that topological sorting can be applied over directed acyclic graphs but here we have a matrix of dimensions three cross three how can I apply topological sorting topological ordering for this type of cells for this type of Matrix now we can see that we want to find the path the longest path such that all of the nodes or the cells along that path are in increasing order like in this case the path is move from one to two then from 2 to 6 then finally from six to nine we can see that what we can do is we can make edges from those cells which contains lower numbers towards those cells which contains higher numbers or greater integers like here in this case we have a cell 2 1 it contains one now we can create an edge from 2 1 to its adjacent cell 1 directed from cell 2 1 to 1 so there will be a node corresponding to cell two one there will be a node corresponding to cell 1 and the edge there will be an edge from one to six there will be an edge from one to two and there will be an edge from this six to eight there will be an edge from six to nine there will be an edge from 4 to 8. like I will connect all these numbers in The Matrix in the order such that each number has an edge outgoing Edge towards the adjacent number which is greater than it itself fine so let's see how we can do that so let's number the nodes let us say fossil 0 we have node 0 for cell 0 1 this is node number one for cell 0 2 it is node number three for cell 1 0 it is node number like for cell 0 2 it is node number two for cell 1 0 it is node number zero one two three and so on will have nodes three four five six let's create edges we can see that we can create an edge from cell so this is cell lets zero one two three four five six seven eight create an edge from 7 to 4. zero one two three four five six seven eight so seven eight okay so from 7 towards eight there is an edge from 7 to 4 we have an edge from 7 to 6 V and Edge now we don't have an edge from seven to eight we have an edge from 6 2 7 to 6 so this is not here okay so then we have an edge from four to one then we have an edge from 4 to 5. then we have an edge from two to one because the integer here is lesser than the integer here then we have an edge from 3 to 0. so we have an edge from 3 to 0. okay then we have an edge from okay three to zero and from 8 we don't have any Edge from 4 we have an edge towards node number one and node number eight from cell 3 we have an edge towards node number 0 and that's all we from cell one we have an edge from four to one and from 4 to 5 and okay then from 2 0 from node number six we have an edge towards we have an H towards three so we from 6 we have an edge towards three from 6 we have an H2 we have that's all there's only one Edge from six to three from Seven we have a H2 4 and we have a H2 6. from 2 to we have an edge like from 8 we have an edge to five so from this cell we have an edge towards five so from eight we have an edge towards five that's all so that's the graph that we have now here in this graph the longest path is if I just find the longest path that would be starting from 7 it will move to six then from six it will move to 3 and from three it will move to zero so this is the longest path that I can achieve okay that is 7 6 3 0 containing four nodes and that's the answer so what I can do is I can simply find the topological ordering for this graph so is it okay node number eight has in degree 0 is there is an edge from four to eight there's an edge from 4 to 8 no there's an edge from there is no Edge from four to eight this is wrong Okay so okay so this is okay let's find the topological sorting order for this graph using Khan's algorithm so what do we do in current circuit then we list first those nodes which has in degree as zero and those nodes are node number two it has in degree 0 here load number eight it also has in degree 0 node number 7 also has in degree 0 and that's all these are the nodes within degrees as 0 now these nodes are there in the queue so we push them into the queue so from node number two so we have like we push two we push eight and then we push seven into the queues now from 2 Traverse its adjacent nodes so from two Traverse the adjacent node that would be node number one only so when I Traverse node number one this Edge will be removed so we remove this Edge and hence the in degree for node number one becomes 1 okay now push another node from the queue that is node number eight so from node number eight move to node number five and remove this Edge so remove this Edge fine and the Integrity for node number five does not become zero now pull the next node that is node number seven and from node number seven move to the adjacent nodes that will be node number six and node number four so remove this these two edges that is they search from seven to four and this Edge from seven to six so here you can see that the in degree for node number 6 becomes zero so that I will push into the queue now pull this node from the queue and push it into the ordering so 6 is there into the ordering now from 6 move to the next node which is node number three so remove this Edge and here you can see that node number three also has in degree as zero so push node number three into the queue and then in the next iteration pull out node number three and push it into the ordering array now from node number three move to its adjacent cells that is node number zero so put this node number 0 into the priority queue and so remove this Edge and then this the integral for node number 0 becomes zero so push it into the queue and put it here in the ordering so put 0 in the ordering now Traverse next node that is node number four it also has in degree as zero so push this node into the queue this was also pushed when I pushed node number six so node number four is also there in the queue now from node number four Traverse node number one and node number five so remove these edges remove this Edge from four to one and also this Edge from four to five and push them into the queue so four and so four is out four is here push one and five into the queue now remove one it doesn't have any outgoing Edge and push it into the order then remove five it doesn't have any outgoing Edge push it into the order so this is my topological ordering array which I have now I will now the next step is I will prepare a DP array where DPI represents the longest path what it represents is longest path so this element represents the longest path taken to reach node number I so let's declare a DP array of size n where n represents the number of nodes in the given adjacency Matrix so how many nodes are there like if the dimensions of the Matrix are n cross m then n into M will be the number of nodes because these are the number of cells we have six cells here we have nine cells here so there will be nine nodes numbered from 0 to 8. okay so in this fashion we'll have our DP array now here in the DP array let's see that let's Traverse over this ordering we have 2 8 7 so this array is initialized with one initially because all of the nodes contains at least one node because like I have a path of length one which is ending at that node itself so start from this node that is node number two so for node number two Traverse its adjacent nodes so for node number two the adjacent nodes are in this adjacency list What will What were the what are the adjacent nodes of node number two now we can see that from node number two we can move to node number one and from node number two we can also move to node number five so that means from node number two Traverse node number five and node number one so node number one and node number five so that means for node number one and node number five the length would be two photo number five it would be two why because we can arrive at node number one and node number five from node number two okay so its the equation is like DP of current node on which I am standing P node DP parent plus one DP of parent plus one okay so this will be the DB for the given node now here you can see that like here in this example we had node number one and node number five and the array for these nodes were was updated from like it had like DP of one had an answer of one and the parent node for node number one and node number five was node number two so for node number two we had one so it would be one plus one so max of one and two would be two so for this for the node number one we would have two and for node number five we would have two okay because for parent node number two we had one and while we arrive at the child node we are adding one more node so in this fashion we'll keep updating the DB array and finally we'll have our answer stored for the like longest path or the longest path following the numbers which are there in the increasing order like in this case for node number 0 we would have four stored why because node number three will have three stored for node number 6 we will have 2 stored and similarly for node number one for node number seven we will have one so from Seven we move to six it adds one node then from six we move to node number three it adds one more node giving a length of three then from node number three we move to node number 0 giving a length of four so the answer is four and we simply return the max element in this DP array fine so this is how we solve this problem it's just simple implementation of Khan's algorithm and a little bit of DP so let's just jump to the code implementation so let's see the pseudo code implementation this is longest increasing path function which takes in this Matrix here we calculate the dimensions of the Matrix then we have then we declare our adjacency Matrix of Dimensions equal to the number of elements in the given Matrix so and we declare a degree array which contains the degree for each node of the cell or the in degree now iterate over each cell of the Matrix now for each cell we iterate over its adjacent cells so there are four adjacent cells for any given cell of the Matrix and we iterate over its adjacent cells like here in this case the for any cell i j the adjacent cell would be x y and let's and this dir is an array which is used to Traverse to the adjacent cells now check if the adjacent cell that we have computed here is valid if it is a valid cell then simply create an edge from the cell from the parent cell to this new cell and the parent cell is simply row number multiplied by the number of columns plus the current column how let's say I want to calculate the corresponding load number for this cell that is node number that is cell 1 now how many rows I have traversed to reach this cell one row how many cells are there in each row we have three cells how many cells I have traversed to reach this cell in this particular row obviously one cell so it would give me 3 into 1 plus 1 that is 4 so it's a fourth cell that's how I am calculating the low number corresponding to each cell of the Matrix so in this fashion I am creating the edges and for each new cell I am simply incrementing its in degree fine so here I will have my adjacency list prepared and here I will calculate the order array algorithm is used to calculate the topological order for this given adjacency list and this is the degree which I am passing now declare a DP array of Dimensions n cross M A DP array initialize it with one now iterate over this order that we have calculated here and for each node in this order array simply update the DP as per according to the equation explained here fine and at the end of this function we'll simply return the maximum element in this DP array so that's all we have to do in this problem so let's just jump to the code implementation part okay so this is the longest increasing path function let's create let's find the dimensions of the Matrix that would be Matrix dot size calculate the number of columns Matrix 0 dot size declare a adjacency list of Dimensions n cross m and a degree n degree automations n cross m then simply iterate over each cell of the Matrix from 0 to n then from 0 to m and for each cell Traverse its edges so I plus let us create a direction Vector so vector Direction Vector it would be 0 minus 1 0. Okay so d i r i plus y j Plus I plus it's not I it's K so it's K plus 1 now check if this new cell is a valid cell if it is a valid cell then simply create an edge from the parent cell I into M plus J towards X into M plus 5. fine and also increment the degree in degree for this cell X into M plus y because we are creating an edge towards it fine so in this fashion we'll have our in degree array prepare and here we'll call this function algorithm pass in the adjacency list and the order and the N degree in degree array find declare a DP array size of the DPR is n into M initialize it with one fine and a trade over all the integers in this order array which is the topological order now for each node iterate over its adjacent cells adjacent nodes for this current node and update the DP array for this adjacent node for this Edge it would be Max of DP of edge DP it's DP of H d p of i t plus 1. at the end return Max element in this DP array now a trade over the nodes we also pass the number of nodes that we have n m a trade over this n degree array if n degree for any node is 0 then so iterate over all the nodes of The Matrix now if the N degree for any node that would be I into M plus J if it is 0 then push this node into the queue so push I into M plus J okay now run the while loop pop the node top node from the loop from this queue towards the adjacent cell for this node adjacent nodes of this current node now for all the adjacent cells decrease the in degree for them so n degree for the neighbor cells will decrease and if the in degree for the neighbor becomes 0 push it into the queue okay so here we are popping this node also push it into the order array fine so that's how the algorithm works and let's try to submit it okay this uh okay we forgot to pass n and M let's see that I forgot to pass okay we create an edge here the problem is that we will create an edge if the we forgot to mention this condition that if we create an edge only if the cell the new cell x y the integer at the new cell we create an edge from the if this contains a greater number than the parent cell i j only in that case we're going to create the Edge so let's now try to submit it okay it got accepted let's just submit let's see if it is a correct solution okay it got accepted so that's all for this video if you like the video then hit the like button and make sure to subscribe to the channel and stay tuned with me for more such content I hope to see you all in my next video
|
Longest Increasing Path in a Matrix
|
longest-increasing-path-in-a-matrix
|
Given an `m x n` integers `matrix`, return _the length of the longest increasing path in_ `matrix`.
From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).
**Example 1:**
**Input:** matrix = \[\[9,9,4\],\[6,6,8\],\[2,1,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[1, 2, 6, 9]`.
**Example 2:**
**Input:** matrix = \[\[3,4,5\],\[3,2,6\],\[2,2,1\]\]
**Output:** 4
**Explanation:** The longest increasing path is `[3, 4, 5, 6]`. Moving diagonally is not allowed.
**Example 3:**
**Input:** matrix = \[\[1\]\]
**Output:** 1
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `0 <= matrix[i][j] <= 231 - 1`
| null |
Dynamic Programming,Depth-First Search,Breadth-First Search,Graph,Topological Sort,Memoization
|
Hard
| null |
1,734 |
hey what's up guys this is chung so this time uh number 1734 decodex word permutation so this one is very interesting uh bit manipulation problem okay so you're given like an integer array a permutation that is a permutation of the first and positive number on unpositive integers where n is always odd so keep in mind so n is always odd because we need this uh characteristic to help us solve this problem so which means that you know the permutation which means that it's like a 1 to n right 1 to n there's a permutation the sequence could be the order could be different and then you know it was encoded into another integer array encoded of length n minus one so the rule to encode uh is like this so for encoded i the value will be the permutation of i x or i uh permutation i plus one so for example if the permutation is one three two then the encode is two because the first one is a one x or three and then the second one is a three x or two that's how we get this two one here and so and then you're given like the encoded array and you need to return you need to revert you need basically you need to decode this array to its original value and it's guaranteed that the value the answer is always exists in the and unique so the first one we're already given that so we have encoded three one and then we are expecting to outputs one two three oh yeah this three one so and this first the second one is like this so the encode is it's like this and we need to get the uh this value and there's some like constraints here cool so and so you know at the first glance right so we have no clue how we can revert this uh encoded basically how can we uh decode this encoded string to its original values so what we should do is that we should at least try some examples and let's try you know let's try this let's try it for example if we have like this one we have four uh 2 4 uh 1 5 3 7 and 6. and let's see this is the original value and so for the encoded string what's gonna what will what the encoded string look like so first one is the two x or four second one is uh 4 xor 1 and then 1 x or 5 x or 3 and then 3 x or 7 the last one is 7 x or 6 so i think most of you know that you know if we x or two values two uh two that's the same values it will be zero right so if we x or uh four is four the value is zero so if you only look at this uh this or x words uh this value here you know and you can find some patterns here right so let's say you if we actually everything so it's going to be uh so this two fourths will be cancelled two ones will be cancelled out there's two five two three two seven and in the end it's actually the 2x x or 6. right but this still doesn't help us to solve this problem because we don't know 6 and we don't know 2. we still cannot get the uh the original value so i mean let's say we have uh a x or b equals to x so if we want to get either a or b you know we have to know the value of a or b right so that we can get we can do the calculation afterwards otherwise you know if we don't know a or b there's no way we can figure out the at the value of a or b so by looking at this one you know it won't help us to uh to calculate that uh so here's com here comes the tricky part you know and if you look at the uh this as this values right like by uh by some uh on one the other instead of a consecutive ones you will find a pattern so let's say if we find if we only look at the even either the even element or the odd element so what can we find out let's say if we only took like the even elements we have two four right two four this is the one and then we have one five and three seven so what numbers do we have two four one seven three uh three seven uh two four one five and three seven if we compare with our original uh array here so basically we're having everything except for the last one similarly for the odd one so if we look at the 4 1 5 3 and 7 6 similarly right we have 4 1 five three and seven six the only thing that we don't have is two then they give us like a strong a very clear hint right let's say if we take the odd element here right we have this one and if we x or if we do a xor of this element and then we do a x work and then we actually another one with the total actual of this one of the arduino uh list here so what will end what we will have we'll have two we will get two because four and four will cancel out one five three uh five three seven six you know if we act for everything they are they will all be cancelled out except for the two so if we do it that way you know then we will get the first element of the uh of the original ray which is two as long as we have one element from the original uh array here we can just use that one to deduce right to deduce the remaining numbers so how can we do that you know okay so we know this one here right so we know this is like 2x or four we know this one let's say for example this one is x because that's going to be the first element of the encoded array here and we know 2. so what do we have 2 x or b right equals to x and we're looking for we're trying to calculate the b here and we already know 2 and x so how can we calculate b similarly right we can use the same characteristics of the x word right we can do a xor of two on both sides so which means we're gonna do a xor uh x or two on the left side and we also do x or on the right side since we have 2 and 2 so 2 and 2 will be cancelled out and the only thing left on the left is b so an x is already known so the result will be x do a xor of 2 that's going to be the value of b and right so similarly if we already know the b here which is 4 right and we already know the 4x or 1 we can use the same formula to calculate 1 5 3 and so on and so forth and we can deduce everything from there yeah i think that's the basic logic here and so here the reason we need to use a art we need to make sure that it's odd it's because you know let's say the n is even uh which means that uh let's say the uh the six is not there so we have six numbers and which means that the last one is not there so if we if the n is even then our solution will it will not work because you know if we only look at the even uh the even element we have four one uh 5 3 but so what's left 2 right 2 and 7. so if we use the same formulas so we'll end up getting the actual of 2 and 7 instead of the 2 itself so which will not help us solve this problem that's why the uh the n has to be even sorry and the n has to be odd so that we can use that uh either the odd uh items or the even items help us get the either the first element or the last element and from there we can just say use the decoded array plus the known numbers to calculate the rest of the numbers cool so let's start coding then and let's say we have an intercourse encoded so i'm using this one uh encoded to get n here so let's say we have so first let's calculate the uh the xor from one to n i'll start from one to uh it's going to be a length of encoded plus one because the encode is a minus one so the end should be length of this one plus one so let's calculate that one first and let's see i'm going to call it x or one how about that so we have actual one equals starting from zero and then we do i in range of one to uh n plus one right and then we have x over one we do a x square of everything from i that's how we calculate the actual from 1 to n so and we call it x for one and then for the x or 2 right xor 2 we have also starting from zero but this time like i said we are since uh we're only considering the odd index so that we can get the first element so we start from one and then we uh we end up with n minus one right and then the jump is two so we have a x or two uh this dot gonna be the encoded i okay so that's the uh this is the even word the odd index element the total actual of that and then we have the then we can get our first element which is the uh answer.append uh x or answer.append uh x or answer.append uh x or one to and the x or two so after this one we will have like we will have our first element uh calculated then from there onwards we can just uh do the rest right so we start from uh the first one we end up with a minus one and then the answer will be append dot the uh like i said right so it's always going to be the encoded of the encoded current element to a xor of the previously calculated result which is answer dot minus one right and in the end we simply return the answer um yeah i think that's it right so this part again right so this is the uh we have the current encoded one and then we do actual or of the previous one then we'll it will give us the next number okay so let's run the code oh okay we haven't defined the answer yet so the answer will be a array here okay accept it all right cool yeah so i mean time and space complexities i think it's pretty straightforward right so it's only one a single for loop so it's a so it's like a an o of n time complexity right and space all right space i think it's probably all still off and since we're using like the answer to store the uh the final result yeah i think that's it i mean this one i think it's pretty interesting because this one requires you have like some uh tricky observations so that you can use the uh the arduino permutations from one to n then to calculate the uh either the first element or the second element by only picking the uh either the even index or the odd index items and from there right as long as we have one uh known a calculate known numbers we can just use this like a x or b equals x if a and b uh if a and x they're both known then we can just use we can do a like uh x a uh x or a on both sides to calculate to get the value of b and that's exactly what we're doing here um yep pretty interesting uh bit manipulation problem and i hope you guys like this video and thank you for watching it and stay tuned see you guys soon bye
|
Decode XORed Permutation
|
bank-account-summary-ii
|
There is an integer array `perm` that is a permutation of the first `n` positive integers, where `n` is always **odd**.
It was encoded into another integer array `encoded` of length `n - 1`, such that `encoded[i] = perm[i] XOR perm[i + 1]`. For example, if `perm = [1,3,2]`, then `encoded = [2,1]`.
Given the `encoded` array, return _the original array_ `perm`. It is guaranteed that the answer exists and is unique.
**Example 1:**
**Input:** encoded = \[3,1\]
**Output:** \[1,2,3\]
**Explanation:** If perm = \[1,2,3\], then encoded = \[1 XOR 2,2 XOR 3\] = \[3,1\]
**Example 2:**
**Input:** encoded = \[6,5,4,6\]
**Output:** \[2,4,1,5,3\]
**Constraints:**
* `3 <= n < 105`
* `n` is odd.
* `encoded.length == n - 1`
| null |
Database
|
Easy
| null |
70 |
okay hello so today we are looking at question 70 climbing stairs you are given you are climbing its decades and it takes n steps to reach the top each time you can either climb one or two steps so how many distinct ways can you climb to the top right so for this question we will need to get out our drawing pads and draw so for two steps oh for two steps we can do one this is one way and then we can do this way one way we get two ways right so let's just keep a record here for one step no for two steps we do we have why am i freezing okay i'm sorry for two steps we have two ways for one step we have one way and then for three steps how do i erase let's see erase i kind of don't want to clear it i just want to erase it is it possible no okay nevermind let's clear it then so for three steps we have one way two ways and then three ways one step two step we have three ways what about four steps let's check out four steps for four steps oh for four steps we have one way jump two step uh two step two ways and then we can have one two one three ways and then we can have one two one four ways and we can have one two five ways seems like for four steps we can have five ways so it seems like the pattern goes something like that for one step we can have we will have one way two steps will have oops oh my god oh hang on how do i do this okay let's to try that again for once that for one step we have one way for two steps we have two ways for three steps we have three ways and then for four steps remember we said we have five ways it seems like it's following some kind of pattern right so for three it's two plus one for five it's two plus three so by extrapolating this we will get the result for five steps we have eight ways so on and so forth so we basically need to return number of distinct ways you can climb to the top right uh so we just need to create an array and look through the array to keep on calculating at which at each position how many steps you take and then we can when we reach the nth number we'll know how many uh like ways we can climb to the top right yeah okay so let us try it out oh okay let's try out the solution a few things we need to define over here first number one we need to okay so there's a condition where if n is less than two we just return n because if it's one step or two step it's pretty straight forward we just return the it's for one step is just one way two steps it's just two ways uh the tricky part is when it gets from three steps and above right so okay let us try something out we declare an array of zeros of size n and then we assign the first element to one because first step is one way second step is second way and then this one to 2 and then we loop over it for i in range 2 length off i'm always really bad at this uh should it be n or n minus one to n of n we assign my array at index i the value of my array i minus 1 plus my array i minus 2 so when it's it starts from index 2 is next this 1 plus 2 and when it goes to 3 is 2 which is the value 3 plus 2 which equates to 5. in the end what we have to do is just return the value at index and let's try it out oh i can't click it my face is in the way i'm sorry oh okay i think it just and index is out of range for this okay let's print it print things out and see print my array wait what did it print out let's comment out this first and see what happens none wait hang on oh it's just two okay um less than or equal to two so we want something else test for this maybe like a five run code okay so we got oh it looks correct but why is it wrong one two three five eight oh wait hang on zero one two three four oh it should return my array n minus one instead of at and i'm sorry my bad okay let's try it out i tried this oh okay all right let's bring up the confetti yay thank you
|
Climbing Stairs
|
climbing-stairs
|
You are climbing a staircase. It takes `n` steps to reach the top.
Each time you can either climb `1` or `2` steps. In how many distinct ways can you climb to the top?
**Example 1:**
**Input:** n = 2
**Output:** 2
**Explanation:** There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
**Example 2:**
**Input:** n = 3
**Output:** 3
**Explanation:** There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
**Constraints:**
* `1 <= n <= 45`
|
To reach nth step, what could have been your previous steps? (Think about the step sizes)
|
Math,Dynamic Programming,Memoization
|
Easy
|
747,1013,1236
|
1,925 |
in this question we are given a number n and return the number of square triples such that abc is between one and n and a square plus b square equals to c square this question is pretty straightforward let's take a look at the solution initially they define a variable count equals to 0 to keep track of the number of square triples and then they use i to represent a and j to represent b they do two loops in the first loop i is between 1 2 and in the second loop j is between i plus 1 to n so j always comes after i j is always larger than i and then we define a variable square which equals to i squared plus j square and we define a variable k which equals to the square root of square and we cast that number to integer why do we need to cast this k to integer it's because the square root of a number may or may not be an integer it could be you could have digits after the decimal so by casting it to integer we can use k to further verify if k square equals to i squared plus j square in the end we check if k square equals to i square plus j square countable increment by two why is two not one that's because the square triple can be either i j k or j i k keep in mind j always comes after i so j is larger than i these two numbers are uh different so the square triples can be either i j igk or jik by definition in the end we return the count that's pretty much it thank you for watching my video if you like the content please subscribe to my channel thanks
|
Count Square Sum Triples
|
count-nice-pairs-in-an-array
|
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`.
Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`.
**Example 1:**
**Input:** n = 5
**Output:** 2
**Explanation**: The square triples are (3,4,5) and (4,3,5).
**Example 2:**
**Input:** n = 10
**Output:** 4
**Explanation**: The square triples are (3,4,5), (4,3,5), (6,8,10), and (8,6,10).
**Constraints:**
* `1 <= n <= 250`
|
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map. If it is, then add that count to the overall count. Then, increment the frequency of nums[i].
|
Array,Hash Table,Math,Counting
|
Medium
|
2129
|
207 |
and welcome back to the cracking fan youtube channel today we're going to be solving lead code problem 207 course schedule before we get into the question prompt you guys know the drill please subscribe to the channel and like the video it really helps me grow all right there are total of numb courses you have to take labeled from 0 to num courses minus 1. you are given an array prerequisites where prerequisites of i equals a of i b of i which indicates that you must take course b of i before you take course a of i for example the pair 0 1 indicates that in order to take course 0 you have to first take course 1. we want to return true if you can finish all of the courses otherwise we want to return false now let's look at two very basic examples before we talk about how we're actually gonna solve this question so we have uh two courses here and here's the prerequisites array so in order to take course zero we have to take sorry in order to take course one we have to have completed course zero right so the order we would take it is course zero and then course one and we're done cool simple what about this one where in order to take course one we need to have completed course zero but in order to complete course zero we need to complete course one which means that we now have you know a cycle right and obviously this is an infinite cycle and we're never going to get out of this therefore we cannot take this schedule because it just doesn't work right this is an infinite cycle so this is one thing that we have to worry about now you know these examples are quite basic but they don't really tell us how to actually solve it you know we can do this on a piece of paper easily but how do we write an algorithm for this so that's what we're going to talk about now so we read the question prompt and we looked at two basic examples but they weren't quite good for actually showing us how we're going to solve this question so let's look at a little bit more of a complex example so we have four courses here and these are the prerequisites so let's build our kind of course dependency graph so in order to take course one we have to take course zero in order to take course two we have to take course one and in order to take course two we also need to take course zero and in order to take course three we need to take course two so this is what our graph would essentially look like so now what we wanna do is basically we need to figure out whether or not we can you know take all the courses and you know this seems like a simple dfs you know can we get to basically all the courses right the way that we want to solve this question is going to be with something called a topological sort and if you don't know what that is i would highly recommend you pause the video and go watch to char roy's video on topological sort and it will teach you the basics of what you need to know for topological sort this is how i learned it and it's really good video it's about 10 minutes and it'll basically just walk you through it super simple to recap what a topological sort is essentially given a node it is a sorted ordering of basically you know the nodes in the graph such that the children of a node always come before the parent of a node in the ordering now for this question we don't actually care about the ordering so you're probably wondering why are we solving it with a topological sort when it seems like a dfs will work well first of all a topological sort is a dfs second of all there is actually a follow-up question to this follow-up question to this follow-up question to this problem called course schedule 2 where we actually want the order that we can complete the courses in so instead of you having to learn two algorithms one for this problem and one for the follow-up why not just learn topological follow-up why not just learn topological follow-up why not just learn topological sort that you can apply to both of them because the code is literally the same except for in this question we're basically just returning true or false whereas in the other one we're returning the order so in this question we can actually just ignore the order but solve it the same way so if you get either of these questions you know which one to do and it's much easier to learn one algorithm than two of them so essentially what we want to do is the first thing that we want to do is just build our graph right we need to take our adjacency well we need to take this list of lists and we need to build a graph right so build graph right where our graph our key is going to be a course and then the value is going to be a list of all the prerequisites right so pre-rec one dot you know all the pre-rec one dot you know all the pre-rec one dot you know all the prerequisites for that course and we're gonna do the same thing for the rest of the graph so we're gonna build it out then what we're going to do is we just want to traverse starting from you know any point in our graph and we just want to basically explore all of the children of that graph and see how many courses we can visit right we're essentially just gonna keep track of all the courses that we visited um you know from this course right so from a course we're gonna check that we can actually get to all the prerequisites from there and we're just going to try to backtrack and we're going to keep track of all the visited um you know courses that we've done right and at the end what we want to do is we essentially just want to make sure that our visited set equals the amount of courses that is here if we are able to visit every single course then that means that we don't have any issues with our graph and there's no kind of there's no cycles that's one thing that we have to watch out for if you remember from the original example cycles will screw us up and then we just need to be able to visit every single course like it could be the case that a course just isn't visible and therefore you can't take it so what we need to do is we just need to make sure that we can you know visit all the courses so we just want to check that our dfs can actually check can actually just touch every single node so that's essentially what we're going to do but we're going to use it do it in a topological sort manner just because we can apply the code um to course schedule two and another question called alien dictionary which can actually be solved in the exact same way so three questions for one algorithm that's basically the same code sounds like a perfect combination to me so hopefully this part wasn't too confusing what we want to do now is actually go to the code editor and i'll walk you through it line by line i understand that this part can be a little bit confusing drawing it out is like a huge mess instead let's actually just walk through the code line by line and it should be a lot clearer for you to just listen and watch me code and as opposed to me trying to draw this out and it's just going to be horrendous so let's go to the code editor that's enough blabbing we are back in the code editor let's type this up the first thing we want to check is actually that prerequisites is not empty if it's empty that means that there's no prerequisites therefore we don't have to worry about not being able to take courses so we can just return true off the bat so we're going to say if not pre-requisites then we can simply return pre-requisites then we can simply return pre-requisites then we can simply return true all right excellent now we need to build our graph and remember that the key of our graph is going to be a course and the values for that key are going to be all of the prerequisites that we need to take before actually being able to enroll in the course so we're going to say self.graph is going to be say self.graph is going to be say self.graph is going to be collections.defaultdict and it's going to be a list now what we want to do is we're going to actually build we want to build the graph so we're going to say four course uh prereq in prerequisites we want to essentially say self.graph we want to essentially say self.graph we want to essentially say self.graph for a given course we want to append the pre-wreck to it right simple enough pre-wreck to it right simple enough pre-wreck to it right simple enough now what we need to do is we typically do a three set approach for solving a topological sort problem so there's three sets and let's define them and talk about each one so the white set and we're going to initialize it to all of the keys of our graph so self.graph.keys self.graph.keys self.graph.keys we're going to have a gray set which is going to be empty and we're going to have a black set which is also going to be empty now let's talk about what each one of these sets represents so the white set represents all of the values that we still need to process so basically you can think of this as a kind of like our work cue this is the you know number of nodes that we need to process in our graph the gray set is going to be all of the nodes that we're currently processing remember that in this step for search we get to a node and then we want to fully explore its children now what happens when somewhere along the dependency chain of its children you actually end up at the node that you started your search from that would indicate a cycle and this is what the gray set aims to prevent when we're processing a node we're going to put it in the gray set and if somehow down the line in the dfs we actually end up at that node again then that means that we have a cycle and therefore we simply exit out because this problem is not solvable we have a cycle the black set is going to represent all of the nodes that we have fully visited and when we say fully visited we mean that we have visited it and all of its children fully so if we ever get back to a node that's currently in the black set we can simply just you know stop the search there and move on to the next value because it's already been fully explored there's no reason to do it twice so those are your three sets now we need to process all of the nodes in the white set excuse me so let's now process the white set so we're going to say while white so while we have something in the white set to process we want to get a course out of it so we're going to say course is going to equal to white dot pop so we're going to pop some random course from the white set and remember that ordering doesn't matter here all we need to do is just make sure that we can actually visit all of our courses so we're going to pop a course from the white set and we're going to go into our dfs function so we're going to say if not self.dfs and to this dfs function we're self.dfs and to this dfs function we're self.dfs and to this dfs function we're going to pass the course we're going to pass the gray set and we're going to pass the black set now what this function dfs is going to return is true if basically we can visit all of the children successfully and false if there's a cycle so if this function ever returns false that means that we have a cycle and we can simply stop there this problem is not solvable so if our dfs function returns false obviously not false is going to be true so this is going to evaluate so we simply return false here right otherwise we simply continue and if we're able to process the entirety of the white set which means that we're able to basically reach all of the nodes in our dependency graph that means that we're able to take every single course and we're good to go we can simply return true now what we want to do is actually define the dfs function so let's define it so we're going to say def dfs we're going to pass self we're going to pass the course that we're processing the gray set and the black set the first thing that we want to do is we are now visiting course so we want to add it to the gray set so we're going to say gray dot add course right because that indicates that we're processing it if we now end up back at this course then that means that we have a cycle and we can return false so remember that you know we want to visit all of its children now so you know for a course we want to start visiting its prerequisites we want to make sure that we can do that so we're going to say for uh prereq in so remember self.graph in so remember self.graph in so remember self.graph for that course we're going to say if that prereq is sorry is in the black set then we can simply continue because remember the black set represents nodes that we have visited uh entirely which means that we visited it and all of its children so if we've already visited that node um in its entirely in its entirety sorry then we do not need to visit it again so we can simply just continue to the next uh node in our kind of list here for that course now we also want to check whether or not the prerequisite is in the gray set so we're going to say if prereq in gray then we're going to be returning false here and the reason for that is remember the gray set represents courses that we're currently visiting so if we're currently already visiting this prereq as part of our dfs and we somehow end up at it again that indicates a cycle therefore we return false because obviously cycles mean that we cannot solve this problem if both of those conditions don't fire then what we want to do is we want to go on to just performing the dfs so we're going to say if not self.dfs going to say if not self.dfs going to say if not self.dfs and we're going to pass in the prereq this time we're going to pass in the gray set and the black set and remember this function will return false if there's a cycle and true if there's no cycle so if we get to this point here where there is a cycle we want to return false all right the last thing we need to do is now that we have fully processed this course by going through the dfs here for all of its prerequisites the last two things we need to do is actually remove the course from the gray set because it's now been fully processed so we're going to say gray dot remove course and we're also going to say black dot add course because now it has been processed and all of its children have been fully processed and since there was no uh cycle detected we can simply return true here and that's gonna be it so let's just run this make sure we didn't make any typos anywhere and let's submit it so whoops let me just open this up and as we can see it is successful apologies for the cut out there i accidentally when i first recorded the code i said the wrong time and space complexity so i just cut that part out and i'm going to redo it so the time and space complexity here uh is going to be your standard topological sort time space complexity so the time here is going to be v plus e so what does v plus e mean so v is equal to the number of vertexes in the graph or the number of nodes and e equals to the number of edges in the graph or uh connections between nodes right obviously you know when we're traversing it the amount of time it's going to take is you know the number of nodes uh with the number of edges right if we have a really complex graph that's going to take longer so your time complexity for any topological sort problem is always big o of v plus e and your space complexity for any sort of topological sort problem is going to be big o of v so this um essentially you're just storing in your graph the number of vertexes you have uh so obviously the graph is going to depend on you know the number of courses you have so that is going to be your time and space complexity you can basically memorize this because it's going to be the same for any topological sort algorithm and remember that we chose to do this problem with topological sort because the follow-up question course schedule 2 the follow-up question course schedule 2 the follow-up question course schedule 2 will actually want some sort of ordering of the courses so like i said why learn two algorithms when you can just learn one and they both work for this question and they work for other questions as well i believe alien dictionary can be solved with the exact same code so you get three problems for the price of one i think that's pretty good value for your time so that is going to be how you solve this question probably going to see course schedule 2 in the next coming days just because the code is literally the same so it's really easy for me to just make both these videos anyway i'm gonna stop blabbing here i hope you enjoyed the video if you did please leave a like and a comment it really helps me with the youtube algorithm if you want to see more content like this please subscribe to the channel otherwise thank you so much for watching have a great rest of your day bye
|
Course Schedule
|
course-schedule
|
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you **must** take course `bi` first if you want to take course `ai`.
* For example, the pair `[0, 1]`, indicates that to take course `0` you have to first take course `1`.
Return `true` if you can finish all courses. Otherwise, return `false`.
**Example 1:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\]\]
**Output:** true
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
**Example 2:**
**Input:** numCourses = 2, prerequisites = \[\[1,0\],\[0,1\]\]
**Output:** false
**Explanation:** There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
**Constraints:**
* `1 <= numCourses <= 2000`
* `0 <= prerequisites.length <= 5000`
* `prerequisites[i].length == 2`
* `0 <= ai, bi < numCourses`
* All the pairs prerequisites\[i\] are **unique**.
|
This problem is equivalent to finding if a cycle exists in a directed graph. If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses. Topological Sort via DFS - A great video tutorial (21 minutes) on Coursera explaining the basic concepts of Topological Sort. Topological sort could also be done via BFS.
|
Depth-First Search,Breadth-First Search,Graph,Topological Sort
|
Medium
|
210,261,310,630
|
382 |
hey everybody this is larry this is day seven of the league code daily challenge hit the like button to subscribe and join me on discord let me know what you think about today's bomb link list random note give me a single link list return a random note row from the linked list has the same probability okay so okay so i mean the easy way to do this is just by um this is annoying though maybe um because it is a linked list um and i'm not only looking to follow up so i think the way that i would probably do it in a real more real setting is to kind of cache everything and then just you know do it right because um assuming that we're going to make multiple calls to get random right because um then now we reduced everything to one after pre-processing and of end space i after pre-processing and of end space i after pre-processing and of end space i think that is technically the ideal situation um but looking at the follow-ups um if um but looking at the follow-ups um if um but looking at the follow-ups um if the link is extremely large and the link is unknown to you i think they won reservoir assembling um but it's still a little bit awkward because every chord that is random is going to be linear so that's going to be a little bit awkward um even though i guess they're not that many nodes but it's still a little bit weird because i read it with this vo of one um and with versatile assembling that's a little different could you solve it well definitely without the extra space um that's gonna be reservoir uh assembling but because we're giving the list as uh whole to begin with i would just put everything into uh i don't know array um either an array or um uh i don't know wait and then just like take a random element from an array which is over one uh because it is random assessed and or you know you have just some kind of like distribution table type thing almost similar to a loot table if you know writing a game or something like that i just realized my camera's a little low so just cutting off my mouth but uh but yeah so there's definitely a lot of things you can do here really depends on what you're optimizing for and how you really use it this api is a little bit awkward for the follow-up because i awkward for the follow-up because i awkward for the follow-up because i don't think they really um really makes sense per se um at least for vegetable sampling i might kind of think about it in a different way um because in that case you're training you're always just trading space for time right so it depends on whether you need to optimize for time or space and of course during an interview in an actual interview you could talk about any of these um of uh during lead code you know like you have no uh you could talk to the website but it probably won't help that much so yeah um okay so that's what basically what i'm going to do um yeah i'm going to have a an array let's just call it elements and then you know current is going to head while current is not none and current is you go oops current is equal to current.next current is equal to current.next current is equal to current.next and then sub.elements.append current.well first sub.elements.append current.well first sub.elements.append current.well first type value right up and then that's pretty much it maybe we could do something like sub dot and as you go to length of sub.n which i and as you go to length of sub.n which i and as you go to length of sub.n which i don't have to put in the back i already finished typing it so um yeah something like that maybe and then random we just get a random number from one to n which is a thing in any language i forget it's like random that random or something right or random something like that uh let me look it up real quick so i actually don't i it's something that doesn't come up that often that we uh need it so uh yeah and of course you could also see it or something like that but uh yeah uh when end is so good oh choice random that choice i mean i assume you shouldn't do random that choice but i am curious whether random that choice is actually over one or bad but i actually don't know in any case though rent range i guess okay fine we're in range to sub.n we're in range to sub.n we're in range to sub.n uh and then this is the index and then we just return self.elements of index we just return self.elements of index we just return self.elements of index right um and that should be good i imagine um yeah let's give a summit i'm curious what i did last time but yeah much faster this time though what would i do last time what did i do last time i did use russell assembling last time um so definitely if i have a video out definitely check that um yeah i mean it's a little bit awkward but i can go by the way but um as you can see it really depends on what you're doing and in this case the extra space is worth a lot of time like i said it depends on where you're optimizing with time or space so there's no uh overly wrong answer per se but you just have to be really uh like you have to know what you're doing right like if you're optimizing for space that's fine if you're optimizing the time that's also fine um and these are known properties that's also fine but you have to know you know what you're doing um yeah i probably have this video out as well so definitely check that out um you know maybe i'll put it in the comments below um but that's all i have for this one let me know what you think hope y'all having a great week stay good stay healthy to good mental health i'll see you later bye
|
Linked List Random Node
|
linked-list-random-node
|
Given a singly linked list, return a random node's value from the linked list. Each node must have the **same probability** of being chosen.
Implement the `Solution` class:
* `Solution(ListNode head)` Initializes the object with the head of the singly-linked list `head`.
* `int getRandom()` Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.
**Example 1:**
**Input**
\[ "Solution ", "getRandom ", "getRandom ", "getRandom ", "getRandom ", "getRandom "\]
\[\[\[1, 2, 3\]\], \[\], \[\], \[\], \[\], \[\]\]
**Output**
\[null, 1, 3, 2, 2, 3\]
**Explanation**
Solution solution = new Solution(\[1, 2, 3\]);
solution.getRandom(); // return 1
solution.getRandom(); // return 3
solution.getRandom(); // return 2
solution.getRandom(); // return 2
solution.getRandom(); // return 3
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
**Constraints:**
* The number of nodes in the linked list will be in the range `[1, 104]`.
* `-104 <= Node.val <= 104`
* At most `104` calls will be made to `getRandom`.
**Follow up:**
* What if the linked list is extremely large and its length is unknown to you?
* Could you solve this efficiently without using extra space?
| null |
Linked List,Math,Reservoir Sampling,Randomized
|
Medium
|
398
|
101 |
hi guys welcome to one more video in this one we'll take a look at symmetric tree problem difficulty level is easy so I have few trees drawn over here so what is symmetric tree so symmetric tree is a binary tree where left no hold on is this left for you guys no this is left for you guys so left tree of the left child tree should be equal to right child rewrite so what does that mean so let's say if this is our tree if we draw like a line in the middle this left tree should be a replica of right tree right so let's say if you draw this tree on a paper and if you fold it in the middle and if you fold the paper they should exactly overlap each other so that's your symmetric tree like it's a mirror image of each other so this is a symmetric tree and if we draw line who we here then this is also symmetric tree and if we draw a line over here then this is not a symmetric tree because this node should be here like just like this one right if this is symmetric tree then this is not a symmetric tree so there you go guys a simple problem and even the solution is simple to it and code is really short so hopefully this would be a short video we'll just cruise through it okay so we'll take this tree to run our algorithm on so for any tree like any binary tree what do we have root node right so the only way to start is like from root load go to the left child and go to right child right so let's do that same over here so from this we go to left child and we go to right child right and whether it's a symmetric tree or not what do we do first we check whether they are null or not like if either of them is null then obviously it's not symmetric and then second we check the value if value of both the nodes is not same then obviously it's not symmetric right so in this case they both match so we say that okay till this level it's symmetric right let's move on so we have these two nodes right now if you have to compare this level what we do so we do left nodes left child and right nodes right child right these two and we compare the same things whether are the nodes null are the value same and all that right since they both match we are good now look at severe still here right so what else can we do we have to compare these two nodes right so left child right node and right child's left node right we have to compare these two well compare whether they are null or not compare the values and all that so what we are doing left child left node right choice right node and left child is right node right choice left node we are doing these two comparisons right let's see if we if these comparisons remain true when we go to the next level right so let's say we are here right left this is our left node and this is our right node now what we need left child left node right choice right node so left child left node right child right node it matches right let's look at the second one right left choice right node right child's left node left child's right node and right child left node matches right let's do one more time right let's see if it continued so this is our left node this is our right node let's say so left child left nodes left child right node right matches right left nodes right child right nodes left child matches so there guys it's a symmetric tree and these are the two rules we have to do so let's look at our recursive function and let's make sure that everything is same so we have is same method which accepts two node left node and right node and what do we do whether we check whether either of them is null so if either of them is null then we return left equal to right so if either of them is null then we return false if both of them are null then we return true right let's say if you are comparing these two so if both the nodes are they return true and if the values don't match we return false and what do we do next we recursively call the same method for left nodes left child right nodes right child and left nodes right child and right nodes left child whatever we did here exactly same thing we're just calling recursively so as soon as any method says that it doesn't match it returns false all the recursive methods will start returning false and then we'll say return false if all the methods finish and they return true then it eventually bubble up and that tree would be true symmetric so there you go guys pretty straightforward let's just go to our visual studio code let's run the code and make sure that this runs this is our vs cord we have our main method where we are constructing this tree I didn't construct the tree as large as what we did on the whiteboard I was just feeling lazy you guys can create the whole tree as big as you want the link to the code would be there in the description so feel free to access it c-sharp java both versions are there so c-sharp java both versions are there so c-sharp java both versions are there so yeah so we are constructing the tree and then we're calling is symmetric and we are passing the root node and in this is symmetric what we do is we pass the left and right child and what we do we compare those two conditions if they both pass then what we do we call is symmetric tree is same recursively and what we pass left child left and right choice right and then left child is right and then right nodes left child till I screw up left-right again you till I screw up left-right again you till I screw up left-right again you guys know what I mean right yeah just we call that recursively and if all the methods return true then we said it's symmetric if any of them say it's false then it's not symmetric right so let's run the code and make sure that whatever I said is true and I'm not lying right dotnet run and this should be symmetric tree right so there you go it's free symmetric yes true so that's it guys if you liked the video give me thumbs up and let me know your suggestion feedback in the comment box and subscribe to channel for more videos see you in next one
|
Symmetric Tree
|
symmetric-tree
|
Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center).
**Example 1:**
**Input:** root = \[1,2,2,3,4,4,3\]
**Output:** true
**Example 2:**
**Input:** root = \[1,2,2,null,3,null,3\]
**Output:** false
**Constraints:**
* The number of nodes in the tree is in the range `[1, 1000]`.
* `-100 <= Node.val <= 100`
**Follow up:** Could you solve it both recursively and iteratively?
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
| null |
525 |
or let's talk about catalyst coding question that contiguous array so we have a binary array with number 0 and 1 and we need to find a maximal length of a contiguous sub array with equal number of 0 and 1 so this is a very similar to question a few question I'd already made videos about you know the sub array is basically a window in between the in India in the whole array and to get the information of the sub array we can actually do a subtraction let's say that we have a window so let's stick with the question that we need to find a sub array with the equal number of zeros and ones so what that means is if we run a contrary on this sub array from I to J which gives us some kind of table we have a number of 0 and B number of ones we just want to test one a or the B so instead of calculating this saying over and over again we can actually just calculate this by a difference so this I to J counter it's essentially equal to a counter from 0 to J minus the counter from 0 to I and if we just do one pass through the array and storing all this contours it will be a linear time operation then we can do pairwise comparison between all the pairs of I J's so the whole time complexity to do this a to equal to B checking's and updating the maximal has to be you know J minus I would be this will be a squared time algorithm but what's not so efficient here is that we let's look up to what this difference is really telling us right so if we have the first contour to be this frequency and the second Condor is we have see number of a and Dean above one the difference is basically another frequency count where the number four zero is a minus C and the number one is B minus D we would us with this equal to B as what desired for here we want one a minus C to be equal to B minus D which is equivalent to C say that we want a minus B equal to C minus D which is the frequency difference between the number of one and zeros and number zero and in the window in there in the window so each of those you know a minus B or C minus T each of these is it's a difference in number of a zero and number ones in that particular window so given this is the most important thing so instead of storing the actual counters we can just sort the CI to be the to be number of zero minus number one then you wouldn't necessarily reduce the time complexity for the algorithm but you would be just be a lot efficient for us to store information and then the most important thing to realize is that instead of starting location to difference mapping we can store the difference to first the location map so that when we go out and scanning some of the array we can populate this and then we can check whether we have seen such a difference in between before if we have seen such a difference than the location between my current location and a lot the first time I see such a difference the sub-array sub-array sub-array defined by that location difference but those two locations is gonna be a sub array that satisfy this condition so by doing this reverse of the information we store we can get to a linear Tyler reason so let's quickly cut this up that's an integer two integer mapping from the difference to location and its initially to be 0 to minus 1 so when we have no elements we have 0 1 so the difference is there as well minus 1 is just you know when we look up the location I a location 0 when we are scanning through this the difference is J minus I so when we have the location 0 with minus 0 minus negative 0 we can get a lens of one from doing that algebra so we have a div to be 0 in the beginning and Maxim lens to be 0 as well and it's just a linear path we can come to the difference between zero and one or we can count the difference between one and zero it's the same thing if we have seen such a death then what we can do sorry it should be a function call then the we should update the maximal ends that's potentially possible otherwise we'll just remember this is the first location we see such a difference in the end we just return the lots of events so this algorithm it's a linear time as we can see here we just do one pass and this hash map will be linear as well the worst case is that we just keep seeing zero so the diff is just keep increment incrementing every time and the size is linear in the entire cart if we ever see one or decrease so that we will see repetitions the hash mouthful size will be good on so that the worst case is exactly the same number as the number of arrays that's the worst case let's quickly check if we have problems yeah it looks fine to me let's submit let's see yeah it's working so that's the question really coding challenge question today
|
Contiguous Array
|
contiguous-array
|
Given a binary array `nums`, return _the maximum length of a contiguous subarray with an equal number of_ `0` _and_ `1`.
**Example 1:**
**Input:** nums = \[0,1\]
**Output:** 2
**Explanation:** \[0, 1\] is the longest contiguous subarray with an equal number of 0 and 1.
**Example 2:**
**Input:** nums = \[0,1,0\]
**Output:** 2
**Explanation:** \[0, 1\] (or \[1, 0\]) is a longest contiguous subarray with equal number of 0 and 1.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
| null |
Array,Hash Table,Prefix Sum
|
Medium
|
325
|
95 |
Hello friends today I'm going to solve political problem number 95 unique binary search tree too in this problem we are given an integer n we need to return all the structurally unique binary search trees which can be formed using the values starting from 1 to n inclusive okay and we return the answer it could be in any order now let's see before that let's see what's a binary search tree is basically a tree structure where any node the children towards its left node are less than the value of the given node and children towards the right art greater than the value of the given node for example in this case we have the node two and since 1 is less than 2 so it is towards the left and since 3 is greater than 2 it is towards the right side of this node same in this example since 1 is less than 2 and 3 that is 3 and 2 are greater so it is towards the right hand side of this tree that is it's the it's forming a right sub tree of node one and here we have node 3 and since we know 2 is less than 3 so 2 goes towards the left side of three so that's what binary resource tree is now what we need to form is a structurally unique binary search tree starting from 1 to n so as you can see for n equals 3 we can form these five different structures okay so basically how are we going to form these structures let's see how can we do that so let's take an example n equals to 4 okay now for n equals to 4 we can have nodes starting from value 1 and values two three four right so we have these three these four values now we can choose any one of these as our node root node so one could be one of the root node we can have two as one of the root nodes okay three as another root note and we can also have 4 as our next root node now starting from 1 if we are taking 1 as the root node now towards the left should be all the values less than one right and towards the right should be all the values greater than one and as we have these values these numbers we know that any value towards left of one is basically it's zero and we do not have any zero node so we do not have any values towards it's left so what are we going to do is we are just going to append a null value so null means there is no node at also we are actually not going to create any branch towards the left now what about towards the right will be all of these three nodes okay so these three will go towards the right 2 3 and 4 will go towards the right now we need to make a choice between which of these three is going to be the immediate child of one right so we have three possibilities between two three and four right for one we have three possibilities between two three and four so let's suppose we choose two so if we chose two so now for two we have to find its left and right children as well okay so for left since we have already taken one as the node so there is no more node no more values to what the left of two that can go towards the left right left child so towards the right we have three and four so here we have two possibilities we can have three and we can have four right we had two possibilities three and four okay so let's just choose three four here so if we choose three then what we found here is now for three we all we do not have anything towards the right because 2 is already taken as its parent node and towards its left I mean towards its left we do not have anything towards its right we have no four so basically four will go towards right and four is the only value so 4 becomes the note um for right node for 3 and now for 4 we do not have any left and any right value so those will be not now that we have formed this node now what we do is we backtrack towards its parent node right and as you saw earlier we had two possibilities right between three and four we chose three here we had three possibilities between two three and four and similarly here we had four possibilities between one two three and four so here we chose node one for two three four we have different nodes uh so since we chose 3 as the possibility now what if we choose one four as the possibility so in that case we'll have a tree something like this okay so we'll still have one we'll have two and instead of three now we'll have four right so we have a value 4 here now as we choose the value 4 over here we know that 3 is the value remaining and it can go towards the right so 3 is the only node that goes towards the right I mean towards the left and towards the right there is no value so it will be null okay so basically in this way we now form the two possibilities of these nodes so these are the two possibilities and basically what are we doing we are appending these two possibilities towards our parent node that is two so what are we doing is we will be recursively performing these problems so as I mean solving these problems so what we start from is one and then we break down that problem we started as one and then we broke down a problem into sub problem so now uh the sub problem becomes two three four basically we had one two three four possibilities now we chose one node one value as the node now are possibly two reduced in its next iteration over here recursive call and same we have now only two possibilities between these two we choose one of them as no as a node and the next time uh we chose another as a node and while we chose these two different values we found a sub tree and these two sub trees are appended to its parent node so basically we will append and these its children to its parent node and we'll keep on doing so on until we reach the node one okay so basically here now if we backtrack from here as well to one so we chose two over here right now what if we chose three so if we choose 3 then towards the right we will have node two and towards the left we can have only node 4 right so this is only one possibility so for one we'll have like three possibilities like this and there will be more possibilities like what if we chose the value 4 so if it shows the value 4 from 1 then from 4 2 and 3 will both be the right at towards the left so we have to possibly it is between two and three if it shows two then three will be towards its right because three is greater right and if it shows three then we'll have one and then full and if you choose three will be towards the left as 3 is less than four and two will also be towards the left of three is two is less than three so basically for one root Node 1 will have these many possibilities so that are five different possibilities right so these five possibilities we will append to root one and then this whole solution will go okay these all of these five Solutions will be appended to our result and similarly we are going to do the same with two three four and then finally append the nodes the three to our result okay so this is how we are actually going to approach this solution now how do we solve it in our code right what algorithm do we follow so for that we are going to perform a recursive call so let me just clear this out okay so let's suppose that we are taking 2 as a node then if we take 2 as our root note then what are the values that came to both that could be two words right well only one right and what are the values that could go towards the left 3 and 4. so what are you doing what we'll do is basically we'll choose the range that can be go towards left and towards the right so here we are going to create a function a helper function which will take the starting and the ending values to what's uh both the sides so here starting value is one ending value is also one because we only have one value right and towards its right its starting value is 3 ending value is four so now we go towards the right towards the left and we have one now in between one we can only have root both one right since we only have one value so we add the root Node 1 as our result now for the right hand side we can choose between these two right so let's suppose we choose one we are actually performing a four operation here so we choose the first one three and we add three to this now we need to find the left and right of this one so the left will be equals to um three and then uh it should be three right but what are we going to do is we are going to pass on to so what's happening is from this root note the end value will Divide Subtract by 1 and that's one over here now if we were to find the left of this one also so we will call a helper function the start will be the start value which is 1 and the end will be the start minus one why start minus 1 because as you could see if we are choosing this as our root node and this is our start this is our end so start will always be the start and now towards its right what is the end here one is the end right one is the start and one is the end and what about towards its right okay this is the left side whatever towards its right well now this is the start right so start e is equals to two plus one so that's why we have here three towards the right and similarly here and is equals to 3 minus 1 that is true since 2 is less than 3 we found n to be less than 3 so it's going to return on null value so we will won't have any more towards the left same in this case since 0 is less than one we won't have any values towards it's left we're about right so for the right also we take start as node plus one so that will be equals to 2 and end will be is equals to n so which is 1 so here also end is less than start so that will return on null and we will have null towards this left and right same towards this left and what about right towards the right now we have start plus 1 so 3 plus 1 is equals to 4 and then end is the end value which is 4 so now we only have one node we choose that as our node and then we try to go towards left right and basically it happens the same thing and we return or no so this is how we form a node here we form the node right so while every time we are forming a node which we backtrack the possibilities a list of possibilities that we uh that could be uh it's subtree towards its left and towards its right so here one of the possibilities was this one the other possibility is if we choose 4 as the node then 3 will be towards the right so this is the next possibility so these two possibilities we will be returning to this node so that we can append it as a right child right once one at one possibility will have this next time we'll have this one okay so basically this is how we're going to solve it now let's dive into our code and see how we can code it and I'll explain it along the way okay so let us first um uh what do we need okay let us first create our helper function equals to function and we are passing the start okay as trt start and end right start and end as you could see we have a function we are passing start and end and when we first call our helper function we are passing the value starting from one and our end is the n right it should be inclusive values n and starting from one now while we're passing the helper function what we did here is for the base case when we saw that one comma 0 right so when end was less than the start we returned all right so that's what we are going to do if start is greater than end and we return an array of null so now next we are going to iterate for each of the values because once we want to make one as the root node next we want to make two as a root node a third time we make want to make three and a fourth we want to make four as a root node so we are starting from our stat is one end is four so we are iterating over each of these values right so let the fourth Loop let I equals to start I is less than equals to end because we want to include the end value and I plus right and now while we are iterating what are we doing we choose one of the notes and now we find it's left and we find it's right and while we're finding its left and right node we are recursively performing that operation right and so while we are recursively performing that operation we have multiple of multiple possibilities so all of these possibilities will be storing in a array okay so let us also create a result array where we'll be storing all of our possibilities and now let left is equals to win want to find the left trees first left sub tree so Helper and then we pass the start which will always be the start and the end value will be our root note that we chose uh minus 1 right similarly uh right will be helpful I plus 1 and end okay now that we have our left and right trees uh now what we want to do is we want to append this left to the left of our note right and since left this is an array that we are returning over here so we want to append each of those right so what if we will be doing that one at a time so for l off left and similarly we will also be appending each of the right okay so now um we will be creating a note at this value right with this value so let know the calls to new tree nodes so we are using this definition to create our node and here we are going to pass the value as I now we need the left right so left will be equals to L right l so it's similar with the right we will be choosing R and this gives us our root node left and right and then uh once we form our node we are now going to append these to our results so result dot uh push to our result note and this result will be uh returning at the end so to read as your LT result so what happens is uh when we form a node let's suppose we chose the value okay let's take this example we chose the value 2 right so I is equals to 2 that would mean this is equals to uh start will be 1 and end will be equals to 1 only so one so now we form a recursive call and since this function is this value want this condition won't be satisfied and now our result is empty and then now we start from one and that one and now we again perform a recursive call now start this one and becomes equals to zero so now here since start is one end is zero this condition is true so we'll turn a null all right so now left is a null area Okay so null array null area for I equals to 1 right for I equals one okay now for I calls two one what are we going to form right so right will be I plus 1 which is equals to two and since n was one so end is less than start and that will also return on null uh array so now that we have an area of nulls so it will take the null value and then also the right will be null and we form a new node with the value equals to 1 and it's left will be null right will be equals to null as you can see it's left and right or not and then push that to our result and now we do not have any more elements in the right either we do not have in the left as well because we only had one value that was null and then what we do is we finally uh also do not have any values start was one and was also one so we do not have any values for I as well so we now return our result which is node one and we are returning our result to the left of two so what happens is now our value return is one okay node returned is one and towards the right we do the same similar three and thing and we'll have three right and we iterate over this of both of these values so we do it over one reiterate over array this array which only has one value that is three and we form a new node where I is equals to 2 so we form a new node with two and towards its left is one towards its right is three and we push that to our result and then we return that result to its calling function and so on so now let's try to run our code and see if this works okay we found an error what was that okay we are actually not returning this value so return awesome let's submit this great now I'm talking about time complexity as you could see um we are creating a for Loop starting from so basically start and end so we will have one to two and right uh and uh each time what are we doing from one to n we are again um iterate I mean recursively calling over this value and again towards these left hand side and right hand side so we form the node um yeah so time complexes complexity should be off and in this case and the space complexity is equals to also off and if we take into consideration the stack space that is occupied by these recursive helper function calls so I hope you liked my solution let me know in the comments down below thank you so much
|
Unique Binary Search Trees II
|
unique-binary-search-trees-ii
|
Given an integer `n`, return _all the structurally unique **BST'**s (binary search trees), which has exactly_ `n` _nodes of unique values from_ `1` _to_ `n`. Return the answer in **any order**.
**Example 1:**
**Input:** n = 3
**Output:** \[\[1,null,2,null,3\],\[1,null,3,2\],\[2,1,3\],\[3,1,null,null,2\],\[3,2,null,1\]\]
**Example 2:**
**Input:** n = 1
**Output:** \[\[1\]\]
**Constraints:**
* `1 <= n <= 8`
| null |
Dynamic Programming,Backtracking,Tree,Binary Search Tree,Binary Tree
|
Medium
|
96,241
|
395 |
good evening, Fedor, less coffee, we continue to solve problems that come up during interviews, let’s come up during interviews, let’s come up during interviews, let’s now see that everything here is translated almost normally and, in fact, the task today 395 of the site is easy with a longhi tray with about string height sheets boil corrector given line dump frame . and we need to given line dump frame . and we need to given line dump frame . and we need to find such a substring of the original string such that every character that is there is found in this string, which character is in this string, it occurs at least once, so accordingly, in the example here we have three letters and then 2 letters b if we need three then the whole string doesn’t need three then the whole string doesn’t need three then the whole string doesn’t suit us the whole string doesn’t suit us the whole string doesn’t suit us the whole string doesn’t suit us because in this case we will have b only twice and accordingly the only way to get here, well in fact the only way to get the answer is a substring of three letters a and there we only have letters and each one has a quantity and at least three symbols, and that’s probably all of it and that’s probably all of it and that’s probably all of it here, respectively, in quality in the second case we have this line and we have c here less than twice, so the entire string does not suit us and, accordingly, we need to discard c to get a string like this from a b so that each letter appears at least 2 times here, but b will now be three times, this is acceptable, so what? such a problem, now let's solve it, so let's start with a young approach, a naive approach, we take all the substrings in general and find out, I don’t know, but it turns out that we find out, I don’t know, but it turns out that we find out, I don’t know, but it turns out that we take all the substrings and find out for each how many of which character in this line is what we then get, the length squared, well, I don’t know, here we add I don’t know, here we add I don’t know, here we add the size of lfo Italy, add if we can use a hash table there it’s arthritis map, then in hash table there it’s arthritis map, then in hash table there it’s arthritis map, then in principle the size of the alphabet won’t even principle the size of the alphabet won’t even principle the size of the alphabet won’t even interfere with us, that is, the size they don’t affect the alphabet if the array is sized or so the size influences and if we count the array by indexing by letters and counting in this array how many of which letters are found then for us for the array it will be the length multiplied by the length plus the size of the alphabet this is what it will be for the array Moreover, this is not necessarily worse than just Elena squared because the constant one or treat me up is very large compared to the array, it can be ten times larger and, accordingly, what we got here seems to be some kind of additional addition in fact, this is compensated for, well, again, this is all about the big one, but this is an addition, it is compensated for by the fact that the constant has decreased greatly, this is our naive approach and we have nothing better, well, specifically here, we probably can’t get better, although let’s can’t get better, although let’s can’t get better, although let’s see but I understood everything, I’m see but I understood everything, I’m see but I understood everything, I’m wrong about the not entirely different approach, because in a completely naive approach, we first take all the substrings, which we have squared, respectively, we also go through this line by line and go through this line by line. we find out for it we find out how many characters how many of which character are in this building then we have a cube here, that is, in general, all the substrings we get a square, we still have to go through each one, but as a result we get a cube if we are talking about an ordered me up to we again have a flashlight we have a map we get a strap for an array you will become a log squared multiplied by the length plus the alphabet so the second option let's see if it's possible to do something here without better of course you can let's do it well that is when we allow let's see what can be improved in the previous approach, let's say we have we look at strings of length 1, then we'll look separately at juices of length 2, separately at buildings of length three, and so on, but if all these substrings, let's say, start from the same Seoul, then we 'll do the same thing. there 'll do the same thing. there 'll do the same thing. there we will start with this symbol and just go a different number of different numbers of symbols to take into account how many we have there, how many symbols from komah we will have here, how many of each symbol we will have to count and it turns out that we go through the same place many times accordingly, of course, we can simply iterate over the beginning of the beginning from where we go from the beginning where it begins along the lines and further and we go from this place and we track how many characters there are we go from this place well, let's go from this place we sort through how many we go through the place of the end of the substring and in one unit we can recalculate the number and quantity of each Seoul in this line in comparison with the previous one in comparison with the one below the line 1 less spa symbol the line is shorter by one character and in one unit find out whether it is true or not what do we have here, that it fits, that this line fits, is it true that in this line all the characters are found, they are no less than 1, all this can be done in one and so we get here, again, from pure years squared, that is we sort through the position of the beginning of the position of the beginning and accordingly from here we sort through the ends line by line and accordingly since we have from one to this to such a transition, then we get the length squared, that’s actually the we get the length squared, that’s actually the we get the length squared, that’s actually the whole third path and accordingly let’s try to come up with something at all something as efficient as possible, and that is, based on, well, not just based on what we can sort through here, and based on what the answer should generally look like, well, let’s call the answer should generally look like, well, let’s call the answer should generally look like, well, let’s call it efficient under the question mark algorithms because well, what if we will get in the worst case n squared what will we do with it then means that we now know means well, in general we need the longest substring is the string itself that is, ideally we should get the line itself, that is, what can we do? For the line itself, we can calculate the histogram of how many characters there are in it and, accordingly, if and if we have the required number of characters, that is, if all are greater than or equal to there and the answer was found here otherwise, but otherwise it turns out differently for us, what conclusions can we draw, let's talk about conclusions, the conclusion turns out that none of the characters of which in the line are less than he cannot get into the answer cannot get into further adjustment, that means this is the conclusion we can draw and then it turns out that we have, well, let’s say here’s the original line and there’s b well, let’s say here’s the original line and there’s b well, let’s say here’s the original line and there’s b and let’s say a-a-a and let’s say a-a-a and let’s say a-a-a and, accordingly, some k let’s say and, accordingly, some k let’s say and, accordingly, some k let’s say equals 2 and if we have all this, let me write some more there, let’s say so let’s say yes write some more there, let’s say so let’s say yes write some more there, let’s say so let’s say yes Well, let’s say like this, let’s say a Well, let’s say like this, let’s say a Well, let’s say like this, let’s say a line like this and accordingly to let’s say 2 and we and the accordingly to let’s say 2 and we and the accordingly to let’s say 2 and we and the fighters don’t reach this equal to 2, fighters don’t reach this equal to 2, fighters don’t reach this equal to 2, which then turns out that we can then consider only a section of the original line, that is, we can get that these are the characters those characters that scored less k they divide the original line into parts they are fragment separators that can be the answer of fragments that can contain the longest substring, that is, it turns out that we built a histogram here once and disqualified some characters and after this disqualification, our entire line turned out to be broken into several parts, which means that then in the worst case, we let’s say we the worst case, we let’s say we the worst case, we let’s say we shortened the line by one character and let ’s say we removed and removed one character ’s say we removed and removed one character ’s say we removed and removed one character and removed it from the permissible ones there is one character from the alphabet, but that is, in the worst case, there we have the letters a and there, let’s case, there we have the letters a and there, let’s case, there we have the letters a and there, let’s say at the end, b, but this is not quite an acceptable realistic case, but let’s say there’s acceptable realistic case, but let’s say there’s acceptable realistic case, but let’s say there’s also no letter there’s a letter at also no letter there’s a letter at also no letter there’s a letter at the end, but it doesn’t matter in general, the worst case of us but it doesn’t matter in general, the worst case of us but it doesn’t matter in general, the worst case of us it turns out that the line was shortened by only one and we again returned to the same problem, here we really need to see if it is really the worst case because if the line and line we just threw out this character, the rest here we found to be suitable, then this is probably not the absolute worst case, let's make it so that this can be continued, let's do some other case, let's make some case, let's say we're b and inside there let's say there was a letter c and at the end book at the end here I am if we have such a letter cyto let's say we had a letter b it was not enough when k is equal to 2 and accordingly we discarded let's go to this one along the line without this letter b but here before we also had c in sufficient quantity but since we now took this line is not in sufficient quantity now, what then we get is that in the worst case, we moved on to, well, we shortened this line by a small number of characters; shortened this line by a small number of characters; shortened this line by a small number of characters; also, if we further try to consider this line as an abandoned letter, then we again have the same the worst case will be when, along with discarding this letter, like this, another letter will also open, let’s say, another letter will also open, let’s say, another letter will also open, let’s say, let’s say this is the line, let’s say this is the line, let’s say this is the line, that is, here we will again imagine that we have such a line, initially then we will find this book for the first time in a cube and shorten the line slightly further, again here we will find the letter c and again slightly shorten the line by again we won’t achieve the fact that we have won’t achieve the fact that we have won’t achieve the fact that we have enough letters and this will all continue like this, which in the end it turns out in the will all continue like this, which in the end it turns out that we are using these lines when we there we broke the original line into parts, we will go through them again, but such transitions from lines to smaller ones are limited by the size of the alphabet, the number of transitions, that is, it turns out that after we, therefore, according to this insufficient letter, we break into parts 1 part and 2 Let’s say there is a part like 1 part and 2 Let’s say there is a part like 1 part and 2 Let’s say there is a part like this, the total number of actions for these parts we get is approximately the same as the length of the original line, these are the transitions down with each transition down we have one letter disappearing, so it turns out that here the complexity turns out to be multiplied by the size of the alphabet and like this so it seems to me that this is close to the optimal difficulty, the only thing that could be done here is that we can do it in advance, which means this is according to this very time, I would say that the size of the alphabet is squared from memory because we will have to at each level We can count the frequencies of these letters and these levels; they are larger than the levels; they are larger than the levels; they are larger than the size of the alphabet, but there are also recursive calls and, accordingly, while we are counting here, we no longer need to count at the next line, so that’s count at the next line, so that’s count at the next line, so that’s why the question here is the depth of the recursion here is no more than the size of the alphabet, but even that turns out to be Allah and squared from memory in the worst case, so now I’m trying to understand whether it’s possible so now I’m trying to understand whether it’s possible so now I’m trying to understand whether it’s possible to do better here, we can most likely do it if we calculate in advance some, let’s say, some, let’s say, some, let’s say, integral sums, that is, we can calculate by day and how many of which character are in which prefix, that is, for each prefix we can count the number of each character, then we get more from memory, that is, we store it all, we need a sign, line length is a powerful alphabet, but at the same time we can for any substring we can for from one factory units and count the number of characters on the segment and accordingly if we can do this factory units then it turns out, well, in the worst case we have the number of recursive calls here, I probably even find it difficult to say that what we will end up with is most likely something on the order of the length of the original string that is, the feeling that the code of years of possible substrings under the lines on which we will be on which we will count it all because every time we move from a line to a partition, some one character falls off and there the total length of the line decreases, that is, every when a character falls off, here's a character falling off, the number of characters falling off is equal to the number of lines that are located above and, accordingly, more characters than the length of the original line will open, so it turns out that the number of these substrings that we are considering is also not greater than the length of the original line, but when in this case, for each line we will have to count the code to count the number of each letter, going through the table with prefixes, and then from alphabets we will have a for subtraction and, accordingly, we have this again, we again got the exact size of the alphabet in time and so much but from memory it’s not a fact that it’s and so much but from memory it’s not a fact that it’s and so much but from memory it’s not a fact that it’s not a fact that it will be worse than here because here from the calculation it’s because here from the calculation it’s because here from the calculation it’s from the calculation of hash tables from the calculation for arthritis we would have a large constant there, here we have arrays and here we have small constants, but nevertheless we are an improvement we don’t see anything asymptotic here, it’s something like that, sad trouble, but in general the solution is better than the length of the string multiplied by the size of the alphabet, I don’t have it, and I’ll probably alphabet, I don’t have it, and I’ll probably alphabet, I don’t have it, and I’ll probably stop there and I’ll probably stop there and I’ll probably stop there and I’ll probably write this, but in principle, even with this solution we can afford there is a line there for 100,000 there is an alphabet if only 100,000 there is an alphabet if only 100,000 there is an alphabet if only English letters my scans but here and no it is said to be completed from lower case letters and apparently it is implied that the English alphabet but accordingly we get 26 letters for a line length of 100 thousand well there are 2 million we have such tests there Well, we can go through hundreds in a second, that’s why, but we can go through hundreds in a second, that’s why, but we can go through hundreds in a second, that’s why, but it seems like everything is more or less adequate, the question in the chat is who will solve multi-threaded problems in the near future, no, let’s go tonight, multi-threaded problems in the near future, no, let’s go tonight, multi-threaded problems in the near future, no, let’s go tonight, I don’t know if it makes sense to I don’t know if it makes sense to I don’t know if it makes sense to look at the previous options here, in principle, it won’t take long to write here, so principle, it won’t take long to write here, so principle, it won’t take long to write here, so you can write options like this string in youtube it’s best to change the lines ourselves, youtube it’s best to change the lines ourselves, youtube it’s best to change the lines ourselves, so we’re not going to change the lines ourselves, so we’re not going to change the lines ourselves, so we’re not going to change the lines ourselves, so we ran further, ran to count, run fest first start from 0 to the long line clos’d last runs from long line clos’d last runs from long line clos’d last runs from festa to long lines first i was inclusive further quantity let me tell you right away the size of the alphabet is 26 for 0 and then we need that the number of letters and letters the number of letters in general that we have and the number of different letters mm good letters in general for which k was also met until zero and then we run along a symbol at first to last let's we get a symbol with this, respectively, if we have an account from this letter, the count from the symbol minus the code of the letter and small if it was zero, then this means that the number of letters we have now increased guitars increases further we add the number of this letter and the same So let's see, if now after this plus we have exactly k, then this means that this letter has reached the necessary barrier, if the count is 7 of the nose and equals k, then this means that the number of good letters has become one more, but accordingly, if we have a total as a result, here it turned out if in good equals m letters then this means that each letter we have reached key and accordingly we need to compare the maximum initially empty substring with the maximum if we have a maximum of 100 d-max function of max- 100 d-max function of max- 100 d-max function of max- let me start with this max m is the maximum length and then the function max is from the maximum length and last minus x 100 + 1 if + 1 if + 1 if inclusive then you need to add one, for example there is the pure last of this position 3 and then from 3 to three we have the length along line 1 something like that and now you can also write a condition if this is the length, let’s do it like this: Elena let’s do it like this: Elena let’s do it like this: Elena equals last minus host plus 1 and, accordingly, if this length turns out to be greater than the maximum, then we don’t touch this at all, respectively, probably don’t touch this at all, respectively, probably don’t touch this at all, respectively, probably break yes, because last is in ascending order therefore, as soon as it became more for us than what was already found, it doesn’t interest us, than what was already found, it doesn’t interest us, than what was already found, it doesn’t interest us, and accordingly, if we got here, then the length turned out to be up to, in general, if it’s equal, we’re also not interested, but if it’s equal, we’re also not interested, but if it’s equal, we’re also not interested, but if we got here, the length turned out to be strictly less, so we’re just here strictly less, so we’re just here strictly less, so we’re just here so we assign the tapes, that is, it turns out that we don’t even do any calculations turns out that we don’t even do any calculations turns out that we don’t even do any calculations if it doesn’t suit us if it doesn’t suit us if it doesn’t suit us if the length is less then we do the calculation and go through it, and accordingly here we assign if suddenly this section turned out to be good, but naturally we return this magician slim, this is the best thing I was able to write everything for the cube with essays, let's see, it probably works, but it doesn't, he says that beeches and so now I'll look at the fest, it's working out for us if the length turned out to be adac, we need it on the contrary, it turned out to be less or equal to the bridge, not interested, well then we are going in ascending order here, so we don’t have any break, let’s so we don’t have any break, let’s so we don’t have any break, let’s better write cantina, of course, it spoils this situation significantly for us, but let’s set a time this situation significantly for us, but let’s set a time this situation significantly for us, but let’s set a time limit, most likely it will turn out to be a date we like, but it turns out like this, okay, let’s save this as a non- like this, okay, let’s save this as a non- like this, okay, let’s save this as a non- working option 395 a goal I don’t know working option 395 a goal I don’t know working option 395 a goal I don’t know if it makes sense to do it completely optimally when we run from the maximum length the knee goes from s says to one even probably I would escalade more lebron ok she goes and accordingly fest we then run from 0 let’s just like this everything is in a hurry from run from 0 let’s just like this everything is in a hurry from run from 0 let’s just like this everything is in a hurry from 0 to as long as we generally have you laying down the fest plus did you find a log and says if we get it like this the last we can get as a host plus n minus 1 like this and then accordingly if we have this thing as soon as we have it found as soon as we have, we don’t even need max ent here, as we don’t even need max ent here, as we don’t even need max ent here, as soon as we have it all in 1 it took off, we can immediately return this length as an answer since we process age y by decreasing the length, then accordingly and here at the end if we have nothing didn’t take off from this, but we have nothing didn’t take off from this, but we have nothing didn’t take off from this, but find out that we return 0 and we have a length of 0 under 40, so we have a completely ideal short scheme, that is, if we first go along the length in descending order and then secondly go according to the position of the first character, but and accordingly let me hand over that ideal short circuit again and again I probably got a time limit and it didn’t work like that 395 b also from the rear I have and it didn’t work like that 395 b also from the rear I have and it didn’t work like that 395 b also from the rear I have questions in the YouTube chat, you can write two pointers, so I’ll explain to you write two pointers, so I’ll explain to you write two pointers, so I’ll explain to you that you are wrong because it says here that this is not the shortest line a is the longest and here there is no monotony, and accordingly, when you added another symbol there, it can ruin everything for you, so no two pointers, well, at least I thought about these two pointers, but it doesn’t seem to work, and pointers, but it doesn’t seem to work, and pointers, but it doesn’t seem to work, and accordingly, here you go your word seems to be probably and ben search is also your word for sure it does not correspond to reality because there is no monotony, that is, at any moment some letter may appear that will spoil you and the quantity will not be enough and then with increasing length you can gain more this letter and suddenly there will be enough therefore there is no monotony and without monotony we don’t have two pointers monotony we don’t have two pointers monotony we don’t have two pointers and binary search too, so we move on to the next solution, the second solution is when we started from the initial characters and accordingly we are trying to increase here We’re fully we are trying to increase here We’re fully we are trying to increase here We’re fully prepared for this, I’m ready to increase this sharp prepared for this, I’m ready to increase this sharp prepared for this, I’m ready to increase this sharp line accordingly, let’s do the same thing, I don’t let’s do the same thing, I don’t let’s do the same thing, I don’t even know if it makes sense, does it make sense to write something here like I described because now I’m I described because now I’m I described because now I’m ready to write a cooler way, but let’s after all, I’ll write as I let’s after all, I’ll write as I let’s after all, I’ll write as I described when we do all the positions, a cooler way is that if we fix two lengths, then first mine for the first line we count everything explicitly and then for each next line we throw out 2 and them symbol yes and add a symbol after here let's use a less cool way I will find the answer to fest feast goes from 0 to says accordingly here we immediately generate this statistics here we have the statistics next we run the class there at first to the length and now this one symbol we add responsibly the symbol we get with at last and we take this symbol into account if we do n’t have a letter here before then we will n’t have a letter here before then we will n’t have a letter here before then we will increase the number of letters encountered if there was a letter and the letters became okay and accordingly and was less than k then we will also increase the number of good ones and, accordingly, if we ended up with if in good turned out to be equal to I am not a torso, then we get the length as last minus 1 plus 1 and, accordingly, the maximum of us turns out to be equal to the maximum of mac slim and m here is the maximum length initially zero and at the end we return this maximum length, this is option number two, this option number two, which I described, and then we can try to pass it I get the time limit again, oh damn, what a misfortune, just a square and we have and it doesn’t work well for us, it doesn’t square and we have and it doesn’t work well for us, it doesn’t square and we have and it doesn’t work well for us, it doesn’t work well, but it works well, okay, this is our n square, this is ours, we can write down that this is our 208 milliseconds, we got 3 st 95 prices 208 m s now I want to make the same square only with the flow that is, we again go along the length goes from the size of the line to those and in decreasing order further we go further, we will first run at first i calculate the statistics that is, here we run let's for young and go from 0 to our length and we count these statistics, respectively, this is what we have, this is our calculation of statistics further, if we have from China and then we first look for the first line is for us, here is the first tape of the Sims, if we have a tourniquet equal to the track, then Lena is suitable for us, damn it since we sort out the length in descending order, then we also return the so-called suitable ones. we also return the so-called suitable ones. we also return the so-called suitable ones. otherwise we now move we move on we try the last character in the layer the last character begins slam and to the end of the line and now we need to do two operations, the first is to add a character to the end, this is what we do about the same symbol, the only thing that I would probably put it in the block because we will have another one about the same but different with a layer, so we will have the force at last and accordingly we add it in the same way if we had 0 then our number of letters will increase further than mine, we reduce from we increase this number letters if it became ok then the quantity is a good letter who will we increase and now we need to throw out the letter that was on the flax before, that is, if we have a letter in the position tape, we have lost the letter in position 0 so we will have a char siu with a layer minus n this letter it will go away accordingly if we had it ok if the count from the symbol minus the move of the letter if it was ok then now it will be reduced and accordingly the number of good ones will be 1 less than the count all minuses minus and now in the reverse order if the number now it has become zero if the count all the minuses has become zero then we have the number of all letters in the line, it also decreases, and after that we can yes, this is what happened to us, I processing happened and for this last if we suddenly for some last happened that the number of good letters is equal to the number of total letters there then we return this length because for but we are just sorting in the correct order from large to less but in the end if none of this took off for us, then we have a substring of length 0 let's see we pass it got worse, but it got worse, it’s worse, nothing can worse, but it got worse, it’s worse, nothing can worse, but it got worse, it’s worse, nothing can be done about it’s a little strange, but it’s be done about it’s a little strange, but it’s be done about it’s a little strange, but it’s like, anyway, here and there’s a square, but it here and there’s a square, but it here and there’s a square, but it turned out that in that version it was more efficient, I did, and I understood why it’s more effective because here we are we why it’s more effective because here we are we why it’s more effective because here we are we just add each letter, and in that version we also add each letter, and you read if the answer was a longer length, that would be just fine, but if the length is just small, it’s suitable, but that small, it’s suitable, but that small, it’s suitable, but that means we need to go through everything here, but that’s all yes, okay, let's do but that’s all yes, okay, let's do but that’s all yes, okay, let's do this 300-400 12 milliseconds, let's this 300-400 12 milliseconds, let's this 300-400 12 milliseconds, let's do the simplest optimization in the past solution because in the past solution we started with last equals fest and no, but it won't work, I wanted to start with plus k minus 1 but it won't work because no one will count for us these letters that the gaps were on the forehead now, in fact, we move on to the most effective third solution when we, in fact, started from the line and began to count everything there, let's actually do this, which means we run, that is, here we have line and we run through the pins of them, well, firstly, if the site turns out to be smaller than the key, then we will immediately return 0 in quality because nothing good will happen here for us further, we need to count the number of each letter, so we created an array for this purpose, then we run along the entire line, let’s even do it like this along the entire line, let’s even do it like this along the entire line, let’s even do it like this now and for each character c we do this, but I don’t know we do this, but I don’t know we do this, but I don’t know if it makes sense and letters in good probably makes sense because maybe not, we just stupidly take and count the brackets of which letter after which we need to go through this array and find out if everything here is good under the line year initially the pipe we initially believe that we did not have a letter that is less than k from zero to twenty-six from zero to twenty-six from zero to twenty-six but we can make a part we can run the symbol from hey yes hare and, accordingly, if the count from the symbol minus the letter a turned out to be less than kay then the year is equal to falls but also break, that is, something like this turns out that is, mine took ours and found out whether it’s true that we have and found out whether it’s true that we have and found out whether it’s true that we have only symbols here that are larger, return if so then we return if good then we return the length from our line says we immediately return our size of this original line otherwise we need to divide this line of the subject with letters of which there are not enough, let me bang everything else here and we run along the line, let’s and we run along the line, let’s and we run along the line, let’s say from 0 to let’s the previous position where there we let’s the previous position where there we let’s the previous position where there we all started with 0 and we run up to the length of our string and find out if we have the number of this letter, let’s we have the number of this letter, let’s we have the number of this letter, let’s select the symbol as full if the number of this symbol turned out to be less than kay then this is an obstacle and accordingly we need to add let’s answer the max for me first 0 let’s answer the max for me first 0 let’s answer the max for me first 0 then the magician slim is the maximum from mac slim and the answer is longhi with sap string from own under the string starting from prev yes previous Seoul to and minus 1 but if yes and not inclusive then the length is exactly the spread, this is how it turns out and where we pay attention, if we have here the string of you to from the appstore works for from one and still without reversing dynamic memory, then we took from all of them up to this point, which means from the previous symbol and not inclusive, that is, if there is an obstacle in the position and we have an obstacle, then we took from previous possible up to the current not inclusive and kay as the second parameter we received this answer and chose better before and after this we also said that the priv is equal to and plus one we say that if in position and obstacles then the next line can only begin you + 1 a line can only begin you + 1 a line can only begin you + 1 a otherwise, what do we get here, otherwise we don’t do anything because we otherwise we don’t do anything because we otherwise we don’t do anything because we don’t have any obstacles here, but in the end at the don’t have any obstacles here, but in the end at the don’t have any obstacles here, but in the end at the end it may be that we, again, have run out of things, it ended at some adequate Seoul and we need it again make this call from the end of the line, again from a priv the size of says minus prev, that is, this is under the line after the last obstacle, by the way, it can be empty everywhere, but with an empty line we will immediately return 0, and at the end we return this maxxmem this thing is so heavy-handed heavy-handed heavy-handed with recursion with calculations but theoretically on large lines there but we don’t know tens of hundreds of thousands and it don’t know tens of hundreds of thousands and it don’t know tens of hundreds of thousands and it should work well, an order of magnitude better than what we wrote before so we have a stack overflow here, let’s stack overflow here, let’s stack overflow here, let’s see how I understood how if we don’t have, wait, don’t have, wait, don’t have, wait, we must have some kind of symbol here that is smaller than those and only if we have some kind of symbol, then in this case we do something further, I don’t like what’s going on in court with us don’t like what’s going on in court with us don’t like what’s going on in court with us it turned out to be a stack overflow, this is very strange because well, let me write iv here if the line is empty I won’t twitch there at all write iv here if the line is empty I won’t twitch there at all if it’s the sprays that are greater than zero if it’s the sprays that are greater than zero if it’s the sprays that are greater than zero then it makes sense, I’ll even say more than those and greater than or I’ll even say more than those and greater than or I’ll even say more than those and greater than or equal to k then it makes sense to twitch here, too, if we with says minus rights turned out to be more took okay, then it makes sense to twitch, if you write like this, then it seems like we won’t have any extra operations here, let’s like we won’t have any extra operations here, let’s like we won’t have any extra operations here, let’s go, no, anyway, we have a stackoverflow feeling with stack overflow that I somehow I call for some symbol which somehow seems to work out like this, let me write sirtec let's write an arrow and a sub under the line we get with abs from rights and minus rights and let me write that usopp says turns out to be less than with says your original line and here similarly, let's get an arrow and the sub is taken from its own like this from the priv size like this and let the devil write that usopp says turns out to be less than with says then it turns out like this let's go to assert it fell off it happened on the thirty- assert it fell off it happened on the thirty- assert it fell off it happened on the thirty- sixth line why this happened I can’t imagine because we can’t imagine because we can’t imagine because we didn’t have to prev, that is, at that moment didn’t have to prev, that is, at that moment didn’t have to prev, that is, at that moment when for some symbol it turns out that I understood everything if the symbol here is 0 if the count from the minus symbol turns out to be more than 0 and less than okay, let me write it like this as a double inequality, then good falls if yes, here it is, good falls, respectively, if it is yes, that is, I’m false, I is, I’m false, I is, I’m false, I wrote the wrong thing, that is, if there is some village of us there 0 then it worked perfectly and let’s then I’ll return everything as perfectly and let’s then I’ll return everything as perfectly and let’s then I’ll return everything as it was, which means, well, although not everything is as it was, I ’ll return it, I’m about to leave just this and this, I threw it here, and this should probably be enough, let’s go, let’s rent this should probably be enough, let’s go, let’s rent this should probably be enough, let’s go, let’s rent out, oh, how beautifully it turned out, how beautifully everything turned out, a sea of milliseconds, it’s beautifully everything turned out, a sea of milliseconds, it’s beautifully everything turned out, a sea of milliseconds, it’s just lovely, we’re all we have 395 we’re all we have 395 we’re all we have 395 m0 milliseconds on the bowl pocket is gorgeous but that’s where it m0 milliseconds on the bowl pocket is gorgeous but that’s where it m0 milliseconds on the bowl pocket is gorgeous but that’s where it all ends today questions part of this I don’t ends today questions part of this I don’t ends today questions part of this I don’t see the next task in two days on Sunday September 6th also starting at 9 pm Moscow time task 210 of the site rows course dropped version 2 this is the problem, welcome to solve it, and with that I say goodbye
|
Longest Substring with At Least K Repeating Characters
|
longest-substring-with-at-least-k-repeating-characters
|
Given a string `s` and an integer `k`, return _the length of the longest substring of_ `s` _such that the frequency of each character in this substring is greater than or equal to_ `k`.
**Example 1:**
**Input:** s = "aaabb ", k = 3
**Output:** 3
**Explanation:** The longest substring is "aaa ", as 'a' is repeated 3 times.
**Example 2:**
**Input:** s = "ababbc ", k = 2
**Output:** 5
**Explanation:** The longest substring is "ababb ", as 'a' is repeated 2 times and 'b' is repeated 3 times.
**Constraints:**
* `1 <= s.length <= 104`
* `s` consists of only lowercase English letters.
* `1 <= k <= 105`
| null |
Hash Table,String,Divide and Conquer,Sliding Window
|
Medium
|
2140,2209
|
304 |
hey everybody this is larry this is day third the third day of june uh for the june the code daily challenge hit the like button to subscribe and join me in discord let me know what you think about today's problem um range some query 2d immutable okay so this one i'll go over a little bit but not gonna lie uh the mb the nba finals is happening soon so i might keep cutting a little bit short i actually have i have explained this in many videos in the past to be honest but i don't think i kept it in a good place that i can reference it to be like hey just look at this but we can go over very quickly and then um what i want to do now is actually just kind of give the concept of the problem and then you can think about how to implement it i mean you could watch me implement it as well obviously but i'm just looking for my drawing pad but i'm going to give you the concept and if you don't know i mean obviously if you know this problem then just do it then you're not watching this or at least you're not you know uh focus on that part you're just hanging out with me and i appreciate that uh thank you for liking the video and all that stuff um but the idea here and i'm just gonna give the idea and then you could uh what i want you to do is if you if um if you haven't done it before see if you can come up with uh with the idea see if you come up to implementation right because implementation is hard as in general as well and even if you have the idea it doesn't mean the implementation is easy but you can give yourself that practice and see if that's good and then you can kind of we could compare notes and see if um see if we have the same answer or we're not saying because it's code but uh you know similar idea and so forth um but okay let me double check that you can see what i'm seeing okay so now let's say you have this right the idea here is um is i'm gonna go a little bit over the idea about one d prefix sum because i guess we skipped a day or a kind of at least in terms of explanation but okay let's look at for now let's just look at the last column right here and then the last column let's say we have a prefix sum all right that kind of disappeared let me try again hang on so let's say we have this and then now we look at the last column right um oh that's my pen so in the last column you can have why is this so weird so now you have the prefix sum including the zero element here and then one four this is kind of a terrible example actually but the idea here is that now that you have the prefix sum uh and what does the prefix sum tell you right every element means that it will give you some subset of the pre the sum of the prefix which is what it sounds like so this element is includes you know or this element where this four element includes you know all these elements right um with the four elements that are in the row um and now we'll just focus on 1d and of course that's helpful but how do you get any range right and the idea behind getting anywhere any range is that let's say you want to look at here right the sum of these two elements well the sum of these two elements is just this entire sum minus this subset right so now to get uh i should have changed the color a little bit so to get this so why is this so weird so to get this three and zero uh 1d box you just take this big box minus this big box and a smaller box and then you get the delta which is in the underneath and that's basically how you do 1d um 1d range sum or prefix sum queries and stuff like that so that's basically one of the core ideas that um i hope you're familiar with uh if not maybe a left entire week but today like i said uh nba play also my fault if uh yeah uh okay so i'm going a little bit fast is my apologies but maybe you know you could watch it again or something hopefully that's good or just come to discord and ch hang out okay so what do we do in 2d right so let's say we have this do i want to use this um okay it doesn't really matter i guess that's just a box um then the idea here is the 2d version of this right uh okay so let's actually bring it back oops hang on the idea is similar but a little bit tricky or tricky to visualize initially right let's say we want to get a certain box let's say actually a box that they give you let's say this blue box right how do you get this blue box well there are a couple ways you can do it but the way that i think about it is that box is just um uh a combination of sorts of a couple boxes right one is that you get this bigger this red box so you get the sum here minus i'm trying to choose another color hang on minus this other box that is on this border right and minus this one because now we know that these numbers are not obviously in the blue box so we subtract it and in here we notice that we're actually subtracting this box twice right we're subtracting this box twice so we have to add it back and that's basically the core idea um you can work out the x's and y's and implementation but that's basically the idea so if you haven't if you have never done this before definitely pause and see if you can implement that idea from scratch um i think you just draw it out and write out the indexes be clear um and also take your time this is if this is your first time doing or even second time doing it uh not necessarily and if you don't feel like you understand it take your time and just pause and then come back to you know um keeping in mind that i have i one is that i still get off by whenever so i have to be careful as well but i would also say that like if it appears fast and i may jinx myself and really type it slowly if it appears that i appear fast or done it quickly um it's because i've done it a lot of times so yeah so that's basically what i was going to say right yeah um so that's basically all i have to say so definitely like i said keep track of um what would you want to do uh and try to do it afterwards okay just checking the bounce receiving track of length and rows and columns and then now we set up the prefix sum and actually you don't even need the original matrix because you can build it back anyway so we have prefix there are a couple of ways you can write it um i write it this particular way so let me know how it goes oh actually just plus one because i like also to have an extra row and column of zeros um just so that you know that represents zero elements so it makes certain maps easier um but that's the way i do it yeah okay so okay and then so that's just setting it up and then now we want to do the prefix version i usually write it this way but i know that people do it in a different way with uh but for me this way makes sense but yeah because now we're aggregate now we're doing the brief exam of the prefix um and in some region like we said we just have to you know work out the corners um so it should be solved that prefix of uh are they definitely smaller than each other okay just want to make sure because sometimes some problems will trick you with if you assume different corners but here it just should be lower left or whatever it is so it should be okay so row two plus one card two plus one we're going to return all right so this is the entire rectangle minus uh or one um and we don't want to exclude it so we want to include it because it's minus one plus one yeah i think this is it i mean sometimes like i said i am way prone to off by one on these wavelengths but uh oh whoops and also you know in good practice you would do probably do some defensive programming but uh they give you cassette constraints so that's okay with respect to like the rose columns and inbounds and stuff like that i do this well i see huh oh wow this is really wrong actually no wow what am i doing i need to do the prefix oops that's why uh okay actually this is right it's just that i was thinking about the prefix array and not okay sometimes i write it differently so i guess i got confused there quick typos okay so this is clearly really wrong um why is that let me see if i got the yeah like i said easy off by once by ones uh let's see what is this so three zero four eight ten looks okay eight four ten is eight plus six yep that looks okay so this matrix looks okay so if i have an off by one here is that reasonable um what are the inputs some region some okay so we want to sum two one four three so are these zero indexed yep four oh wait which one is the red one i guess they tell you uh the red triangle a rectangle so two one i mean it should not be negative in any case but i guess we can huh what am i doing wrong um okay i mean i guess just putting out the components maybe i just messed up somewhere oh wow okay it's just a easy type boat because i don't know these lines were a little bit long maybe i should have been a little bit better about um because i don't like having these long lines but python is very weird about it so okay so let's give a submit hopefully this is good and i don't have more typos on the plus one but i mean that was technical if i wanted more like typo oh wow how am i so much slower than last time um cool let's take a look to see what i did last time then i guess i did the same thing maybe it's just um they just add more test cases or something like that but yeah you can't really do that much faster i mean this is linear maybe you can get rid of some four loops but um well yeah this is all one so that makes it easy because oh one is pretty much as fast as you can go uh this is going to be r time c which is linear uh what did it call it um uh pre-processing is what they call it uh pre-processing is what they call it uh pre-processing is what they call it but yeah that's all i have for today gotta go run to the game stay good stay healthy take a mental health uh i'll see you later and take care bye
|
Range Sum Query 2D - Immutable
|
range-sum-query-2d-immutable
|
Given a 2D matrix `matrix`, handle multiple queries of the following type:
* Calculate the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
Implement the `NumMatrix` class:
* `NumMatrix(int[][] matrix)` Initializes the object with the integer matrix `matrix`.
* `int sumRegion(int row1, int col1, int row2, int col2)` Returns the **sum** of the elements of `matrix` inside the rectangle defined by its **upper left corner** `(row1, col1)` and **lower right corner** `(row2, col2)`.
You must design an algorithm where `sumRegion` works on `O(1)` time complexity.
**Example 1:**
**Input**
\[ "NumMatrix ", "sumRegion ", "sumRegion ", "sumRegion "\]
\[\[\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]\], \[2, 1, 4, 3\], \[1, 1, 2, 2\], \[1, 2, 2, 4\]\]
**Output**
\[null, 8, 11, 12\]
**Explanation**
NumMatrix numMatrix = new NumMatrix(\[\[3, 0, 1, 4, 2\], \[5, 6, 3, 2, 1\], \[1, 2, 0, 1, 5\], \[4, 1, 0, 1, 7\], \[1, 0, 3, 0, 5\]\]);
numMatrix.sumRegion(2, 1, 4, 3); // return 8 (i.e sum of the red rectangle)
numMatrix.sumRegion(1, 1, 2, 2); // return 11 (i.e sum of the green rectangle)
numMatrix.sumRegion(1, 2, 2, 4); // return 12 (i.e sum of the blue rectangle)
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m, n <= 200`
* `-104 <= matrix[i][j] <= 104`
* `0 <= row1 <= row2 < m`
* `0 <= col1 <= col2 < n`
* At most `104` calls will be made to `sumRegion`.
| null |
Array,Design,Matrix,Prefix Sum
|
Medium
|
303,308
|
127 |
hey everyone welcome back to the channel i hope you guys are doing extremely well so in this video we are going to solve this word ladder one problem which is an extremely hard problem so what does the problem state the problem states you're given two distinct words two distinct so a start word and a target word and a list denoting one list of unique words of equal lengths find the length of the shortest transformation sequence from start word to the target word now you need to keep the following conditions in mind a word can only consist of lowercase characters only one letter can be changed in each transformation very important each transformed word must exist in the word list including the target word the start to word may or may not be part of the word list so what does uh this particular problem define so it defines a given a begin word so over here it is hit given an end word over here it is cog and you are given a word list which will be containing certain number of votes and if you see all of them are of length three so if i start with it so let's start with something like hit now what you can do is you can change any one of the character like there are three characters in hit you can change h you can change i you can change t you can change any one of the characters of it so as you might say that hey i'm going to change this i to o so what i'll get is hot and if you carefully see hot is there in the world list so you can have this transformation done in the next step i say i'll change hot to dot which means i'm going to change this h to d and if you see dot does exist over here in the next i say i'm going to change dot to dot basically i'll change t to g which is dot to dot and if you see dog also exists in this particular word list in the next i'll say i'll change talk to i'll change the d and i'll make it c and i'll have a comp which is nothing but our end word if you carefully see this is nothing but our end word so if i ask you how many transformations did you do there was like one two three four and what is the sequence length that's five so thereby i can say that this is the shortest transformation sequence if you wanna start from hit and you wanna end at something like a so if i show you one more example over here we have the world list as des dr dfr dgt dfs so dr can actually be changed to dfr and dfr does exist if you see and then dfr can be changed to dfs and dfs also does exist over here so over here the sequence is of length three thereby the output is three now it might now what if it is not possible to change a particular given word to any other word in that case you will just return zero stating that it is not possible the sequence length is zero now you must be thinking which algorithm to apply but before going into that direction let's analyze the problem we are given hit right so what can we do to the set so hit is getting converted to something like hot where the eye is changed to oh right so the second alphabet in the world is changed so if i say hit where can i change you can be like striver i can change the first h driver i can change the second i striver i can change the third t make sense now let's go deep if i ask you if you change h in hit what can you make hs you'll be like i can change h to ait make sense i can change edge to vit makes sense i can change h to cit does make sense i can change h to d i t make sense i can change h to rit makes sense i can change h2 zit sorry zit does make sense so apparently in the head i can pick up the first character and i can change it to anything from a to z do you agree i you do agree right similarly can i say i can pick up i and i can change it to anything from a to z do you agree in this you have to and when i change i to o i get hot and that hot does exist over here if you see the hot does exist separately you can try changing like h a t h b t h c t het hft but the only one valid will be hot why because that exists in the old list and the next step you can be like i can change t as well t can be changed to a to z and the what has to be in the world list agreed so this is the brute force that we will follow we will start with the particular word and we will try changing it on character to character and every character we will replace from a to z and we will see if it is in the word list or not got it so as of now you know the brute force right so if you know the brute force is pretty simple you have hit you take h and you try to change it from a to z you take i you try to change it from a to z you take t and you try to change it from a to z and you count the minimum lengths yes you count the minimum length because the question states you have to find the shortest transformation sequence so you have to change it in such a way that you find the shortest transformation sequence now which algorithm to apply if you are willing to find the shortest sequence let's analyze that so if i say i will keep the hit as the level one right at the top according to brute force i'll try to do h to a i t b i t c i t d i t and so on till z id i'll try to do this right in order to transform hit to any of these in order to transform it to any of these words should exist in the world list and they do not if you go and see in the word list there is nothing like ait bitcit none of them so not possible next i'll take i and i'll try to change it from a to z so i'll get like h a t h b t h c t dot so these are all the words that i can change head to and apparently only hot does exist if you go and see hot is the only one that exists over here so i can say from hit i can go to hot now i'll take t and i'll try to change it to h i a h i b h i c so on to h i said let's see if they exist in the world list none of them yes none of them do exist in the world list so that is not possible so only hot is possible can i say this is the second step because the length of the sequence will increase to two perfect now i have a word as one i'll again perform the same thing i will take h i'll try to do it like aot bot cot d or t and so on till zot and i'll see only dot exists only dod exist if you go back and see only dot exist and lot also exists and d o t and lot also exist so if i change this to dot and i can also change it to lot so that's when i change h let's see for o h a t h b t c hct hdt and so on till h z t does anyone exist let's have a quick check no one next let's try to change t that will be and so on does anyone exist have a check hot does exist because if i change this t to t hot does exist but you will not take that into consideration why it's the same word it is the same word so you do not take that into consideration because there's no point in going to hot again and going to hot again or there's no point in getting to hit again i can change this o to i as well and i'll get h i t but if i've come down from hit to hot is there a point in going back to it because that will only elongate the sequence so apparently this is the step three similarly i can take dot and i can do the transformations similarly i can take lot and i can do the transformations and this will be level four similarly i can just go on doing the transformations and this will be level five since we are going something like a level whenever assume somewhere over here we reach the particular cog can i say the length taken will be five and that will definitely be my shortest sequence can i say this i can why because beyond this since i'm doing level wise anyone that will be level six the length will increase so i'm definitely sure i am definitely sure whatever i'm getting over here that's the first instance of cog it might come over here again but length five is what matters so the first time whenever we encounter the end ward that is when we end which traversal is this guys yes it is nothing but the bfs traversal so we go ahead and apply bfs traversal to this in order to solve this amazing tough problem so you saw how i started the problem using simple brute force then i analyzed the brute force and figured out that we can apply bfs algorithm that's trying to do a dry run on this particular example so that the algorithm gets into your head straight away so you know that this is the beginning word and in a bfs algorithm we always start with a q data structure so what i'll do is i'll just take the sword and say hit comma one because the length of the sequence as of now as one so you have taken that and put that into the queue data structure the next thing that i'll do is i'll take this out from the queue data structure and i will start working on it so as of now we have a word hit and we have the sequence length as one right now what i need to do is i need to take h and change it to a which will make it ait and then i'll check does ait exist in the world list now this is an array if i go and do a linear search and check that is definitely going to take a lot of time so what i'll do is i'll take a set data structure and i'll make sure that the same thing yes the same word list does exist in the set data structure so that whenever i change this edge to a and make it ait i can easily check in the set data structure if they exist or not in a very less time complexity so ait doesn't exist then i'll make it bit that doesn't exist then i'll try c i t d i t e i t so on till zit none of them does exist next i'll move to the next alphabet i and i'll be like h80 does it exist no hbt does it exist no hct does it exists no hdd doesn't exist no i'll keep on doing and at h o t when i convert this i to o i see hot does exist case i see hot does exist over here so what i'll do is i'll simply take this and convert this to t like oh and that will be sequence length of two so i'll put that into the queue data structure saying this is of a sequence length two right so hid got converted into a hot weather sequence length of two now do you keep the hot in the set data structure do you the answer to that is no because if you remember in a bfs algorithm whenever i visited the notes i used to mark them as visited but over here we are not using anything such as visited so what i will do is i'll say okay we got taunt so we will remove it from the set data structure now you might say but strava what if we get this in a future let me come back and explain you this with a very trivial example imagine in order to go from orissa to kerala there is only one particular way okay there is the shortest way because from orissa to kerala there will be one shortest way and the shortest way will have a length of three secrets right so tell me one thing from kolkata you went to orissa right and from there you'll take a distance like a sequence of three to reach kerala right so if odyssa is on the level two right will you take orisa again in some other levels for an example from kolkata you went to bangalore and then to odessa does it make sense to take odessa in this third step because you've already taken is in the second step and you know from the second step that is the minimum that it will take and even if you start from what from here it's again going to take three so if before you have got orisa before you have got redesigned you're taking three after you're getting odyssey again taking three that's better now once you've taken orisa there's no point in taking again afterwards because the lengths from modista to the last guy is three so if afterwards you take it's already a lengthier guy so it's better you do not execute orisa in the future so similarly i can say something like hot i'll not execute hot anywhere in the future because if i got that in the second step or second level there's no point in encountering them in future levels because from here i can travel wherever i wish to going from further levels will actually increase the length right done next i'll try to convert i to everything else till h z t but nothing will be there next i take t and i try to convert it so h i a h i v h i c h i d so until h i z none of them is in the word list so we do not take so we just got one and we have inserted that into the q data structure time to offer the saw next take the next guy from the queue data structure that is hot with a sequence of two so as of now i can say where can hot go let's analyze so we need to change h be like a oh sorry e o t b o t c o t d o t so on till z o t and you'll get dot and you'll get plot you carefully see you get lot and you get dot so you can actually go to dot with the step 3 or you can also go to lot with the step 3 because both of them do exist so when you go to dot you just erase it and you put them with three and when you go to lot you raise it and you put them with a three so since we can go to dot and not we will remove them dot is removed and i'll put that into the queue next i'll get lot so lot is removed and i'll try to put that into the queue data structure so can i do anything else let's uh try it out we can change this o so h a t h b t h c t h d t h e t and so on till x t none of them is there so next i'll change uh t h o a h o b h o c h o d h o e and so on till h o z none of them is there next nothing so what i can say is we got it so this traversal of the queue is complete what is the next thing let's get dot of three so dot of three now let's try to change again so we have d let's try to change d so it'll be like a o t b o t c o t like d ort until z o t none of them does exist in the word list next i'll change o so i'll get like d a t d b t d c t d e t none of next i'll try to change t so it'll be like d o e d o b d o c d o d and so on d o g so dog does exist if you carefully see dog does exist so what i will do is i'll take that yes i'll take the dog so i'll take the dog with a step four and i'll try to insert that into the queue data structure with a step four what is the last word it was log not dot so done nothing else is possible next take lot3 outside let's see what can we make lot3 let's try to change l aot nothing possible let's try to change oh lad lbt lct ldt so under lzt nothing is possible next t l o a l o b l o c l o g log is there so you can take it to l o g but step four removed log with step four perfect next dog of four dog of four so as of now can i say if this is dog of four thereby when i try to change this d i mean like a o g b o g c o g and we see c o g is present here so we insert cog with a five step you can stop over here but i generally do not i just want to explain you so cog5 is there done cog is removed now this is the point you'll understand someone reached c o g with five but the next time when the q tries to get this up l o g four and tries to change it will actually get something like cog it'll actually get cog because of this l when this l gets converted to c it will get cog but there is no cog in the world list because you've already encountered cog this is what i was trying to explain once you have got someone it will take its path why will you again visit that path so this is how the set helped you if you erase it from the set there will be no further occurrence of like cog5 otherwise you'd have taken cg5 again and would have kept on going so that is how the set helps so log cannot be made into anything next time when you do an uh extraction from the queue you get cog with five so your end word or c or g the word that you get from the queue is cog and the steps that it took was five so your answer boils down to five yes your answer boils down to five and this is the answer that you will return and imagine if the cube becomes empty you have tried out all possible changes and you never ever reached the end word during the extraction from the queue then you can after the end of the queue you can return 0 which will be your particular answer so you have figured out what is the algorithm that is required to solve this complex problem so i'll be coding the c plus in the right and if you have anything tactical issues related to java you can watch it out on the left so we have a start word we have a target word and we know we need a queue which is going to store a pair and the pair will be having a string and an integer this is the queue that will be defined and we know we always start off with the start toward and the sequence length is one and we know there will be a set right and this particular set will always have this particular target word so it's uh sorry the word list so you can always write something like this in c plus it's a very simple thing you can just write this and that will take the entire vector and put it into this particular set data structure you can use the unordered set it takes amortized time complexity of uh one big of one but the worst case is still being co-open but the amortize is we go off co-open but the amortize is we go off co-open but the amortize is we go off one so we'll be using an ordered set now you remember whenever we pushed something into the queue we marked it as visited so we can always use visited as deleting from the set so we can say that okay can you please go and delete start one so if it exists it will delete the start word from the set this is done what's the next thing is very simple we say we will iterate till the queue is not empty so go ahead wait till the queue is not empty done what's the next thing that you do you say okay give me the word so can i see the word will be very simple q dot front dot first i organized these steps or the length will be very simple again q dot front dot second once you've got it from the queue can i say q dot pop is what you'll say take it out of the queue now every time you get a word for every character you're doing a change for every character so what you'll do is okay for every character i'm doing a change so can i actually travels to all the characters i can so let's traverse to all the character which is something like this right now every character is nothing but can i say uh the character alphabet or original there's nothing but modified this is the character that i'm looking to change so can i say what am i looking to change i can change it from a to z so can i see i'm looking to change it from a to z this to this so every character what i is what i'll replace so i'll say would i can you get replaced by ch every time it comes up it gets replaced by a new character first time let's imagine the word as just imagine though what do we had okay so what will happen is for the first time original we'll have something like h right so this what i will be like instead of h it will be having for the first time a80 next time b80 next time c80 this is what the internal for loop will do is this is what the internal for loop will do so you will be changing the values you'll be changing the values now what is does that value exist in your set so you'll be like okay center find does this word exist and if it does exist then it will never be equal to n because if it exists it will always like if it doesn't exist it will be pointing to it this means it exists in the set it is the count as well uh so done what's the next thing that you'll do if it exists what way are we doing we're saying okay say market is visited which means do this tell the queue this guy is there with an increase steps done once you have pushed back into the queue make sure you replace it with the original y because over here you're always changing so the last moment the word why what i will always have z or z so you need to make sure that it gets back its original value so this is what you'll do right and over here can i say every time you're getting a word can you just go and quickly check if that is the target word can i say these are the steps that i'll take again you can write it over here as well over here also you can have a check but i usually prefer keeping it over here and then we can return a zero saying in case it did not find in case it finds it in return the steps otherwise a zero this is how simple the code is so if compiler it is working now let's quickly try to submit this so when we submit it is running absolutely fine so this is how we can easily do this particular thing and you might uh ask me about the time complexity and something i know for sure is whatever the word length is word length into 26 these things are running for what length into 26 like whatever your word length is because they have already stated all the word lengths will be same so whatever is your word lengths into 26 is the internal loop now how many transitions will you do at the worst case you can do a lot of transitions but if you carefully think can i see the number of transitions you can carefully see one two three four five six can i see the number of words over here will be the number of times it will go into the queue at the worst case because if it is not in the set of words it never goes into the queue so can i say the queue will run for n times the number of times the words are because that is only when it gets into the queue otherwise it will not go so can i say the complexity is n into word length into 26 every time can i see this i can definitely say that you're using any extra space yes you're we're using an ego of n space to store all of these things into the set and by the way there's a logarithmic factor if you want to include it for set if you're assuming that your hash set works in big o of one but then you can use bingo of one over here otherwise you use a logarithmic if you're using something like a set you'll have a logarithmic so depending on what is the time complexity of a set this can vary so guys this will be the time complexity and the space complexity for this particular problem i hope i was able to explain you just in case i was please make sure you like this video and if you're new to our channel what are you waiting for i think it's time that you hit that subscribe button and if you haven't checked out our dp series and the hd sheet and you're missing out on a lot of content the links are in the description please make sure you check it out and yeah with this i'll be wrapping up this video let's meet in some other video till then bye take care ever forget you're golden
|
Word Ladder
|
word-ladder
|
A **transformation sequence** from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that:
* Every adjacent pair of words differs by a single letter.
* Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in `wordList`.
* `sk == endWord`
Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return _the **number of words** in the **shortest transformation sequence** from_ `beginWord` _to_ `endWord`_, or_ `0` _if no such sequence exists._
**Example 1:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log ", "cog "\]
**Output:** 5
**Explanation:** One shortest transformation sequence is "hit " -> "hot " -> "dot " -> "dog " -> cog ", which is 5 words long.
**Example 2:**
**Input:** beginWord = "hit ", endWord = "cog ", wordList = \[ "hot ", "dot ", "dog ", "lot ", "log "\]
**Output:** 0
**Explanation:** The endWord "cog " is not in wordList, therefore there is no valid transformation sequence.
**Constraints:**
* `1 <= beginWord.length <= 10`
* `endWord.length == beginWord.length`
* `1 <= wordList.length <= 5000`
* `wordList[i].length == beginWord.length`
* `beginWord`, `endWord`, and `wordList[i]` consist of lowercase English letters.
* `beginWord != endWord`
* All the words in `wordList` are **unique**.
| null |
Hash Table,String,Breadth-First Search
|
Hard
|
126,433
|
587 |
hey everybody this is larry this is day three day third day of september hit the like button hit the subscribe button join me on discord let me know what you think i will be doing this all month and maybe beyond anyway today's problem is direct defense um i usually solve this live so if it's a little bit slower awkward um you know watch it on your own speed uh maybe 2x if you need but okay so you're given trees you find a minimum fan said okay so this is just exactly uh what's it called convex hull uh n is 3000 so you at least in python probably you cannot do you have to probably do a n square algorithm oh sorry n square algorithm isn't fast enough so you can't do something like i mean gift wrapping is technically n squared or also technically is n times h where h is the size of the um the whole um they also like n log n and like h algorithms um divide and conquer uh what's it got uh mono chain algorithms for it um but to be honest no one is going to um excuse me but to be honest no one is coming out with dissing in an interview no one is going to come up with this like you know without already knowing it so either you know no you don't to be frank uh both in an interview and or maybe even a contest though of course unless you're on site you just google this because this is just silly but yeah um there are a lot of them i'm not going to go over too much because they're literally like there are as many convex whole algorithms as their sorting algorithms pretty much so you know i'm not gonna get into that much especially in a two-dimensional much especially in a two-dimensional much especially in a two-dimensional point of space um because you know it's just a very common thing like as often as you do sorting um as often as you do sorting uh you uh on a list of numbers you do a comic saw in computational geometry uh okay i'm gonna make um what am i what do i want to do for this one because this is a this is literally a textbook problem meaning you copied a code from a textbook or something um well i think i'm gonna do is that i usually try to remember if i can uh prove this from first principles uh or we do this from first principle so we'll see uh the one that i like to do is called mono um monotonic chain i don't know monotone chain kind of exhaust algorithm uh is it's one that actually relates a little bit to um to uh what's it called mono stack or mono q if you will uh the idea is that you calculate the top hole and then the bottom hole at the same time let me double check for a second uh okay so one thing that is um sometimes awkward on um sometimes and yeah it depends on what they ask because you want the comics hole so then you want to what is the answer that you want right you can either have the points on the parameter you could get the area which is a common one um and so forth um this one's also a little bit you have to be careful because on the perimeter um you know three points could be co-linear right three points could be co-linear right three points could be co-linear right and in that case or even in this case for example actually they tell you uh in that case then you have to return to like sometimes you can sometimes you don't depending on the problem so that's something that i'm thinking of as well um okay uh okay let's see so now we basically calculate the bottom chain maybe i mean it doesn't really matter per sec so yes let's do it um so we basically sort everything by the x coordinates so we sort everything by x so let's just say uh coordinates for coordinates of zero so then now we're going from left to right i'm scrolling up just because i'm trying to see if i can have a mental visualization it's been probably at least uh when did i learn this maybe like 2003 2004 and then after that i mostly if i need it and even then i probably only needed camerax or maybe like five to ten times ever uh in competition um so like every couple of years and every time i mostly already know or like i have the library that i've written before right so i don't have it uh so this is gonna be the first time i'm trying to implement it from memory so you know we'll see if we learn anything or if i learn anything or anything like that right uh but yeah okay let's just have a lower bottom we go lower upper whatever let's do a lower and then now for x y increase what do we want to do right so basically we're trying to find from going from left to right the bottom is the bottom mist and it's not just the bottom list but a point that allows you to um like there's no point to the right of that point right and there are actually a couple of ways to do it you can draw lines um let me see if i can pull up paint shop over here the thing that i remember from my day which i think people don't care as much anymore for whatever reason uh is that you can actually do all these sort of ints and the way that you do them with int is by doing something called like is left and then it's left is of course just like a um the course product right something like that but yeah but basically the idea is that okay you have some points on the field on the thing some points on the plane and then the idea is that now you're going left to right um and to be honest right now i'm explaining to myself more than anything um so yeah so then initially we have this point and then next point we can say at this point let me change the colors a little bit try and see if i can uh refresh this yeah yellow is terrible hang on uh the next one is obviously this point so then now we tentatively draw a line right um and this is going to be very similar to um like i said my uh mono stacks algorithm right like it's monotonic stack algorithms um yeah and you'll maybe see why in a second and next one we consider this here um and this one obviously is to the left of it so that means that it cannot be the bottom so then we skip it and then the next one we is here and then of course this is to the left of the previous line so then now we erase that line and then draw a new line right and then now this is no good maybe i should use a different color right same logic here oh i think i messed up a little bit i think um i think it was too early to say that this one was no good i think to be honest i think technically speaking sorry it's been a while um we would draw a line here and consider that as lower hull um but then of course now that we're here we try to draw this here um of course that's no good um because if you look at this line change color again because this line uh straight line please because this line is to you know um to think of this so then now we pop this one and then now again we do go next which is that uh this line is if you think about it from that perspective um you know you can get lower right so then now you get rid of this one as well um and then next one you go here you basically um go here because now you have a or maybe you could just do a cross product where you can clearly see that the triangle has a positive thing if this has a negative area maybe it has a negative area i mean i know that negative area is technically not a thing but assigned an assigned area maybe it has a negative area then you go up and then so forth and then yeah and then you're gonna eventually wrap around uh oh i guess i've skipped this one technically you wrapped around here then this gets popped off the stack and then you get here and here so roughly speaking i mean okay fine you go here pop off and goes here right so that's the bottom of the um chain and then of course you do the same with the top let's choose and so then you go uh this will pretend that this is the top and then here uh going this way is too bad so then we actually pop off and we go here and so forth and then we go here and then we pop that off to go here and then and lastly here and then now you have the top chain and the bottom chain right um anyways a lot of this is established literature so i know that i'm not doing quite perfect with this per se but uh but like i said this is from my memory from when i learned this um was it 2003 2002 you do the math how long ago it is and from here it's all memory so um so yeah okay so then now let's do lower first and then we go from left to right um the tricky thing is that i have to remember how to do the uh how to check whether uh we're going left or going to the right of course that's the signed area um i don't remember that formula though hmm and i do remember that formula but i forget whether it is signed or not because it is just uh the cross product of um so okay it's just embarrassing how bad i am at geometry um okay well okay first of all if is less than two then we just append x y and then we continue otherwise we get the area of a triangle right uh and then now basically we have ax a y is equal to two points back okay so we do this while length of lower is greater than or equal to 2. okay and then b x b y is equal to lower minus one and then x y is just the current but that's just for consistency sake uh for my because this is consistency's sake um it's been a while so basically it is the cross product um is i mean and this we only care about the sign so i know that is something over two to be honest um but um yeah just also to uh yeah i mean okay so it is how does that go again uh times b x plus b x times c y plus c x times a y and then technically is this over two i think um wait no i forgot the other path i'm it's been a long time so it's um what was this but it's minus um p x times uh a y yeah okay yeah that way uh hmm okay i guess we could do it both legs it's been too long um but i'm just trying to so what i'm doing in my head is just doing the diagonal thing in your head um minus ax times oh sorry yeah times c y i think this is right sorry i'm like taking a few more minutes to double check because i'm just doing basically the cross string for cross product uh okay that looks okay i hope i'm okay it's been a long time okay right so that's the area um and to be honest i don't remember whether this should be positive or negative for this one so we'll just i guess it doesn't really matter either we get the upper or the lower so i guess it doesn't really matter but uh okay uh yeah okay so um okay now what we want to do um we have to double check this of course later but um but let's just say if area is zero then what i always forget which way your cross product goes but anyway uh so let's just say if it is okay so this is less than 0 then we pop lower from the stack and then we continue otherwise we append cy and then we break okay maybe this is okay let's uh let's print this out real quick at the end just to see oh whoops time is of course maybe i'm thinking up to the pier okay is this reasonably right i don't even know what does this look like is this the well this is the input so one and then four one so this is probably uh or four two is this one on top uh yeah so we're probably going the wrong way maybe something is just wrong in general well it only it has two numbers because these are the first things that gets popped i'm thinking about how i should be sorting it correctly uh let's see um this is a little bit awkward now that i think about it because this could pop but then now if your popping is lower than whatever then huh um i think i need to put this here and then we just break early okay let's try again okay this is slightly better maybe oh the four two i think i confused two four and four two so now we have to lower i hope this is right i mean this look this is right for this input i believe but they're only like five points or six points so you can just get lucky um okay and this is also a degenerate case where this is a line um so for a line i might have to handle this a little bit differently i don't know how okay so this is the lower thing um we can also do it at the same time do the upper thing um we can do it at the same time to be honest but i think it's just a little bit clearer if i do it separately at least for me i mean you know uh especially as i'm proving from first principles uh but feel free to do whichever way you like um okay i'm just gonna copy and paste this part which means that i've done something silly but okay if i need to do this again i'll put in a function how about that and then in this case if area is greater than zero i'm trying to think about a case i think the there is a weird case where um i'm trying to understand whether i'm parsing these correctly or sorting these correctly i might i think well i'm actually relatively certain that i'm wrong um in the edge cases basically um if this is if there are two points that are on the same x coordinate i'm trying to think about if i'm handling them correctly okay let's print it out real quick and then we one obvious case is just like a box which is just say 0 uh one zero right so if we get the upper bound and lower or upper um chain and the lower chain corrector on this one then i'll be very happy uh i didn't print it anything so i don't know what i expected uh okay so the lower bound is zero one zero that's true upper bound zero one zero which is technically true but i think it just doesn't um feel too right for me um and you can also think about like a um a box with three on the side right that's not going to be correct so i think i have to handle it a little bit better and i have to think about how to handle that edge case so let's also do the do that case right of you know three by three say so yeah i haven't implemented this in a while but it's kind of fun did i mess up i no okay oh i did mess up it's kind of fun to kind of be able to prove something uh from scratch uh and i think i'm mostly there even though maybe not i mean i'm mostly there but the edge cases may be the other 90 of the problems they say uh okay so yeah so the bottom i needed to go all the way up right how can i be sure of this ideally so given a i don't even need to look at the other ones but given a three by three box and maybe i could bring back the drawbrush to drawbrush basically what i'm trying to think about here right now is that okay we have essentially a box right um and i want to make it so that my chain is consistently um everything from here to oops i even everything to up to here including this one and then my upper chain could be everything um here and including this one and the overlap just fine we can use a set to remove them but that's what i'm trying to figure out um how to make sure that i do um okay that's basically what i'm going to struggle with for now um okay if there were no uh co-linear points i if there were no uh co-linear points i if there were no uh co-linear points i think we're actually done to be honest um yeah but there are so we have to think we have to handle this a little bit better uh the only seven points no did i mess up nope i think their answers are wrong because there should be 8 on the perimeter because it should be 0 1 0 2 um and then it goes up and then one two yeah there's no one two you know that is on the point unless i messed up no it's one right here so i think their answers is wrong too or they don't handle the code linearity uh quite correctly um yeah maybe i could submit for extra points but um yeah pretty sure that's right or at least like in terms of what i'm saying uh okay so basically we need each one to have five points what so zero uh okay oh wait did i do the output first no i do the lower first i'm sorting by x so this is not doing so one zero got eliminated let me also just double check that i am live hmm let's check every state so that i want to see if 0 1 or 1 0 got eliminated along the way so it seems like did i mess up the sorting no oh i see because it uh it goes to zeros it the first two so it goes here and then here it goes right to do the area is less than zero shouldn't be stable should be exactly zero right let's print that out real quick okay we don't need y'all for now all right let's put in the bottom so that i could look at the one that i care about on top yeah so this is zero this is still two and then so this is what i expect on the bar where am i messing this up which one is x again x y so maybe i'm just mixing things up to be honest uh because now you have because my lower fingers going i'm just confusing my x's and y's uh to be honest and this is terrible because they did one that's symmetric no that's not true they have a two one so this is one two or two one or two zeros right so they have a two zero so so that means that this is going upward so this is actually my lower bound is an upper bound yikes um we can actually fix that though let's see what happens here so then now we go zeros hmm zero one so two and then now one um if this is lower bound this is very wrong let's see um okay so this is the so i draw it going up okay and then now we do one and as a negative sum or negative area as a negative area i messed that up so negative errors to do if it's zero we just keep going that's fine no so okay so maybe i had it right last time it's just that's just the nature of things going up because if that's so okay maybe that makes sense okay so actually no where did the one zero go did i mess up why is it one let me print that out i was just lazy about printing it but huh did i mess one oh i am dumb okay i was wrong about maybe the test cases being well i did mess up on the test case i put distance uh okay wow yikes i just put in the wrong input that's all okay maybe this is a little bit better now maybe this is better now okay so this goes up and then this goes down okay now i'm way happier uh well at least this part let's see let's look at this part um this one just looks awkward though so i think this is wrong the lower um thing is right maybe what did i fix okay so i fixed the lower frame i ordered i think the lower thing is lower chain is flexed to zero to here okay and then here this is just crack really well maybe there's one two yeah this is just really weird and wrong um hmm maybe the way i'm doing is funky let's actually do this the other way where we go backwards and then we uh we do the same things so then we're going clockwise is it clockwise i don't know anymore um okay let's see i guess i don't print the intermediate stuff for the upper but let's see so we start at the two zero we go to hmm how do i only get part of it wrong what is happening like how is that possible it shouldn't be mostly symmetric am i even confident anymore so we start here oh i see um this is not good enough because we have to also okay we actually have to sort no that's not true no this is good enough because this automatically means that in the same thing the y gets sorted okay yeah so we start at 2 that's reasonable 2 1 doesn't make sense for an alcohol in fact now we're just returning more or less than tie every number on the upper bound oh that's why i uh did i copy and paste this i guess so i was wondering like this doesn't even make sense like it should be wrong consistently okay there we go two one two zero one zero okay i wonder if my original code would have worked out too i think it should but i'm just gonna do it for science otherwise but not that much science if it doesn't work i'll just go back to what i was doing okay so zero it goes up and then okay um this one is the regular square 1 0 for the lower yeah i guess that makes sense do i still want it to go upper that would have a positive one why doesn't that work well why does that not do anything that's weird did i mess something up more and why does this look like this shouldn't it begin at one first point should be oh no i changed it back i forgot uh okay so then now it goes zero once up and then the corner but then why does it keep going or like it should be the sorting doesn't make sense here because did i saw it right oh i am being silly i poop i guess i'm glad i caught this i think what i meant to write is actually this um well or it's just something like this but because i did the worst of both worlds in which i left it out it just kind of treat everything as the same so it wasn't sorting by y at all so actually but because we're starting by x y in the natural order we can just remove it anyway okay there we go silly lady and then now we can just put everything in a set and i think we should be good um and it's showing the overlap in the corners anyway so yeah uh oh whoops i meant uh it's a little bit late in the day i mean i know that this video has been half an hour or so but i hope this is interesting just because um you know i like i said i don't know comic so in my heart but i am able to well okay let's actually submit before i say that uh but he's like conceptually i've been mostly able okay there we go yay i'm able to prove from first principles how to um you know how to solve this problem with comic so and i would also say that you know um you view my discord or even in my youtubes or whatever um one thing that i always advocate is just like don't do memorization right actually learn the principles and once you learn the principles you can come you know like just a little bit of detail like observations about each part and you're able to kind of re-derive everything for me for example re-derive everything for me for example re-derive everything for me for example like i said i'm just able to kind of wait is my thing blocking no uh just like using a chain like i knew i learned it enough the first time to go okay just like go back and then you just keep on you know hugging the bottom or whatever right um so yeah uh anyway so this is going to be the end log n because it gets dominated by this sword in the beginning um and of course this is just um you know using the stack every number is only processed or every coordinate is only processed once well once in the lower and then once in the upper so constant number of times each and linear number of time in total um yeah that's what i have hmm i mean i don't really have much to add because like i said this is a very textbookie problem um so like the literature is you know a lot so um so yeah but one just a few more fun things i would say is that there are a couple of very fun algorithms that are actually faster than this technically speaking um because this is n log n uh no matter what how many numbers are in the chain um but there are actually things uh there are actually algorithms that are output sensitive algorithms that uh means that the fewer your final uh points are in the chain which is the output uh or the sorry the number of points in the hole is h then you can solve an n log h time and this is obviously faster than n log n because h has an upper bound of n so there are a lot of interesting things there if you want to play around and read up on that literature um but that's all i have for this one you can check it out here lower upper um and then i did it this way because i don't know i think you can actually maybe reason that the first point and the last point should be the same but i was just lazy um but yeah uh that's what i have let me know what you think hit the like button hit the subscribe button join me on discord uh have a great weekend have a great long weekend for yao that uh in america's or labor day uh and yeah enjoy and i will see you later bye
|
Erect the Fence
|
erect-the-fence
|
You are given an array `trees` where `trees[i] = [xi, yi]` represents the location of a tree in the garden.
Fence the entire garden using the minimum length of rope, as it is expensive. The garden is well-fenced only if **all the trees are enclosed**.
Return _the coordinates of trees that are exactly located on the fence perimeter_. You may return the answer in **any order**.
**Example 1:**
**Input:** trees = \[\[1,1\],\[2,2\],\[2,0\],\[2,4\],\[3,3\],\[4,2\]\]
**Output:** \[\[1,1\],\[2,0\],\[4,2\],\[3,3\],\[2,4\]\]
**Explanation:** All the trees will be on the perimeter of the fence except the tree at \[2, 2\], which will be inside the fence.
**Example 2:**
**Input:** trees = \[\[1,2\],\[2,2\],\[4,2\]\]
**Output:** \[\[4,2\],\[2,2\],\[1,2\]\]
**Explanation:** The fence forms a line that passes through all the trees.
**Constraints:**
* `1 <= trees.length <= 3000`
* `trees[i].length == 2`
* `0 <= xi, yi <= 100`
* All the given positions are **unique**.
| null |
Array,Math,Geometry
|
Hard
|
2074
|
1,958 |
hey everybody this is larry just me going with q2 of the biweekly contest 58 check if move is legal hit the like button to subscribe and join me on discord let me know what you think about this prom and if you are here right after the contest come join me on discord because there are a lot of other smart people who uh and me who likes to talk about the contest right afterwards um yeah so if you're into that come check me out anyway so the table is uh this problem q2 is check if move is legal but this one is actually not that hard conceptually i think everyone gets it conceptually the hard thing is kind of thinking about all the edge cases and test cases and just doing it correctly implementation wise because you can they're definitely like a billion ways to do this incorrectly um but i think everyone gets the concept once you are fully awake and able to read it because i was just struggling with the reading for a little bit um and because this is an implementation heavy problem uh we'll go over my solution very quickly but the first idea the first observation is that well um well the first thing to know is that you need three or more cells right so that means that for whatever color that you're doing that there's the input you can either go up down left right and the four diagonals you have to find one of the opposite color uh and then keep going until you find one that's your color and you skip three spaces um i actually made a mistake where i thought i did something funky and then i took a long time to debug but otherwise i think i had to code mostly what i wanted to in the beginning um and this is my code and you see this directions thing happen a lot if you're new to the implement implementing these grid problems and it basically represents the x direction and the y direction as you can see here dxd right in directions um we start with the offset of one meaning that we're one space away i actually started on zero in the beginning which is why i messed up because i forgot to color this in i usually do but i think the reason why i didn't is because this is a list of lists of string instead of a character thing and i got confused but anyway but basically this is saying for each one of the eight directions and that's what's critical here is that um one thing that i would notice that i usually try to write this the exact same way otherwise you're gonna miss one and you know that's where things gets a little sad anyway um yeah so we started offset of one so we look at that direction and we just keep on going uh this is also a formula of okay we start at x we look at we get a direction and then we see how many steps we took in that direction um if this is our balance then we just break because that means that we haven't found something to be true um if we are in bounds then there are a couple of conditions right if i wrote it in a different way but if this is a free space that means that we out then again we terminate because they tell you to in the problem it's a it's an illegal move so we look in another direction otherwise if this is the same color as the color that you're trying to color uh this is the same color then there are two conditions right one is either this is farther enough away and we'll get to that in a second if this is only one step away then this is forced to re-break is forced to re-break is forced to re-break because again this it's not a legal move because we need uh we need a space of the opposite color before that and kind of i kind of did this is a little bit shorty way in that if this is you go to the opposite color it actually just breaks through so then we go to offset plus one and then we keep on doing that if it's of the opposite color until we reach a cell that is the same color and at least two offset away the assumption being that if this if the offset is at least two steps away that means that we executed this at least once and that means that there is at least a cell of the opposite color in the middle um yeah and in that case we return true if we checked all eight directions and it'll still be sad then we return force what is the complexity of this well this is gonna be o of n where n is the length of one side and of course that is eight so that is um yeah that is going to be o of n times 8 where 8 is the number of directions so yeah it's a little bit hazy but you could say this is of n where n is the length of one side which is you know sublinear and that you don't have to look at the entire board um yeah that's all i have for this one let me know what you think you could watch me solve it live and see my confusion as sadness during the contest next see messi okay cool type of white sun endpoint of a good line what does that even mean and this is too much reading and when you just wake up uh white input okay whoops choosing a free cell and changing the color you play with okay wow this is this has to form what is a bad line oh south africa okay i mean this is for you okay there's so much reading but it should be okay uh let's see yeah okay oh you still be better about this one nope so i guess it's always eight uh that's quite otherwise we keep going oh shouldn't we turn forth it should be quick true and true color white why is this wrong we oh three or more cells okay i did because i counted the two cell example that's why okay hmm actually not super confident about this well probably more so now that this is wrong so hmm why is this true six four okay i mean that's true but it looks at this stuff in the middle as well four five four what am i doing there's such an annoying part of it all right let's look at it one at a time why is this one so four three oh did i mess up the no four degrees right okay four three pack tries to go five four that's one five two as well hmm why is this not going away hmm i feel like i'm almost done but i've been very dumb about it huh i mess up somewhere why is this so weird so forth away my sister's not going up uh sorry friends i've just been very bad at debugging today i guess maybe it's good that i didn't compete on the contest okay this should be good oh i am being dumb wow no i am being dumb that's not right do you have to choose that as a legal move how was that human right okay so this is a legal move okay foreign i just have one typo i guess true force okay um whoops what a typo misunderstood the problem a little bit all right let's give it a submit not super confident either but okay fine it is okay let's do it hey uh yeah thanks for watching hit the like button hit the subscribe button join me on discord let me know what you think about this prom again you know if you came from the contest we like going through the contest right after contest so yeah contest so come join me on discord and hang out with me and other smart people i'll see you later stay good stay healthy to get mental health bye
|
Check if Move is Legal
|
ad-free-sessions
|
You are given a **0-indexed** `8 x 8` grid `board`, where `board[r][c]` represents the cell `(r, c)` on a game board. On the board, free cells are represented by `'.'`, white cells are represented by `'W'`, and black cells are represented by `'B'`.
Each move in this game consists of choosing a free cell and changing it to the color you are playing as (either white or black). However, a move is only **legal** if, after changing it, the cell becomes the **endpoint of a good line** (horizontal, vertical, or diagonal).
A **good line** is a line of **three or more cells (including the endpoints)** where the endpoints of the line are **one color**, and the remaining cells in the middle are the **opposite color** (no cells in the line are free). You can find examples for good lines in the figure below:
Given two integers `rMove` and `cMove` and a character `color` representing the color you are playing as (white or black), return `true` _if changing cell_ `(rMove, cMove)` _to color_ `color` _is a **legal** move, or_ `false` _if it is not legal_.
**Example 1:**
**Input:** board = \[\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\],\[ "W ", "B ", "B ", ". ", "W ", "W ", "W ", "B "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "B ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", ". ", ". ", ". ", ". "\]\], rMove = 4, cMove = 3, color = "B "
**Output:** true
**Explanation:** '.', 'W', and 'B' are represented by the colors blue, white, and black respectively, and cell (rMove, cMove) is marked with an 'X'.
The two good lines with the chosen cell as an endpoint are annotated above with the red rectangles.
**Example 2:**
**Input:** board = \[\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", "B ", ". ", ". ", "W ", ". ", ". ", ". "\],\[ ". ", ". ", "W ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", "W ", "B ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", "B ", "W ", ". ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", "W ", ". "\],\[ ". ", ". ", ". ", ". ", ". ", ". ", ". ", "B "\]\], rMove = 4, cMove = 4, color = "W "
**Output:** false
**Explanation:** While there are good lines with the chosen cell as a middle cell, there are no good lines with the chosen cell as an endpoint.
**Constraints:**
* `board.length == board[r].length == 8`
* `0 <= rMove, cMove < 8`
* `board[rMove][cMove] == '.'`
* `color` is either `'B'` or `'W'`.
| null |
Database
|
Easy
| null |
16 |
hey Dad is again and welcome back to another co2 channel today by the captain number one six and its recent closest it is another version threesome is here we can apply the same logic to it yeah so we have a way with target engines read now burning center route to sound we have to make sure that we ace must be here Madison Street that's the H case and when I start from the edges first one Matthew to get to stand until we find closest so you need to use mass absolute building function to compare first without idiot original without comparing hometown and guess what first so it's getting order easier pointers and and get updated Umbra absolute so on the closest and find a great tournament now they will have it's not the fastest solution but it works well subscribe people comment like share the video see you again next one
|
3Sum Closest
|
3sum-closest
|
Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.
Return _the sum of the three integers_.
You may assume that each input would have exactly one solution.
**Example 1:**
**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
**Example 2:**
**Input:** nums = \[0,0,0\], target = 1
**Output:** 0
**Explanation:** The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
**Constraints:**
* `3 <= nums.length <= 500`
* `-1000 <= nums[i] <= 1000`
* `-104 <= target <= 104`
| null |
Array,Two Pointers,Sorting
|
Medium
|
15,259
|
29 |
all right let's do a much hated question today at this question 29 divided two integers we have two integers divine and divisor we need to perform a division between this two without using multiplication division and mod so we're looking at addition subtraction and potential a bit wise operation like a shift so when you do shifts it's equivalent to multiple I and or divided by the powers of tools so we can potentially use that to reduce the complexity of the time complexity of the algorithm we need to return the quotients after the division and the quotients are truncated towards zero if we have 10 and divide by 3 we get 3 and 1/3 the final result after truncation is 1/3 the final result after truncation is 1/3 the final result after truncation is 3 the second example we have 7 and negative 3 the after truncation the result is negative 2 so we notice that the divide and then divisor can have different signs so based on the signs they have four different combinations if we have if out there are some different ELLs logics to handle the case differently there would be complex so I just look at 7 negative 3 if we divide 7 by 3 we get the 2 and our third after truncation would become 2 we can effectively convert this to a number into the same song and do a division and in the end plug back the correct sign before the quotients that will resolve be the same so just some simplification of code we can convert them posed to the same sign to division and plug back the signs some notes here blocking it so the both numbers are 32 bits signed integers and assume that we are in an environment and we could use only use this integers so the 2 bit integers signed integers so if the code has kind conversion from signed into integer to unsigned or using long it's violating this requirement actually notice this range of integers for the city to be signed integers it's a negative two to the thirty one to two to the thirty one minus one so we have one more number in the negative side and if we divide this negative two to the thirty one by negative one it will overflow because the in the positive side the Maxima is one less than the you know the division result from divide this minimum integer by negative 1 so you will overflow in because of overflow we're gonna return this the maximum integer as the result so we're gonna have some code and you beginning to handle that overflow situation and this also tells us that if we indeed compare post number into the same sign we need to convert them into the negative side that's because if we have divided and then divisor to be this minimum integer here if we convert that into the maximum you will overflow and caused the population to be problematic so that's pretty much the question just on the notion of quotient so the quotient is basically the number of times we can subtract the divide divisor from divided if the other same sign so let's say if we have ten three we can subtract 3 from 10 three times before we couldn't do that right we would get a 1 in the end and one is less than so we couldn't do one more subtraction so if we just do that kodada heuristic in encode it would be linear time with respect to the number of times we can do subtraction which is effectively the absolute value for the quotient so that will leads us to a linear time algorithm and we were trying to optimize from at that point so let's first code the question with the linear time algorithm because there lates the fundamental foundational code blocks for the further for this problem and we will try to improve that you know the first phase linear then what the improvement we are looking at has tried to bring the time into log territory we're gonna talk about that later on as well so just a just you know come to this heuristic if we can if we convert both number into negative the times that we can subtract the visor from divided is that the divisor divided that it's less than divisor so the it has a larger absolute value compared to divisor and then we just do one subtraction and increment quotient in and we will turn the quotient in the correct sign so to get the side or just see if and only if a one of the system number is negative it's a boolean flag let's user exclusive also only if and only if one side is true this is true so that handles the sign and we need to do the conversion if it's positive we convert that into the negative sign otherwise let it be we do the same thing for the divisor as well and in the word beginning we'll handle the overflow edge cases we're probably gonna add one more line to make this a little bit faster okay so that's pretty much the linear time algorithm okay let M be the correct absolute value for the quotient the this loop is order of n towards that would basically increment from zero to get to the end here so that's pretty much the time complexity for this algorithm it's a naive first to try so we want to look into how we can speed up this process so instead of subtract by this divisive number we can actually try to subtract a multiple of the divisor we can do that by trying to double this divide they have an accumulator initially to be the same amount of divisor but try to double it every in every iteration so that can so in the end the we let's say that we have like surge 363 / - instead of have like surge 363 / - instead of have like surge 363 / - instead of subtract - every time we would do we subtract - every time we would do we subtract - every time we would do we would just consider 2 4 8 16 32 until we couldn't double the accumulator so that's gonna be improvement so the code will be the termination criterias are still the same we're gonna try to subtract a number for undivided until we couldn't do so instead of subtracted by divisor we're gonna subtract it by our accumulator so we need to initialize that here actually inside here so the condition for this we want to double this accumulator every time and this I hear just you know keep track of how many times we did the double so we could increment or a shift by one it's the same that's just the condition here is that the accumulator when we do the doublings it's still smaller than the divide and in the absolute value kind of sense and we don't want this to be overflow as well so we don't want to double to be overflow as well so we compare that with a half of the intermediate in miniature minimum integer so the logic here is that we shifted the minima integer towards right by one so that's a having it so we know that when we double this we were not gonna be overflowing and we don't want to overflow this dividend as well divide and as well so that's the condition we're just trying to double this accumulator every iteration until we couldn't do so anymore that's the time we do the actual subtraction we increment a quotient by the I here so that's a improvement on the linear pass algorithm the time complexity for this can be a little bit tricky I guess so we are essentially reducing the number from 32 to 63 231 and 215 - seven I guess so the number of times - seven I guess so the number of times - seven I guess so the number of times we done this is going to be log of n so that's the outer loop but inside that it's another log as well so you know we started with a divisor and double it every time until we reached the divided number so in the worst case you know which is the very first iteration of the inner loop it's gonna be log n multiplied by log in roughly is so it's a log n squared worst case so I think it's it should be just I'm not proving it I think it's by a quick reasoning it's less number all right so it's not entirely logging yet but it's much better than the linear time algorithm so let's just look at this code and see what the redundant work that where can we still cut extra work that's I think that it's quite obvious that we in every in the loop here we start that accumulator by this divisor number and just double it every time the other way of doing that is to figure out the maximum accumulator that we're gonna be you know being able to get still within the divide and for each in the loop here instead of starting with zero we're actually gonna have in the accumulator that would be just having the number will be just shift as this accumulator by two to us right by one we don't need to go start from one two the maximum accumulator in every inner loop here that will reduce the running time from square to you know strictly login so let's call that just do that improvement as well so instead of directly go to the loop who will try to figure out the maximum accumulator if maximum month we can subtract from the TV Department it's gonna be the same code as here except we just do that once I should just copy it yeah it's the same but for I it's the same answer is always going to be positive numbers let's leave it there and then we're gonna do the actress abstraction so we have to do a condition testing here because every iteration inside the wire loop we can have the accumulator I have but after we do the having we can still be larger than the divided so we need to do a testing only if we can do the subtraction we do the subtraction so it's effectively moving this divide and this updates inside this condition and then we do the half we have the accumulator as well as happy you know the counter I here so this is the improved code it should be longer because the inner loop here we're doing this shift this - it takes at most a 32 this shift this - it takes at most a 32 this shift this - it takes at most a 32 or 31 32 shifts to make this accumulator from the number into zero so that's pretty much so we effectively multiply 32 to the log N and since there is constant it's kind of a constant that's this algorithm is constant so that's the rush the code let me do a quick check to see if we have problems this beginning here we handle the divide on being the integer minimum and could potentially overflow here this is just I'm not sure if we'd need this line let's just keep it here I would try to remove it later on to see if it works if it didn't then there must be some modification to the body here that can handle this just a saving simile to me I can immediately return a result for this educates that's why I put it there the this gets the sign and this converts the number both of the number to be negative quotient that's initially zero then we try to figure out that the maximum number we can subtract in the rare first I Inc with a loop here and then we just try to subtract the number from the divide and until we couldn't do that anymore each in the loop here we do a testing and then do a shift in the end we'll return the quotient in the correct asana so it looks right to me let's submit to see if it works okay yeah it's working all right so that's this question I actually don't think it's that bad and it requires you some reasoning actually and thinking about how you can improve something that's linear so you go to log territory by try to reduce the number by half each time instead of decrement by one so that's very much the this question so bye for now
|
Divide Two Integers
|
divide-two-integers
|
Given two integers `dividend` and `divisor`, divide two integers **without** using multiplication, division, and mod operator.
The integer division should truncate toward zero, which means losing its fractional part. For example, `8.345` would be truncated to `8`, and `-2.7335` would be truncated to `-2`.
Return _the **quotient** after dividing_ `dividend` _by_ `divisor`.
**Note:** Assume we are dealing with an environment that could only store integers within the **32-bit** signed integer range: `[-231, 231 - 1]`. For this problem, if the quotient is **strictly greater than** `231 - 1`, then return `231 - 1`, and if the quotient is **strictly less than** `-231`, then return `-231`.
**Example 1:**
**Input:** dividend = 10, divisor = 3
**Output:** 3
**Explanation:** 10/3 = 3.33333.. which is truncated to 3.
**Example 2:**
**Input:** dividend = 7, divisor = -3
**Output:** -2
**Explanation:** 7/-3 = -2.33333.. which is truncated to -2.
**Constraints:**
* `-231 <= dividend, divisor <= 231 - 1`
* `divisor != 0`
| null |
Math,Bit Manipulation
|
Medium
| null |
1,751 |
hi guys good morning welcome back to the new video and firstly if you want to get the intuition please give the next 15-20 the intuition please give the next 15-20 the intuition please give the next 15-20 seconds which I'm gonna tell if you had done this then please try it by yourself so if you have watched our complete tpn tuition playlist wherein in which specifically if you have watched he used to then please try it by yourself because you can't do it let's start the question itself uh so basically it says that the maximum number of events um that can be attempted to so basically an event is defined as what a start and end in a value so the event has a start day uh n day which means if I do an event then I will do it from Saturday to end day and the value earned by attending that event is this event value which I have in the third argument of this event array now um it just says multiple things now we are having okay a number K itself which just says that okay maximum number of events which I can attend so I can attain at Max key event now what I want to do is I want to return the maximum sum of values so values is this sum which is in every event itself um that I can receive by attending all these events and you know that I can attain at Max K events now adjust one note please mention it because please remember it sorry that um the end is inclusive which means um that I cannot attend two events where one of them starts and the other one ends at the same day which means that you know it start it's in its value right so if the one events end at two so I cannot start with one event starting at two itself because it will in the picture it will look something like this one two even ending at two even starting at two so you know that it is overlapping right so I can start with the next event starting from three and not two so please make sure this thing is very important now as we look at the example itself it's very clear okay the one event is this uh one event is this right so ultimately if I just want to maximize my value I will just take this event which is having value four this event because it is having value four I can take at Max 2 even so I can have both of them and for sure the value earned will be 7 which is the maximum possible uh as we see this picture itself we can get to know one thing okay I have multiple such events now out of them I will choose a few of them ultimately in the last which means a few of them will be taken and the remaining will not be taken because it won't give me that value or maybe they are overlapping so out of all a few I will take and a few I will ignore now as I am seeing the picture itself and okay a few I will take a few I will ignore so one thing can come easy in my mind is I have two options either I can take an event or I can ignore an event as soon as this picture came in Taken even ignore an event simply it will just infer us think of in the knapsack way which means we will write the recursion and then ultimately we'll see okay bro um it's a recursion and we know that take it leave it's an it's a kind of an abstract problem so for sure and that's the reason in the last I specifically showed you that if you had not what watch The Deep intuition building playlist in this intuition is being built it's not the standard vehicle I will teach you in abstract no I will teach you how to think of okay if this doesn't have a problem or not right and specifically in these you will see that happening so that's the reason I specifically mentioned let please go and watch that now coming back to now you know it's an absolute problem it will take it now it will leave it now as we know it so people have the blood cells now you know in the start see now I will teach you the flow of how to think of a recursion that okay I know the recursion is being applied but I cannot build the recursion by myself please don't think of building recursion directly think of what is happening what we do what you require now when I say take it when I say leave it now you will be taking what taking an event now you have an array of events right see please think in picture you have to take what you have to take an event even you have to In and Out of all the events and all the events as in you know the array of events where event of IE event of ie2 and like so on support so basically you have to go at every event itself so for sure I can have an index to every event I have an event array where every event is something like this now I have to go at every even which means if I could take it or if even if I ignore it so I have to take what and event itself right so take an event I will represent that okay by the position or buy an index anything you want so if I take this event then what ultimately I am taking its value so if I am at this position event and I am taking it so I'm taking its value which is at the second index of this position even now okay it is I'm taking it but is it done am I done to take just one event no I have to read the entire thing so I will just go and ask my question hey bro I took this event which is at the position now go and see what is the maximum you can bring because for short I am just reading the question itself what is the maximum you can make I am asking my question and I'm not writing exactly education I'm just thinking okay what kind of something I can write in my recursion I just go and asked him hey bro you will add something as the value of this event because you are taking this event and ultimately I'm going to ask a question bro hey bro whatsoever you can bring me from the next index what's the next index you will have bring me anything which is the maximum I can get but you also know that I have to I have grabbed one event so for sure remaining number of events are nothing but K minus one so buy this is making this thing I get to know okay my DP states are one thing is position other thing is K because as I go on and take every position every index or every of this event then as I am going on taking it my K is being reduced so the impact as soon as I'm taking it or leaving it the impact will be on the position and on the cape so I know these two things will be impacted so it is in my arguments of my recursion and for sure as I am taking the position next I can grab off is at the index I and that can be anything which is a possible now as you go on can I just go and start from the position plus one simple why you take the I why not position plus one because if you take the position then start for the next position but I will say wait hold on if you take this event then it was a condition to take the next event it should start off with ending like it should be more than if the if it is let's say two so it should start off with three or more so that is one thing that you have to take off you have to take care that okay this I is the next possible index you can take but the next possible index I can start from going on in my array and see here I did a position plus one which means if I have the events like this one even next event so if I'm at this position let's say okay if I'm at this position then I'm going on and checking for the remaining positions in the right why not in the left because ultimately it just means earlier I would have sorted my entire events so that it is sorted in the ascending order of your start and if they are have a start same then for sure it will be sorted in the ascending order of their ends so by this I will only go and check for the remaining part if you don't want to sort it no worries go and check for the entire again and it will keep on repeating and you will never issue an answer so now you know okay I will just go and Reduce by shrink my size from position plus 1 to n but in that also I will start from that event which is having my events of I of 0 which means my start of that even which is of the I8 index it should be more than the end of my current position which is the current position of one it is the end it should be more not equal it should be more than my start then by this I can easily say and go at this index and start from that index later on because if I have taken this position the nearest index I can take off this is this I and you will see I'm just going one going on as soon as I will just grab this first I will simply break this because it I just want okay if I grab this position as an event in fact the others even what is the next nearest event I can look for and start my recursion so by this you know okay you will and see it is something you thought of later firstly assumed okay my recursion will land on to some index after taking it and I will look at that I will look at the sickness later on let's leave it but you can also leave it you can just think of letters so please break this in the steps now what if we do believe it simply if you leave it okay you leave the position you leave the event at the position so for sure no value will be added and simply you will start from the next position itself no because no boundation on the next position you can start from the position plus one itself so start from the position one plus one itself and for sure I never used any of the event so for sure my cable also remain same that is how in this picture up till so far initially we thought okay what to add if we take it then for sure we go to know what is the arguments what are the arguments which I actually required because I started with the one argument simply position but then as I was taking it I realized okay I need another argument as well which is K with this I realized okay I need to add the value Okay add the value I will go and ask my question okay what's the next index you can start off with because it cannot be just position plus one it needs to be some specific index so I simply go on and find that specific index which is after my position and to get after I need to sort it first so I just simply went back and in the starting itself I will just sort my entire array done by this you know okay it is a flow that's a reason a specifically told you to flow that okay how to think of recursion problem itself now we just have got the recursive cases not base case not anything and not the related return that's the reason start off with actual recursive cases now simply going on and we will start writing the recursion itself now to start writing we just got to know one thing we have to firstly sort my entire even sound because you know if you're at position you have to go and look for the next so as to shrink your sizes cool but yeah you also remember I'm writing the recursion But ultimately the back of my mind I know I need to memorize this why because I know it's an acid problem cool I sorted it I started with these will remain same no worries the main arguments are nothing but index which is starting by position represent my position and for sure my K which I can take any I can take K events for sure now comes the base case right when will you stop ultimately you know one thing if you're see what you have to return is what is the maximum value will only be added if you have something and no you know the argument is position or a key so any way you're gonna end either position or okay so if the position has extra has reached the end it is greater than equal to n which means it has reached the end for sure you cannot take any more event first or the event will return simply a zero which means a value it will return is a zero you know you have to return the maximum value so if it has reached the end returns some minimum thing which will not affect your answer because you know that you are adding in your answer so return something which will add in your answer and it will also not effect it should be minimum it should not affect your answer and it should be like adding something because you have to add something so either I can return an entry minimum because it will not affect my answer because I want maximum but no it should not affect my answer also because I am adding so I'll simply determine 0 that's the reason see now in this case you know okay I have to return something minimum because I have reached out of my bounds and I am taking maximum so I can do inter minimum also but I remember I realized I'm not taking anything as this comma this I'm adding it so I should add something which should not affect my answer and it should be minimum so I simply added a zero that is you know okay as you have reached the end or if you have no option to take which means you cannot take any event which means k equal to 0 simply it as you zero that's how you got the base case now simply as we told off that if we take this position so the next index I which I can take is simply going on and checking okay if the end is more than the start simply take this particular index I which is saying okay ultimately RN you have two options either leave it which means start from the position plus one k will remain same or take this even which means the value will be added of this and simply going on with the I which we have grabbed above and simply as we have reduced one so simply K minus 1 and taking the maximum out of these two options that is simply returning my actual so you know that you have to return the maximum value now ultimately you know what's your equation you have to memorize this simple three-step memorization initialize your three-step memorization initialize your three-step memorization initialize your DP with n plus 1 comma K plus 1 before actually going on to the recursive part just simply ask hey bro have you found it which means if it is you have found it simply return that and before returning simply put that in the DP that's how you can simply do it but if you look at the complexities n into K into n but the big question mark in this question is they have given the complexity of Simply n into K which is 1 E6 they have not specifically given what is the n bounded at it can be One E3 also it can be one E5 also if it is verified it will fail if it is 1 E3 it might pass if it is money too it might pass so if it is one E2 or less it might pass so for sure you if you will try to push it if you try to submit this particular code it is n into K into n because of this particular Loop which we are doing in the worst case it can go up till n or itself and the DPS itself the recursion itself is a n to K so for short for sure in the worst year it can go up to n into K into n and into case itself one E6 so considering that this is passing in the actual use case it can be either one E2 or something lesser but is it actually good to actually assume this maybe we can optimize it also so yeah it is the first thing which you can tell in the interview but then as you will see okay n is not bounded in the question so we are very like they're not sure but still we will try to optimize it if you think of optimization what we can optimize this no because we know we have it's actual abstract which it's already optimized we cannot optimize it we can maybe think of something in this what's happening first I'm going on linearly but you also remember one thing in the initially you what I am saying because I was at these events right I am at this position event now I want to go and look for some event I and you also remember that so as to not go back again and again in the entire uh events array you just sorted it down so that you will only get the right part but even if sorting it down okay sorting it down and doing a search for the next event sorting searching binary search simply if you know it is sorted you have to search for some element more than this particular event simply why not I can simply apply binary search so rather than this which is actually linearly searching I can simply go and apply a binary search for what simply you know one thing if you had an event currently if you take this event which has some start ending at two and has some value so the next event I can take is I can take a two no I cannot I can take some even starting from this which is more than my actual this particular start so what I can do is I have this entire events one events entire events array I will from this particular thing I will go and say hey bro I will make a mask or kind of a temporary something like this as two comma inter Max comma into max and I will go and ask anyone who is more than face value he should come in first so I will go I will do a binary search in this entire events and for sure you remember events is assorted events are sorted I will do and go and do a buyer search and will tell anyone who is more than you like you saw one thing it was the end I made attempt vector starting with two but then I also put as interbox impacts why it can happen that okay if it is a one if it is a two it can happen that okay or something like this it comes in two and uh let's say three and three so if I take as anything into minimum or a zero then for sure it will come in next but I know the thing that should come in should be more than two so and I also know that okay I can do something else more than two so I'll take the rest of the argument into max so anything which is coming in more than and I'm taking upper bound which is more than this value anything which is coming more than two interested index will actually start from three or above or you can also take it as three which means uh if this is a start you can take it as start plus one intimate and then you can do a lower bound so that anything greater than equal to this will start from this so anyway you can take it in this example I just took this as a start so I take this start into max into Max and do the upper bound to get a next higher value and next higher value will always start from three and something so I will take this and simply get this by simply losing your binary search which means I will make a temp as simple that end which I showed you it's an end right it's an end and into max so when I'll do upper bound on this particular temp I'll simply get the index but you also remember the range which you will start from because you know okay it is if it is a position the next range you can start from is actually from the position plus one right although you can take it as the entire uh entire itself from zero to end but yeah it's just you are making the range shorter in the question itself so it may much it might be a little bit faster so what I can do is I can start from the search from the position plus one itself so in this you will see that okay we started from the position plus one as the search engine although it won't hamper anything in your code you can simply start from events or begin also because it just simply acts like a very slight mod a very slightly Optimizer very slight cool by this you can simply get the index by simply using a binary search rather than using a linear search and by this what will happen is you can simply modify this code in this where you are searching linearly now you will search do a binary search and buy this you can simply get the answer and for sure you must remember you have sorted already by this a simple rather than a login Factor will come in picture and for sure even if n is 1 E6 or maybe 25 still it will be very less thus it will for sure pass but in this example of lead code currently both the approaches which means o of n into K into n and also of n into k n to log n are both passing and the biggest uh you know the kind of surprises you will see that the runtime of n into K into n with the it shows okay it is faster than all these numbers of all these percentages it is showing much faster in that o of n into K into n v and it is showing a bit slower but yeah actually technically it is much faster or I need to K into login cool by this you can simply solve it the code is down below and for short please go and utilize the intuition building playlist it is not your actual going on and studying DP it is actually going on and building the intuition of firstly how to think it's a DP problem and again if it's a it is a d problem then how to think of the base cases recursion all that stuff so please
|
Maximum Number of Events That Can Be Attended II
|
slowest-key
|
You are given an array of `events` where `events[i] = [startDayi, endDayi, valuei]`. The `ith` event starts at `startDayi` and ends at `endDayi`, and if you attend this event, you will receive a value of `valuei`. You are also given an integer `k` which represents the maximum number of events you can attend.
You can only attend one event at a time. If you choose to attend an event, you must attend the **entire** event. Note that the end day is **inclusive**: that is, you cannot attend two events where one of them starts and the other ends on the same day.
Return _the **maximum sum** of values that you can receive by attending events._
**Example 1:**
**Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,1\]\], k = 2
**Output:** 7
**Explanation:** Choose the green events, 0 and 1 (0-indexed) for a total value of 4 + 3 = 7.
**Example 2:**
**Input:** events = \[\[1,2,4\],\[3,4,3\],\[2,3,10\]\], k = 2
**Output:** 10
**Explanation:** Choose event 2 for a total value of 10.
Notice that you cannot attend any other event as they overlap, and that you do **not** have to attend k events.
**Example 3:**
**Input:** events = \[\[1,1,1\],\[2,2,2\],\[3,3,3\],\[4,4,4\]\], k = 3
**Output:** 9
**Explanation:** Although the events do not overlap, you can only attend 3 events. Pick the highest valued three.
**Constraints:**
* `1 <= k <= events.length`
* `1 <= k * events.length <= 106`
* `1 <= startDayi <= endDayi <= 109`
* `1 <= valuei <= 106`
|
Get for each press its key and amount of time taken. Iterate on the presses, maintaining the answer so far. The current press will change the answer if and only if its amount of time taken is longer than that of the previous answer, or they are equal but the key is larger than that of the previous answer.
|
Array,String
|
Easy
| null |
51 |
in this video we're going to look at a legal problem called in queens so basically in queens the end queen's puzzle is the problem of placing a number of queens on a end times n chess board such that no two queens can be put to kill each others so given a integer n and this n integer value is between one to nine we turn all the distinct solutions to the end uh in queens puzzle so each solution contains a unique uh board and configure of the end queen's placement were q and dot uh both indicates a queen and a uh an empty space right so you can see here we have a 2d array and the size or the width of the board is n times n so you can see n is four so we have in four times four grid and then inside this grid we have you can see we have unique uh solutions you can place a queen here and then therefore there's no queen can be able to kill this queen right here right so you can see here for queens they can be able to move this way and also all four diagonals directions as well right and then you can see here that if i were to place this queen here there are no queens that can be able to kill this uh or can be able to reach to this queen right here right and you can see that's about one valid solution so we want to save it in a array in a list of uh string um and then you can see here we also have another solution right and you can see that for each and every single piece or each and every single queen they cannot be able to reach to another queen right so this will give us total of two distinct solutions uh to this four to the four queens puzzles as shown above right and then you can also see that we can have one if there's only one right if i only have like just one i can only place it here and then in this case the only solution that we can have is this right and because in this case we have to place a number of uh n number of queens in our grid so that's the requirement we cannot leave it empty like we cannot leave it empty and this does not count as a solution because we need a number of queens in our grid so to solve this problem is very similar to the solve sudoku problem basically what we're going to do is we're going to start at the very top left so the top left position is right here and then basically what we're going to do is that we're going to check right so to see if we can be able to place a queen here we have to check all uh in this case all the directions right so in this case all direction to see if there's any queens if there's no queens then we can be able to place this piece here right if there is a queen let's say we have a queen here right let's say we have a queen here then i cannot be able to place this piece here so what we have to do is we're going from the top to the bottom and if we see that we cannot be able to place a piece here then we have to leave it empty we have to move on to the next cell right and then basically that's exactly it and what we're going to do is that um we're going to each iterate each and every single row right to place a valid piece there and at the end right if we can be able to uh before we reach to the end of the board um if we can be able to place a number of peas then we can return the current board right so that we don't have to continue to traverse um if we cannot be able to reach and if we cannot be able to uh place a number of queens by the end of the board then what we had to do is we have to uh backtrack to the previous cell to see if we can be able to um skip or in this case to backtrack to a cell that um that has a piece there and maybe we can be able to put a dot there or put like a empty cell and then we can try it with a different option right so for example if i'm uh in this case so far i have one and i'm right here and in this case i can place a piece here right but then when i reach to the end i realize i only place two queens right so then what i can do is i can be able to go back so backtrack can i be able to um like don't place any queens here can i have a solution right so then if i don't place a queen here can i place a queen here in this case i can't because i have one queen right here that's blocking our way so what we had to do now is we have to keep backtracking all the way um to a valid solution in this case we can place a queen here right and if we place a queen here maybe then we can continue and then in this case we cannot place a queen here because this queen is uh can go this way right so then we continue to backtrack right until we found a solution in this case we can try to place the queen here right in this case if we place a queen here then we continue we can also place a queen here so now we have three right you can in this case we have a four by four so we need one more and then if we try to place a queen here that's not going to work because we have one here and one here so in this case we have to continue to backtrack to the original in this case you can see uh back to this one right here because those cells right here cannot be placed right so in this case we can backtrack this cell to this stack and then we can remove that queen and we can place it somewhere else so that we can be able to get a solution right so now you can see we can also have another example right for example if i place a queen here and then i can go this way right and then if i and then i just basically uh find the next cell that i can place in this case if i go if i place a queen here right then in this case i can be able to place it here and i have to continue to traverse in this case i cannot place it here because this queen could go here and all the way right so in this case i continue to traverse and then i found a blind spot in this case right here right this queen cannot reach to here this queen cannot reach it here so i place it here but then i realized like okay well i cannot continue in this case if i reach the end right these are dead spots right so in this case i have to backtrack and then in this case the backtrack we have to re we have to place this back uh to a empty just basically a dot right and then in this case what we're going to do is we're going to continue to backtrack if a the last piece was here so what we can do is we can just erase this and see if we can leave it empty uh if we can be able to make any changes right if we leave it empty then these spots are oh this spot is not open and in this case this spot is not open as well but this is open right we can try to place a queen here and see if we can be able to make any changes right so you get an idea and this spot is also open uh this is not open right and you can also see that uh this spot is open and this spot is open right so those spots are open but we can basically try to place a queen there and if we can't find a solution we backtrack and then uh until we find a valid solution right if we find if we can be able to find place a number of queens uh before the end of the grid before we reach the end of the grid then we can pretty much be able to add the current board onto a save it onto a result list right so now let's take a look at how we can do this in code so to do this in code uh what i basically did here is i um i first create a um grid right and by end grid and then i fill the grid with a dot right because the dot represents the empty so then i call this helper function we start at the zero position the top left and then we have a number of queens that we have to place and this is our board so at the end we're returning the results right in this case the result is basically the um all the valid solutions all the valid boards that we can place right so unlike the sudoku solver there's only one solution we have to uh you know try with all the solutions right so in this case we have to return a list of uh boards that are valid so you can see here in our helper function uh basically we first check to see if it's out of bound right if it's out of bound we're gonna reset we're gonna put column is equal to zero we start traversing the next row right so it's kind of like if we have a table here uh we finish the entire row right we iterate to finish the entire row then what we do is we just move on to the net uh to nest row right starting at the column zero so you can see here uh basically if i find that n is zero now like if i can if i already place a number of queens on the board then i can be able to add the current position i can add the current board onto the result um and then we can just return right um and then you can see here what we're gonna do is that if the row is out of bound that means that we basically should successfully traverse the entire grid so what we can do is we can just return right and then what we're gonna do is that we're gonna place queens here if it's valid right if we have a function check to see if this position is a valid position so just like i mentioned here i have to check this way so all the directions that queen can go right to see if it's valid we can place it here we just put a q represents the queen at this position and then we decrease the number of queens that we have left right that we have to place left and then what we do is we do a dfs just to move on to the next cell um to um uh do a dfs right and then at the end we're going to backtrack this current stack and then we're going to unchoose this position and then we're gonna uh revert the changes that we made right unchoose that option and then what we have to do is we can be able to try to skip the cell right it doesn't matter if we can be able to place or not be able to place the queen at this current position we still have to try uh to see if we can be able to skip the cell um to have to generate a valid solution right and this is very important because in this case you can see here uh like for example this one right here if i only place it if i don't do that if i only try to place but uh forgot to do the skip right then in this case i have to place the pong at the first cell and this will not give us all the solutions right so then what we do here is these are the sub functions like the two string uh basically i convert the chessboard to a list of string so the 2d character into a list of string and then i add it on and i return it as a list of string right and then here is the is valid function i just you can do a different way here but this is how i do it i basically iterate the top and down um to see if there's any position that does not equal dot if it's not if it doesn't equal dot then we can just return false because we found a queen right and then what we do is we uh we basically just try to search the top left the top right down left down right so this is the top left so in this case we're basically going to the upper level right and if it's not out of bound we're going to continue to search and then we're going to search the top right the downright and we're also going to search down left and at the end if we found a valid solution sorry if we be able to search all eight directions if there's no queens at all we can just return true right so this is pretty much how we solve the end queen's problem so there you have it thank you for watching
|
N-Queens
|
n-queens
|
The **n-queens** puzzle is the problem of placing `n` queens on an `n x n` chessboard such that no two queens attack each other.
Given an integer `n`, return _all distinct solutions to the **n-queens puzzle**_. You may return the answer in **any order**.
Each solution contains a distinct board configuration of the n-queens' placement, where `'Q'` and `'.'` both indicate a queen and an empty space, respectively.
**Example 1:**
**Input:** n = 4
**Output:** \[\[ ".Q.. ", "...Q ", "Q... ", "..Q. "\],\[ "..Q. ", "Q... ", "...Q ", ".Q.. "\]\]
**Explanation:** There exist two distinct solutions to the 4-queens puzzle as shown above
**Example 2:**
**Input:** n = 1
**Output:** \[\[ "Q "\]\]
**Constraints:**
* `1 <= n <= 9`
| null |
Array,Backtracking
|
Hard
|
52,1043
|
981 |
Hi gas welcome and welcome back to my channel so today our problem is to store the value of time waste so what is given to us in this problem statement here we have to implement a time waste key value data structure what to do is to implement okay Which is what will store for a particular key different at different time different value OK so here what we have given you in this time map is your class this is your constructed okay and a set A function has been given, a get function has been given, what is yours in the set function, what is the string is the value and the time stamp, it means that your value at this particular stamp of this key will be this much, maybe from to your If there are different times stamp, then there is different value, then you have to store it according to that, the value is fine, then you must have been given the get function, so it means here two arguments have been given that end time is for this particular key. The value that is on this particular time stamp has to be given to us by donating it. It is okay if we get it, if not then we will see for what time the time stamp is given by you, is it less than that, is it the one with less time stamp than that? How for B, if there is one, then you have to return the value which will be the largest among them. Okay, so let us understand it through an example. It is possible that you are not clear here, so let me explain to you through an example. What is given? Okay, so let us first understand the problem here. What is our problem? Time has given us a class, what we have to do is we have to implement it. Okay, we have given time map constructor, so if we construct it then there is no body type. It happens in the constructor, so what we have to do in this case is that here we have given our key, we have given the value and we have given this time stamp, we have to store the value for this particular key and on this time stamp, okay then you The get function is given, what is there in the get function, what is your key and time stamp, what is your value for this time stamp, if so, what will you do, if you return the value given, then out here. It will be your key, it is your time stamp, so here you have made 12 buttons right, then your gate function is there, it is kept here, we don't have it, we have just given the van, if it is not available. We will check that there are different keypad values, if there are any less than 3, then whatever will be the largest value here, there is only one value, so what will we do, we will return its value here. So it is given outside here, okay, if there was a four here, this would be the answer, okay, if you were there, this would be the answer, but if this was your four and zero, then what answer would you not be able to return because the van is greater than zero. There is no one less than zero, there is no one equal to zero and there is no one less than zero, so here is the van, I am explaining to you with an example what can happen in this case, okay, here you have given something like this which The time stamp will be that it can be from your van to 10 tu di power seven. Okay, I am just explaining to you through the example, what can be the different case, what can be the greater element, if there is a lesser value than that. So, what can we do in that condition, the one who is the largest among them will attend, but if you have already been asked for lesser time and you have time stamp of greater value than that, then in that condition, you can attend anything. If you can't turn then you will return empty string now. Okay, after that look here, set function is given, that part is two and four, that is, this is four, this is the value of se, four times 10, now we have this value here, 4. It has been asked that what will be the answer for this and what will be the hello for this four time stamp, so here it is from this, here you return is not even one, so you will see four and one which is less than five. Okay, it is less, okay, so we can take which of these, which one will be the largest, if it is the largest among the less, then it will be four, so four, what will we do, what will we return, what will be the value of four, then we will turn here, okay? I hope you must have understood that what happens here is three, what happens in the case of three, see what happens in the case of three, 4, so it is related to this, see, whatever time stamp has been given to you, here we have given you all the time stamps in constant. The offset is exactly increasing, that is, from whatever set will come, whatever will come to you, I will also do it, so for that, whatever will come to you will come in the increasing order only, okay, it will not come in the decreasing order, it means what is your time stamp, you will have to come in the increasing order only. OK, so how can we solve this problem? What we will do here is that we will create a data structure to store it, first we will map the vector, OK, what will we do in this, we will take the map, the first key of the map will be of string type, OK and the second You, we will take here, we will take the vector of feet, okay, whatever value will be, I will take that vector of feet, first wait, let's take the type, it will be string, okay, we will store it will be time stamp, why are we doing this, I will tell you that, okay we Basically, what we have to do is to store the time stem for any key. We have to store the value. Okay, so if we have been given a key, we have given a time stamp, then first of all we will see whether this key is ours or not, if it is that key then it is okay. We will see further whether we have that time stamp and if not, is it less? If it is less than that, will they turn us to the lesser one? If we don't get even one, what will we do? If we do a sting here, then in a way So what do we do, we are searching for the key, first then we will see all the values in it, in a way we will see all the values in it, in a way we will see all the values in it, in a way we will reduce the search, okay, so you can do linear search here and you can also do binary search, so in linear search. If it takes more of your time, what will we do here? Mind research because we know that the time we are going to get will be given in increasing order, so first we store it, whatever amount we have given in our set gate, let us see this. Okay, so how will we store it here? Let's take this map. I am just telling you to show. Okay, so the first one here is our set, this is yours, so you do this here, what will you do after that, the vector here. The vector of feet is ours, so for this what will be your van, the first element in the vector will be feet, it will be in the form of feet, this van is yours, this is your time stand, this is your value, okay, you have stored it, okay if any other value comes. So this is how it is stored here, then there is a third value in the form of right vector. Hope you must have understood, then we have given here the gate function. Okay, what have I given here? Get function 41. So we are all What will we do first, we will find it, okay we have found it, what will we do after finding it, we will search all the elements given in it, okay, so here you have to find only one element for the first time, but if many More happens here there is some value for you, there is something for 3, there is something for four, so what do you do now? Let's try to find this particular van. Is the van ours? So here, what do you do? Linear search. You can also do it one by one, you see all the elements equal to one, are any of them being found? Then whatever your time stamp is given, are any of them are being found? What is its value, second value, meter it. We will give here which is sorted, when we can do it, what we will do is we will index it and the last element will be taken, we will take L, we will take R, like we search for mind, you will know that mind research is fine if I do n't know, please go and watch the video, watch any article of your choice, understand well what we will do here, we will search, okay, we will search, we will find, if it is okay, there is someone equal to the time stamp given by us. If found then it is correct. If not found then what will we do? We will write an answer and also the previous value. If we have found any then we will store it. If we have not found any equal then we will keep the condition there in binary search that if we have found our equal then We will attend at the right time. If you don't get it, then what will we do in the answer? We will store the previous value, so what will we do in the last one, we will return it. Okay, so this is how we are going to do it here, so for this you have done it here. If you want to get it only for the first time, then you will return it, you have to go out, okay then what is there after that, what is 43, what is there on here, if there is three, then in the case of three, you will see here, three, it will not be found anywhere else, but in the answer. What will it do, this previous value will be stored here, that is, if we say the value of previous, then how much less it will be, we will store that value of time here, okay because look, L will also be the same, R will also be the same for you because there is only one element. In this case, on the right, L and R are equal, so the middle will also be the same. If the right mid is also the same, then in this case, we have to get equal. In this case, we have to get equal. What is we to get on the right in this case? If we have to get equal, then we will come on time return. We will do this value but when we will be asked for three, then L and R will be from our own here because there is only one and same elements, so in the medical case we will see that the value is not found but we have given the time stamp of the meeting. Give the lace, which is our given time student is three to one, if it is lace, then what will we do in the answer, we will store the value of this lace, what is it for, after that it is ours outside, we will store it here, okay, I am in the code. Also, I will explain to you again that this part will be this, then your second set has been given to me, that bar tu four, this will be your store in this four is fine for time stamp, after that what is its value, bar tu hai here, hair. You have given it, now look here 4 has been asked. Okay, now what we have to do is to search for this time stamp. Okay, so this is your last value, this will be L, this will be R, this will be right, this will be zero and this will be on van index. So what will we do, first of all we will find if there is anyone by phone name, is there any key, then what will we do, okay, now we will find it here, we will do this binary search, is anyone available at this time, just by time, if not. If we get less then what will we do in the answer we will store it Ok what will we do in the answer we will store it so L here pe apna kya hai in this case L will be yours zero and R what will be our van so meet what will be ours Van hai ok and what is this is your bar value and we have been asked for four which is kya hai kam hai apna right ye jo meet pe jo hai yeh van hai van time stem hai we have been asked for four which is If it is less then what will we do, we will make L as med plus van i.e. L will become yours 0 + 1 i.e. 1 will become i.e. L will become yours 0 + 1 i.e. 1 will become i.e. L will become yours 0 + 1 i.e. 1 will become van, if you are right then you will find mid 1 + 1 / 2 then this van will come out, if you 1 + 1 / 2 then this van will come out, if you 1 + 1 / 2 then this van will come out, if you go to van you will see. Yes, this is equal to four, then your four and this time stamp is also asked for 4. Okay, so what will we do, we will turn this value, so here we will get our part, you will get it, okay, this is done, then your here. If you are asked for five, then what will you do when asked for five? Look, there will be a case from here, what will you get a van, what will you get first, sorry, first you will do 0 + 1, then when we are asked for this, what will we do? You will start from lagro and right will start from R1, so what will we do then we will find its mid, Mir, when we find 0 + 1 / 2, then what will happen to Mir, when we find 0 + 1 / 2, then what will happen to Mir, when we find 0 + 1 / 2, then what will happen to you, your right will become zero, when it goes to zero, then you will see the time stamp. If it is less than five, OK, if it is less, then what will we do in the answer? We will store the bar and what we will do is increase L to med plus van, which will become 0 + 1, that is, plus van, which will become 0 + 1, that is, plus van, which will become 0 + 1, that is, van will be on the right, so L will be with us. What is Van and what is R? You have Van. Okay, now if we find its mid, what will be our 1 + 1 / 2, then Y21, what will be our 1 + 1 / 2, then Y21, what will be our 1 + 1 / 2, then Y21, this is done. Now if we go to Van, we will see that it is four because what is this, is less than 5. Okay, if it is less then what should we do again in the case of less? Answer: We will update our part Answer: We will update our part Answer: We will update our part because this will be the largest in minimum. We will store the value of the code for right five here. Look at us equal, what have we done here. Here we have taken a map, here first is your string, second is your vector leg of leg which is waiting, first is time and second is string. Okay, what will we do when the set function comes, in the case of set function, we have to set it. We will take the key in the map and do some things, first is the time stem, second is the value, okay, then when you set the get function, you will call it, what is the time, you have to find the value for this and this time stamp. So first of all you people see whether it is your present then find it, if it goes till N, if it is not that key from Redmi, then you will turn here by doing empty, okay people, if it is not found then it will definitely be you. What will you do? Take L zero and start from zero. You have to find the dot size of the MP, which means whatever value is there, you will get that vector. What is the second value of this. If the second value of the map is the factor, then what will be the size of the vector. 2 - 1 Then you will get the right. If what will be the size of the vector. 2 - 1 Then you will get the right. If what will be the size of the vector. 2 - 1 Then you will get the right. If you have got it then first check what is the zero in your map, what is the first value of zero and next of the particular key of the map, is the date equal to the mains? The value for which you are searching will be greater than the right one. If it is the first element, then it is given in increments. If it is given in increasing order, then all the values will be greater. then all the values will be greater. then all the values will be greater. So what will we do in that condition because we are not going to get anything similar or equal to this, okay, first we have checked the value, so it is okay, if this is also not fulfilled, you will go ahead and see, we will keep the sting answer okay. Now what will we do, we will see the first value, are you equal, what are the times, if yes, then we will return a time, mid dot second value of MP, we need the first value of the foot, what is your time stamp, second value is the value given by you. It will be right and that is what we need, so we will turn here. If this case is not complete for you, then we will check here whether the time stem has been given to the person you are looking at, if it has been given then what is the answer? Do this first update the answer then what to do with L then do my plus van if this condition is also not happening then what to do with R then do my - 1 ok so this is what to do with R then do my - 1 ok so this is what to do with R then do my - 1 ok so this is your mind search done if this is said from last Equal must not have been fulfilled even on the page. If you have not found it then give its value in the answer. If you have found it here, then what will you return the answer finally? Please like, share and subscribe. Thank you.
|
Time Based Key-Value Store
|
delete-columns-to-make-sorted
|
Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)` Stores the key `key` with the value `value` at the given time `timestamp`.
* `String get(String key, int timestamp)` Returns a value such that `set` was called previously, with `timestamp_prev <= timestamp`. If there are multiple such values, it returns the value associated with the largest `timestamp_prev`. If there are no values, it returns `" "`.
**Example 1:**
**Input**
\[ "TimeMap ", "set ", "get ", "get ", "set ", "get ", "get "\]
\[\[\], \[ "foo ", "bar ", 1\], \[ "foo ", 1\], \[ "foo ", 3\], \[ "foo ", "bar2 ", 4\], \[ "foo ", 4\], \[ "foo ", 5\]\]
**Output**
\[null, null, "bar ", "bar ", null, "bar2 ", "bar2 "\]
**Explanation**
TimeMap timeMap = new TimeMap();
timeMap.set( "foo ", "bar ", 1); // store the key "foo " and value "bar " along with timestamp = 1.
timeMap.get( "foo ", 1); // return "bar "
timeMap.get( "foo ", 3); // return "bar ", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar ".
timeMap.set( "foo ", "bar2 ", 4); // store the key "foo " and value "bar2 " along with timestamp = 4.
timeMap.get( "foo ", 4); // return "bar2 "
timeMap.get( "foo ", 5); // return "bar2 "
**Constraints:**
* `1 <= key.length, value.length <= 100`
* `key` and `value` consist of lowercase English letters and digits.
* `1 <= timestamp <= 107`
* All the timestamps `timestamp` of `set` are strictly increasing.
* At most `2 * 105` calls will be made to `set` and `get`.
| null |
Array,String
|
Easy
| null |
78 |
hey guys welcome back to helper function in this video we will discuss a popular question subsets so the problem statement says that given a set of distinct integers none return all the possible subsets now all the possible subsets of any set is also known as a power set and also there should not be any duplicate subsets in our answer now for this example num sorry contains three elements 1 2 3 and there are 8 subsets generated in total we can see that the empty set and the whole set is also considered in our answer and also the return type of our answer would be a 2d vector where each vector represents a subset also it is given that you can return your answer in any order it need not to be in sorted form so let's see how we will solve this for the array of size n the total number of subsets generated would be 2 to the power n this is because for every element we have 2 choices either to take it in our subset or not to take it thus taking this combination for every element we can generate 2 to the power n subsets thus by taking this idea we can make a recursive function which for every index have 2 choices first either to choose the current element and second not to choose the current element here's the approach how we will solve this problem initially we will have an empty vector now for every index we are going to perform these two operations the first one is to ignore the current element and call the recursive function with current subsets and next index which means that we are not going to take it in our subset and the other one is to insert the current element in the subset and call the recursive function with the current subset and next index that is we are going to take it let's try and understand with example initially we will have this empty vector now for index 0 we have two choices either to take one or not to take one the yellow box represents not taking part while the green one represents the taken part so if my array size was only one these two were the subsets which I would have got now we will perform the same operation recursively for the next index so this time our element is 2 so for the simply subset if it does not count 2 it remains the same otherwise 2 gets added similarly for 1 if we not count 2 it remains the same otherwise 2 gets appended here now we will again perform the same operation for all these subsets for the last index this time our element is 3 similarly every block will have same option for the first part it will remain same as it is and for the other part 3 will be added thus you can see that we have got our all different 8 subsets now let's try and understand the code we are given with the num Swifter we declared a 2d vector answer which will store our answer now M is a vector that will store all the states we are calling affine function which has 4 parameters first is the number 2 second is the temporary vector third is our answer and fourth is the index so we will start with index 0 now in this find function this if condition is the terminating condition which says that if our index has reached to end of the array which means that we have got our answer and will push our tempo actor in answer and return otherwise we have got two choices first we will ignore this element and just call this find function with increased index otherwise we will push this num shevai in our temp vector and again call this find function so from this figure you can visualize that all these boxes that are generated are nothing but the temperature the yellow boxes are those function calls where we ignore the current element while the green boxes are those where we count the current element also at this level we will reach the terminating condition and thus we will insert all these temp vectors in our answer and finally after all the function call we will return this 2d vector as our answer now the time complexity for this problem is order of n into 2 to the power n to generate all the subsets and order n for copying them into the output list and the space complexity is also the same because we have to keep all the subsets of length n since each of n elements can be present or absent so this was all about the problem I put the problem link in the description so you can go and solve it if any doubts of suggestion please write in the comment thank you for watching
|
Subsets
|
subsets
|
Given an integer array `nums` of **unique** elements, return _all possible_ _subsets_ _(the power set)_.
The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
**Example 1:**
**Input:** nums = \[1,2,3\]
**Output:** \[\[\],\[1\],\[2\],\[1,2\],\[3\],\[1,3\],\[2,3\],\[1,2,3\]\]
**Example 2:**
**Input:** nums = \[0\]
**Output:** \[\[\],\[0\]\]
**Constraints:**
* `1 <= nums.length <= 10`
* `-10 <= nums[i] <= 10`
* All the numbers of `nums` are **unique**.
| null |
Array,Backtracking,Bit Manipulation
|
Medium
|
90,320,800,2109,2170
|
208 |
hi everyone my name is Steve today we're going to talk about try or implement try prefix train while use legal problem 208 to help us go through this problem because since LICO has a lot of wonderful corner cases in its code base so we can use this to make sure that our code is correct but actually this tribe is a very common and very useful data structure it has a lot of very practical use for example if we just go to google and type say TR are i.e all of these you and type say TR are i.e all of these you and type say TR are i.e all of these you see when we type TR i it's autocomplete Trip Advisor triple rad trivago all of these things is how to complete how this is implemented most likely a very efficient algorithm that's backing this Google search is try in when it comes to string comparison it's in super efficient data structure that can streamline your process a lot it saves a lot of space and time so try is basically a tree with a special note it's not a regular binary tree node instead we have a node called tri node we only need two fields one is a boolean variable we drastically simplified this for the purpose of understanding this tri data structure in real world it's much more complex but we own building it this video is just to help us to understand the concept and another I'm just simplifying in this using an array of course you can use a map or like a hash map so that we can accommodate Unicode that's fine but for this video I'm just going to assume everything is in uppercase letters so only 26 or you can put 255 that's fine too but I'm going to use an array to represent this the type of this array is triangle so how do we construct a tri tree first we initialize in now as its root node which is a very typical and standard way to initialize in triangle suppose we want to insert a PP app this word this is one word into thus this triangle at the beginning with an empty try tree how can we achieve this so first we initialize an empty tree node is word is going to be fast there is no word here it's an empty array in this rule we will go through every single character in this given word one at a time we try to find it if we have this one in this tri note level then we are fine if it doesn't have it we'll just insert it into this tri note so the first character that we are going to insert it is it because this is an anti one this is the first word that we're gonna insert into this try--try a so we gonna insert into this try--try a so we gonna insert into this try--try a so we initialize a new triangle this joint and is word is going to be false I'm just going to ignore it here and try note it's empty it doesn't have any children yet right so we initialize a tri note with the value of a that's the only calculate that it has at the moment next we do the same we initialize a another try note but this one is one of the children is the only children at the moment of the trial with value a still is word is false for this trial so we're going to continue to ignore that in this try note then we move on to the third character which is P so we'll initialize a new try note with the value P in here and then this P is children of this P meaning it's following this the order goes from the root all the way to the leaf but at this point we need to do one more thing we need to set the value of is words to be true because this is the ending capture of this entire world so we'll just put a subscript of this word just called W means it's a word it's a valid word it's an ending character in this word all right we have finished inserting this entire word into this kind of how about we want to insert one more word Apple we want to insert Apple any PP these three captions we have these three countries in our trying tree already so what do we don't need to create a new because we have it for the first level we have n here for the second level we have P here for the third level we still have P here so we don't need to create any new trying nodes in these first screen levels however for the fourth character we still do need to create a new triangle with the value of L which should be the child of this P this is not the ending character of this word so we'll continue to create a one more try node with value e so E is here and eeeh we need to mark a subscript of W here which meaning this is word is going to be true because E is the ending character of this world that we're trying to insert all right and then we have finished inserting ample this is the second word that we insert it into this try note as goes well a few more examples Fisher let's try to insert Fisher so this is a completely new word at is first character we don't have F in the first level so we need to add this F into the first level of this final meaning the all of these are children of this root note previously the only child then this root node has a at is another child we need to add into the children array of the root note all right next one continue to do that same for F I create a new one as H E all of these will need to create because and second level third level et cetera all of these following levels we don't have the corresponding characters right so we need to create all of these following levels of try notes to have this Fisher this word inserted into this try note alright this is the third one let's go through one more s insert coded so the first capture of this word to be inserted is C so C is a new word in the first level right prior to this point it is to have only a NF C it doesn't exist in the first level so we need to insert a capital C into the first level then we'll continue oh d ER right oh we don't have it we create a new one d e are all of these we don't have at the subsequent levels so we need to create new triangles remember we need to mark R as the ending keyword W just is standing for is word is going to be marked as true same as for our W subscript meaning is where it is going to be math that's true alright that's the coded this work we have successfully inserted into this try now let's go through April how do we insert April into this try tree the current try tree a is fine we don't need to insert it and second character P is also fine we don't need to insert it but for the third capture our we need to insert it right because the third level here in has P so we need to create our here a new character it needs to be padded then moving on from here our next one is on so we need I here mal L needs to be mark as ending character for this entire world now we have April you see we don't need to create a new any MP but from the fill level we need to add our and then moving on we create a new try notes this is how we can insert a probe the last word I want to show is cat and the first level we do have it but the second character which is a we don't have it so we need to create a an a is created and T it doesn't exist we need to create T as well and mark T as the ending character for this entire world so say 80 cats this world is inserted into this country all right that's basically how I train really works the reason why this try Trini is very popular and it's it has a lot of practical use is that it's really efficient in terms of both space and time complexity you see for space we don't need to store every single string exactly n times we break every single string into each capture and for each character if it's a duplicate we store it only once time complexity let's think about what's the lookup time say if you want to solve the entire Oxford Dictionary into your computer try tree is absolutely the way to go and when you do a Luka how does Google perform the autocomplete when you type something into Google right lookup time for try tree is super efficient why suppose the length of the word that you are trying to find in the dictionary in the try tree is W say this one say 18 the length of the this word is 3 so the look at time is going to be o W instead of the total number of strings that you have in this entire dictionary why it's a tablet because at each level we only check once the time complexity we need to find this character is a 1 so we do this only W times and then we can determine whether this word does exist in this country or in this dictionary so it's super efficient again I'm simplifying this here just using an array of triangles ideally if you want to include Unicode or more complex data structures you can use a hash map here which is basically keeping in mapping relationship between the parent node and its next level that's all it does now let's put this idea into the code here is the little problem again the reason I'm using this little project has a lot of very great test cases to make sure that we are writing the correct logical code all right the first thing we need to do is we need to create a triangle class here we only need two fields bling is word and another one is trying node or called children here new and what just instantiated to be 26 again we assume everything is a prayer or lower case alphabetical letters so just to simplify this and this is what this problem is asking okay it's all lowercase letters so we just simplify this to be 26 and we'll have a constructor do we need it no we might not need it's just we'll just leave it empty there all right inside this try class or have a trying node first one is no root and inside this constructor we just need to initialize any an empty node that's it we don't need to do anything else now we need to implement these three methods first one is insert remember how we went through insertion so we go through this word one character at a time so that's what I'm gonna do for in time smaller than from zero all the way who I plus person so we check at every single level does this try node have this character if it doesn't then what just to create it if it does what just to move up assign it to this node so first we need one - let us go through so we're just quite - let us go through so we're just quite - let us go through so we're just quite node and then first one is root of cost and then here what will happen is the first we'll check every node children were so what check if this capture does exist at this level weird child act basically we get every single character in order from left to right we check minus a which is going to give us the index that this character maps you to this children are ready to see if this one equals now that means this character doesn't exist at this level of the try tree so what we will do is we'll create it with chopped at minus one we'll just create a new triangle basically to initialize to create this triangle object at this level and then at this point we'll just assign this new try tree node to this node to let it continue to build up this try tree branch so next we'll do is chop note children would charge at I minus a again this is how we'll branch through and every single level to check and insert every single character that if it doesn't make this exists we'll just insert this captured into the character level of this try tree and then in the end we will assign this is word to be two before we exit right because we're inserting a correctly completed word so in the very last level of this node we need to mark this is word boolean value to be true for all of the other levels we shouldn't mark by default is going to be false right that's for the insert method next is search and starts with these two methods are pretty much very similar we can quickly write it first we'll also have a temporary know what is called node from root then we'll have in for loop to go through every single cap of this word which is i0 a smaller than word man I plus we go through every single note so first children word Chara hat hi hey if this one doesn't exist then we can just directly return false right because this is a broken link we don't have this character at this level already there's no point to continue to look further right so we can just return false here directly if that's not the case then we can just continue to search down the levels of this try tree so we'll move on though children and word which are at minus a this is how we are going to move on so that's the followed so with this if it can finish until it breaks out of this followed that means we have at least we have this entire prefix we have this entire word in this try tree so at this point we have braved out of this while loop success without directly returning false here then we can just safely return though is worth because we are looking for in word we need to make sure that we did have inserted such a word into our country to make sure that this word is a valid complete one that's it for this method so if we have implemented this one search method start with is going to be even simpler right it's the only difference is that we don't need to return note is word here we only need to return true if it didn't break up from here so let's quickly implement that have any kind node root exactly the same for loop this parameter name is different its prefix now nothing changed if no children prefix char at I minus a doesn't exist down were just a directory then post again we don't need to look even further down the levels there's no point otherwise we'll continue to level it down those children graphics char at I minus a then this lets us to continue to move down the levels of this try tree if it didn't break out any it successfully finished this for loop that means we do have this valid prefix in our try tree so we're just directly return true that's it this is how we can quickly implement this country using Java code very straightforward now let me hit run code huh compile error line 20 what is this word chart at Oh should be - Einstein word chart at Oh should be - Einstein word chart at Oh should be - Einstein equal run code again accept it now let me hit submit all right accept it this is the idea of trying tree I hope this video does how people better understand how try tree it really works and I hope I did convey the idea that try tree is a very useful practical and powerful data structure to do string comparison especially when it comes to how to complete and dictionary storing am searching use cases like this it's just a wonderful algorithm that you can keep in your toolkit one day it will come very handy if this video helps you to understand try tree do me a favor and hit the like button ah I'm doing you really appreciate it and don't forget to subscribe to my channel as we continue to go through a lot of interesting problems dinner structures or in the best problems that's it for today's video I'll see you guys in the next one
|
Implement Trie (Prefix Tree)
|
implement-trie-prefix-tree
|
A [**trie**](https://en.wikipedia.org/wiki/Trie) (pronounced as "try ") or **prefix tree** is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
* `Trie()` Initializes the trie object.
* `void insert(String word)` Inserts the string `word` into the trie.
* `boolean search(String word)` Returns `true` if the string `word` is in the trie (i.e., was inserted before), and `false` otherwise.
* `boolean startsWith(String prefix)` Returns `true` if there is a previously inserted string `word` that has the prefix `prefix`, and `false` otherwise.
**Example 1:**
**Input**
\[ "Trie ", "insert ", "search ", "search ", "startsWith ", "insert ", "search "\]
\[\[\], \[ "apple "\], \[ "apple "\], \[ "app "\], \[ "app "\], \[ "app "\], \[ "app "\]\]
**Output**
\[null, null, true, false, true, null, true\]
**Explanation**
Trie trie = new Trie();
trie.insert( "apple ");
trie.search( "apple "); // return True
trie.search( "app "); // return False
trie.startsWith( "app "); // return True
trie.insert( "app ");
trie.search( "app "); // return True
**Constraints:**
* `1 <= word.length, prefix.length <= 2000`
* `word` and `prefix` consist only of lowercase English letters.
* At most `3 * 104` calls **in total** will be made to `insert`, `search`, and `startsWith`.
| null |
Hash Table,String,Design,Trie
|
Medium
|
211,642,648,676,1433,1949
|
449 |
okay let's discuss about this question uh nicole 449 series lines and a d series lines bst so what's the mean of this question so given this a binary circuit wait so what's the mean of bandwidth surgery so it means that the elements on the left side of the root is smaller than the root all the elements on the right side of the root is all larger than the uh root and also the rules apply for all the elements in the tree okay so the question is asking you to seriously what's the meaning of that so you have to turn the tree into a continuous stream it's kind of like to make it more compact yeah right and then just uh okay you can use the pre-order in uh okay you can use the pre-order in uh okay you can use the pre-order in order post order and also you even can use other ways like from top down and from left to right okay you can do that and after that and now you have the input you have the serial size input and then you have to turn the series input into the uh this three it means that you have to de-seriously deseriously this input and de-seriously deseriously this input and de-seriously deseriously this input and reconstruct the output so as long as the output is exactly the same as in the previous input for the serial series notation okay so that's the mean of the question so how can we do that so here is a strategy i want to share with you guys so uh given this binary surgery so i will use the post order to uh seriouslies the balance regime what's the meaning of that so the post order is like a left right middle right so it means i'm going to uh serious this part and then the right part and then the center so that's the result so it means that the orange color is means the left side of the root all right okay let's change the color here and on and the blue color is the right elements um in the banana which is uh so now uh the next step is that uh we have no problem to serialize because we can always use the post order it's like so it's uh straightforward so the next step is we want to uh the serious lies right so how can we do that so firstly we need to uh initiate a stack so we put all the elements in the stack one by one yeah omega one so now uh so this stack and also we want to set an upper value and a normal value so the upper value initially is the maximum value of the integer and low value is a minimum value of the initial and i will explain later why i need two variable so uh initially i saw the pointer so you need the pointer is pointed to the 50. so i will make 50 as the root of the final result and after that uh i will move okay firstly because i picked this value so i need to pop it out right so i move the pointer to this position and also i need to um because this is the right side of the tree so all the elements in this part is smaller than the 50 right so um so i will i'm going to using this way to reconstruct the right part of the tree so now the 60 is between this range so i will put 60 here right okay so the 60 is ready and now i will continue go going this way because now here is the 60. so the lower bound is 60. so the 67 is in this range as well so i will put the 630 here all right and now okay that's the point pay attention here so here is 50 right so 50 feet uh so 55 is actually uh it's out of bound it's not here so it means that the 55 is not belong to the further right uh right hand of the chain so the 50 is actually belong to the left side of the 16. so that's the reason we need to put 55 here okay and so okay now the lower bound is 50 fifths so now let's get let's go to continue okay that's one thing i just updated so this one should be one because this one should be smaller than three so i updated the input okay so all the input i should be uh update it here okay so now uh so now the 40 is actually out of bound so when out of bound it means that the right so the rough subject was actually reconstructing so we will use the same logic to build the right part for example here so the 40 should be put here and after that we will go to three so the three is actually uh okay one second so in this way actually the upper bound would change because now i'm going to build the right uh build the left string so the left hitter the bound was actually updated right so it's actually uh since we have 40 so the bound is like this the upper is 40. so when we have the three so three is actually uh in this boundary so the three should be here and then uh we find the lo the okay the upper bound so now we found a f one is three okay we find this is three and then we found the uh nine um so nine is actually uh it's larger than uh then three so it means that the knight is no longer behind the belong to the right subject of three and then you'll be on the right side and after that uh the lower bound is actually tonight right and then we find a wine so the one is actually out of bound again so i will put a one here so basically this is a strategy how we to uh how we can discuss about the code uh so basically uh we need the post order to turn the binary search tree into the uh in the uh series right so this is uh so when we do the serial serialization we need this uh function okay so when we do the serialization you're given the tree uh tree root and then we put the root into the post order and then return the stream builder right so the stream builder will then turn to stream okay so in this way uh so this is the serialization step that's very simple the difficult one is that uh we want to do the uh the serialized dc realization okay so when we do the serialization let's say uh the input can be something like this right something like this so but when you uh have the input like this and then you want you may want to put this into the stack so once that when that is empty actually then we need to return no right because what's the it's empty the empty set when we check the stream is empty that the learns is actually equal to zero and then we initiate the stack and then we put all the stuff into the stack right so now i'm going to use a pointer at the top of the element and then an each time i'm going to pop one element out yeah okay let me see uh okay so this one uh in this way we'll put all the elements in the stack and after that we use the helper have the lower bound and upper bound and the stack then how can we do this so let's dive into the function so uh if the stack is empty so it means that there's nothing to cope with right otherwise we will get the last uh elements so here okay let's so when we want to get the last element here so the pointer point to the 50 so we want to get 50 out and then if the 50 is lower than a lower bound so why we need this part we don't actually need to compare with the upper bound we only need to compare with the lower bound all right so because uh when you move the uh when you move your pointer here for example if you move your finger here and then you find that find out that this pointer is smaller than the lower bound which is what uh which is uh 15. okay so this smart i know about it so it means that now we have completed the right ratios construction so now we will begin the left tree conjunction okay so and after that yeah okay let's start from this place so when we get one uh element out so we will move the pointer here and uh and also we need to uh make this 50 as a root right so we make the 50 at the root and after that we're going to build the right subtree for the 15. so how can we put the right subtree for the root we're using the helper so is this it is a dfs so we go to deeper and but uh the problem is how we use the parameters so we always use the same stack so the stack itself will keep it the same all the times but when we do the right that the lower bound should be the value itself because all the elements on the right should be larger than the 50 so 50 is now it's a lower bound and for an and for the upper bound is always the largest staff so after we finish all the stuff you see we need value we need to check if the value is smaller than the lower bound we need to check if the body is smaller than this if once we find it is smaller than 50 for example when we come to this position 40 is smaller than 50. so it means that we know that this part is complete right so now i can start to construct the left string right so that tree is upper bound in 70 yeah so we're going to use in this way to reconstruct the tree this code uh so we need to serialize again and then deserialize and for each function we need a helper function for that for the first half function it should be the catholic void uh half a one all right so the hyperline is actually trying to help you to uh do the post order travelers and then to make them in the one stream right um so in this way uh i'm going to uh firstly uh we need to check if okay i think we don't need to check that we just need to put them in the in the helper1 and sp and this sp is the stream builder sp equals to new stream builder okay and also yeah we need to put it please here stream builder and after that we need to return what return the sp to stream okay there's a corner case we don't need to cope with is that what if the route it's actually equals to uh to now yeah in this way uh in if the root is uh equals to noun so when we around the hepa one so it will it'll be around nothing because here we will do a change uh checking is if the route is to now if yes i'm going to return nothing here otherwise we will to further to do the hamper one helper two right still have a one okay so for the hubble one because i'm going to do the uh we are doing a post order so it means that we were left right uh middle right so in this way let's see we will get the left first and then get a right first and then to get a get what uh get center um so the center is the root value plus okay i will further later explain why we need a comma here because we need a command to do that this realization right otherwise we cannot differentiate all the elements here okay so that's pretty much for the serialization so let's continue to the um let's do the let us do the deserialization so the first step is that we're going to check if the data is empty right if it is empty then i'm going to return no right and otherwise we will uh we're what we're going to stack we have a dq stream so we actually used need a stack to do linkedin right so we need this uh and for order current right it's uh it's what is data split this so how do we split this so we have the stack at what is we are going to add integer parse int right we're going to move the stack and after that we're going to return it's a hyper 2 so i have to do with the what after we'll do the there is uh the lower bound it should be the integer mean value so this is the lower bound and after that we pass the stack to the hepa2 okay so how the hyper2 will do the work let's say we have the g note helper and so we're going to have in lower bound and also the eq um it should be dq dk what step all right and after that if we found the root if the stack is empty dart and so we're going to return now otherwise we will get the huh let me see the did get the dq should be integer okay so we're going to integer current is equal to stack get last get elements right so if the current is smaller than low lower bound okay our we were discussing this later so if it is smaller than the lower bound so it means that we have already completed the right subject right but uh but after that uh we will uh step remove last right so if and so the root and then also we're going to make a root should be uh the current value right and then the root the roots left equals to all right the right is equal to cover two the lower bound becomes to current and then also the sec we use the same stack all right after that we use the root left and help her to also current stack please pay attention that because now we have round for the relationship first and after we can show the left tree so that's the reason even though the stuff here the same but the answer is actually makes sense okay so but when we run this part how can we understand that actually uh for the left tree the lower bound should be the previous lower bound so the lower bound should be passing here yeah so here's the way we build the dev stream because the left side is actually uh should be always lower than the current route but for the radishes if the current value is smaller than the lower bound already and in this way we're going to return now because if the so this is the lower bound right this current is the it's a dysfunction lower bound but if we found somebody in the stack is actually smaller than this one so it means that we're going to return nothing here that doesn't return so the element should be belong to here if the current is smaller than the left bound it will directly return now so it will not remove the last element so the last element will pass to the this part okay let's run if we can pass the examine this 21. uh we should update a type here and it is uh 50 so maybe it should be updated integer no it's not a program uh should i add dq all right so i have to return it right okay i passed
|
Serialize and Deserialize BST
|
serialize-and-deserialize-bst
|
Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
Design an algorithm to serialize and deserialize a **binary search tree**. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.
**The encoded string should be as compact as possible.**
**Example 1:**
**Input:** root = \[2,1,3\]
**Output:** \[2,1,3\]
**Example 2:**
**Input:** root = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the tree is in the range `[0, 104]`.
* `0 <= Node.val <= 104`
* The input tree is **guaranteed** to be a binary search tree.
| null |
String,Tree,Depth-First Search,Breadth-First Search,Design,Binary Search Tree,Binary Tree
|
Medium
|
297,652,765
|
1,071 |
Hey guys welcome back to my channel and this is a new question of lead code 75 challenge whose name is Greatest Common Divisor of Strings. This is a very lovely question. It has been termed in easy but it may seem difficult at times for beginners. Let's see what is there, so if you look, we have given the string ABC and here we have given A BC, so can we divide it if we divide it by dividing it by ABC these two times. ABC is ABC, if we divide it by ABC, then we may have to multiply ABC kind of twice. Right and if we look at this, then basically we have to find one, which is our greatest common divisor. Meaning, which string is so big that which is the biggest string which can divide both string A and string B and here if string one and string two, if you look here then from A B C to one here. Multiply by one is over here and one over here so if you multiply this by two you will get both if you multiply this by one you will get this or at the same time if you look at a If you multiply it thrice then you will get this. If you multiply it twice then you will get this. If there is no such thing in the lead code then what will you do with it. You will return a blank string to it. So let's solve this. There is a simple way to do this. That is, you can use the Greatest Common Divisor which is a Euclid's algorithm, so I will tell you how we will do that but before that it is very important for us that if you have seen here, there is a common factor which is Is it a string? It is running in a pattern. A B C is such a kind of pattern. If you see here, there is a pattern of A B A pattern. If you see here, there is a pattern of A B. So what will we do, first we will check if a not string and plus string. Two dot equals string two plus string one. Okay, if this is not equal to us then what will we do, we will return this which will be useful in this case. Our third example was, so here you can say a kind of base case. What happens to us is where we have to return the MT string, that is our kind of solved. Now if we see, if we have to look at these things, we have to find their GCD which we will be able to get from Euclid's algorithm, then what we have to do for that. Int will return us a kind of integer number, yes, we will pass two keys in it, we will make a method by doing GCD, below and in that, we will pass string dot length, comma string to dot length, okay and we will return string and Dot sub string of G GCD Now let's come and write, we will write the function of GCD: Now let's come and write, we will write the function of GCD: Now let's come and write, we will write the function of GCD: function public end GCD int A comma int B This is a Euclid algorithm, so you can see its implementation by going to Euclid's website, you can take an example and it is very detailed. It will be easy for you to understand what we will do in this. Return if B is equal to G then A and else we will return that. One thing we will do is we will keep calling GCD on B comma insurance A on B let's C this. Let's run this, it has probably been run here and it has passed all our three test cases. Let's run it once and see. And yes, we have passed all three test cases. Let's see by submitting one. And let's see where the solution stands. Does A Solution Beats 83.119990
|
Greatest Common Divisor of Strings
|
binary-prefix-divisible-by-5
|
For two strings `s` and `t`, we say "`t` divides `s` " if and only if `s = t + ... + t` (i.e., `t` is concatenated with itself one or more times).
Given two strings `str1` and `str2`, return _the largest string_ `x` _such that_ `x` _divides both_ `str1` _and_ `str2`.
**Example 1:**
**Input:** str1 = "ABCABC ", str2 = "ABC "
**Output:** "ABC "
**Example 2:**
**Input:** str1 = "ABABAB ", str2 = "ABAB "
**Output:** "AB "
**Example 3:**
**Input:** str1 = "LEET ", str2 = "CODE "
**Output:** " "
**Constraints:**
* `1 <= str1.length, str2.length <= 1000`
* `str1` and `str2` consist of English uppercase letters.
|
If X is the first i digits of the array as a binary number, then 2X + A[i] is the first i+1 digits.
|
Array
|
Easy
| null |
1,962 |
so you are given 0 index integer array files and where piles represent the number of stone in ith files and integer K you should apply the following operation exactly K times right so what we can what we have to do we have to choose any piles right this is the array right that is given right it's it stores number of stones okay so what we have to do we have to choose any piles and we have to remove the float piles how by files by two any operation right on the same pile more than once you can do that right so we have to return the minimum possible a minimum possible total number of stone remaining after applying the K operations so what I'm going to do we have to take load of X is the greatest integer that is similar than equal to X right so let's understand this question is given this one uh five four nine in the piles and k equal to two right so what do we have to do what we have to do we will do apply uh files onto right any we have to we are applying operation on piles 2 and we will what we will do we will uh result files as five four five right how see actually when we are doing this one right see what we have to do we have to apply the operation K times means two times at least we have to do how we will do that we have to do but we have to choose the file side and then we have to remove from that how we'll do that we have to take the floor right Pi is why do we have to do that files by 2 is what if we will do if we are choosing this one right so we are choosing this one let's say what we are doing files on this number right so we will get the fluid value what nine five right and similarly if we apply zero right what will happen at index 0 right what I will do we will apply at index 0 right this is our price value uh at index this one right we will divide by 2 right what I accidentally will get the flow value we get three so similarly we have to face the files calculations right and then we will do so what we understood to till now that we have to do uh we have to choose the piles right we need piles them we have to choose and then we have to remove right so how we will remove we have Bluetooth piles by 2 we have to apply and how many times we need to do exactly K times we have to do we have to apply right so what is the intuition behind this problem right so we have to apply the approach that is grid greedy approach right and then we will use the max shape right because intuition is saying at any given step right at any step which numbers should be choose right which number should we use right we will choose we want to minimize the total number of stones remaining which means we want to maximize the number of stone we remove at each step so we should choose greedily we have to choose the largest at every step largest we have to choose largest at every step correct so every time we compute an operation the data changes correct we see the data is changing right then we need to find the maximum number again right we have to find the maximum number again so the waste data structure for this would be Heap right so it allows us to update the data always and then we will uh always retrieve the maximum value of determinate o log n but because we used to do that right then we have to compare with compared to right and then that will take o n right because this is just an array right so if we'll talk about how we'll Implement that is very easy right so let's what we will do that you will talk about algorite we will what we will do let's start here then we will understand okay so if we will talk about algorithm what we have to do we have to first initialize Heap and piles right evens so how we'll do that how we will do that we will take the we will start from here right so I am going to start a heap right so we will take a heap we will initialize Heap from piles right how we'll do that we will take Heap new right and this is what the server priority give priority Q okay priority queue and this priority queue will take what two short two value at this we will pass so that we can easily sort it right let me take little space okay and then I we will use like this right B minus a correct uh wait okay so this is what we are talking about correct so this is our Heap right so we have any slice if from pile side we have to initialize a maxi from piles this is our Maxi so how we have to initialize the hip right and this is priority queue correct so we have to Define this is a prior to Q okay priority give you to Define and we'll see that it will take what a heap right integer the seven integer so it will automatically sort it right now we are in sliding a heap right this is the first step we have to do then we have to perform K times correct we have to perform K times and then we will do float value right float value and the data at the data and then we will do we divided by two so actually and eat at this step we will pop the maximum element from the Heap and we'll call it current right so if we'll talk if you take a for Loop right so how we will Traverse each value right we will take each value that is called our num right we can say num and then we'll take from what piles right the server files so here what we have to do we have to take the Heap and then everywhere we have to add on the Heap so it will automatically add all number onto there we are doing adding here right and for that what we have to do we have added all the value we have initialized all the value on the Heap this job is done so at the step two you have to perform the K times right so what we have to do the first we have to pop the maximum element from the Heap and we have to call it current correct so for that what we have to do we have to take a loop and if you can take but make sure you will have to pass the index side equal to 0 we will start from 0 and then we'll take I less than what k number of times we have to repeat number of times correct we have to repeat number of times now we have to do I plus and then we'll start with VA start with what we have to initialize a current right we have to take a current so we have to take current you have to take current and current is what Heap Dot we have to take we have to remove from Heap dot remove the max value order will come here after the Sorting that will remove right and we have now current now we move right so what we have to do we have to take int what we have to remove correct so remove is what we have to take the current and that is that by 2 right that it is already given right how to do that now again we will add this after removing we have to add at what Heap and that is what current minus you will take current minus remove d right that we are doing here correct after that if you'll see that we have to check the all the values right not here we have to go outside and then we will take one in answer okay we will take an answer and that is what 0 will take and then we'll check for all the Heap element right so we'll take a one by one number from here we will take from Heap correct and then we will do answer plus equal to what num so now we have this sum right this is this should be the maximum sum right because see initially what he initially what we have to do we have to in increase the uh we have to initialize the Heap correct we have to initialize the Heap from piles and that we have did from the piles we are adding onto the Heap that we have in slides second what we have to do we have to pop all the elements right we have to pop the all the element and that we can say that is our current we have to call it as current then we will calculate the remove right how many Stone we have to remove and should be removed from the current right that we have to do we have to current by 2 means half of the stone we have to remove from the current and that we have did here after removing we have to add again right so we have ADD again correct so each time we have to calculate how many Stone we have to remove we should remove from the current and after performing the current it is the floor of the current Y2 right that we have did here right and after we have uh we have to post current minus remove onto the Heap and then finally there we have to return sum right the sum should be what sum of element of the Heap right sum of the element of the Heap that you are seeing that all the elements we are doing sum and after that after completing this what we have to do coming after the for Loop we have to return this right and this written is what this return is our answer why because the final step is saying we have to return but we have to return the sum of elements in the Heap right what is the sum of the element Okay so if we are we will talk about time complexity okay we will talk we have talked about time complexity then what is the time complexity see we are arranging a array so an array can be converted to a heap in linear time right and that will take our word our take o n sorry that will recover o n correct an array can be converted to a heap in a linear time o n using a method will take if I anything right but after converting the input to Heap we have to perform K Heap operation and each K Heap operation cost is what now is we can take like this login correct we know that and so that time complexity will be what o and then n Plus k log n correct we don't know how many operations we have right so these operations should be multiplied with because number of times right we're doing and this time we are doing 2 right then if number of K is that we have to do K into correct I think you understood and another we have a space complexity right a space complexity and that is what see heaps length is equal to n correct and we which is our extra space we have used right and that's why we will take o of n only right so let's compile the code yeah now we can submit this code yeah working thank you so much guys so if you have any doubt please bring me in the comment box
|
Remove Stones to Minimize the Total
|
single-threaded-cpu
|
You are given a **0-indexed** integer array `piles`, where `piles[i]` represents the number of stones in the `ith` pile, and an integer `k`. You should apply the following operation **exactly** `k` times:
* Choose any `piles[i]` and **remove** `floor(piles[i] / 2)` stones from it.
**Notice** that you can apply the operation on the **same** pile more than once.
Return _the **minimum** possible total number of stones remaining after applying the_ `k` _operations_.
`floor(x)` is the **greatest** integer that is **smaller** than or **equal** to `x` (i.e., rounds `x` down).
**Example 1:**
**Input:** piles = \[5,4,9\], k = 2
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[5,4,5\].
- Apply the operation on pile 0. The resulting piles are \[3,4,5\].
The total number of stones in \[3,4,5\] is 12.
**Example 2:**
**Input:** piles = \[4,3,6,7\], k = 3
**Output:** 12
**Explanation:** Steps of a possible scenario are:
- Apply the operation on pile 2. The resulting piles are \[4,3,3,7\].
- Apply the operation on pile 3. The resulting piles are \[4,3,3,4\].
- Apply the operation on pile 0. The resulting piles are \[2,3,3,4\].
The total number of stones in \[2,3,3,4\] is 12.
**Constraints:**
* `1 <= piles.length <= 105`
* `1 <= piles[i] <= 104`
* `1 <= k <= 105`
|
To simulate the problem we first need to note that if at any point in time there are no enqueued tasks we need to wait to the smallest enqueue time of a non-processed element We need a data structure like a min-heap to support choosing the task with the smallest processing time from all the enqueued tasks
|
Array,Sorting,Heap (Priority Queue)
|
Medium
|
2176
|
1,395 |
Hi to Jhal I am the option that Rajan will solve the question which will be taken from account number 3. Who will be tried after leaving the question? It will be seen how you think of the question. When any question is found then how should it be answered from the fruit. Can be insulting and optimization cost. Originally in the interview it was said that first you bring the boots, then you try to try them on, then you remind them that you should speak like when you start the interview, so I copied this question here. I have this online return so in this I have copied the question Jab Hum Kaise Question Ko Play List Question Laga 11 And Soldiers Standing Alone In This World Other Community Radio Gwalior And Soldiers Ek Question Hai Kumar Apnaye Unique Rating Person Who Has All this is west and second is that polling booth number 63 of Mahi River Krishna Jha and sub-division is to sub-division is to sub-division is to make 3310 meetings and give some commission and there is a condition but mostly due to this the indicating is this and the team first tip ready for a native of judgment activated. If this time is used every day by Dam Rating of a Great Gangetic Object author, this seed, either of these two shatterers will do their work, then if we can remove the roots, what will happen or if any number is taken hot, if that number is fixed Give it to brother, we need it for life, so let's look now and fix it. If we need it for the future in the next look, then we will fry it from here. Okay, it may be increasing. If we take this, if it is seen, then if better than this, it will come. Whatever we look at in every form, if it is better than that, it is only cricket from number two, whatever cultural committee is there, if it takes seconds to fix it, if it gives us better and greater, then how will it be for us, it will be a grated subject, we will see, if it Like Vijay Mishra, there is free leg type of Yaduvansh here, then after that we will need Ban Lekh, if we see the option this year, then if we see then we will need three lakhs, but what vacation we have, what can we make in it, next Dhoop and Loo and what can 210 do? It's a pipe, it can't be three, I can become one, and you don't have any chance, why can't I do this? We removed all the others as we could, now we breathe, if we see the bike, we can become white. Is it quiet? There is something left in the degree, yes, then this for increasing is not even one and if seen, there is more fruit and one more in one evening, this is three, can understand what could not be found, no, okay, then it came close quickly, if seen. Its time complexity and first look is loot lo the kid that it is contracted, it will come to us, thank you, okay, if we look at it, we can write it like this, in the film, why will one come after this, okay, now let us try to optimize it so that we can hit first. Now we will try to do peace march, how will demarcation be done, then how will the looted weight be improved and the optimizers will notice it. If you think, there is only one in it, you see, if it has come to us, then what would have been done for it, we have to cover it. If we want, the jewelery we should have, should it be big or should it be small, strong, okay, the condition of the parties is that if we fix Jio 4G, I have been referred to it, come from here, we have mixed it in the past. If we add things on top of this, I will work on things, this is a condition on 2000 or increasing, I am in increasing, this immortal is decreasing, both of them together, let's see, don't talk about intake, let me talk about the juice of his mind. If I talk about, you should have a degree then there is no addiction with me that is the question, so if I want to try then we should do JK decreasing because I want, then by joining these programs, we will know this thing whether But if there is a need and if someone notices that you are very distracted from meditation, then remind me to fix my eyes and remind me that I need two of these in the meeting tomorrow. Set a computer property boom laptop reminder. If there is a problem, then now we will do the second thing. People can approach in the same that an office eye test should be done and it should be fixed whereas Sadar thanks here graphics Jain president Vijay should be picked up so we have condition calculation see how many big ones do we need bhairu Now, like the small one should be there and here it should be like this, here and like the small one should be in the sense, if you think about this a little bit with your mind, then we can say that what do we want here in total, we want this, how many numbers of Increasing is fine petrol laying total will be bigger like that means greater total great we will cut it ok and peak greater from here bhumidhar what will be needed negation of total should be like owner and totalizing is needed that for war and this is ours to check if We are total greater total aa a total great if to goes in this season then we can easily do this by using kim check me we so she me this see this here if we talked about free to then nothing Have to my below let's talk about three if we talk about 2030 big how much is 1994 and then make it small how much is one that is a little less than hands free how much is one that has to be recharged look here it is made but I have one more condition not if we Total, we have to follow that if we offer it to G, then the check can be bigger on the left side as many numbers as possible and after this and the Ismail which is from it, this cake has two conditions, then two pensions, if we buy one product now Greater that here Agrate Amit Kaya and then educate this more Jain why will you click on then our water will be hot to appoint and tot that greater film total means a total is just done of Britain will know this Bluetooth setting see this The first condition was that the total number of the real is the second condition that instead of the rating falling, it is for our second one, so if we want to excite them, which is fine, then we have to check how big the laddus are in total and how many are smaller than this. So we can easily say that if we multiply these two by the number of times like this here, now look at this, take the extra one for free, how much bigger than this is, okay, how much is one photo here, meaning that if seen for free, then Take three located near us, then in Greater Noida, how many of this model are there, then that pipeline, use it, Pocket Dad that it has increased by drinking the juice of Dalits and backward people, how much pride do we have in this matter, then are we able to make 5310 perfectly and this is the senior Thing we give you the second eclipse of test cricket and we have this test case and for the soil in this we understand the ease that we do so that in o famous for us not only for so there is nothing because this App one we are Generali Thakur three Uddin that what will we have two-three days. If we see what happened two-three days. If we see what happened two-three days. If we see what happened then we have how many have we seen, just leaving the bag to increase money and the interval is big. Now look at it on the left side it is big. Ghar mein mil gaye kuch chhota hi ho song infection mein do hai, that comment is correct that sister Amar Pratap Singh is taking a text on the left side, 811 comedy is small and how much will be found in the computer system, if the account is seen then welcome to the And four have become one, we will get so much till sleep, we have become so welcome two and here is a broken toe multiply and how much is there in the left right side, one is till one inch, we have Sichuan formed, now the negation of the second, the first went with the pension, now Second condition: We will give the phone number. It went with the pension, now Second condition: We will give the phone number. It went with the pension, now Second condition: We will give the phone number. It should be bigger than 13, so there is no need for three. This cannot be bigger than 34. Here on the left side, there is no big one. Glycemic should also be small, so now we blow the second condition, we can put If this can happen even with two, then look at the one that is small here and the one that will grow here, will be born in this soil with conscious suggestions. I have two of them, which will become a clean * be born in this soil with conscious suggestions. I have two of them, which will become a clean * be born in this soil with conscious suggestions. I have two of them, which will become a clean * stomach. If the tow dies, then one more will come. Dr. One photo. So send it, now release this thing separately, this thing of yours, then the Yagya question which is this modeler will be here from the multiply grater. The item number will be here if we fax it to Music G, then we get it here, then we can say this. Model na multiply there greater a stop greater and one more thing is in this turn on the greater that the smaller of the star we will get the total in both the parts and make it total and we will cut both of them okay if we cut it okay total and So, how will we write in the matter of the court that here we will get total number of Jasmine and total number of rate Great up BJP Ninja and together understand this, let us write in English as much as we can on the playlist, people will be written in the back. Before that, how will it be done, I told that I need a laptop, any number is fine, it will definitely be used, it will be guaranteed, it will be kept from the peaks, that if any number comes to me due to lightning, then there should be a first one, then there should be a zero around it, anything smaller or greater. So I became an Olympian, the net had become bigger, so now I came to us quickly with this, otherwise the video will become too big, so let's make it right, come right, Madhav ho, I have washed the [ __ ] because 10 I have washed the [ __ ] because 10 I have washed the [ __ ] because 10 minutes are over. It is written in the form that there is not much time, let's go to the video, okay, after that let's select you here, how we will catch any eye, i.e. any one element we will catch any eye, i.e. any one element we will catch any eye, i.e. any one element and shift it from left to right side through the helicopter of that cholesterol. The tractor is the latest one and has a white key on the right side, so the method is like, it means make a calculation, go till the first one from the districts, then it means left side, if seen, it is left side, let us comment. Okay, we will do this website, this dating will be a greater than lightning, if it means that it will be greater, please make the electronic return payment, next, the death was unique, so it cannot be equal, and what is the second position, this is the right side that Film Friday, so where do we get to start it's fine, then start after that, you finally have to go and watch Batting A Aap Cigarette, now the rating has been reduced, then the height will be again in minutes, otherwise the lights will be reduced, now just after that. What you have to do is after that let's move it there, don't look at Malik here, give tips to Malik, then on the left side above it, he has a regulator, only he will be able to make increase increasing in the degree which the makers have to make the object greater and right smaller then decreasing. You will be able to send it every time you turn it on and return whatever total I used to write. I told you that the thing that we wrote, take it, let's get the original total smaller which will market it. If you click on it will come and there. On the left side, Total Greater and Total Smaller, on the right side, Nilesh is mixed, then there were desires that were increasing and decreasing. For increasing, I am small aristocrat, I want Hrithik after Dushwaar, for every limit, so this and this, we have the previous one. And you see this and Squares of but stable and our Boxer also and give me the question if your problem will not be there, let's put it for worship, there should not be any Dalit that from here you prove that this and this Santosh Kumar sleeps Why will CAT upload Kaushal soon?
|
Count Number of Teams
|
minimum-time-visiting-all-points
|
There are `n` soldiers standing in a line. Each soldier is assigned a **unique** `rating` value.
You have to form a team of 3 soldiers amongst them under the following rules:
* Choose 3 soldiers with index (`i`, `j`, `k`) with rating (`rating[i]`, `rating[j]`, `rating[k]`).
* A team is valid if: (`rating[i] < rating[j] < rating[k]`) or (`rating[i] > rating[j] > rating[k]`) where (`0 <= i < j < k < n`).
Return the number of teams you can form given the conditions. (soldiers can be part of multiple teams).
**Example 1:**
**Input:** rating = \[2,5,3,4,1\]
**Output:** 3
**Explanation:** We can form three teams given the conditions. (2,3,4), (5,4,1), (5,3,1).
**Example 2:**
**Input:** rating = \[2,1,3\]
**Output:** 0
**Explanation:** We can't form any team given the conditions.
**Example 3:**
**Input:** rating = \[1,2,3,4\]
**Output:** 4
**Constraints:**
* `n == rating.length`
* `3 <= n <= 1000`
* `1 <= rating[i] <= 105`
* All the integers in `rating` are **unique**.
In one second, you can either: - Move vertically by one unit, - Move horizontally by one unit, or - Move diagonally sqrt(2) units (in other words, move one unit vertically then one unit horizontally in one second). You have to visit the points in the same order as they appear in the array. You are allowed to pass through points, but they do not count as visited unless you stop on them.
|
To walk from point A to point B there will be an optimal strategy to walk ? Advance in diagonal as possible then after that go in straight line. Repeat the process until visiting all the points.
|
Array,Math,Geometry
|
Easy
| null |
699 |
by 699 clone squares on an infinite infinity no infinite number line we drop different squares in order they're given the I Squared's Bob position goes left silent is a square of the leftmost point decision hi Sue and Simon x1 okay we just have a square that starts on that point and it's of length you doctor named your square out the point we wait for each square to stick before dropping the next the squares are infinitely sticky on the bottom side and will remain fixed any positive length service they touch and squares property each other will not stick together prematurely okay return to miss and of heights each height represents two could hide a side of any square root drop after dropping squares represent my position zero and Ryoga let's see yeah okay so we just have to return the maximum height and in this point it just sticks so there is five okay yeah so this is just this seems to me just to be a way to 55555 maybe I suspect this I'll have to return a list of them clearing highest - you have to be well clearing highest - you have to be well clearing highest - you have to be well cats I was going to say this is just interweb merging or inter well overlap interval overlapping detection or something like that essentially what you are doing is it is giving me some ranges you just kind of come back yeah see how they drop the extra yeah the extra kind of fun part is that usually you get to but in this case because DC fans you know DC friends actually happened in time so for example you can imagine you drop it you drop one two laptop on to the right and they build a table so it just order sensitive in that case don't know up to a thousand places so we say so we could keep track that way what is to users right okay so I think what I'm thinking right now is like if there's only a thousand element do we have to do better than quadratic right like I you know I don't want to prematurely optimize and usually when I get these kind of questions I would try to think about the linear time or at most n log n times but maybe if n is only a thousand maybe it's okay well maybe it's okay to go an N squared and just do a scan like but I'm also trying to think if this is a hard why would you need like we'd like to naive and square algorithm is just for every cube that you drop you do the math and see where that goes but can that potential you have essentially I mean n is a thousand but that means yep two thousand nine points and with open happen things that might create even more perhaps hmm oh that's good I this yeah mate - any skillet right okay this yeah mate - any skillet right okay this yeah mate - any skillet right okay this is just a running count so you can finally I want to say that if you have a good in data structure you could do a binary search on the left and the right and it's not good no because you have a bigger square guy because you can imagine there's a 1x1 square everything on top that is three by three squares and then that is not help or you know it overlaps at the one by one hmm I mean the question is do I just do the linear thing and then see what happens not linear but they're like imperative thing it's a fastball time and then see what happens Sammy's potentially N squared you look at all of them with an empty it Sanskrit fast enough and maybe passing that bad I mean go down okay hmm you still thinking about it now this code up there not you've won for Senator Vinick I see where that takes us we need to put some black I hear you actually that's tricky goes to max yes I guess each square previously just has a height oh god yeah maybe that's not so bad let's talk first one the base case because often actually anyway so I mean what is the overlap of one of the coins are there then there may be some edge cases of ecocide Wingull the tricky thing am i I have to consider is that it enters to a naive in I mean you can't with one square but then you have these chains that you have to consider them you can't just add them so you have to take it over the lapse of time then you have to take the count sign okay that should go actually something like that it overlaps that's it just overlaps then at the end this is the back side of this previous screen which is like to say this black let's see what that give us that makes some kind that one that's please yeah I think there is definitely a tricky cases that might not be even just wanted longer and value like this okay def statements for that and I know the fixed time and not super confident about this to be honest so I'm going to play around this a little bit more it works for the test cases but now let's say yeah that's a yup cases we're trying one and then my wife is getting done looks roughly the same so I just oh I shall test them empty cases in southern thinking okay so that works please join for Lee she's just not some stubble but uh yeah I think my kind of hesitation on his problem was that they don't understand it in that or like the quadratic equation is pretty straightforward and having the trickiest part about this plom and maybe a little gotcha e if you haven't done these integral overlapping forms it's kind of despond to check whether they're overlapping and once you kind of get that part that I'll check out is that we just kind of keep track of where things were and where things all right actually I happen for like I'm now I'm thinking what happens if I was an interviewer and would I give this prom I probably won't give this around I'm not Jeremy a fan of skylines and selectors and I think in to go these things are like a little I mean they're in style but I don't know what it tests for me and can I even do better than any time I don't know but yeah I'm not a big fan of this bike but I can also see this thing asked in general so I would definitely do that but I think having a quadratic one time problem is always a little envious I don't I mean not all the time but these things where maybe you could do it in many a time that I don't and for me I'm actually not still not convinced whether you can do it faster or not but it is efficient and they anyway and the only thing that convinces me status we're finding 1000 pounds so I don't know but okay
|
Falling Squares
|
falling-squares
|
There are several squares being dropped onto the X-axis of a 2D plane.
You are given a 2D integer array `positions` where `positions[i] = [lefti, sideLengthi]` represents the `ith` square with a side length of `sideLengthi` that is dropped with its left edge aligned with X-coordinate `lefti`.
Each square is dropped one at a time from a height above any landed squares. It then falls downward (negative Y direction) until it either lands **on the top side of another square** or **on the X-axis**. A square brushing the left/right side of another square does not count as landing on it. Once it lands, it freezes in place and cannot be moved.
After each square is dropped, you must record the **height of the current tallest stack of squares**.
Return _an integer array_ `ans` _where_ `ans[i]` _represents the height described above after dropping the_ `ith` _square_.
**Example 1:**
**Input:** positions = \[\[1,2\],\[2,3\],\[6,1\]\]
**Output:** \[2,5,5\]
**Explanation:**
After the first drop, the tallest stack is square 1 with a height of 2.
After the second drop, the tallest stack is squares 1 and 2 with a height of 5.
After the third drop, the tallest stack is still squares 1 and 2 with a height of 5.
Thus, we return an answer of \[2, 5, 5\].
**Example 2:**
**Input:** positions = \[\[100,100\],\[200,100\]\]
**Output:** \[100,100\]
**Explanation:**
After the first drop, the tallest stack is square 1 with a height of 100.
After the second drop, the tallest stack is either square 1 or square 2, both with heights of 100.
Thus, we return an answer of \[100, 100\].
Note that square 2 only brushes the right side of square 1, which does not count as landing on it.
**Constraints:**
* `1 <= positions.length <= 1000`
* `1 <= lefti <= 108`
* `1 <= sideLengthi <= 106`
|
If positions = [[10, 20], [20, 30]], this is the same as [[1, 2], [2, 3]]. Currently, the values of positions are very large. Can you generalize this approach so as to make the values in positions manageable?
|
Array,Segment Tree,Ordered Set
|
Hard
|
218
|
35 |
hello today we're going to go through Elite code problem 35 which is search insert position let's look at the problem here so basically it's saying given a sorted array of distinct integers and a Target value return the index if the target is found if not you need to return the index where it would be if it were inserted in order and you must write an algorithm with Big O log of N Run time complexity all right let's look at some examples in the first example we have a nums array of 1 3 five and six and the target number is five and this is the output is two so if you look at the position the indexes you have one 0 1 2 two so five is at index two in the second example you have 1 3 5 and six the target is two so you have index zero and then the two should actually appear between one and three so that's why the output is one for index one in the third example we have 1 3 5 and six and seven and because seven does not exist in the input we're going to do 0 1 2 3 and then put it at the end for index X4 all right for example four here we see nums is 1 3 5 and six and the target is zero so that is going to be at index zero because it obviously becomes comes before any of these other numbers the last example nums equals 1 Target is zero and this is also zero like the previous example it become it come comes before the number one all right so let's go back to before I do the pseudo code I want to explain a binary search because we're going to do this with a binary search This Is A New Concept it also adheres to the log of In Time complexity that we need to use so I think it's our best option and it's a fun one so hang on all right so l z so this is saying index zero so when B to do a binary search you sign a left value and a right value and using the left and right you determine the mid value middle value so L equal 0 for index 0 and r equal 6 for index 6 and the mid is going to be 6 + 0 / 2 so it's going to be three so 0 1 + 0 / 2 so it's going to be three so 0 1 + 0 / 2 so it's going to be three so 0 1 2 3 mid the value of mid is four and the target number we're looking for is six so because 6 is greater than four you assign so it's basically divide and conquer so you're going to slice the array in half so we're going to take L is equal to the mid value + one so because the mid value + one so because the mid value + one so because the mid value is three we're going to add one and so now L becomes four R is still the six and 6 + 4 is 10 / 2 is 5 now keep in and 6 + 4 is 10 / 2 is 5 now keep in and 6 + 4 is 10 / 2 is 5 now keep in mind these are the index values so because the array is now just three elements they still keep the index numbers so this is index four five and six now taking the mid value and binary searches just hinge off the mid value you're just going left or right based on the if the target is greater than or less than the mid value so in our case the target value is six and the mid value is seven so six is less than seven so now we're going to take the right value and assign it to the mid value minus one and so R is six mid value is 5 - one is four so L is four R is four and - one is four so L is four R is four and - one is four so L is four R is four and we get a target number of six so that's how a binary search works okay so let's pseudo code this so this is the method leak code gives us so we're going to create a variable called left and assign it to zero just like we saw in the previous slide then we're going to create a variable called right in the center to the nums length minus one which is the rightmost index in the array so then we're going to Loop through each number while left is less than or equal to right because once we get right or once we get right greater than left then they overlap and then um you definitely don't you can't go any further than that so we're going to create that variable called middle and assign it to left plus right divided by two if num's middle equals the target number we're going to return the middle number and this is the best case scenario this is actually o of one because if the target is equal to the middle value then you just you return the middle number and you're done so if num's middle is greater than the target number we're going to make the right value equal middle minus one else if num's middle is less than the target number we're going to take the left and equal middle + the left and equal middle + the left and equal middle + one we in the loop and then if we enter a case where the right is where the left is actually greater than the right then we're just going to return the left all righty so let's code this for reals int left equals zero in right equals the num's length minus one so while left is less than or equal to right which we saw in the pseudo code we're going to sign the middle equal left plus right / left plus right / left plus right / two so if the num's middle equals the target we're just going to return in the middle else if num's middle is greater than the target then we're going to assign the right value which is the index equals the middle index minus one else left equals middle plus one so this else is basically when uh the nums middle is less than the target then we're end the loop and return the left value and that is all she wrote so let's go into intellig and run this all right so I used 1 two three four five 7 as the array and the target is six so I've got to eventually stick five or six between 5 and seven so let's run this so in left equals z the right equals nums length minus one so while left is less than equal to right which is true in this case the middle is going to be 5 + 0 / two which middle is going to be 5 + 0 / two which middle is going to be 5 + 0 / two which will be two the energy values we you um it ignores the remainder okay if num's middle equals the target which it does not else if num's middle is greater than the target which it isn't so now we're going to enter the case where num's middle is less than the target so we're going to sign the left value equals middle + 1 sign the left value equals middle + 1 sign the left value equals middle + 1 middle value is 2 + 1 so that will make middle value is 2 + 1 so that will make middle value is 2 + 1 so that will make the left equal to three all right so left is less than equal to right which it is still we sign middle equal left plus right which evaluates to four if nums middle equals Target which it doesn't else if nums middle is greater than equal to Target which It Isn't So other in other words we still have our Target is still greater than the middle value so we're going to assign the left value equals middle plus one so left value becomes five so now we enter into this case where left is actually equal to right and so we have left plus right divided by two middle becomes five if num's middle equals Target which doesn't L if numbs the middle is greater than Target which it actually is and so basically we have uh the left equals five and the right equals five so 0 one 2 3 four five so seven is actually greater than our Target of six so we make the right equal middle minus one so now we have the right equal to four and left equal to five so then okay that's false so we're going to turn the left which is five so if you look at the result the target number was six so index 0 1 2 3 4 five is where the six needs to be placed so that is the answer we're looking for so let's go back into lead code and see how this works so I have the code here I'm going to run it accept it and submit it look at that once again we are faster than 100% which means we are the fastest than 100% which means we are the fastest than 100% which means we are the fastest submission all right so the memory usage is 38.8 megabytes is 38.8 megabytes is 38.8 megabytes Which is less than 51% so about half Which is less than 51% so about half Which is less than 51% so about half yeah we'll take what we can again all right so here comes the fun part the time complexity is O log of n which is logarithmic complexity so what in the heck does that even mean so let me try to explain logarithmic complexity so big O uses What's called the worst case scenario um if you have the best case scenario you know that's the fastest that would be o of one which we saw when the number was actually equal to the middle value but that doesn't happen all the time so O big O uses the worst case scenario so in that case the number is either at the beginning of the array or at the end of the R so we're keep dividing stuff in half and so we divide it you know all the way down to the first or the last number so let's say our array has eight numbers so we divide by two until we reach one so have eight divided two is 4 you have 4 ID 2 is 2 and then 2 / two is you have 4 ID 2 is 2 and then 2 / two is you have 4 ID 2 is 2 and then 2 / two is 1 so it takes three iterations another way to write this is 8 / 2 to the 1st which is 2 = 4 and then 8 / 2 to the 1st which is 2 = 4 and then 8 / 2 to the 1st which is 2 = 4 and then 8 / 2 the 2 so 8id 4 is 2 and 8 ID 2 the 8 / 2 the 2 so 8id 4 is 2 and 8 ID 2 the 8 / 2 the 2 so 8id 4 is 2 and 8 ID 2 the 3 is equal to 1 all right so let's try and use variables in place of these numbers so we'll say Y is the array size and B is the base so divide array into two half so we're always going to binary search always divides step in half so B replaces the two in this case and then X is the number of iterations perform the power or the superscript so what we have instead of 8 / 2 3 power so what we have instead of 8 / 2 3 power so what we have instead of 8 / 2 3 power we have y / B to the X power = 1 and if you multiply both sides by B to X B to the X you get y = b to the X B to the X you get y = b to the X B to the X you get y = b to the X looking at our chart over here y = b to X is the exponential form here y = b to X is the exponential form here y = b to X is the exponential form now we need to Define Big O notation in form in terms of the logarithmic form so you see here b xal y we need to get y by dang it b x y we need to get X by itself so we take the log of B multiplied by Y and that's exactly what we see over here x = log of B * we see over here x = log of B * we see over here x = log of B * y okay so when you can get rid of the we can get rid of the x equals because we're basically trying to see how many iterations it takes to get to the solution or to get the value equal to one so they just replace that with the Big O and this is Log and B in this case is the two we divide by two so log two and we don't use y we use n as we've seen in the past now we don't really it could be log base 2 it could be log base 10 They Don't Really Care care about the base so the answer becomes o equals log of N and that took me some time to figure out so hopefully that uh is makes sense to you the space complexity is the total amount of memory and this is O of one doesn't matter how big the array is and definitely not how big the target is the number the target it doesn't nothing inside the logic of this solution changes the size of that so the space will be constant and that is it so as always thanks for watching and if you have questions leave them in the comments and we'll see you next time
|
Search Insert Position
|
search-insert-position
|
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[1,3,5,6\], target = 5
**Output:** 2
**Example 2:**
**Input:** nums = \[1,3,5,6\], target = 2
**Output:** 1
**Example 3:**
**Input:** nums = \[1,3,5,6\], target = 7
**Output:** 4
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` contains **distinct** values sorted in **ascending** order.
* `-104 <= target <= 104`
| null |
Array,Binary Search
|
Easy
|
278
|
767 |
hello and welcome to another video in this video we're going to be going over reorganized spring so in this problem you're given a string s and you want to rearrange the characters such that any two adjacent characters are not the same and you want to return any possible rearrangement of s so it's pretty intuitive what to do here but yeah essentially so if you have a b you would want to return something like this then for a b you can't really there's too many A's you can't really do anything what this is probably one of the most intuitive algorithms I think personally on what to do but essentially what you want to do is let's say we have some word right whatever it is like a b or whatever essentially all we want to really do is use the most frequent character as often as possible in the word so for example in this word let's just say we have this word just say we have like this right so what we want to do is first of all we want to have a hash map for every character supposed to be like four B3 C1 and I'm going to show you like the intuitive approach of what to do and then we have to figure out how to actually make that happen essentially whenever we can use the biggest character we want to use it so like here we would use an a and then it would go down to let's say we had five A's so we'd use an a it would go down to four and now we would say okay what's the most frequent character okay it's a again but we already have an A so we can't use it twice in a row so then we want to get the second most frequent character which would be the B so then we would put in a b and this would go down to two then you try again okay let's try to use our a because that's almost freaking we can use it okay perfect all right now let's decrement that okay now let's try to use the a again okay well we can't so you see how like the pattern is we can't use the a so we'll use the B and this will go down then we try to use the a again now this will go down to two then we try to use the a again while we can't so then we'd use a b or c we'll just say a b let's go down to zero then we try to use the a again it goes down to one and then now we can use either one of these so we can't use the a so we would use the C this would go down to zero and then we'd use the a again essentially you try to use the most frequent character as often as you can and let's look at our cases that can happen so let's write this down so use most frequent character as often as we can and then if we can't use it then let's use the second most frequent character right because naturally if like if we had let's say if we had an a with a count of 10 you're gonna hit B with a count of nine we'd want to use the B right we want to use the B because we want to minimize our counts as much as we can so then we can fit all of our things but how do we ever run into a problem so the problem there's a couple problems we can run into so a if we don't have a biggest character well what would happen then right like if we don't have a biggest character then we need to check this essentially means we don't have any characters left so that's one case right if we don't have any characters left or not really any characters left it would be more like no actually yeah it would be if we don't have any characters left essentially that would be one of our cases right so if we don't have any characters left then we're done right like that'd be fine if we don't have any characters left then we are done but what are some of the issues we can run into so the issue we can run into there's only one really and that's if we do have the biggest character sorry we have only one character left but we can't use it right that's our like base case where we can't do anything right so we have two cases either we just use every character or like in this example here you know we're gonna have an A with a few use Cases left like we're gonna we can write it like a b a but then we have an a left over with a count one and we can't use it so that's our last case is if we have a character left well we can't use it then so for this we return true for this we return false and now it's pretty straightforward like all you do is you try to use your biggest character whenever possible then you try to use your second biggest character whenever possible and if you ever run into a case where you only have your biggest character and you can't use it and you have nothing else then you would return false so now this problem boils down to how do I get the biggest character and second biggest right in terms of frequency and there's two ways you could do this the first way I thought of personally doing was you can make your helper function it'll just go through your dictionary and it will just get the account of the biggest letter and the count of the second biggest letter pretty easy to do that you just have two variables for that right you need to Loop through all your keys that would be o of 26 and you can do that every single time you want to get your second your biggest second biggest letter that's one way you could do it and that would be totally fine and the second way to do that is would be a q or a heap and it keeps a little bit more intuitive so with a heap we're just going to store the counts of every character so like for example with A's and B's let's say we're gonna have a heap and we're just gonna have the letter and the count we're gonna have to count first so let's call that c and then we'll have the letter second right so it'll look like you know for a word like a b we would have like four a three B and then we're going to store these as negative values because we're going to have a Min Heap so we want the biggest count first and then we can simply just pop values right so we can just plot values and then we can just check the counts that way we could plot values we could push them back in and popping the value would give us the biggest count right away and if we pull up the biggest count and pop again we get the second biggest count and so on so that's a little bit more intuitive than a helper function that actually Loops through your keys and values but you could do that either way is fine and the nice thing about all these things is because these are of 26 you can technically say they're o of one because it's only 26 letters Max so this Q will only be 26 letters this counter will only be 26 letters so you can say you're using constant space pretty much and the time complexity for popping like it's going to be kind of similar because if you go through a list that's o of n but it's only 26 letters that's constant time and if you do heat pops and heat pushes that is log of 26 which is also constant time so either one works it keeps a little bit faster because you're going to have a logarithmic insertions and deletions but like I said it's only 26 Max so either way you can argue their constant time it'll just be a little bit faster on leak code but essentially that's all we need to do is we just need to have a heap with all of our accounts and then for all our counts we just keep pushing and popping back and forth until we get rid of every single letter or until we have one letter left that we can't add so those are our two edge cases one letter that we can't add because it was the last letter or we got rid of every single letter okay so now we can code it up we have enough so first we're going to make this uh we're gonna make this Heap so we're going to call this letters and we are going to use a um we're going to use a list comprehension here so we're going to make a negative value because we want it to be negative because we want the biggest value in some in Heap negative value key for key value in and we're going to have counter here dot items and so if you didn't know um items in a dictionary is going to be a list of key value pairs you could just make a counter and you could just Loop through this so you could totally make a counter here counter and then you can just say like four key uh and then you could say like counts key or something you know that would be totally fine but we're gonna do it this way okay so now what we introduce me to heapify it and yeah the originally way I did this was with a helper function but it's a little bit less intuitive so I'm just going to show the Heap away but it's basically the same thing you can practice the other way with a helper function that just Loops through all your values then you just have your like your biggest value and your second biggest value equal to null and then if your key if you can ever fill up the biggest value fill that up first and then you fill up the second value second it's roughly the same logic so we're gonna Loop while this letters exists while this heap of letters exist let's just keep doing stuff so we're going to get the biggest letter and the second biggest letter so we're going to say biggest equals key pulp from letters and now what we need to check is can we use this letter so if there is a result array and so remember that biggest is going to look like uh let's just write it over here it's going to look like a number value and then a letter right so if the last letter in our result equals the letter for biggest right that means we can't use it so we can't use this letter so now what we can do is we can actually check if the Heap is empty and if the Heap is empty there are no other letters we can just return straight away otherwise we can pop another letter and that will be our second biggest letter and that's our algorithm we ideally we want to use the biggest if you can but if not I'll do the second biggest we're gonna do second same kind of thing he pop we fall from letters and then we are going to so now we know we can use the second biggest letter right because you can have alternating characters so if you can't use the biggest character you're guaranteed to be able to use the second biggest character for sure we don't have to check for that so we can append that character and once again second is also going to look like this here okay and now we need to so remember this is a value in a letter and we're going to be storing them negatively so this will be like negative 3 or whatever so to actually decrease the count we need to add here right so if this had a count of like negative three we'd want to add one to make it negative two so we would say second zero plus equals one and now we have to actually check like let's say the account was all right let's say our count was one it would be stored as negative one we would add one and now our count would be zero and then we wouldn't want to put it back in the Heap so we have to make sure if there's still a count remaining so if second zero does remain then we want to push it back in letters second and we always want to push in the biggest letter regardless because this is the situation where we didn't use the letter so we're always going to push in biggest okay there we go and now we have our else case where we can use the biggest letter so if we can use the biggest letter it's going to be kind of similar so it's going to be biggest zero plus equals one we're going to add 1 to it and we're going to use it so we're going to append biggest one and then the same track is here so if biggest zero key push letters biggest and now finally so I think I did have I think I write the check if the length of our result is long enough but I don't think we need to I think we can just join it should always be long enough here assuming we used every letter so I think we can just do a join here so we can just do this uh going on result see if we do need to chart we might have to but I don't think so and this is like totally random for as far as efficiency because everyone has kind of similar Solutions so it's as efficient as the other ones as you can see okay so let's go through the time and space here and yeah like I said technically you can argue that these are all of one space and that's what we are going to do so essentially we build up this counter and so when we build up this counter this is of m space where n is the length of the string then we will be heat popping and heat pushing and how many times will we do that it's going to be o of n as well so this will be like n log and how many letters are there's only 26 letters right so that's why this is going to be of one because you're essentially doing you know there's only 26 letters here so this is going to be of end time the heat pops and heat push and then you're going to be adding to the result which will also be o of N and then for the space so we have two things we have a counter which is a dictionary with only 26 letters and then we have a heap which Can Only Hold 26 items as well so that's going to be of one as well uh but yeah that's gonna be all for this problem hopefully you liked it and if you did please like the video and subscribe to the channel and I'll see you in the next one thanks for watching
|
Reorganize String
|
prime-number-of-set-bits-in-binary-representation
|
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same.
Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_.
**Example 1:**
**Input:** s = "aab"
**Output:** "aba"
**Example 2:**
**Input:** s = "aaab"
**Output:** ""
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of lowercase English letters.
|
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
|
Math,Bit Manipulation
|
Easy
|
191
|
1,727 |
hello guys and welcome back to lead Logics this is the largest submatrix with rearrangement problem it is a lead code medium and the number for this is 1727 so in this problem we are given with a binary Matrix of size M cross n and we are allowed to rearrange The Columns of the Matrix that means we can move the columns of the Matrix uh any anywhere and replace with any other column in The Matrix so the main objective of the problem is to find out the area of the largest submatrix within the Matrix where every element of the submatrix after reordering the columns is one so suppose you have this sample example one Matrix so we have 3 cross 3 size Matrix so if you move the third column this third column if you move to the second position second column position and second to the third so you can get uh some Matrix of size 2 cross 2 with all the elements as one and I think this is the maximum possible uh size of the sub Matrix where each and every element can be one so this is the possible answer so the answer will be 2 cross 2 equal to 4 because there are four uh cells with one so let me uh just tell you about the intuition once again so the problem asks for the area of the largest sub Matrix containing ones after rearranging the column Pro optimally so this is the problem statement and the solution which I have thought that involves pre-processing of uh Matrix that is the pre-processing of uh Matrix that is the pre-processing of uh Matrix that is the first step first of all we'll do the some pre-processing in pre-processing we some pre-processing in pre-processing we some pre-processing in pre-processing we will store the height of consecutive ones ending at each cell and then for each row we are going to sort the Heights in non decreasing order and then calculate the area for each possible Matrix now let's see through an example suppose we take this sample example one and try to explain you so this was the S the exam input Matrix so now we are going to do some pre-processing and pre-processing is pre-processing and pre-processing is pre-processing and pre-processing is what you in pre-processing you store the what you in pre-processing you store the what you in pre-processing you store the height of consecutive once after adding the previous height so suppose we for this cell we have a previous height of one and current height of one so one is added to previous height and uh stored at the at that particular index so this becomes two whereas for this index or this index the previous was zeros so there are no change in that because zero is added to that so that makes no sense and for this the previous was one so it becomes two and for this previous was two so this becomes three so this is the pre-processing of the Matrix now the pre-processing of the Matrix now the pre-processing of the Matrix now the next step is uh like sorting of the each row and then after sorting of the each row the area of sub Matrix is calculated and how the area is calculated the area is actually given by the height into width so the height is the height of the consecutive cells consecutive once ending at the particular cells that we have already calculated using pre-processing and the width is the pre-processing and the width is the pre-processing and the width is the position of the cell in the sorted array so width is calculated using the position of the cell in the sorted array and now we have to Simply update the maximum area accordingly by multiplying the height into uh width and checking if it is a maximum or not and then we can simply return the answer so this was the approach to the problem so now let's come to the coding section but before that please remember to like the video share the video with your friends and subscribe to the channel if you're new to the channel so first of all we'll Define uh sorry so our first step was uh pre-processing of the was uh pre-processing of the was uh pre-processing of the data so in the pre-processing of the data so in the pre-processing of the data so in the pre-processing of the data we need to define the length of the grid first because we need to make looping convenient so we are defining here the length then for uh pre-processing we are going then for uh pre-processing we are going then for uh pre-processing we are going to start from the first row because if you start from the zeroth row you will check for the index of IUS one and for zero it will become uh a index of minus one so it will throw a index out of bounds error so that's why you have to check for from first index then we have i ++ j we can start from zero and J will ++ j we can start from zero and J will ++ j we can start from zero and J will go till n this if Matrix of I and J equal to 1 then in that case Matrix of I and J becomes it will be IUS one so this is our pre-processing part one so this is our pre-processing part one so this is our pre-processing part this part is done with the pre-processing so we'll now be having a pre-processing so we'll now be having a pre-processing so we'll now be having a pre-process uh Matrix already then we pre-process uh Matrix already then we pre-process uh Matrix already then we store the answer this is to store the answer then for you can use a int array instead of the V which I have used here but that does not make much difference so we'll be now sorting the rows and then we are going to loop from n minus one and we need to also Define a k = to 1 and we need to also Define a k = to 1 and we need to also Define a k = to 1 here and J should be greater than equal to Z because it is an index and row of J should be greater than Zer because we are we only need the cells with the ones we don't need the cells with the uh zeros so till the row of J is greater than zero we are going to Loop continue the J Loop and then otherwise J minus so here we are defining the area so row into K is actually the area of the particular uh sub Matrix and we'll check if the area of the particular submatrix is the maximum of all the answers then we'll store it in the answers and then finally we are going to return the answer now this is the code let's try to submit it for the sample test cases there is some error here I think uh there will be a comma here okay so the sample test cases are passing let's run it for the hidden test case as well so yeah okay it passes the hidden test cases as well and good time complexity but the space complexity is fair not excellent I would say but the space complexity which we have used according to the big or notations is actually constant it is of one since we are using no other uh space for variable except for the variables uh we are not using any other space and the time complexity for this is M into n uh into log of n because we are sorting the arrays so that uh particular rows so that will take n login it will take n login because we are only sorting the U rows and for uh the other part that is uh M cross n so from here we get M notation and this part takes n cross n so the time complexity becomes M into n cross M into n into M into n log I know that was a little confusing so the time complexity is M into n login and the space complexity is over one so I hope you uh understood the logic and you can do it in the interview if it comes this question and thank me later so thank you for watching the video have a nice day
|
Largest Submatrix With Rearrangements
|
cat-and-mouse-ii
|
You are given a binary matrix `matrix` of size `m x n`, and you are allowed to rearrange the **columns** of the `matrix` in any order.
Return _the area of the largest submatrix within_ `matrix` _where **every** element of the submatrix is_ `1` _after reordering the columns optimally._
**Example 1:**
**Input:** matrix = \[\[0,0,1\],\[1,1,1\],\[1,0,1\]\]
**Output:** 4
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 4.
**Example 2:**
**Input:** matrix = \[\[1,0,1,0,1\]\]
**Output:** 3
**Explanation:** You can rearrange the columns as shown above.
The largest submatrix of 1s, in bold, has an area of 3.
**Example 3:**
**Input:** matrix = \[\[1,1,0\],\[1,0,1\]\]
**Output:** 2
**Explanation:** Notice that you must rearrange entire columns, and there is no way to make a submatrix of 1s larger than an area of 2.
**Constraints:**
* `m == matrix.length`
* `n == matrix[i].length`
* `1 <= m * n <= 105`
* `matrix[i][j]` is either `0` or `1`.
|
Try working backward: consider all trivial states you know to be winning or losing, and work backward to determine which other states can be labeled as winning or losing.
|
Math,Dynamic Programming,Breadth-First Search,Graph,Memoization,Game Theory
|
Hard
|
805,949
|
432 |
hey everybody this is larry this is me doing a bonus question a problem that i haven't done before on lead code hit the like button hit the subscribe button join me on discord let me know what you think about today's randomness let's see which one we are we going to get all one status structure oh one what does what is distinguished oh one data structure okay so yeah um today we're gonna get a hard problem hopefully this is gonna be fun let's take a look design a data structure to store the strings count with the ability to return the strings and minimum and maximum accounts not sure what that means yet still but also we just want to say you know weekend is here so hope y'all are having a good weekend coming up i've been watching through the intro a little bit lately but you know hope you all have a great weekend hope you have a great week summer's almost over uh so yeah i hope everyone's just enjoying themselves and yeah uh um yeah okay cool let's see what this all one actually is so have i haven't done this before right it's feels some familiar but i don't know though the title name is a little bit weird okay so all one initialize in command increment to count the string of key by one what is that i mean we have a key increment okay document get max key okay so maybe that's the tricky part return one of the keys of the maximal count uh okay can we run the minimum key with the maximum current count i mean this is way weird i don't get why is what is the definition mean all one well i guess it has to be done in o of one i guess maybe that's the tricky part or uh or all of one data structure i get it now but don't there's i don't know what happened here um well first of all it's going to be depending on how you want to say of one it's a little bit awkward right because incrementing by key is always going to be o l where l is the length of the key that's just the size of the input you can we do better than that no matter what and also one we this is going to be of l as well um okay and the question is let's see the question is okay the maximum and the minimum count the maximum count i think is easier you can just keep well is that even true um i don't know if that's true actually i was going to say like you could just uh keep track of things in a good way but maybe it's not that simple because once you because when you delete stuff your max can change but no i mean i think that's fine i think this is all just bubble sword right um yeah i mean it's not a yeezy bubble sword but it's a possible bubble sword and you can do that with um so yeah so it you do bubble sort on either linked list or something like that maybe you don't even have to you just kind of make sure you keep track of it no i mean yeah i think that's fine i think it's annoying but possible so yeah okay let me give it a try i think we have the idea but it's a little bit so we have a lookup table basically just looks up the index of the stuff and then we have a sorted list we're not going to use sorted lists here because uh it won't even be fast enough but you know this is just basically the idea um okay so then increment so if key is not in self.lookup so one other thing is that if it's not in the lookup then we have to keep track but the part of that invariant is that you're not inserting an arbitrary key right um or actually i want this to be a deck is that true because i want to pop i want to add in the front and then maybe we have to change some data structure but the idea is going to be right i think but yeah if the idea here is that you always only increment from the beginning so that's fine so if this is not then uh self.lookup of self.lookup of self.lookup of actually i don't know i mean it's still true but because i think the way the right way to do this is using a linked list and i mean i'm trying to use it with you know all these things and what you should do is have a linked list and this points to the pointer directly so we'll use a double lea link list here let's do that and then um yeah so let's say we have a node we have um let's say a key and a value or something like that right to be honest i was just being lazy because i think i knew that i need to do this anyway but so something like this right so doubly linked list and then we have a self.lookup and then we have a self.lookup and then we have a self.lookup and then we have a head this is equal to you know just a regular um uh whatever right like a sentinel head and then for increment if this is not in the key we do self.lookup of key is to go to a we do self.lookup of key is to go to a we do self.lookup of key is to go to a new node of value key and one because we have one element um and then here because we're increment uh here we will let's see at to the beginning right so self.he at to the beginning right so self.he at to the beginning right so self.he because it is a sorted list so self.head it is a sorted list so self.head it is a sorted list so self.head that next is you go to how do i say this it's gonna be you go to this thing but not quite right because you need to insert it so okay so previous next is equal to self.head.next is equal to self.head.next is equal to self.head.next and then we do this thing and then self dot lookup of key dot next is equal to previous next but then now this is a doubly linked list right so we have to keep track of that as well um and alpha hopefully my explanation isn't is pretty okay in a sense that i think this is just being really careful one step at a time right so here now previous next dot previous is to go to sub.lookup to sub.lookup to sub.lookup of key uh maybe i should just write this as a node so much typing and so much look up so yeah no does he go to this right um yeah and we might think about ways to make this a little bit cleaner but for now let's just focus on getting it right uh and going through being exhaustive uh but yeah it's equal to node and then node.previous is to go to node and then node.previous is to go to node and then node.previous is to go to self.head yeah so this is just changing self.head yeah so this is just changing self.head yeah so this is just changing back to back okay so that's good else if key is in it then we go node as you go to self.lookup of key and then know that value we increment by one so that means that now as we said it's kind of like a i want to say this is kind of like a bubble sort but maybe this is a little bit wrong or it may be too slow even though it may be or we have to be a little bit smarter to get it to be over one so that's a little bit awkward because for example you can have like i don't know let's say you have a abc and then you keep on you know that you increment by one so then now you move to a to b c a and then now you move to b to c a b or something like this and then increment the c and then you have b c now it takes it's not over one every loop so i think we're a little bit off here you have to do some sort of um you have to do some sort of like speeding it up type thing but uh but that's basically the idea because the way that you would fix this is by just more bookkeeping really maybe i'm doing this in a funky way maybe i could do this in another way i think the way that we can do this is fine but i think that the cause of democracy is not quite right uh like we what we want is maybe just more tracking um and what i mean by that is we can maybe do something just like that and then yeah and then we just have a you know uh like a second count array or something like this and then basically if key is not in lookup then look up of key as you go to oh i said look up no this is just count this is counts whoops and then we can do something like and this is self.counts this is self.counts this is self.counts and then we can do sub.lookup well it and then we can do sub.lookup well it and then we can do sub.lookup well it didn't exist before but now the one we can append key right and then else if it is in there then well self.count of p we in there then well self.count of p we in there then well self.count of p we increment by one and then here we do self.lookup of and then here we do self.lookup of and then here we do self.lookup of um oh then we want this to be a set so we actually want uh add now we have to do a little bit uh we want a collection style to of a set we add this key and then we're here on the previous number so here we remove first uh key and then here we add back afterwards right okay i think this is fine we're increment and then decrement we go if and we have to keep track of the max and the min so and that's fine but yeah if uh let's see oh it guarantees that it exists okay so if key is has to be in it then right so self.counts of key self.counts of key self.counts of key subtract by one um we can do this thing again and then you know um here we go if sub that counts of key is not zero then we do this thing we add it back um it is equal to zero though then self dot uh counts you want to delete it from existing or together i mean i think this probably good so get max we might have to keep track basically the only place that it will get maxer is here so let me think about this right but we just have to keep track i don't think this so okay so if self. counts of key is greater than max index then sub.max index is equal to index then sub.max index is equal to index then sub.max index is equal to self.counsel key right that part is fine self.counsel key right that part is fine self.counsel key right that part is fine um min is a little bit tricky you might have to think about it a little bit um but let's do this one first so here we go basically if self.counts of key is equal to if self.counts of key is equal to if self.counts of key is equal to um sub.max index um sub.max index um sub.max index so if this is the max and we remove it n length of this thing is equal to zero then sub.max index also minus one right sub.max index also minus one right sub.max index also minus one right because now we just go up down here um so then now we just have to return self dot lookup of self dot max index and then we just take this first element um if no element exists we turn the empty string fine if okay fine i'll return empty string and then getting min is the tricky one because okay so yeah if this happens then this is always going to be min just because that's how min index works um and then incrementing it when would that change basically it's just more if statements i guess if self diamond index is equal to um this number wait did i do that right i think this is right if you go to this number so this is equal to this and now the length of this is zero then we are incrementing it right um because that means that the new min get incremented okay so they're now decrementing uh so this is the max index but also if this is the min index maybe i add this if this is the min index and we subtract then we subtract by one right is that right how do we think whether there's a case where this is just not right well if it goes from one to zero it's where this is not right but then the min index will be zero i guess so yeah so i think we can now just copy and paste this for a little bit let's give it a spin am i confident not at all but yeah uh huh set is not subscribable no but if i convert it to list this is expensive right let me see set first item i think you can do like a first or something like that or next item or something let me see because if you uh create it to a list that's not great okay so it's just next let's see that's just syntax ring okay so i am so that does not make me feel confident because i don't know i don't think that this is a very good um you know i don't think this is a very good example at all that types of stuff but i am lazy so i'm just gonna submit and then use tdd if you want to say for practice uh yeah and as expected let's see um so basically i increment and then like max key is already not working why is max key already not working oh huh this is dumb okay if subtit it's less than one then wow that is pretty bad actually i mean i just never said it here i think that's really it all right let's give it a submit again i'm expecting like four wrong answers for this farm uh just because i'm a little bit lazy today but let's see huh seems like i'm making very silly i mean this is just all bookkeeping and making sure that we track all the states of everything so it's very easy to be off by one but um so we'll see so get min key and so this stuff is wrong that means that we don't keep track of min key in a good way oh wait no i just quote it up okay um let's see why is that so increment all the way uh until here so basically you have 1a for b 3c right and then we decrement the a uh we have min key and it's gonna be a we get rid of it and then huh max key why is max key c oh no to go because the two b's are decommended okay i miss and so that means that there is one eight reason so they're not three c's left oh i see i didn't so basically now if this decrements with this but if this is zero i don't do anything okay um that is tricky actually i don't think i consider that in a good way can i do this in a while loop or is that too slow i mean we can keep track of it to do things in an old one kind of way but it's just messy um but i know why well we're wrong because this goes from um one to now zero how do i keep track of that in a good way right um i thought about this case but clearly i did not oh maybe i thought about the min this case but even this hack is a little bit weird but uh okay yeah because this case then now we're trying to think if we delete it and it was the min then what do we do now because you always have to keep track of all um you hmm let's see i mean i know how to fix it i'm not gonna lie i'm just trying to figure out how to fix it in a not um exhaustive kind of way and the way that you would fix it is kind of what we had before with a linked list right so when you decrement stuff like not justice link this but like a skip list which is what we kind of have here but um let's see right maybe i could just be a little bit lazy here um if this is the case then okay um i'm going to do a for loop but i think that degenerates two and square anyway now because every decrement it amortizes out um so i think maybe i mean i don't like doing it but i think that should be fine so yeah we have to do something to but um but i have to do something to make sure that this is an infinite loop first which is that so that counts i guess okay let's run it because i so the reason why this i think amortized works is because um because this is a sort of a symmetry right what i mean by that is that um if your min gets resetted a lot then you need to go up so basically you're i don't know that i can say it in a good way but let's say you have you know um we have a ref ccc as we did before right um let's say we remove a and now we have five c's and then we have to do this while loop well it only goes up to the number of c's that are before so therefore this is linear in the size of the input because we this will increment this is amortized as the incrementation right because we only go up for the for every um for at most every character that we've seen right so for example if you have like a b c d e and so forth right um in this case let's say you remove a um then now you only go up twice and then now you know let's just say you remove b so then it's still twice and then now you only go up five right and then now you only go up eight or whatever and then so i think in that way it is amortized constant um i think in my head i was trying to prove that a little bit or just have a queen of solution to be honest but uh but yeah um as i mean this is really yucky code um but this is going to be o of one for every operation uh maybe of l depending on you want to say that's the length of the keys but yeah um that's pretty much all i have it's a really annoying problem um but not difficult to understand per se but i just had a bit of silly mistake well this one was silly um and i knew that and i mentioned this a little bit is that um i mentioned this a little bit right which is that i knew that this was gonna be an exhaustive one and what i mean by that is just about thinking through and executing on all the cases which i failed twice on so um but yeah but this is good practice maybe i need to think about it a little bit more but yeah that's all i have with this one let me know what you think hit the like button hit the subscribe button join me on discord i'll see you later soon um take care and goodbye uh hopefully now we'll do the i think the contest is in like 11 hours or something so we'll do it together um i'll see you guys soon bye
|
All O`one Data Structure
|
all-oone-data-structure
|
Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.
Implement the `AllOne` class:
* `AllOne()` Initializes the object of the data structure.
* `inc(String key)` Increments the count of the string `key` by `1`. If `key` does not exist in the data structure, insert it with count `1`.
* `dec(String key)` Decrements the count of the string `key` by `1`. If the count of `key` is `0` after the decrement, remove it from the data structure. It is guaranteed that `key` exists in the data structure before the decrement.
* `getMaxKey()` Returns one of the keys with the maximal count. If no element exists, return an empty string `" "`.
* `getMinKey()` Returns one of the keys with the minimum count. If no element exists, return an empty string `" "`.
**Note** that each function must run in `O(1)` average time complexity.
**Example 1:**
**Input**
\[ "AllOne ", "inc ", "inc ", "getMaxKey ", "getMinKey ", "inc ", "getMaxKey ", "getMinKey "\]
\[\[\], \[ "hello "\], \[ "hello "\], \[\], \[\], \[ "leet "\], \[\], \[\]\]
**Output**
\[null, null, null, "hello ", "hello ", null, "hello ", "leet "\]
**Explanation**
AllOne allOne = new AllOne();
allOne.inc( "hello ");
allOne.inc( "hello ");
allOne.getMaxKey(); // return "hello "
allOne.getMinKey(); // return "hello "
allOne.inc( "leet ");
allOne.getMaxKey(); // return "hello "
allOne.getMinKey(); // return "leet "
**Constraints:**
* `1 <= key.length <= 10`
* `key` consists of lowercase English letters.
* It is guaranteed that for each call to `dec`, `key` is existing in the data structure.
* At most `5 * 104` calls will be made to `inc`, `dec`, `getMaxKey`, and `getMinKey`.
| null |
Hash Table,Linked List,Design,Doubly-Linked List
|
Hard
| null |
983 |
hey guys in this video we shall sell the problem only for myself on guitar so today's problem is minimum cost for tickets we have planned some train traveling one year in advance the days of the year in which you travel are given as the integer that it is from 1 to 365 that's that means it's a long leap year and what else they have given train tickets are sold in three different ways of train tickets are there one is one day pass one is seven day pass another one is 30 day pass and one day pass cost is that so for cost of zero two rupees here box and seven day passes sold for cost of one seven bucks and 30 day passes so for cost of two dollars whatever we have the passes that I tell you many days of consecutive travel for example what does it mean it is nothing but if you start from the second day and you take a seven day pass on that day from the second day till this uh plus seventh day that is the thing with three eighth grade two three four five six seven eight total seven days the seven day passes value you can travel with the salary pass among all this place from 2 to 8. so if you take a seven day pass on our day two of the year then the summary pass is valid until seven days from the day too that is nothing but two three four five six seven and eight total of seven is one two three four five six seven so from day two till the seventh day this seven day passes valid similarly that a plus for 30 day parcels foreign approach what we have to solve here is written the minimum number of dollars you need to travel every day they give a list of things that means if you take this example oh yeah one sec so if I take this example you could see uh if you take uh this is one day pass this is some in the past and this is until the past cost right so if you imagine you are taking one day pass for all the days here you are traveling on the first fourth sixth seventh eighth and 20th Day in the year in a three so you have to take classes imagine you are taking one day pass that will cost you two rupees for each so total monthly for six days six into two foreign so that will cost you how many rupees how many Bucks seven bucks so after this seven you check for eight and then the next the 20th so both this doesn't come in the same to be correct it is that doesn't come in same so if you take month that comes in the same month but if you take that monthly task that will cost you 15 rupees total of 15 rupees but if you take daily pass for each of them but here if you take monthly pass 7 plus 15 that will cost you more than 11 right so you can see instead of taking daily pass day one day pass that would cost it 12 rupees if you take seven day passwords and then one day pass it will cost you 11 rupees which is the optimal it is a minimum number of dollars that we need to travel every in the list of given list of books so we have to find Optimal solution similarly it applies for this uh example as well so what's the place to solve the problem so we'll be using dynamic programming approach so as we use a direct programming approach we'll be using the bottom up approach related from the back till the front so let's consider the RF 1. 4 6 . so if you take this up this would be it as I said we will be starting from the last about it till the front right so we need this element first so for this element last element you have to check whether the given costs are 2 7 and 15. so 2 7 and 15. since it's a single life I take daily pass but sometimes the monthly pass will be lesser than the one day pass so monthly pass or weekly pass will be lesser than the daily pass foreign so now you have something minimum of all three next comes in this part next element from the backwards so here it for eight you have to check whether the I plus one element is appears in the same way does it appear in the same week no so it's better to take a gate when they pass that will cost you C1 that is number two rupees then file you know you might take 30 day pass but most of the data pass is more than cost of Winter Pass so you are taking C1 here again we are doing the minimum operation so next again you come to the next one so all these things yeah these things have not been calculated focus on because you're using you're doing bottom of approach the end of the rate in the beginning of that now for seven if you consider and how do you solve this problem yeah let's take a general case here so if you have something elements like this um these many things you have calculated earlier that is that will contain 8 and 20 as I said that things we did C1 and here we took C1 already one day pass and here Universal seven and one four six are present this side both sides so at this point you have the pointer node now here you have to take uh you have to check whether or not you have to take is it one day pass or is it seven day pass or is it 30 day pass for that what you have to calculate each one of them and find minimum of one forget it here so how to calculate each one of them in such cases in the mid of the array if you have some number so for that C1 it is nothing but the cost of Base whatever you have let me see one plus DP of I Plus 1. TP of I plus whatever this is further when they pass if you calculate so c 1 equal to C1 plus nothing so C7 seven day pass here so from here for 7 day pass this one they will be included from here till the 7th today to the seven days so here you if you have D7 that will be applicable and the remaining dates after this whatever you have foreign calculated before C7 that will applicable to 7 days then for the later part is a liquid DP of t7 D7 will be pointing to some ith value here coming from here seven days ahead like similarly for 30th pass also if you have if you take 30th 30 days pass um which is better anything you can take if you take 30 days pass from here till the 30th daylight is applicable so if here it is P30 from here your normal calculator so that for 30 day possibility Plus TP of P30 that type of 30 days from the E1 pointer so you have to find minimum of this and this that will be yeah uh for cause bugs will be open to this big particularly similar you do for all other days and finally you will get dprc as a result so let's score this so that you will better understand I should ex I'll explain the example hide in hand at first we need to calculate the length of the so once you calculated now let's create the dynamic array print AP equal to new end of n Plus 1. so now we have to initialize the array with some value so for if I equal to 0 I minus and I plus AP of I will be equal to some charge value 365 star cost of that certain but you are taking the one day pass COS of zero so this is the worst case possible you are considering next after this coming to the actual part we will start with the end of the array till the beginning of the end so whatever so far if I equal to n minus 1 I greater than or equal to 0 and I plus at first you need to calculate the one day pass then uh similarly submit a pass and similarly 30 day pass so how do we do that when they pass that initialize to C1 equal to COS of 0 because you are taking one day pass that is for here you are pointing here COS of 0 plus the remaining cost that is nothing with DP of I Plus 1. that is this cost which we initialize right that is for one day next coming to the let's initialize the um 70 plus t7 equal to I and D 30 also equal to I fine now you have to calculate the submit the password so why D7 that I value should be less than n and I have to check if we are pointing here you have to check the next value is coming in this same week how do you check that there's nothing but place of p7 that value is lesser than base of I Plus sub so if you are pointing here from here to still the seven days with the days of decent value is lesser than this then that means that comes in the same way so at that time you have to increment yourself 87 plus 330 whatever value you have here that should be less than days of I Plus 30. so for example if we take 30 day pass here consider imagine the point reporting here so days of 30 is pointing here at 37. and there is of I plus 30 is nothing but 7 plus 30. so 37 yeah it is coming in the uh portals 30 plus so increment D30 so it will Point here now again he said whether it is something 38 plus 30. so 8 is less than case of I plus 30 raise of I set up at 7 plus 30 yeah it is coming in that value so whatever from here how many values you get inside the place you take all those into form and Implement each plus so once you have this A7 v30 and the constant C1 also you have to take the minimum Matrix so PP of I finally it would be meaning of or C1 comma again math 30 because in Japan meaning of 70 and 30 seconds from that minimum part you take compare it with the one day pass so enough COS of 1 plus DP of D7 that is one thing then again COS of two plus DP of d 30. somewhere over here right so that in the course you have to add whatever you put so at last as we are having the Quantum of approach from the back build the beginning DP of 0 so this at last it will have open so we'll run this we take seven out of three this should be I minus sorry yeah it's been accepted I will submit this yeah problem has been successfully submit so basic logic what we applied actually is that is and yet each time that each index you calculate the birthday pass what will be the one day pass this is available 30 days and we take minimum of all three that is work done so to calculate one day pass so if you can support the password is it will be nothing but DP of I plus one that's what written here if you consider 70 plus how do you check that so each element I trade whatever we have that should be lesser than the 7 plus 37 Days 14 days if you come here if you consider so days of days are 20. 2 is 20 lesser than 7 plus 7 Days of ie7 plus 740 no so that won't be coming in that week so but for a eight plus uh eight is lesser than 7 plus 7 14. so that will be incremented so T 7 plus that cost you add so COS of one means till the 7 days this is 5 COS of one and for the remaining part whatever you have D7 in this point in here so that cost DP of D7 too happy I hope you guys have understood the problem with another video next session better then subscribe to the channel we keep learning thank you
|
Minimum Cost For Tickets
|
validate-stack-sequences
|
You have planned some train traveling one year in advance. The days of the year in which you will travel are given as an integer array `days`. Each day is an integer from `1` to `365`.
Train tickets are sold in **three different ways**:
* a **1-day** pass is sold for `costs[0]` dollars,
* a **7-day** pass is sold for `costs[1]` dollars, and
* a **30-day** pass is sold for `costs[2]` dollars.
The passes allow that many days of consecutive travel.
* For example, if we get a **7-day** pass on day `2`, then we can travel for `7` days: `2`, `3`, `4`, `5`, `6`, `7`, and `8`.
Return _the minimum number of dollars you need to travel every day in the given list of days_.
**Example 1:**
**Input:** days = \[1,4,6,7,8,20\], costs = \[2,7,15\]
**Output:** 11
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 1-day pass for costs\[0\] = $2, which covered day 1.
On day 3, you bought a 7-day pass for costs\[1\] = $7, which covered days 3, 4, ..., 9.
On day 20, you bought a 1-day pass for costs\[0\] = $2, which covered day 20.
In total, you spent $11 and covered all the days of your travel.
**Example 2:**
**Input:** days = \[1,2,3,4,5,6,7,8,9,10,30,31\], costs = \[2,7,15\]
**Output:** 17
**Explanation:** For example, here is one way to buy passes that lets you travel your travel plan:
On day 1, you bought a 30-day pass for costs\[2\] = $15 which covered days 1, 2, ..., 30.
On day 31, you bought a 1-day pass for costs\[0\] = $2 which covered day 31.
In total, you spent $17 and covered all the days of your travel.
**Constraints:**
* `1 <= days.length <= 365`
* `1 <= days[i] <= 365`
* `days` is in strictly increasing order.
* `costs.length == 3`
* `1 <= costs[i] <= 1000`
| null |
Array,Stack,Simulation
|
Medium
| null |
131 |
of legal question palindrome partitioning and this is a median legal question so giving a string as partition s such that every sub uh every substring of the partition is a palindrome return all possible palindrome partitioning of s so if you take a look at the example is oh a palindrome string is a string that reads the same backward and as forward so a palindrome is like a you breathe backward it's also a right so if you give an example string aab and when you slicing partitioning it you can partition into a b and a b are all palindromes because they read the same forward as backward so they are considered and then the next way is you slicing it into a and b so a is palindrome and b is palindrome and there's three character here if you want to continue to slicing it's aab right but a b is not a palindrome so it's not included in the answer and another example the string is a and you're slicing into a and the a is a palindrome so you only have one combination so you return the answer and there's some constraint here and this is a question asked by amazon and google these companies uh this amount of times in the past six months um if you look at this question um using one of the example right um let me show you it's um aab so the way you want to slice it is um it's you can basically easily do this from that first by using that for search and when you do that research you want to slicing it as first time when you go through it you want to slicing it as a um and then the remainder character so you want to pass through two parameter one is the string itself and then the second one is basically the path the subset and if you uh slicing them at the beginning with the first character right and then you left this a b for the remainder and then you can continue to run that for search on the a b and until the end of the entire string like you also gonna then the next step you're gonna repeat to run that first search on b and after the entire cycle when you run the that first search and when you complete the entire data search on this once that's the time that you want to append the result like you have a b you append the result to the um the uh and the result that you're looking for basically this is one type of combination then you want to continue the that first search and basically a string right i already tried to um slice the um string this way one by one right and then the next time i'm gonna increase the slicing uh partitioning i'm gonna slicing it partitioning it into two part and a two character right and i'm so i'm gonna do a as the first part and then i'm check i'm gonna check if this is a palindrome if it is i'm going to continue to run that for search on the remainder characters and it is a paulo jones as well so in the end there's no nothing left in the character because every time when you do the um that first search you um check on these characters the characters will remove the from the string right so the base condition that we want to do when we want to terminate the loop is that once you can complete the entire string so like the second case you finish a and you also finish b you finish the entire string and then that's the time that you can append the result to the result that you're looking for and also then the third time you're gonna run it is you're gonna run slicing by slicing two or three sorry because we did a one and we also did two and then the third time you can do three times and then you can check if this is a pound palindrome if it is a palindrome continue the devil search if not simply no need to do anything so that's basically the thought process and it's pretty straightforward and i'll show you how to do it in code so i'm gonna define the defer search function like i mentioned i'm gonna pass two parameter one is the string and the other one is the path or subset basically whatever you wanna call it and uh the pa the string is uh a b originally passed to right and then the pass is um whatever part of the pass that you get and if you um if the pass is a and then the string will have a b left if that makes sense so i'm gonna say define the base condition remember that we mentioned that when i finish slicing up the entire string so when there's nothing left in the string i'm going to append the result of the path to the end result basically i'm going to append aab to one of the result so that is the base case actually so if not s then i'm gonna rest append the pass yep that's the time i wanna finish this loop so then i'm gonna partition it for i in range so i'm gonna set a range for the eye which i'm gonna how i'm gonna partitioning this so i'm gonna start from index one and also the length as plus one the reason is because how the string is um the string is sliced and you will see when i uh write this encoding and you understand why it has to be starting from one and length plus one here so i'm gonna say if the string that i'm slicing at is a palindrome so it's draw i'm just i'm going to write the power excuse me i'm going to write the palindrome function a little bit later but basically i'm going to slicing the string into the uh from the beginning to the index i and i start as star from one right so if i start from one that means the first one that i'm judging is if a itself is a palindrome if a is a palindrome what i'm going to do is i'm going to do run the daffo search on s i so basically i want to start from the first uh star from the first character so basically run that for search on a b if that makes sense to you um if a is a palindrome i'm going to run that for search on a b that's basically what it means here because i passed another parameter also the past right and when i run the path it will be the original path plus on top of what the um the uh a the s i is uh partitioned at so basically the path will be original path added to add the path of a so the path becomes a in this case but i'm running defer search on the string a b in this case so then that's the main part of the different search function and then i'm gonna write the palindrome function is palindrome so i'm gonna pass the parameter as a string so it's actually pretty straightforward to write a pound zone because if the string is read same backward and forward so essentially what you want it to return is the string is equal to this is how you do in python you read the string itself and if you read it the backward is if they are the same it will return true if they are different then return false that's how you judge it as a if it's a palindrome and i'm going to assign a result so basically the result i appended it here and then i'm going to call the different search function and the string is the one of the parameter i'm gonna pass through and the second one is the path pass i want to start from our empty path right so after that i'm gonna return the result i hope this is helpful and please give me a thumbs up if you like my video and subscribe to my channel and i'll see you with more legal questions bye
|
Palindrome Partitioning
|
palindrome-partitioning
|
Given a string `s`, partition `s` such that every substring of the partition is a **palindrome**. Return _all possible palindrome partitioning of_ `s`.
**Example 1:**
**Input:** s = "aab"
**Output:** \[\["a","a","b"\],\["aa","b"\]\]
**Example 2:**
**Input:** s = "a"
**Output:** \[\["a"\]\]
**Constraints:**
* `1 <= s.length <= 16`
* `s` contains only lowercase English letters.
| null |
String,Dynamic Programming,Backtracking
|
Medium
|
132,1871
|
286 |
hello welcome back today let's try to solve another lead called Problem 286 Wars and dates so for this problem yeah we can understand it according to destroying example one yeah because example two is a substitute forward if there's a minus one needs it is worse yeah we're gonna just have to return the rooms our final grade yeah and now let's text example we just need to attack the empty this empty needs rooms so what is the shortest distance so one two three it means four here one two three it means here is three so it means the shortest distance is the three this is why for this one it is this ring that's a technology grid for example this one it should be one because it has to go here now let's check if it is one yeah I'm not going to attack all of them but this is such examples meeting and we also have a infinite it does matter because this infinite Sesame is empty rooms and minus one means walls and zero means skate now how can we solve the problem of course we think about the BFS yes if we use BFS with the brute force it means that from this point we're going to attack what is the shortest distance by BFS it means we've used how many BFS M times nbfs because for each of the integrated we needed to use the BFS and for each of the BFS we fixed M times n time so finally the time complexity will be all M Square Times a square yeah as you can see this usually takes the time yeah and this is the Python Meaning of the square I just use this sign yeah but actually we can just use M times n times complexity to solve the problem why because we can use the multi-source we don't need to Loop multi-source we don't need to Loop multi-source we don't need to Loop through all of them use M square and square time we just need to use M times n yeah if we use multi-source we're n yeah if we use multi-source we're n yeah if we use multi-source we're going to start from the date not from the Looms so this is something yeah you need to think backward not forward you need to think from the result and then go to the empty rooms not directly by the back group now if we use the money Source we put the empty yeah we put the gate inside our multi-source inside gate inside our multi-source inside gate inside our multi-source inside double queue and set after that we're going to use the DFS it starts to take so om times n time to update all of the empty grid inside the drawing for example here will be updated to 1 and this one will be 2 and this will be two this will be one I will not put all of them but you can see the drawing this is one two three and this is two this is one and this is two three and four it makes sense right because the drawing is like for each of the grid we need to find but for us we need to go from the date and then go to the empty rooms as you can see that it's very straightforward yeah now let me just start my coding so for the multi-source BFS we're gonna so for the multi-source BFS we're gonna so for the multi-source BFS we're gonna prepare some template code let me prepare RNC should equal to length of the zooms and the less of the rooms zero let me prepare a queue with a visited set the two should be the queue and which to the set should be empty set now I also need a directions item is a I'm gonna have four directions so inside the directions I'm gonna prepare some setting for my calculation so zero one zero minus one this just means four directions and one zero and minus one zero after initializing all those variables we can start to the first multi-source we can start to the first multi-source we can start to the first multi-source we're gonna fight the multi sauce so for our in Ruins capital r and for C increase Capital C here we need a condition tag if looms are say equal to let's attack the gate because the gate is zero if it is equal to zero yeah it's from here if it is a gate so what are we gonna do we just need to put it inside our queue 2.2 append our queue 2.2 append our queue 2.2 append with the RC and 2 dot add with RC yeah this one without the finished our multi sauce because we don't need to update our rooms are safe because it already started from zero and then from the next place we first use this zero plus one for the next neighboring empty room this one for example this one and this one now let's just start our BFFs so for the BFS we're going to use a while loop Wireless q and RC is equal to 2 dot pop left after popping the first knot we're gonna update the RC so for Dr and DC in directions if let's update to the new low and new column should be R plus ER and C plus BC now we just need a tab so for zero less than the low last layer and equal less than or equal to low less than R and similarly for the column should be more than and equal to zero and less than capital c and also everzo and the column Tuple not in visited yeah now let me spread a little bit to make it just one line yeah for attacking mistakes as you can see I have a typo it should be visited now after second if it is not invented I don't need to check these numbers infinite numbers as you can see because I used a visit to the set yes if it is inside visited set it means the gate has already been inside visited set but I need another attack I needed to attack if it is not a wall and if and Looms row and column not equal to minus one because this wall is -1 yeah minus one because this wall is -1 yeah minus one because this wall is -1 yeah if it is it's not I can update the queue 2. iPad with a manual and new column similarly the related set dot add with the new low and new column now I can safely update my rooms so the rooms with low and column should equal to rooms where am I coming from RC yeah this RC means from here it is popped out yeah it means this is RC and this is my neighboring empty looms yeah plus one finally I just needed to return the rooms I hope there's no typos yeah let's assess the tag if it works okay or the Q add I use a Heroes would be related set dot add yeah really set dot add let me run it again to tag yeah and you can say it works now let me submit it to attack if it can pass all the testing places foreign two percent of all python submissions and the code is quite clean let me spread it yeah as you can see the time complexity is last time and for this one this area is just a template with for any kind of a money Source problem we need to prepare this and we also needed to prepare this is the basic situations for us because the rooms are say equal to zero we don't need to set it because it's already started from zero even it started from other numbers it doesn't matter it's not depended on the description on the output of the problem as you can see here this area is also the template here the only difference is we have what was we need to attack if it is not equal to -1 but to attack if it is not equal to -1 but to attack if it is not equal to -1 but for other normal problem we don't even need to tax this condition and here is also the template code there's no other new code in a template yeah thank you for watching if you think this helpful please like And subscribe I will upload the money to go to problem fluxes and I will prepare all patterns of the electrical
|
Walls and Gates
|
walls-and-gates
|
You are given an `m x n` grid `rooms` initialized with these three possible values.
* `-1` A wall or an obstacle.
* `0` A gate.
* `INF` Infinity means an empty room. We use the value `231 - 1 = 2147483647` to represent `INF` as you may assume that the distance to a gate is less than `2147483647`.
Fill each empty room with the distance to _its nearest gate_. If it is impossible to reach a gate, it should be filled with `INF`.
**Example 1:**
**Input:** rooms = \[\[2147483647,-1,0,2147483647\],\[2147483647,2147483647,2147483647,-1\],\[2147483647,-1,2147483647,-1\],\[0,-1,2147483647,2147483647\]\]
**Output:** \[\[3,-1,0,1\],\[2,2,1,-1\],\[1,-1,2,-1\],\[0,-1,3,4\]\]
**Example 2:**
**Input:** rooms = \[\[-1\]\]
**Output:** \[\[-1\]\]
**Constraints:**
* `m == rooms.length`
* `n == rooms[i].length`
* `1 <= m, n <= 250`
* `rooms[i][j]` is `-1`, `0`, or `231 - 1`.
| null |
Array,Breadth-First Search,Matrix
|
Medium
|
130,200,317,865,1036
|
1,004 |
hey what's up guys this is juan here so this time they called 1004 max consecutive ones number three so you're given like a binary array numbers and an integer k you need to return the maximum number of consecutive ones in the array if you can flip at most k zeros okay so for example we have the cell rays here and k is equal to 2. so in this case what the answer is 6 because so this is the longest uh consecutive ones we can get which is six by flipping two zeros into one right and so here's another example right and then the constraints is like uh 10 to the power of 9 and k is the same as this one right so this one i mean most since we're looking for like a consecutive ones so this one it's obviously it's a sliding window problem right basically we just need to maintain like sliding window and within that sliding window we need to make sure the zeros in that flat in the sliding window will not be greater than k right that's how we can do it basically we try to expand this line window as much as we can until the zero is exceeding k then that's when we stop that's when we uh we need to shrink the sliding window right basically slightly window is one it's one way the other one is like the binary search right so obviously the sliding window is of n time complexity but a slight by the binary search even though it's unlocked and but it's also uh worth mentioning here basically the sliding the silver binary search right what we'll do is that we simply just directly search the answer which is the maximum consecutive ones basically we search that sliding window size directly right because so the reason being is because the uh you know the longer the sliding window is right the longer the sliding window is the more uh the basically the zeros it includes will be uh bigger right so which means that you know we'll keep increasing the signal size keep going until it reaches a certain point right once we once it reached a certain point here the zeros right basically all the possible uh sliding windows with that specific size the zeros will be greater than k right that's when we when you stop and that's how we use the uh basically the binary search to find the answer because there as you guys can see we have a trending here right so the size of the sliding window right increasing and then the uh the k will also be increasing right so by the time k is this one is greater than this k here that's when we need to stop and yeah so what shall we do here um let's do a slide let's do the binary search first because i think first sliding window is kind of obvious right so i'd like to do a binary search so for binary search you know the uh obviously the left is zero right and the right is n right but we need to have a n first that's the boundaries of this binary search okay and then since we're looking for the maximum right and we can utilize the maximum slightly binary search template right l middle is going to be the l plus l minus allow left divided by two right and then we're going to have like helper functions right so basically this helper functions will take a size basically a fixed size of the sliding window and then it will check which this size of sliding window does it exist any uh a window with this size whose zeros is either equal smaller than k if it is no we know okay so this uh this size of sliding window is a satisfy the condition right that's when we need to set the left equals to the middle because we're looking for the maximum numbers that's why you know this basically this middle could be our answer and since we're looking for the maximum that's why we're trying to push this the left boundaries as right as to the right as possible right i think i have already talked about uh this maximum template a few times here so i'm not going to the too much of the detail here else right how's the me the r is going to be the middle minus one right so in the end we return the l cool so that's that and then the only thing left is just to implement this hopper function so we're taking the length of the sliding window right or the size or let's call it length and then we can do a flips right so equal to zero so this flips actually is uh equals to the number of zeros right in it's in the sliding window uh we have a bunch of ways we can do it so for me i just do this we have the size of the length right and then flips equals what basically if the numbers of i right equal to zero right and then that's when we need to flip it right that's how we do a flips plus one right and then basically and then we check if the flips right it's either equal or smaller than k and then we return true right so actually you know what so actually this one can be simplified basically you know we only increase by one when this one is zero which means we can do what we can do this you know we can do this one kind of times i here that's so this one means that what means the uh if we do x over here right we'll never own this is zero we have one when this is one we have zero actually this one is equivalent to this one you know you can either do a one minus this one or you can do this one uh x or this one basically if it's one then we'll not flip it right that's why we get zero but if it's zero and then we need to flip it right okay and then we have i in range of length dot n right so this is where we start the uh moving the slide window so this is we create the first sliding window and then we check that up and then every time we move to the next to the current sliding window we're gonna update the flips right so similarly as this one right so we that's the we need to increase the flips right and then we're also gonna decrease the flips right for the left side which is uh which is the i minus length right and then we do the same thing here basically right so and then in the end right return false right so you couldn't find any of any valid sliding window right or stop string right or stop array then we return fast in the end yep so that's it run the code i guess it should oh yeah so keep in mind that every time when you set this left to the middle you need to do a plus one here otherwise you will basically you and it will end up in an infinite loop here right so now if i run it okay accept it and then cool right so it passed so as you guys can see this only beats like five percent right so don't the reason being is because this one is like unlogan time complexity right because we have i think this one is n right the number is yes so this one is n and this one is a login and for each of the helper we have a of n right that's why we have this one uh yeah so that's the sliding window i'm sorry not sliding that's the binary search right and then for the sliding window selecting one is pretty actually see it's easier you know so same thing right we have n is going to be the length of numbers so l is going to be at zero and then the answer is zero as well and then for r in range of n right so this time um we can either use uh flips or we can use k uh yeah let's stick with flips here since i'm i've been using flips from the beginning right or you can decrease k either way it's fine so let's since we use flips for the binary search let's keep stick with flips here so basically flips uh gonna be class right same thing here uh for this one right okay and if the flips right is greater than k right that's when we need to shrink the left pointer which is the uh so when we shrink it we have to do this right similarly as that binary search thing so flips gonna be one x or nums uh left right so this one is r okay and then we move l to it to the move out to the right by one and then we can check if the flips right is either small either smaller than k if it is then we can update the answer right dot uh l minus l plus one okay then return the answer in the end because here you know we need to check it again because once we and once this if it's finished right it means that maybe the ones we are where we are like moving out of the sliding window is it's one it's not zero that's what and if that's the case you know the flips will not be decreased right which means that you know we have to keep uh we have to keep shrinking the left until the flips uh is smaller than the k that's when we can update the final answer right so run it yep so that's it sliding window right and obviously this is a often time complexity um yeah i guess that's it right i mean i don't know actually you know to me uh i first came up with a binary search solution for some reason and then while i'm implementing this helper functions i realize that you know this one is actually a sliding window problem where which means that we can simply just use a slide window concept right there with the left and right pointer to solve it yep i think that's it right a very classic sliding window problem and cool thank you for watching this video guys i guess and then stay tuned see you guys soon bye
|
Max Consecutive Ones III
|
least-operators-to-express-number
|
Given a binary array `nums` and an integer `k`, return _the maximum number of consecutive_ `1`_'s in the array if you can flip at most_ `k` `0`'s.
**Example 1:**
**Input:** nums = \[1,1,1,0,0,0,1,1,1,1,0\], k = 2
**Output:** 6
**Explanation:** \[1,1,1,0,0,**1**,1,1,1,1,**1**\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Example 2:**
**Input:** nums = \[0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1\], k = 3
**Output:** 10
**Explanation:** \[0,0,1,1,**1**,**1**,1,1,1,**1**,1,1,0,0,0,1,1,1,1\]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
**Constraints:**
* `1 <= nums.length <= 105`
* `nums[i]` is either `0` or `1`.
* `0 <= k <= nums.length`
| null |
Math,Dynamic Programming
|
Hard
| null |
48 |
okay so let's start our today's daily recoding so today's question is rotate image and i checked it is a medium question so uh let's see how much time for me to spend on this question if i could resolve it okay so let's take a look at the question so rotate image you are given an m by n2d matrix representing an image rotate the image by 90 degrees clockwise okay you have to rotate the image in place which means you have to modify the input 2d matrix directly do not locate another 2d matrix and do the rotation so for the example that we have uh so we see that it's one two three in this direction from left to right and the result is that it also it's a counterclockwise rotation from so now uh originally the one start in the top left corner and then now one becomes in the top right corner and then it's from top to down which is one two three so the input matrix is one two three four five six seven nine seven eight nine and then it will become seven four one eight five two nine six three okay so for me it's like um i don't know we are supposed to do that in place which means ah so there i guess so yeah there is no return value so it's rotate yeah we are supposed okay so let me think about it so we have a one mapping from this to that and um uh i don't know so what about the inside so this become this and okay so by rotating counter clockwise 90 degrees the index 0 becomes the index n 0 n so the 0 and becomes that okay is there a better way of doing this i don't know if i would do it in place can i only have one temporary uh integer when i am doing the swapping okay i don't know um let's try it so if i would only have one temporary memory temporary integer to save the value if i save five i can move this to here okay if i save 11 i move this to here and then i save this one and then i move 11 to here okay so that's the first one so um god okay but what's the order though so i change five first and then i change this then all the outer one got fixed right because if i would put 1 in here then i need to put 10 in here then i need to put 11 12 in here and then i will need to put 13 back to here and then the same thing when i do the 9 goes to here 7 goes to here and 14 goes to here so if i do it like onion like layered by there so start from the outside layer and then do this one and then until there's no one to switch okay so let's try it but how to do the math though so i will need to have a temp let's give it matrix zero so um for integer i equals to zero i smaller than matrix that then is this length divided by two so what if it's 5 divided by 2 is 2 right so oh let's use this as an example so if we have 3 the length is three divided by two is one so we only need to do one layer because this one we don't need to touch it so divide it by two sure works and um and i need to smaller or equal right for example this one i need to do it twice and i should start with oh i do not have to be equal because this is zero this is one and we should stop okay good increment i okay so for each layer we do from the first one to the length of that there that layer minus one okay so for example so for this i start with i which is zero this i start with one index one and this is layer one two so we have a integer j equals to i and um j smaller or equals to so originally the first layer is the length minus one and then this minus two right because with shrink yep so what's the length so the lens will be um not length so i want the column count will stop at uh the first one start at this the second one stop at this right okay let's do the length hmm okay let's have a integer to store the length of each layer so i will start it with m so it's let's say that it's n by n okay so and equals to tricks done length and m equals to matrix 0 star length so let's change this to n and the length will be okay so then j could be this and j less or equal than m minus one right j plus okay so the first index will be uh i'm t so do we have a temp yes we do have a temp equals to matrix i start with i uh god i plus what i plus j is that correct i think so that's our temp and after i save this value i could move this so then i could move this one i could move in the same column so this won't change move up to the first row so the last row is the length wait so it's m by n okay so the next one is so this is i plus m is that right minus one is that right this is this how about this is 13 okay i have some math problems so i am moving from okay i'm moving what is the oh god so okay let's write it down to see if we can figure out or if i can figure out so for the first layer you move uh 0 zero two hmm so this is n equals to four and you move zero to zero 3 and then you move 0 3 to three and then you move three two three zero and then you move zero one oh god to zero one two three all right zero one two three one three and then you move one three two uh okay three two and then you move this three two zero can i find a math pattern which can represent this so for i always start with the i so j let's see j if diff well it's a little bit confusing but j is this front or distance right so i save this and then the distance from the zero column so the same column and the length so you're always going to move from the same column and the length minus one this is the length minus j is that right and then i will move this one i will move from the other corner which is the same row and the distance the length minus j and then this will be matrix the same column but okay the same column and distance from the top so the row will be i okay minus one minus j isn't that the same okay what am i trying to do nope jay no so this is the eighth row i plus j and then finally this will equals to temp okay so i start with the i minus j i put that into the temp and then i will move the one in the same column but uh is this minus i minus j okay now the starting point is n minus one and i'm getting confused so this one will become the same role but m minus 1 minus i minus j i am so confused is there an easier way so this will be the same column a different role okay let's see so let's try it so for i equals to zero and j equals to zero we have temp equals to matrix zero and we have matrix 0 equals to matrix n minus 1 m is four minus one three and zero and we have matrix three zero equals oh i'm so stupid oh my god and this one is three minus zero and this is three and then we have matrix three equals to zero three finally we have matrix 0 3 oh my god equals to temp is that right so r00 moved to zero three right so zero three equals temp which is zero r zero three moved to three is that right so three is zero for three move two three zero so three zero is three so it looks like it's correct one j okay my cat is blocking my view hey come on can you move empire okay sorry my cat is on the move say hello okay now we are back but where is my cursor oh god okay so let's see what if i equals to zero j equals to 1. temp equals to math i plus 1 so i 0 i plus 1 is i plus j is 1 and the next line is matrix m minus one which is three minus zero still three minus one is two so two okay hold on so we have temp equals to this and this will equals to matrix so three or four minus one three two and then two one that looks weird two one so that is wrong oh my god my math yeah of course they are a different role so if you put this to temp this has to be one two zero two this has to be zero two oh god i am confused about my math okay so this is i plus distance the row is i the row is always i and then you're moving from ah god i need a math for me to turn things to 90 degrees how to map thing to 90 degrees just oh my god it's already 40 minutes i haven't been able to resolve this issue because of my math okay my cat is here again okay like i am confused about myself hmm i need to do so this is always i right so let's make sure that i know the four point the top left is always i and the top right is always i plus the length do i need to make things so complicated because the top right could be n minus 1 minus i right i and the bottom right is or let's do bottom left first bottom left is this backward is the column is the same so it's i right but this is the row will be m minus 1 minus i and bottom right is m minus one minus i m minus 1 minus i is that right so i start from i ugh so i still have i start from zero two and divided by two but what is j though i might be able to start with i and stop right at this and j plus and then the first one will be ij and then i j will become so i need my button left hmm oh the bitrate i am not sure i guess it's lagging because of my let me see my bit rate oh it's pretty low okay so am i able to like change my bitrate while i'm streaming i'm oh i'm using obs i'm not sure or do i need to like let me try it warning recording save okay let's reduce it to 3500 okay i'm not sure if it's getting better though maybe yeah i don't have good internet speed okay we still have i guess it's still lagging let me try yeah i don't have really good internet speed but we only have two hours before the daily questions and i still am struggling with my math oh my god okay now streaming at sorry i'm new to the streaming i'm not sure about how to set it up correctly okay i forgot about my math and it's still lagging here okay anyways let me come back to my math oh my goodness so for the bottom left i always start from this right and then i will keep minus in j so this should be minus j right okay my cat is here the annoying cat is messing up with my math ability okay so the row is different but the column should be the same which is i and then this one my kid is trying to type for me come on okay i'm still struggling with my math ability and my network and my cat okay so this one is then i will need to move another one so i move this one to there right or not bottom left will keep in the i column and my bottom left will move from my bottom right then they will be in the same row so it will be this one okay i am going to adjust my network next time when i streaming and so the matrix they will come from the but it's backward so it's m minus one okay now i'm getting confused so they will always be the same role so um i'm confused again you know what j is moving while i is not so if you are going to move from the bottom left to the top one and you need to keep it in the white row so the bottom right will always be on the same row which is this one but it's a moving one and this one is to move from bottom right to top right so that one will be always in the same column so the top right column is this so is this but the row is increasing so the row is j okay let's do the math again so if i and j are both zero so the temp will be matrix zero and then matrix zero okay my cat is doing something again what are you trying to do okay you can sleep here i have a little to solve sleep here okay no i can't type okay let's check so matrix three zero so the 0 which is i will become the n minus 1 which is 3 minus i okay i think the first is right how about the second one so the second one is star from temp is 0 1 and 0 1 is matrix this is still 0 so it's still 4 minus 1 which is 3. and minus j which is i which is one so it's four minus one is three minus one is two so this one is two is that right so m matrix 0 1 this you put it into the temp and then matrix 3 0 1 2 3 2. okay it's completely wrong m minus one minus i oh hold on this is zero this is one which is two so two zero is thirteen okay this time it looks it's right how about the next one okay i need to type i need to be able to type okay so let's check the next one so to 0 is this is four minus one minus zero why do i think it's wrong four minus one is two so which one is three two oh it looks correct this move to there and then we need to have 10 move to here so let's try it okay where were we so we are in the j which is i which is one we have four minus one with three minus zero three so which one is the matrix one three this one okay it looks like this one is correct how about let's return oh we don't even need to return i don't know is that it are we able to run this compile arrow line knighting what did i do oh my god it's still wrong why okay ah let's drink some coke and coke is not helping i'm curious i did this before i almost gonna cheat and see what i did long time ago what is this question 4da wow i did this really long time ago yeah it should be seven four one right so how about let's do only do i equals to zero let's try it i want to see so when i equal to 0 it's already wrong right know i equal to zero is already wrong so it's like i put one into temp and i should move seven to one so what is wrong let's do it step by step yeah right so i put seven to the one position which is weird okay hold on oh i guess i know why but i don't know how to fix it and divide it by two so i all so i is always the starting point right but what is j though and when should j stop so when j is when i zero so j will be start from zero to n minus one and when i is one so j will start with one and end with minus one which is three oh which is two so this part looks correct okay try to reduce the frame rate sorry let me try i just don't know if obs can reduce the setting while i'm streaming okay i reduce it again hopefully it won't keep delaying because i don't know maybe i have some problem with my network right now so sorry what's even more sorry is my math ability okay let's recoup oh my god it's delaying again okay so j now is not the distance right so j is oh god it's okay because of my network issue now i'm confused again so j start from i okay let's try how about we only do the first how about let's try i equals to 0 and j equals to i so we move seven to the one position and then we move one to the three position and then we move three to so it looks like something is wrong so 3 we move to 9 position for 9 we move to 7 so it looks like this is correct ah i sort of know what i'm doing okay i probably move one too much so where should j stop for the first row j should be equals to 0 1 2 not 3 right so why am i stopping at this so maybe oh god this time it looks okay so let's try this one okay both paths let's try submit it oh my god okay so this is not hard this is only a medium question and it's number 48 but wow it's been i spent more than one hour for this problem so yeah it's supposed to be easy and then the time complexity is n square because there are n square of element and we need to move all of them but the space complexity is none well it's constant because we are doing this in place okay so that's today's daily question i didn't do i didn't string yesterday's question because yesterday was a hard question and that was uh i guess there was a amazon oa question backed in 2020 last year and then somehow um the code decided that's a good one for you to try during the weekend so i didn't do that i will try to stream when i read the solution and then make sure so i want to make sure that i can write yesterday's uh the critical connection without look keep looking at the solution so i will try that one and then i will also try to fix my network issue because today we have a new let me see today we have a new database question here so i'm going to stream this one too and okay thank god i am able to finish this before the deadline and i will try again tomorrow also try to fix my network issue that's it for today hopefully i will be here tomorrow again thank you bye
|
Rotate Image
|
rotate-image
|
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise).
You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation.
**Example 1:**
**Input:** matrix = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[\[7,4,1\],\[8,5,2\],\[9,6,3\]\]
**Example 2:**
**Input:** matrix = \[\[5,1,9,11\],\[2,4,8,10\],\[13,3,6,7\],\[15,14,12,16\]\]
**Output:** \[\[15,13,2,5\],\[14,3,4,1\],\[12,6,8,9\],\[16,7,10,11\]\]
**Constraints:**
* `n == matrix.length == matrix[i].length`
* `1 <= n <= 20`
* `-1000 <= matrix[i][j] <= 1000`
| null |
Array,Math,Matrix
|
Medium
|
2015
|
34 |
foreign welcome back to the DSA classes dear friends today we are going to be solving a question from leap code 34 right and this is a medium level question and this question goes something like this you need to find the first and the last position of the element in a sorted array and this question has been asked previously in companies like Facebook as well so quite an interesting question right let me also show you how the question looks like on week code so if you notice it's fine the first and last position of the element in a sorted array it's a medium level question the question goes like this given an array of integers nums sorted in ascending order or beautiful so it's a sorted array find the starting and ending position of a given Target value for example and he's also told if Target is not found in the array then return an array with minus 1 why because this is starting Index this is ending index if it is not formed element is not there at all starting index is also minus one ending index is also minus one that is what you are supposed to return you must write an algorithm with logging complexity login complexity so look at this here itself your brain should start working you have given and sorted array login complexity here itself your brain should start connecting the dots anyways it doesn't matter now example one uh so you have an array num so five double seven double eight ten Target is eight now if you look at it starting index of 8 is 0 1 2 3 ending index of 8 is 4 so 3 comma four starting index and First Position last position right so for example five double seven double eight ten Target is six is not there so minus 1. if I scroll down uh MTI Target is zero so minus 1 minus one any confusion delay and of course you have to paste the you have to put the code inside this function called as search range and you have to run the code and submit it okay so let's go try to come up with a solution right I have all of you are as excited as I am so now let's get started watch it guys first and foremost let me take an example this is the array that I have definitely it is sorted in the ascending order right so this 3 followed by eight fours and a six now let us assume the target is 4. so obviously there are many Force at different positions but I want the first position of four which is one and the last position of 4 which is eight now how would one go about doing this it's quite simple first and foremost a Brute Force approach if you think of it forget about a very optimized approach Brute Force approach will be what very simple you will maybe probably uh run a loop right where there is a variable which is going from starting to landing and the first time you encounter four return its index that will be the first position run a loop from the last element till the first element and the moment you encounter four return the index in this case it'll be eight but the problem is if an element or the target is searching for is not there then this Loop would go till the end even this Loop would go till the end however the thing and whenever you're iterating through all the elements in an area it is obviously Big O of n complexity so linear time complexity is a big no so what to do if you ask me simple I have a sorted array and I ultimately have to search for something first of all you have to search after everything sorted array search put together is the best combination to perform binary search using binary search how will you find the first position and the last position if you ask me very simple listen to me and listen to me carefully I'm bringing up the binary search algorithm right by now all of your experts are this algorithm what I will do is I'm going to create one array called as result and its size is going to be two it's an integer I am going to initialize this array with minus 1. so on zeroth index also minus one first index also minus one why if you ask me ultimately this zeroth index should contain the first position this first index should contain the last position of my target element initially I'm making it as minus one now parable now we have arrived at binary search see what I will do I am bringing up the table my research means this is the low that is the high value first index last index then I'll calculate mid right so 0 plus 9 divided by 2 is 4 so it will come at the fourth position what is the element at the fourth position is it equal to Target Yes means this condition will be true if it comes inside and returning mid if I return it yes I'll get the position of 4 but that is neither the first index nor the last index neither the first position nor the last position but this allows me to find the food now how am I going to modify this code such that from here I come to the first index of 4. very simple listen to me carefully and understand the changes that I am going to make my friend what I will tell is Hey listen the moment you find the target element here I've called it as key is nothing but the target the moment you find the target element what you do is assume that wherever mid is that is the first position I will assume so if it is the first position I must be storing it here so how will you do it sir like this I'll tell you whatever is there in mid please store it inside result of zero if I do this what will be there in result of 0 is nothing but mid value which is 4 it is going to be 4. any confusion till this point of time yes sir we understood next what you may ask next what if you ask me please understand if really this is not the first occurrence then tell me even the first occurrence come to the right side or when the first occurrence come to the left side would all of you agree that if this is not the first occurrence will only come to the left so now I am assuming that hey there could be more Force to the left so now I want to again perform by my research but from mid minus 1 to low or low till mid minus one so if I want to do search till here should I adjust slow or should I adjust high I should adjust high and bring it here how will you bring it here sir very simple I will tell high is equal to Mid minus that's it the moment I do this now high value is going to be updated and it will come here any confusion same thing is what I'm showing high value is going to be 3 low value will be the same again you are within a loop you will find mid so 0 plus 3 is 3 divided by 2 is 1 which means mid is now going to come to the first position is it equal to the Target or the key yes it is also four if it is 4 then I will assume that is the first position I will assume and how will you concretize your assumption or how will you store your assumption by storing the mid index in result of zero because this is reserved for the first position and you know what is mid one store it inside zero which means this was 4 but now it is going to become 1. again I don't know whether that is the first position so what I would like to do is I would like to again look to the left if I have to look to the left then low will be wherever it is but high should be brought one step behind mid after able to take one step behind me if I do that high is equal to Mid minus 1 that is what I am also showing here high value was 3 so it is going to become mid minus 1 so 1 minus 1 is 0 lower remains as it is which means both high and low are going to be in the same position and if you calculate mid also will be in the same position check if in case it is equal to the key or it is not equal to the key not equal to the Target if it is not equal to the Target check if in case the key is lesser than the mid element is it lesser than the mid Element no it is greater if it is greater than the middle element according to binary search I am not going to adjust low what I am going to adjust is high I hope you're able to think which means what is going to happen is high or sorry if it is greater after just low so what is low going to be mid plus 1 which means like this low value is going to become mid plus 1 it will come here that's what I am also showing you video Zero the value is mid plus one high value Remains the Same for the first time ever lowers become greater than high and that is your termination condition so you will come out of the loop when you come out of the loop ultimately what has happened in result of zero I have a value one and one is the starting position of four so I found my target starting position beautiful did all of you understand but the question ultimately is not only to find the target position starting positions also to find the ending position or last position that is what this first index was that is still minus one so what I will do now is I've come out of this Loop and I'm going to write one more Loop so I'm going to remove all the values here I am going to readjust slow readjust height bring and so that's what I'm telling L is equal to 0 H is equal to length of a minus 1 and mid initially will be zero okay again I'm reinitializing them this time what I will do is I will again apply binary list when I apply binary search First Time Low zero high is 9 mid becomes 4 great is that equal to the Target is the key equal to the element you're searching for Yes means don't return mint don't return it instead what I am going to now do is I will assume that value is my last positions index like how previously we did first position I will assume it's my last position and where to store my assumption that is what the result array is which index in the result array first index which means I will go here and I will tell please in result of one store the mid value now my assumption may be right my assumption may be wrong but I need to check to the right side now see whether there are more Target elements or more Force which is the last position actually so if really I have to search to the right hand side tell me should I adjust high or should I adjust low obviously you should adjust low should come here means what mid plus one that is what I will do I will tell no is equal to Mid plus 1 how we're able to think which means low becomes mid plus 1 5 high Remains the Same you are within a loop again you will find mid 5 plus 9 divided by 2 is 7 which means mid is now going to come to seven is seven equal to 4 Yes means yes means now I'll assume that is my last position so I will take the mid Value Store it inside reserve it so if I store it inside result first time this was 4 right next time it is going to become 7. I may be right I may be wrong but I'm within a loop I will store it inside seven and then now tell me I'm here if I have to find the last position again I should search to the right which is again low value should be adjusted it should become mid plus one if I do that then the low value is going to come here that is what I am also showing you low will become mid plus one seven plus one is eight high value is 9 only 9 plus 8 divided by 2 is nothing but eight any confusion to that which means mid value also is going to come wherever low is I hope everybody understood this any confusion again check is it equal oh yes it is equal if it is equal then take that index store it inside result of one so if I do that I will get the index as eight next I am checking for last index so again to the right I should since again low value if I do that no value is now going to become mid plus 1 which means it will come to the last index that's what I'm showing 8 plus 1 9 highest line only you are within a loop again find mid 9 plus 9 18 divided by 2 is nothing but 9 okay which means mid also becomes 9. our grades are next what check if the element is equal to the key which is nothing but my target which is four no it is not equal if it is not equal come down check if it is lesser is it lesser no it is greater if it is greater then it will be to the left side according to binary search so high should be adjusted high will become mid minus 1 and see if High becomes mid minus 1 mid to us 9 minus 1 is 8. low Remains the Same and now something happened no became greater than high obviously this condition will terminate I hope you're able to think conditionally terminate and once the condition terminates you will come outside and when you come outside the loop kindly look at the result array and tell me in the first index which value is there eight look at eight and tell me what is special about it is the last position in the assorted array for the Target 4. so this result array has my first position has my last position how we're able to think now what was the initial value of this array minus 1 minus one imagine four was not there only then ultimately what would have been the value inside this minus 1 and minus 1. how we're able to think any confusion to that so we have taken care of it so ultimately what did I do in my function first I'll have a while loop which will find the target element and keep checking to the left to find if you will find it again and ultimately find the first position store it inside the zeroth index as you can see I'll come out of that Loop re-initialize my binary search I'll re-initialize my binary search I'll re-initialize my binary search I'll bring low high mid to its original positions again I'll apply research where I will find the target element and keep looking to the right of the array to find it again and ultimately in the first position of my array I will store the index so I got first position last position this is also binary search which means login time complexity log n Plus login is 2 login 2 is a constant it will go so what is the time complexity of the code you have written okay would have loved you for this I hope you're able to think so binary search is very powerful no wonder it's one of the favorite questions to ask and I hope slowly your brain is getting wired to think in some terms of binary search any confusion to your friends wonderful now that you guys understood this it is time for us to go and implement this and finally paste the solution in lead code to check whether it will actually work so what are we waiting for let's go do that all right stand right code if you notice I've given the same uh name as lead code it's called search range it should return an integer array and what it has to basically accept is a nums array and a Target okay so here I have the skeletal structure of binary search ready with where I have initialized node to zero High to the last index midnight zero then this is the condition I'm finding the announce it if I'll come here and I'll tell if in case Target is equal to the mid element so that is nothing but non software okay if Target is equal to the mid element then what I will do is I will assume that the index mid is the first position and that must be stored in my reservatory where is my result array let's go create it so I'll go on top and I will tell uh integer array res is equal to and I'll directly initialize it with minus 1 and minus this is what it initiates okay so now what I will do is if I found it then I will assume that is my starting position so in result of 0 that is in the first index I will store Mid now I want to check to the left I want to go to the starting so if I have to go to the starting High I will bring it before mid so I will tell H is equal to minus 1. then after that else if I will check if in case the mid element is uh lesser than the target element so nums of mid is less than Target if it is less than Target then what is going to happen is I will come here and I will just adjust the high pointer so H is equal to okay uh yeah L sorry L is equal to MIDI plus one because if the midday element is lesser than the target then obviously you have to search in the left uh right hand side that is what it is otherwise H is equal to Mid minus this is the normal binary code logic any confusion till here guys so this is simple now by the end of this Loop within the zeroth index I would have had my actual first position now what I'll do is I'll copy this entire Loop paste it again okay so countdown here what I will do is this result of 0 I'll make it as 1. and then this H I will make it as L is equal to Mid Plus 1. right and then rest everything Remains the Same also please understand you have to re-initialize low higher mid to re-initialize low higher mid to re-initialize low higher mid otherwise whatever was a lower iron medium this Loop will continue here you will get a mistake so I'll go back there and I'll tell L equal to 0 comma H equal to length of a minus 1 I mean a DOT nums Dot now it's dot length minus 1 and mid is equal to zero so I'm just re-initializing re-initializing re-initializing again I will perform binary search but this time if I find the middle element I am assuming that is the last position and I'm storing it in the first index of my result array and then I'm restricting my search to the right side by telling low is equilibri plus one keep repeating ultimately this first index will have the actual last position I'll come out of this while loop and I'll just return my resultant array right so go on top ultimately if I in both the loops if I never found the target element anywhere then initially I made it as minus 1 and it means not four okay any confusion till here correct now what I'll do is instead of re-executing I'll just copy instead of re-executing I'll just copy instead of re-executing I'll just copy the center code paste it inside lead code because they will automatically pass test cases for us so if I go to lead code and if in case I paste it inside this yeah and if I first run the code let us see what happens so it has been accepted if I submit the code and it will pass multiple test cases and upon doing so pull this here it has told me that you know certainly my submission has been accepted it took just zero milliseconds or lesser and it is quite fast and 44 MB is what it is used in the memory so okay great awesome so I hope you enjoyed this question and we will be solving many such questions in this DSA course I hope you are also you know building up that excitement as I am to teach you anyways let's catch up to the next class with an even more cooler program till then take care bye
|
Find First and Last Position of Element in Sorted Array
|
find-first-and-last-position-of-element-in-sorted-array
|
Given an array of integers `nums` sorted in non-decreasing order, find the starting and ending position of a given `target` value.
If `target` is not found in the array, return `[-1, -1]`.
You must write an algorithm with `O(log n)` runtime complexity.
**Example 1:**
**Input:** nums = \[5,7,7,8,8,10\], target = 8
**Output:** \[3,4\]
**Example 2:**
**Input:** nums = \[5,7,7,8,8,10\], target = 6
**Output:** \[-1,-1\]
**Example 3:**
**Input:** nums = \[\], target = 0
**Output:** \[-1,-1\]
**Constraints:**
* `0 <= nums.length <= 105`
* `-109 <= nums[i] <= 109`
* `nums` is a non-decreasing array.
* `-109 <= target <= 109`
| null |
Array,Binary Search
|
Medium
|
278,2165,2210
|
1,370 |
welcome back to our Channel where we discuss and solve popular coding problems today we're going to be tackling leap code problem 1370 increasing decreasing string the problem statement is pretty straightforward given a string s we need to reorder the characters in such a way that the characters in the resulting string are in increasing order followed by characters in decreasing order until all characters are processed let's take an example to better understand the statement and start thinking about its solution for the input string accbb the first step would be to create a data structure such as an array that contains the list of unique characters present in the string since the statement talks about order we need to sort the list in ascending order and since we don't want characters to appear more times than they are present in the string we will have to calculate their number of occurrences now that we have a structure that contains the necessary elements to solve the problem the idea is to go through the list from left to right because it is the increasing order of characters by working on each element we can be sure that the next one will be the one that immediately follows since the list is sorted in alphabetical order for each character we will analyze we will decrease its number of occurrences by 1 to indicate that we have processed it when the number of occurrences reaches zero this means that all occurrences of this character have been processed and it can no longer be used we then move on to the next character once we have processed all the elements in the list we reverse the direction of traversal to follow the decreasing alphabetical order we perform the same treatment on each character that is decreasing its number of occurrences by one we continue to alternate between ascending and descending order until all occurrences are at zero in summary to solve this problem we adopted a two-step approach adopted a two-step approach adopted a two-step approach first we created a data structure to store the characters present in the input string and their number of occurrences then we iterated over the length of the input string during this Loop we iterated over the data structure to check the number of occurrences of each character and if it was greater than zero we added it to the final result and decreased its number of occurrences by 1. we then reversed the order of the data structure to start the process in decreasing order we continued this way until the end of the main Loop now let's move on to implementing the algorithm using JavaScript first we will create our data structure we will start by creating a map that will contain all the characters and their number of occurrences in this step we will go through all the characters in the string we will use a variable count to record the number of occurrences of each character if the character already has an entry in our map count will take the value of its number of occurrences otherwise count will be initialized to zero finally we will update our map by increasing the value of count by one for each character once the map is created we will reorder the map in ascending order and put the result in an array next we will create a variable to store our final result initializing it with an empty string then we will iterate as many times as there are characters in our input string in this Loop we Traverse our array sorted alphabetically if the character has An Occurrence count greater than zero we will concatenate it to the final result and decrease its occurrence count to indicate that we have processed it otherwise if the character has An Occurrence count equal to zero we will move on to the next character once the loop is finished we will reverse the order of the array to be able to go through it in decreasing order and repeat this step until all characters have been processed at the end of the main Loop the result variable holds the desired outcome we can then return it and run the necessary tests to verify its validity in this video we presented one approach to solving the increasing decreasing string problem using JavaScript there are other ways to solve this problem as well we hope that this demonstration was helpful to you we will continue to explore other problems in future videos thank you for watching and we would appreciate your support by leaving a positive comment or giving a like on the video thank you
|
Increasing Decreasing String
|
count-number-of-nice-subarrays
|
You are given a string `s`. Reorder the string using the following algorithm:
1. Pick the **smallest** character from `s` and **append** it to the result.
2. Pick the **smallest** character from `s` which is greater than the last appended character to the result and **append** it.
3. Repeat step 2 until you cannot pick more characters.
4. Pick the **largest** character from `s` and **append** it to the result.
5. Pick the **largest** character from `s` which is smaller than the last appended character to the result and **append** it.
6. Repeat step 5 until you cannot pick more characters.
7. Repeat the steps from 1 to 6 until you pick all characters from `s`.
In each step, If the smallest or the largest character appears more than once you can choose any occurrence and append it to the result.
Return _the result string after sorting_ `s` _with this algorithm_.
**Example 1:**
**Input:** s = "aaaabbbbcccc "
**Output:** "abccbaabccba "
**Explanation:** After steps 1, 2 and 3 of the first iteration, result = "abc "
After steps 4, 5 and 6 of the first iteration, result = "abccba "
First iteration is done. Now s = "aabbcc " and we go back to step 1
After steps 1, 2 and 3 of the second iteration, result = "abccbaabc "
After steps 4, 5 and 6 of the second iteration, result = "abccbaabccba "
**Example 2:**
**Input:** s = "rat "
**Output:** "art "
**Explanation:** The word "rat " becomes "art " after re-ordering it with the mentioned algorithm.
**Constraints:**
* `1 <= s.length <= 500`
* `s` consists of only lowercase English letters.
|
After replacing each even by zero and every odd by one can we use prefix sum to find answer ? Can we use two pointers to count number of sub-arrays ? Can we store indices of odd numbers and for each k indices count number of sub-arrays contains them ?
|
Array,Hash Table,Math,Sliding Window
|
Medium
| null |
148 |
yo what is up youtube today i'm going to be going over sort list it's a medium leap code problem asked by amazon if you guys haven't already check out my channel i post these videos every week today and i'll see you guys soon okay so now we have sort this sort of linked list and of end login time using constant space complexity so why is it doing that oh so we spit constant base complexity so we can't that means in place we can't create a new linked list um and o of n log n that should give you a hint that we need to use merge sort because word short is log n um space complexity and or not space runtime sorry and then we have to do it n times call the function n times um so yeah we just have to sort a linked list the fact that it's a linked list data structure um just makes it a little different um maybe a little bit harder so i just wanted to go over merge sort on the whiteboard so we have merge sort here so if this is our list i just wrote a bunch of random numbers it's eight numbers one through eight um so as you guys know merge search recursive uh technically it could be iterative as well but it's typically used as recursion so it's just going to split the uh list in half so it's going to do the left half first and then it's going to split that one again so the first call it's going to call the left half and then it's going to split it again until it's all like single numbers and then we're going to um when we merge them so the first part is the partitioning which we just went over is which is splitting it um and then on the way back up we're going to merge them but in sorted order so this is going to be six eight and this is going to be one five and this is going to be um one five six eight and then it's i don't wanna write this one out too it's going to be sorted this side's going to be sorted same thing um and then we just merge those two lists and then they're going to be in order so that's how we're going to solve um so there's going to be a lot of little nuances that we run into so let's get just start so if head equals null or head dot next equals null um we're just going to turn no so we actually need that um actually it's not null is it no i think i don't know we'll figure it out oh somebody's sorry guys i'll be right back this is important text all right so sorry i had to take that phone um text was important um anyways so what we want to do is we want to split the we don't want to split the list in half but that's not really easy because it's a linked list so we want the first we want to be able to set a tail here a head here and a tail here and a head here and a tail here so um we could do that by doing um well heads already here so we already have a head so we need to we could do a slow and move it one at a time and do a fast which moves two at a time and as soon as fast.nx equals null then and as soon as fast.nx equals null then and as soon as fast.nx equals null then we're done um so uh let's create let's do that sorry i'm like thinking about it in my head as i'm doing this video and we just want to uh tail for the left half so it's all going to be equal to head and one and fast dot next does not equal no and you know what i just realized this is supposed to be head why where not we have to return the list node so and this did an indent so we're going to set tail equal to slow because this is going to be the tail and then we're going to increment slow so it's going to be the head of the right half um and fast equals fast dot next so what's that's doing is uh fast is going like this so fast is here fast slow is going to be here um and tails here and then the second iteration um tails here fast is gonna be over here it's gonna be null so that's the tail um we want the tail to be null um so we also have to remember to set a tail no for the left half um and where was i going oh and so slow is going to be the head of the right half so um so yeah so now we just need to set tail.next equal to null because we need tail.next equal to null because we need tail.next equal to null because we need the um to have like an end so to otherwise it's the head is just pointing to the whole list still we just need to do the recursive merge sort calls so uh list node left equals merge sort and we're going to do um so left is head and slow and less node right is merge sort um it's going to be no this is not right this is supposed to be tail sorry guys um i probably should have named them better tail or slow and fast okay so now we have everything set up correctly we just want to return no it's not merge sort it's sort list so this is we're recursively calling sort list this is sorting it into halves it's just gonna keep breaking them in halves um i don't want to draw out the recursion stack uh that'll just take way too long i'm already at like a six minute video so and then we want to do merge sort so this is where we merge i'm just going to call it merge left and right okay so let's do list node merge list node left and wrist node right okay so um now we have to merge them um we need to create a list that we're going to return so list node merged equals new list node so let's start it at the beginning so we can return dot next and it'll be pointing to the head and if we do a current node equals merge that's pointing to it's pointing to that but then now we can set current.next to but then now we can set current.next to but then now we can set current.next to the first node um so if left dot or now let's do it's wall left it does not equal null and right does not equal no yeah that's correct um if left that vowel is less than right vowel then current node dot next equals left so that's just setting since current nodes pointing to zero we want to do dot next so we're at the head and if left is less than right we want to put left at the beginning um it's not always going to be the getting it depends where we are in the wireless and we need to increment move the pointer for the left and um so this is just if they're equal or right.vowel is less than left.val or right.vowel is less than left.val or right.vowel is less than left.val so we do the same thing and up here we could have do done current equals current dot next but i'm gonna do it outside we need to remember to move the pointer along in the current uh list current node equals current okay hopefully that makes sense and so this one's just the opposite right equals i'm sure you guys have done stuff like this and typing too fast okay so now if um if left does not equal null then we want to current node.next current node.next current node.next equals left um else if which means if right is not equal no because we're always gonna one's always gonna be empty before the other one and i think that's it and then we just want to return merge.next because merge is still merge.next because merge is still merge.next because merge is still pointing right before the head so return merged dot next and i'm sure i made an error in here so let's debug it now um expected uh oh wow i just put ore that is dumb short list oh okay um so we just need to pass the head so this is just head and this is just slow i was writing it out for merge the merge function okay sweet so that i did do that right all right that wasn't bad that was just a few syntax errors okay so this is um of n uh runtime because we're just um no it's o n log n because we're using merge sort we already went over that in the beginning and um space complexity this is o one so this is just uh constant um because we didn't need to create a new um linked list we just had we created a pointer to the linked list um so yeah that's how that works if you guys have any questions let me know i like to answer your questions and if this video helps let me know hit that like button and i'll see you in the next one you
|
Sort List
|
sort-list
|
Given the `head` of a linked list, return _the list after sorting it in **ascending order**_.
**Example 1:**
**Input:** head = \[4,2,1,3\]
**Output:** \[1,2,3,4\]
**Example 2:**
**Input:** head = \[-1,5,3,4,0\]
**Output:** \[-1,0,3,4,5\]
**Example 3:**
**Input:** head = \[\]
**Output:** \[\]
**Constraints:**
* The number of nodes in the list is in the range `[0, 5 * 104]`.
* `-105 <= Node.val <= 105`
**Follow up:** Can you sort the linked list in `O(n logn)` time and `O(1)` memory (i.e. constant space)?
| null |
Linked List,Two Pointers,Divide and Conquer,Sorting,Merge Sort
|
Medium
|
21,75,147,1992
|
1,094 |
Hello hello everyone happy wala doing well so im back with another letter from delhi zip code number 104 car polling station medium level question and subscribe the channel kilometers from the mission possible dot com changer for all the given tips and false advice So if taken in the Distic in the question example in subscribe number one is the subscribe live special guest came from abroad and 370 guests on but in this place a little over lapping maybe picture free plus to will give five career and fold this interval Ho main office in trouble aur 12th 500 oy hai so what is the problem hai it's return forms with reasons of the city of the only for you can only but at a distance from subscribe to hai udhar 8.1 5209 J2 7 Capacity inside is 500 OA cyber law from danger only passenger and from there are 27 by passenger from subscribe And subscribe The Amazing interesting like subscribe and share and subscribe from 8th that and from year to year it has been replaced this point is overlapping Per Already And Need To Put Him On Passenger In The Soe Subscribe And Subscribe The Subscribe Must Subscribe My Channel Must Subscribe Ok In Whole Day Go Into Raw Michael Committee Member Tarf First For The President 2850 Not Provided In The us and soen idiot ho hai so I will take away after ok I will take vector off and foot of intent is present form ok Android I will find a point for example 551 will not be alive they will put on this point - but ok And to what is not on this point - but ok And to what is not on this point - but ok And to what is not taking - taking - taking - sexual more subscribe my channel don't forget to subscribe and doing just hydraulic element one like of oil poster two also like 3gb ram and rom last labs pe ki saharanpur mat harisharan ko - paper Need to know why all these ki saharanpur mat harisharan ko - paper Need to know why all these ki saharanpur mat harisharan ko - paper Need to know why all these elements and villages in the best position Adhir vo number four Kumar Ajay Kumar Jha A Plus Paaye Aur Something Like A Plus Two K Distributor Present in the Subscribe subscribe to subscribe And subscribe The Amazing spider-man Thanks and After PERFORMING ALL THE CALCULATIONS IS SIMPLY Show more ki nahi ki bread pizza bread and a pun question indore description box shift incident the handed over 110 taste video fennel thank you by you
|
Car Pooling
|
matrix-cells-in-distance-order
|
There is a car with `capacity` empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).
You are given the integer `capacity` and an array `trips` where `trips[i] = [numPassengersi, fromi, toi]` indicates that the `ith` trip has `numPassengersi` passengers and the locations to pick them up and drop them off are `fromi` and `toi` respectively. The locations are given as the number of kilometers due east from the car's initial location.
Return `true` _if it is possible to pick up and drop off all passengers for all the given trips, or_ `false` _otherwise_.
**Example 1:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 4
**Output:** false
**Example 2:**
**Input:** trips = \[\[2,1,5\],\[3,3,7\]\], capacity = 5
**Output:** true
**Constraints:**
* `1 <= trips.length <= 1000`
* `trips[i].length == 3`
* `1 <= numPassengersi <= 100`
* `0 <= fromi < toi <= 1000`
* `1 <= capacity <= 105`
| null |
Array,Math,Geometry,Sorting,Matrix
|
Easy
|
2304
|
474 |
hey everybody this is larry this is day 23 of the may leco day challenge hit the like button to subscribe and join me in discord let me know what you think about today's font so you're given binary strings m and n what does that mean return the size of the largest subset of string such that they're at most m zeros and n ones in the subset okay uh so this is saying we have okay so first thing i'd like to do is kind of look at the constraints to see what are the things that we can do the thing to notice is that um m and ends are terrible so let's call it let's change it to zeros and ones right um yeah so we're given a hundred zeros and 101 so what does this mean right um and maybe this is still dynamic programming session i don't know anymore right but um but the idea here is you know thinking about the states right the question is um what's a hundred times six hundred or something hmm oh no in this subset okay yeah um the couple of ways we can think about doing it uh i think the first way is just thinking about um dynamic programming and then whether that is fast enough a hundred times six hundred is going to be feels a little bit too slow for states um so i don't think i want to do that and this is just the number of things in each let me think about this for a second 100 times because that's 6 million right 100 times 600 so that is diffuse slow uh at least in python uh in other languages maybe it's a little maybe it should be fast enough um so i'm thinking to see whether i'm missing something obvious but the constraints are pretty okay i mean this one doesn't really mean anything it's just you know you could go through the entire thing linear and then do the math anyway um of course you should pre-calculate this of course you should pre-calculate this of course you should pre-calculate this so that you don't have to or pre-process so that you don't have to or pre-process so that you don't have to or pre-process this so that you don't have to keep on going to it but the 600 is a little bit peculiar okay so i think the first and this is where you know we talked about in the last week if you haven't been or you should be uh doing it together last week um or if you did then they'll be easier for me to explain one is kind of thinking about analysis right so the analysis that i'm thinking of is kind of just like get uh get max i think of an index zeros and ones right and this will be our constraint uh this is what's been going on in my mind right and what let's say we have this and these are our states what does this mean my index and go from zero to n with where n is less than 600 uh zeros ones that's separating out zero to one hundred and once it's also one zero to one hundred right and of course the time complexity roughly speaking is going to be a number of inputs times input or time per input so number of inputs is gonna be a hundred times six hundred while uh each input time per input is probably over one right is my projection in my head i'm thinking that this is maybe a little bit getting it close with respect to time and space um and some of the uh i know that uh very often i've been kind of hand-wavy on the often i've been kind of hand-wavy on the often i've been kind of hand-wavy on the space um but there is a things do tie in together right meaning that space is not just space for space sake but also it is possible that you know in allocating the space it takes a lot more time in total um but that said i think the one key thing to know about this particular problem is that a lot of inputs are not possible and what do i mean by that what i mean by that is that for example uh so you know this is a very rough analysis for a number of possible inputs but a lot of those inputs are not possible right um because for example let's say we have uh let's even take this first example right let's say we have this example uh and if we set up naively we set indexes 0 zero is the first one zeros is equal to five once it's equal to three right um and then now let's say we process the first item we and the only two choices where we put this in the subset or we don't and we put it in this can only go to index is equal to one zero is zero to four wants us to go to two if we do put it or if we don't put it in then this is equal to this right someone like that but of course in this case it is impossible to go to index is equal to one zeros is equal to ones for example and one is equal to zero something like that right so this is an impossible case so in reality in theory the space is uh better but to be honest this is a little bit hand-wavy and i'm not super confident hand-wavy and i'm not super confident hand-wavy and i'm not super confident about the analysis about this unless i'm just doing something really wrong right so that's kind of you know sometimes maybe it's okay to yolo a little bit and six million is probably really tight but that said maybe enough of it is not possible that we can go okay so then now the thing we try to do is if index is equal to n we process all of these then we want to return zero right and then otherwise um actually we should pre-process first um actually we should pre-process first um actually we should pre-process first like we said so we don't keep on pre-processing the string so then that pre-processing the string so then that pre-processing the string so then that let's just go um z is equal to zero times n once uh always if you will and then for i and range sub n um z s is equal to that count of zero you can write this in other problems more efficient ways but this is the way that i'm going to write it um and then here now then to get max is that we can two choices right we can either use this subset use or use this string in the subset or not so if we use it then the okay let's say best answer is equal to zero if we use it then the best possible answer is going to get max of index plus one we move on to the next index and then zeros minus so yeah oh this is messed up oops um sub index and then plus one oops plus one for um using the subset or using the string or not which is just going on to the next index right oh i forgot to do the ones i got confused because i hit on the volume button instead um also this is in the wrong place it should be inside the function okay and again i don't do the memorization yet just so that we can kind of let's play around with it right um yeah oh i this is obviously wrong because we have to check that we have enough zeros and ones on the restriction so if zeros is greater than uh zero and x and once it's green okay hopefully this should be good without no more typos though again this isn't cash but that's fine oh this is an infinite loop because i've got to do an x plus one silly typo but that's fine easy typo to fix all right so this looks good again this is going to time out because we have really big numbers um so then so i would say one thing that i did in the past with these videos and i urge that if you have confusion about these kind of problems look at my last couple of videos because we've been doing dynamic programming right so the way that i usually do it is just has cash and a cash spring so the problem here is that and if we do that has cash in the cash thing we would allocate space for every possible item right so what we want to do is actually only allocate space for stuff that we use um so then here we would have a lookup table it is harder to show the bound but that's basically um yeah and then here we can go if in depth and we just use the tuple as a key then we turn lookup of this tuple otherwise we at the very end we set the tuples up let's see if this is slightly faster oops i don't know how i missed that but okay it is not but let's give it some let's see how that goes see if it's fast enough okay cool uh yeah this one is tough because it's tough to kind of narrow down the bounds a little bit let's see what larry did in the past uh oh he did it bottoms up i did do the caching though uh so if you want to see the bottoms up check out my video from last year but this is how i do it tops down um and apparently the running time is roughly the same so i don't know what to make of it uh but yeah as we talked about i didn't do the actual multiplication so yeah so the time complexity is going to be o of z for the number of zeros over the number of ones and then n is the number of inputs is time and then space is also the same thing because same logic here um yeah uh cool uh yeah that's all i have for this one uh let me know what you think stay good stay healthy to good mental health i'll see you later and take care bye
|
Ones and Zeroes
|
ones-and-zeroes
|
You are given an array of binary strings `strs` and two integers `m` and `n`.
Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_.
A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`.
**Example 1:**
**Input:** strs = \[ "10 ", "0001 ", "111001 ", "1 ", "0 "\], m = 5, n = 3
**Output:** 4
**Explanation:** The largest subset with at most 5 0's and 3 1's is { "10 ", "0001 ", "1 ", "0 "}, so the answer is 4.
Other valid but smaller subsets include { "0001 ", "1 "} and { "10 ", "1 ", "0 "}.
{ "111001 "} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
**Example 2:**
**Input:** strs = \[ "10 ", "0 ", "1 "\], m = 1, n = 1
**Output:** 2
**Explanation:** The largest subset is { "0 ", "1 "}, so the answer is 2.
**Constraints:**
* `1 <= strs.length <= 600`
* `1 <= strs[i].length <= 100`
* `strs[i]` consists only of digits `'0'` and `'1'`.
* `1 <= m, n <= 100`
| null |
Array,String,Dynamic Programming
|
Medium
|
510,600,2261
|
139 |
welcome to this video now we're going to solve a coding interview question word break you're given a non-empty string s and a you're given a non-empty string s and a you're given a non-empty string s and a dictionary word dict containing a list of non-empty words determine if s can be non-empty words determine if s can be non-empty words determine if s can be segmented into a space-separated segmented into a space-separated segmented into a space-separated sequence of one or more dictionary words this is the problem statement for example if you are given s equals to liquid and word equals to this list of word we have lead and code word in this word dictionary now we can generate this string from this word dictionary we have here the word lit and we have the word code so in this case we have to return true if we are given this string apple pin apple and word dict equals to apple and pen from this word dictionary we can generate this string apple then pin then apple we can have repetition of word we see apple repeated twitch in this string so in this sketch we have to return true now how we can solve this problem for sake of understanding let's assume s equals to liquid and word dict equals to lit and code first we're going to construct a hash set and this is our hash set this hash set contains two words lead and code then we're going to construct a dynamic programming table and this is our dynamic programming table and the length of this table is the length of the string plus one the length of the string liquid is eight so eight plus one is nine the length of this dynamic programming table is nine for the first index we inserted true initially why we have inserted true to the first index we'll talk about that in this video we have this string record and we have this set now first we're going to check this first letter and this is l okay does l adjust to our set no l is not exist l does not exist in our set so we'll not change the value at index one then for index two we're going to get this word l e does it exist in our set no l e doesn't exist then we're going to get the letter e does he exist in our hash set no e does not exist in our hash set so will not change the value at index 2 then we have index 3 for index 3 we have this word l e okay l e doesn't exist then e doesn't exist in our hash set then e also does not exist so will not change the value for index three then for index four we will have this word lit does lead exist in our set yes it is then we're gonna check whatever word we have on the left of the word lit we have nothing right and we have here true for nothing because lit is the word and on the left we have nothing so this is true and it exists in our set it's also written true so true and true evaluated true then we're gonna change the value here to true okay then we're gonna check e t we see e t does not exist in our hash set then e t does not exist then t also not exist in our hash set then we have index five for index five we have this word l double e t c we see this is not exist in our hash table then ee tc also eetc is not exist in our hash table then etc it is not exist then tc also not exist then just c we see this all word does not exist in the hash set so we will not change the value at index 5 then for index 6 we have this word lwtco does not exist eet co does not exist etc does not exist in our hash set tco co and o all the word does not exist in our hash set so will not change the value for index six okay then for seven we have this word lwt co d and this word does not exist this word also not exist this word nor exist this word then this word od and then the letter single letter d all of them does not exist in our hash set okay so let's change the value at index 7 then for index 8 we have this complete word okay we see lead code doesn't exist in the headset e-e-t-c-o-d-e does not exist e-e-t-c-o-d-e does not exist e-e-t-c-o-d-e does not exist e-t-c-o-d does not exist e-t-c-o-d does not exist e-t-c-o-d does not exist t c-o-d-e does not exist t c-o-d-e does not exist t c-o-d-e does not exist c or d-e does exist c or d-e does exist c or d-e does exist right c or d we have in the hash set this exists so it will return true then whatever word we have left on the code we have lit so let's get the value for t at index 4 right at index 4 we have 2 so true and true is true so it will be replaced with true so we will stop here because we don't need to check for the rest when we have found a word that match our condition and this is how we can solve this problem i know this solution bit of exaggerated don't worry let me show you how you can solve this problem using the health of sudar code first we're going to declare a function word break that takes a string under dictionary list let's suppose that s equals to let code and word dict equals to lead and code here word dict and dict list are the same okay then we're going to construct a dynamic programming table the length of the string plus 1. this is your dynamic programming table of length 9 then we're going to construct a set from the dictionary list this is our hash set okay then we're going to insert at first position 2. okay why is that what do you have found a complete word suppose that we found this word lit when we found a complete word in the set then what we will do we will find the left portion of the word in this case in the left portion of this word is nothing right for that we're inserting here true when we go through the iterations of our loop then you will see how it's work okay don't worry for now we're gonna run a loop for i from one two length of the string minus one we're starting from one because we already inserted true at the first position then we're going to run another loop this is nested loop for j from 0 to i minus 1 and this will generate word of length from 0 to i minus 1 then we're gonna check if dv z and this divisor means if we found the left word then return true if we do not found the left word in our set then written false or if we found empty word on the left then return true and if the current word is exist in our set then set true to the current index and then break at the end we'll have our answer right here and we'll return that okay dp length s minus 1 sorry it should be just dp length of the given string not minus 1 all right now let's see how it actually works for first iteration of this for loop i equals to 1 then we'll have z equals to only zero so we generated the word of length one okay and this is yield l does not exist in our hash set so we'll insert here false then for next iteration of this loop i equals to 2 and j equals to 0 for j equals to 0 we're going to generate a string of length i minus z and that is 2 and that is here l e does not exist in our hash set also e does not exist in our high set so let's insert here false we don't have to insert your false because by default we have the value for all the field faults and that's why we're not inserting false here we can do it by using else statement we don't need that right then for next iteration i equals to three we have the word l e doesn't exist in our hash set ee doesn't exist he also doesn't exist so here we'll have the value of false then for next iteration i equals to 4 then we found a word lit we see that lead exist in our heart set then let's check whatever value we have for the left word we see the left word is nothing in this case for that we are going to return whatever value we have at the index 0 okay then we have inserted here true and we don't need to check for x equals to 1 2 and 3 because we already found a word that exists in our hash set and the left word is empty or we have found in our headset already then for next iteration of this loop we have i equals to 5 we have generated all possible words we see no of them exist in our hash set then we have i equals 2 6 here also we see no of the exist in our hash set then for next iteration of this loop we have generated all possible word here also we see no word exists in our hatchet then for the last iteration we see when we have z equals to four we found a word code in our hash set now let's check the left word if that exists in our hash set the left word we have for code is lead and we see that lead exists in our hash set so it will return to and we have in our headset so this two will return to at the end we'll insert here true by default we have all the value faults this is how we can solve this problem if you aren't understanding this problem take a look at for the is iteration we have break it down the is iteration for the two loops so you can understood easily you will have it you will have easy time understanding this problem if you take a look at for the all iterations what's going on in the code we have right here everything we break it down to make you understand this problem clearly at the end this function will return this value true and this is how we can solve this problem the solution will takes big of n squared time complexity where n is the length of the given string and it will takes bigger off in space complexity to construct our dynamic programming table hope you have understood this problem if you have any question if you have any suggestion let us know thanks for watching this video i'll see you in the next video
|
Word Break
|
word-break
|
Given a string `s` and a dictionary of strings `wordDict`, return `true` if `s` can be segmented into a space-separated sequence of one or more dictionary words.
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
**Example 1:**
**Input:** s = "leetcode ", wordDict = \[ "leet ", "code "\]
**Output:** true
**Explanation:** Return true because "leetcode " can be segmented as "leet code ".
**Example 2:**
**Input:** s = "applepenapple ", wordDict = \[ "apple ", "pen "\]
**Output:** true
**Explanation:** Return true because "applepenapple " can be segmented as "apple pen apple ".
Note that you are allowed to reuse a dictionary word.
**Example 3:**
**Input:** s = "catsandog ", wordDict = \[ "cats ", "dog ", "sand ", "and ", "cat "\]
**Output:** false
**Constraints:**
* `1 <= s.length <= 300`
* `1 <= wordDict.length <= 1000`
* `1 <= wordDict[i].length <= 20`
* `s` and `wordDict[i]` consist of only lowercase English letters.
* All the strings of `wordDict` are **unique**.
| null |
Hash Table,String,Dynamic Programming,Trie,Memoization
|
Medium
|
140
|
1,603 |
hi everyone today we are going to solve the little question design packing system so design a parking system for parking lot the parking lot has three kinds of parking spaces big medium and small with a fixed number of slots for each size implement the parking system class the parking system initialize object of the parking system class the number of slots for each parking space are given as a as part of the Constructor so build as a car checks whether there is a parking space or car type for the car that wants to get into the parking lot card type can be of three kinds big medium or small which are represented by one two and three respectively a car can only park in the parking space of each car type if there is no space available return false else park the car in the size space and the return through yeah um so this is a very easy question so that's why I don't explain detail so directly let's jump into the code before I start my explanation so let me introduce my channel so I create a lot of videos to prepare for technical interviews I explain all the details of all questions in the video and you can get a call from GitHub for free so please subscribe my channel hit the right button or leave a comment thank you for your support okay so let's write the code I think there are many ways to solve this question so in this case I use hashmap so slots equal and one is a big and the two is a medium and their three is a small and then for other car method so if not save dot slots and a car type that means zero in this case we should return both if not the case add minus one to um slots and a car type minus equal one and then return to yeah that's it so let me submit it yeah looks good and the time complexity of this version should be order of one which means it has constant time complexity regardless of input size or the number of elements in the slot dictionary the execution time of other car function remains constant so this is because the code performs a fixed number of operations irrespective of the input so that's why and the space complexity also order of 1. constant space complexity the space used by the code does not depends on the input size or the number of elements in the slot slots dictionary it only requires a fixed amount of space to store the slots dictionary and function parameters so that's why so as I told you so there are many ways to solve discretion so you can use a list instead of a hashmap here so in that case um be careful so index number should be car type -1 because uh big is one and car type -1 because uh big is one and car type -1 because uh big is one and this medium is two and there's small is three so index usually starts from zero so if we if you use the list here so index number should be cut type -1 so index number should be cut type -1 so index number should be cut type -1 so be careful yeah so that's all I have for you today if you like it please subscribe the channel hit the like button or leave a comment I'll see you in the next question
|
Design Parking System
|
running-sum-of-1d-array
|
Design a parking system for a parking lot. The parking lot has three kinds of parking spaces: big, medium, and small, with a fixed number of slots for each size.
Implement the `ParkingSystem` class:
* `ParkingSystem(int big, int medium, int small)` Initializes object of the `ParkingSystem` class. The number of slots for each parking space are given as part of the constructor.
* `bool addCar(int carType)` Checks whether there is a parking space of `carType` for the car that wants to get into the parking lot. `carType` can be of three kinds: big, medium, or small, which are represented by `1`, `2`, and `3` respectively. **A car can only park in a parking space of its** `carType`. If there is no space available, return `false`, else park the car in that size space and return `true`.
**Example 1:**
**Input**
\[ "ParkingSystem ", "addCar ", "addCar ", "addCar ", "addCar "\]
\[\[1, 1, 0\], \[1\], \[2\], \[3\], \[1\]\]
**Output**
\[null, true, true, false, false\]
**Explanation**
ParkingSystem parkingSystem = new ParkingSystem(1, 1, 0);
parkingSystem.addCar(1); // return true because there is 1 available slot for a big car
parkingSystem.addCar(2); // return true because there is 1 available slot for a medium car
parkingSystem.addCar(3); // return false because there is no available slot for a small car
parkingSystem.addCar(1); // return false because there is no available slot for a big car. It is already occupied.
**Constraints:**
* `0 <= big, medium, small <= 1000`
* `carType` is `1`, `2`, or `3`
* At most `1000` calls will be made to `addCar`
|
Think about how we can calculate the i-th number in the running sum from the (i-1)-th number.
|
Array,Prefix Sum
|
Easy
| null |
1,489 |
hey what's up guys this is chung here so today uh let's take a look at lead code uh problem number 1489 find the critical and pseudo critical edges in minimal spanning tree so this one is a very interesting graph problem okay so you're given like a weighted undirected connected graph right with n vertices a number from 0 to n minus 1 and an array of edges where the you know each edge has like starting point start and the weight these are pretty standard right and then it asks you to find the uh the critical and the pseudo-critical the critical and the pseudo-critical the critical and the pseudo-critical edges in the minimal spanning tree so there are like a few terminologies yeah we need to be clear first right so first what is the minimum spanning tree uh which is in uh in short it's a mst so a minimum spanning tree is a subset of the graphs edges right that connects all the vertices without circle right and with the minimum possible total edge weight okay so here i mean for those who are not familiar with the mst which is a minimal spanning tree you know if we have like a very a lot of uh nodes and there are like a bunch of edges right yeah i'm just trying to uh write a bunch of edges here you know and each eye has like weight right so a tree of course right the tree is something a tree the subset of the graph of course right i mean a tree means what a tree means that you know the edge so the edge equals to the node minus one because a tree cannot have a circle right if we have like the edge greater than n minus one then we know it has to be have a circle i think that's the that's one of the way we can detect a circle okay and among all those kind of uh tree structures right because you know with this kind of uh many address right we can have like multiple a tree and a minimum spending trace is a tree that has the smallest uh possible weight and obviously they could there could be multiple mst as long as they all have the same minimum total weight right and then it then is this a critical and pseudo critical edges so for the critical edges this one is easier to understand which means that you know uh mst edge uh it's this address is critical you know if you delete this edge the total weight i mean if you delete this ad basically either if you don't include this edge from your uh from the spinning tray spanning tray you know the weight the smallest weight you can get is greater than the minimum one then this edge will be the uh the critical edge right oh and actually there's like a implicit uh condition here you know if by removing this edge you will not be able to form like a connect a graph that connected all the vertices this edge will also be a critical edge so what does this mean means that you know let's say you know they're like there's like this edge this like graph right okay here there's like this graphic here so this edge this one it doesn't matter what's the weight on it this one is definitely a critical edge because if we remove this edge now there's no way we can form like a minimum spanning tree right for all the vertices so this is the implicit like condition here you know we have to be careful all right okay so now we have talked about what the critical address is basically if you remove that if you exclude this edge you know and if you and no matter how you try to form like a minimum spanning tree and you always get like the uh a bigger weight then this ad is a critical one okay and so for how about pseudo-critical one and so for how about pseudo-critical one and so for how about pseudo-critical one so the pseudo-critical one is a little so the pseudo-critical one is a little so the pseudo-critical one is a little bit tricky here basically the pseudo-critical one is the pseudo-critical one is the pseudo-critical one is the pseudo-critical ad is that you can it pseudo-critical ad is that you can it pseudo-critical ad is that you can it can appear in some of in some minimal spanning tree but not all of them okay so what does it mean it means that you know uh if you remove it from the if you exclude basically if you exclude from the uh from the minimum spent uh from the minimum spanning tree we can still get uh the same minimum value the minimum weight then this ad will be a pseudo critical one so how about some examples right so for example we have this kind of map here right sorry not map graph and as you guys can see the uh the minimum spanning tree we could have like four minimum spanning tree all these four minimum spanning trees they all have the same weight which is seven right and as you guys can see you know so the answer for this one is what basically adds zero and one they are critical they're critical uh edges and the rest are pseudo-critical and the rest are pseudo-critical and the rest are pseudo-critical and why is that because you know let's say if we remove this edge right if we remove this edge no matter how we uh try to form like a tree the total weight will always be greater than seven same thing for this one right you guys can try it okay but in terms of the pseudo critical one are the two three four and five so which means that you know if we remove this one you know we can still form like uh a minimum us spanning tree right of it's the is the same weight which is seven so basically that's the uh that's how this problem was described right cool and to solve this problem you know we need some basic knowledge about how can we form a minimum spent a spanning tree right so we do it by using a union find okay so that's a very classic i mean uh solution uh code you know first minimum spanning tree basically we stored first we sort the high digest by the weight from the smallest to the biggest and then basically we greedily pick the edges from the smallest weight and we try to union them together right then by the end we finish the union you know the all the edges we have been union together will be the will be one of the minimum spanning tree uh spanning tree so that's how we do that right and then obviously you know once we have that minimum value right by uh by utilizing that union find uh algorithm you know to find the crit the critical one it's pretty straightforward right basically we'll try to exclude that edge from we'll try to exclude the edge and then we'll apply the uh and then we'll apply that same uh union find solution and then we'll try to get a new uh minimum we will try to get a new weight and if that weight is greater than the minimum one or like i said or the uh where we cannot form a proper as a graph a spinning tree right a spanning tree and then this ad is a critical one and then how about the second one right the f and in regards to the pseudo-critical edge we can do something like this so basically you know if the uh the first condition is this right so if the weight okay i'm using w if the weight is greater than the minimum weight okay right or it's not like we're not a graph okay we're not a tree right or not a tree and then this one right then this edge it's like a critical edge i use c e to represent the critical edge right okay so that's the first condition right second one is the ios right so remember you know since we already have this kind of minimum weight right the minimum weight across all the other trees right so which means that no re regard regardless what uh which combination we what kind of edges we i mean we choose the weight will always be either equal to this one or greater than this one right so what is ours you know since we already covered the cases when the weight is greater than this one so the house means what else means the weight is similar the weight is equal to the minimum weight right so in this case okay so the precondition is like this so this one is like by after right after excluding right average excluding edge at h i okay after excluding the edge i you know if the weight is greater than this one no so this adds basically i is the critical edge right else what else means that you know if the after excluding this edge the weight is equal to this one then there are like two uh two possibilities here so the first one is that of course this edge is one of the uh the pseudo-critical one is one of the uh the pseudo-critical one is one of the uh the pseudo-critical one right and the second one is what second one is that you know this edge will not be cut should not be included in any of the minimum speed spinning a spanning tree so which means that you know let's say if there we have a bunch of uh a bunch of at the edges right it doesn't really matter what that the edge is you know so let's say there it there is an edge so this actually has like a weight 10. all the other has one two three one two one something like that you know so obviously you know by excluding this 10 right i mean we can still get this minimum weight but this 10 should never be exist appear in any of the minimum spanning tree so which means that you know when it comes down to this house condition here it means that we have two conditions so the first one is that you know i does not right it's not belong to any mst right so if that's the case so if i does not belong to any the mst obviously this i should not be a pseudo-critical edges should not be a pseudo-critical edges should not be a pseudo-critical edges right because remember the definition for the pseudo-critical address is that for the pseudo-critical address is that for the pseudo-critical address is that you know this edge belongs to some of mst but not all okay so again i might see means that you know it has to be the weight has to be equal to the minimum right so okay so and then the second one of course the second one is that i is a pseudo coil it's a pseudo pc i use pc to represent pseudo-critical pc i use pc to represent pseudo-critical pc i use pc to represent pseudo-critical edge okay so which means that you know when it comes down to the else condition here we also need to check uh we have these two conditions so which means that you know we want to check if we force the solution to include this current edge right and then if we got like a bigger weight then we know okay so this i does not belong to any of the mst right because i think i'm repeating myself right because now the because the uh we have a minimum uh weight there already fixed right so if we include this edge and we gather like a greater one it means that this edge for example this 10 does not belong to any of the mst and we can simply use that to verify if this edge is a pseudo critical edge or not and that's all the logic here and as you guys can see since we're going to run that you know the union find the solution multiple times and it's better for us to create like separate class so that we can create uh multiple instances to run uh to run those to run multiple like unifying solutions okay cool so let's start coding then um like i said we're going to create like a separate class for the union find okay and all right so here we have in it right we have self and we have n right because we need that so for the union find you know i'm not going to talk too much details about how should we implement the union find right basically we need a parent going to be a list of the range of n right at the beginning every node has a parent equals to itself and then we're gonna have like two methods for the union find of course the first one is to find it's gonna be an x so the way we're implementing is you know whenever the x does not equals to it to itself sorry the parent of the x is not of the value itself then we know we need to go back right we need to sorry we need to keep looking forward keep looking to the uh looking for the parent that's how we do this parents.x that's how we do this parents.x that's how we do this parents.x because we self.find self.parents.x okay and then we return self.parents.x okay and then we return self.parents.x okay and then we return this self.parents dot x self.parents dot x self.parents dot x so here this is like a technique it's called path compression so which means that you know so the idea of the find here is you know it's the is to find the root for this kind of for this x right and like i said you know so let's say this is the root right and if we have like a lot of uh child nodes that who has the same root here let's say for example this one is x right you know if we don't compress the compressed the path here you know so every time when we are every time we try to find the root for this act we have to go all the way back to the root it's a linear scan right but so this kind of uh recursion call what it does is that you know after the first query this x will be moving to here instead of uh at the end of this kind of a tree structure that's how we uh that's how this kind of recursion works so basically only the first time it will cost a linear time the next time it will only cost one time okay so a little bit about this uh fine right and for the union you need to like pretty straightforward so we have a uh x and a y right and then for the root one it's going to be the self dot find x so first to union a two note we first get got each of the notes like root or parent and then we only union when they are different right so r then we do a unit self.parent dot r2 equals r1 self.parent dot r2 equals r1 self.parent dot r2 equals r1 right so that's how we do the union actually you know it actually took us to make this unified complete the complete union find algorithm should also include like a ranking for each of the route so which means that you know every time when we assign the uh when we assign this uh the parents you know we can as you guys can see we can either assign r1 to our to uh assign r2 to r1 or we can also sign r1 to r2 right either way it's fine but which way should we use basically if we have like a ranking here you know we should always assign the root has a smaller ranking to the root has a larger ranking so that you know this kind of can guarantee that you know the tree is like kind of balanced you know we won't take too much time to do the union and find but for our case i simply remove that ranking parameter to make this algorithm a little bit simpler yeah and about okay so that's basically the union find uh code here okay and so let's add a few more stuff here okay so first you know we have since we need to get the weight here right we need to get the total weight of after do this union find so we can have introduce a second parameter or a field called weight equal to zero okay so and every time right every time when we uh do a union uh we're going to pass like a third parameters called weight so whenever we include this edge right we simply add this weight to the total weights okay that's that all right okay so i think we can leave this one for now and we can add more stuff later on so let's try to use this one to find the minimum uh find the weight for the minimum spanning tree so like i said first we're going to sort this edges by the weight right and since we're going to return the indices of the edges now we're going to also store we're going to add the original index to the to this list so which means that you know since we're going to start by the weight i'm going to put the weight at the first element it's going to be a weight and we have a b and i right nine okay then for i uh a b w right in your marriage address right so i'm a i just did a little massage right to this one and then we just simply sort store this one okay and then so here okay step one right step one find minimum weight for mst actually not me find weight for mst okay so we have um so we need to have a like union find instance so union find n right for w a b i right in range actually we do in edges so actually we don't need this i here we can just use it like this one underscore right we do union find one dot union a and b and w okay and then the minimum weight right so we have minimum weight it's going to be going to unifying one dot weight right so after doing this kind of union find this weight will give us the weight for the mean for the mst which is this one okay now let's find the uh the critical energy in pseudo-critical ad so for the energy in pseudo-critical ad so for the energy in pseudo-critical ad so for the critical edge i use the ce it's going to be a list right and then the pseudo critical edge is another also like list so here you know step two right try to exclude each edge right and then run the mst algorithm right so for i in range of uh of m maybe okay so let's do a time equals the length of the edges right so for each of the edge we're trying to exclude right uh we're going to run like union find that's why i'm going to have a union find 2 in this case going to be a same thing union find n right and then for j in range m okay so if the i is equal to j right we simply continue which means we are like excluding this edge otherwise we'll do uh what you will do a union find what do we unify again right so we have a w a b this one equals the address of i right sorry edges of j okay union find two dot union right of a b and w okay so now like i said if the union find two dot weight right not union fine two dot weight this one is greater than the minimum of weight then we know okay so this edge is a critical edge right so this critical that append dot i uh actually not this i because we need original uh index which is the uh the address right i just dot i dot three right that's the original index so like i said you know here this is not on the only condition we also need to know by excluding this edge if we cannot form a proper tree and then this one is also like a critical edge right so how can we check that remember so when i say you know for tree you know for a tree to include all the vertices you know let's say the vertices is n right so the edges has to be the same as has to equal to n minus one that's a condition to form a tree so which means we can also have like a edge count right in this union find uh class so every time we include an edge we simply just increase this counter by one okay and then here we just check right or the uf2 dot edge count is smaller than the n minus one then we know okay this one is also like a critical one so basically if the new weight right is greater than the minimum weight right or we cannot form a tree right a proper tree which contains right all the nodes right then this one is like a critical one else right so also like i said we have two conditions here out means this weight is the same as minimum weight then we need to check right need to check if the edge if at the igi right if the ihi should not belong to any mst right so how can we check that like i said we force to include hi and then run mst algorithm again right so then let's do it right so which means we need another like union find right so that's why i create this class right so i have a union find of n again right so we have so now to force include this one of course now we simply just do a union find right we do a w a b this one equals the address of i right because this is the edge we're trying to force to include and we simply do a unifying three dot union okay of a b and w right because at the beginning you know everything there's nothing union together you know that's why when we try to union this ad it will definitely be unique right and then we just do another we just run a like algorithm followed continually right after this one so we have j in the i'm going to use the j in the range of m right so again we're going to have m w a b and this one right equals the address of j okay then we're going to run union 3 dot union dot a and b w okay so now if we check if the union three dot weight is equal to the minimum of weight then what then this one then this edge is a pseudo-critical one append dot address i.3 i.3 i.3 yep so and then return the c and p pc that's it uh yeah i think that's it right let's run the code real quick here i think there's there must be a typo here you need to find three unions union okay accept it right if i run it yeah cool so it's passed right so and oh the time complexity of space complexity so we have like uh distorting it's not it's nothing i think because here's the real time complexity so we have a we have m right so obviously we have an acid uh for loop here so this is going to be a m square right and so we have a m square and here it's like also a for loop here there are but they are like parallel yeah so i think the time complexity will be m square because like i said you know each of the operation in the union find either like a final union we can treat them as o1 time complexity that's why you know the total time complexity is going to be a m square right where the m is the total it's the edges right well and space complexity is going to be a o of m right because we have this kind of edges and yep so that's it right i mean it's a pretty tricky one you know it actually it requires you to have many uh small pieces then small knowledge pieces and you need to stitch them together the first is like what is mst how can we get uh get a mst weight right the minimum weight then from there you know we have to run a bunch of uh for each of the three of the edge right after it's cooling excluding it we run this mst again and then if this uh after that if the weight is greater than the minimum weight or this one's pretty tricky or this one will break will not form a proper tree you know and then this one is critical one you know else actually this one is even trickier else this one you know this one it means that you know by excluding this current edge we can still get the minimum spinning the minimum weight right but to be able to check if this ad is a pseudo-critical one uh we have pseudo-critical one uh we have pseudo-critical one uh we have to basically force to include this one because you know there are like two cases here you know either this edge is it's the pseudo critical one or this edge should not be included in any of the mst right so the way we're checking is that you know if we force to include this edge and if the mean if the weight is greater than the minimum one then we know this one is not like pseudo-critical this one is not like pseudo-critical this one is not like pseudo-critical edge right and we only include this one when they are the when the weight is the same as the minimum weight and yeah that's it cool i think i'll just stop here then all right thank you for watching this video guys and stay tuned see you guys soon bye
|
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
|
pizza-with-3n-slices
|
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight.
Find _all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST)_. An MST edge whose deletion from the graph would cause the MST weight to increase is called a _critical edge_. On the other hand, a pseudo-critical edge is that which can appear in some MSTs but not all.
Note that you can return the indices of the edges in any order.
**Example 1:**
**Input:** n = 5, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,2\],\[0,3,2\],\[0,4,3\],\[3,4,3\],\[1,4,6\]\]
**Output:** \[\[0,1\],\[2,3,4,5\]\]
**Explanation:** The figure above describes the graph.
The following figure shows all the possible MSTs:
Notice that the two edges 0 and 1 appear in all MSTs, therefore they are critical edges, so we return them in the first list of the output.
The edges 2, 3, 4, and 5 are only part of some MSTs, therefore they are considered pseudo-critical edges. We add them to the second list of the output.
**Example 2:**
**Input:** n = 4, edges = \[\[0,1,1\],\[1,2,1\],\[2,3,1\],\[0,3,1\]\]
**Output:** \[\[\],\[0,1,2,3\]\]
**Explanation:** We can observe that since all 4 edges have equal weight, choosing any 3 edges from the given 4 will yield an MST. Therefore all 4 edges are pseudo-critical.
**Constraints:**
* `2 <= n <= 100`
* `1 <= edges.length <= min(200, n * (n - 1) / 2)`
* `edges[i].length == 3`
* `0 <= ai < bi < n`
* `1 <= weighti <= 1000`
* All pairs `(ai, bi)` are **distinct**.
|
By studying the pattern of the operations, we can find out that the problem is equivalent to: Given an integer array with size 3N, select N integers with maximum sum and any selected integers are not next to each other in the array. The first one in the array is considered next to the last one in the array. Use Dynamic Programming to solve it.
|
Array,Dynamic Programming,Greedy,Heap (Priority Queue)
|
Hard
| null |
112 |
this problem is called path sum and here we are given a binary tree and we have to check whether there is a path from root to its Leaf nodes such that the sum of values equals a given value so let's see the problem statement so we are given this root of the tree and we are also given one target sum and we have to find whether the path exists or not so in this case the paths are you can take this path or you can take another path like this so there will be as many paths as the number of leaf nodes so you start from the root and try to reach one of the leaf nodes so that will make a path and you cannot skip any nodes so you have to go through only left and right pointers are there in the node tree node so you have left pointer you have right pointer and then you have one integer value within this node so uh let's see whether a path exists or not in this case so let's say we are given this tree binary tree and the target value in this case is let us say twenty two so if you see that if you come here it's 5 so if you go from 5 to 8 and then to 20 you have reached a leaf node so this is a path what is the sum here it's 33. so this path does not satisfy this property now let's take another path so we come along this four then so we start from root always 5 4 then 11 and then we go to 2. now what is the sum here 5 plus 4 is 9 plus 11 is 20 plus 2 is 22. so this is a valid path now once you find a path whose sum of values is equal to the Target you need to return true you don't need to Traverse other parts in the tree if you are exhausted with all the possibilities you checked all the paths and you never found uh any path with this target sum then you return false so you have to Simply return true or false instead of returning the complete path so let's see how we will do it so we have some function let's say ah path sum and you are given root and you are given a Target value so what you will first check if root is empty or the tree is empty then you return false so these are the base cases so if tree is empty you return false else you check if there is only a single node in the tree in that case left and right both will be null so if Roots left is null and Roots right is null then you check that the target should be same as Roots value if that is the case it's true so you can return this conditional check if Target if this is the case that is left and right both are null that is just one node in the root in the tree then Target must be equal to whatever value this tree contains so let's say there was a node with a value of 5 its left and right terminal and the target was also 5. then this equality will return true but let's say if this value was 6 or any other value then it will return false so these are some of the base cases if that is not the case that means 3 has more nodes so what you will do uh you will try to find uh if left is there so root left is not null then what you will do you will add whatever is the value so how we proceed so initially we call this function on root then there are more uh children nodes so what you will do you have to include this value within the a given node whenever you reach any node you add that value so now initially the running sum or the sum we encountered so far was Zero now you reach this root so you add its value to the sum so now sum is 5. so remaining sum is so initially Target was 22 now you come to root so remaining Target root you have to include so the remaining value is 17. so from here in this sub tree or this sub tree left sub tree or right sub tree you have to find a path uh whose sum is equal to 17 because 5 is already included so what you will do you will call this path sum function recursively on root left and the target new Target will be Target minus uh Roots value so if this is true you can return from here if not you can check if right subtree exists or not right now it exists or not then again you will call PS root right and again this same value Target minus root value so if either one of these is true the complete value is true so now let's write the function for this the code for this uh so time complexity uh in the worst case you may end up traversing this complete tree so time complexity will be of the order of n space complexity since you are doing a recursive call here it may be a straight tree and this calls it's left so you may end up storing all of these in the function stack and so in that case a space would be o of n now let's write the code for this so if root is null return false if root left is null and root right is null return Target sum is equal to Roots value this is the case where there is just one node so even if we make this recursive call so ultimately let's say we reach here and we passed some Target updated Target and here's the target remaining was two so in this case also so this is the case for a leaf node and not a single node if I confused you so now let's continue so otherwise we will have a boon a path some exists equal to false and if root left is there then part some exits equal to add some root left Target sum minus root well and same thing for right so if either it was found in the left or it's found in the right it will capture that value so finally we have to return but some exists and let's run it so it's false let's see what is the mistake uh it's fine okay so we do not change this and okay now let's run it yeah so this works let's submit the solution and the solution is accepted
|
Path Sum
|
path-sum
|
Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`.
A **leaf** is a node with no children.
**Example 1:**
**Input:** root = \[5,4,8,11,null,13,4,7,2,null,null,null,1\], targetSum = 22
**Output:** true
**Explanation:** The root-to-leaf path with the target sum is shown.
**Example 2:**
**Input:** root = \[1,2,3\], targetSum = 5
**Output:** false
**Explanation:** There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
**Example 3:**
**Input:** root = \[\], targetSum = 0
**Output:** false
**Explanation:** Since the tree is empty, there are no root-to-leaf paths.
**Constraints:**
* The number of nodes in the tree is in the range `[0, 5000]`.
* `-1000 <= Node.val <= 1000`
* `-1000 <= targetSum <= 1000`
| null |
Tree,Depth-First Search,Breadth-First Search,Binary Tree
|
Easy
|
113,124,129,437,666
|
1,854 |
hey everybody this is larry this is me going over weekly contest 240 q1 maximum population year so this is a simulation problem or just do what they tell you problem um uh to be honest i did it even more naively the key thing to note is that there's only 100 n and the difference can only be a hundred so you're gonna do a hundred square and that's basically what i did i just have two for loops i just keep track on each element and then i take the max element and then the first index the first year that has the same element um there are other ways to do it the probably the best cleanest way to do it is about with a sweep line algorithm um the way that i did it like i said it's gonna be 100 square it's not quite n it's n times uh u where u is the size of the domain um but yeah and you can you know with sorting and sweep line you could get an end log in and that's probably the way that i would go if the bounds were a little tighter but uh but yeah let me know what you think let me know what you know and you could see me salvage live during the contest next this takes like a couple of seconds and i always get a little bit not everybody about it all right let's go this is inclusive and inclusive to f minus one that's awkward but do a little bit awkward but that's okay yeah uh hit the like button hit the subscribe button join me on discord let me know what you think about this promise explanation and all that good stuff um i did okay but i don't know uh anyway i will see you later uh stay good stay healthy take your mental health bye
|
Maximum Population Year
|
maximum-population-year
|
You are given a 2D integer array `logs` where each `logs[i] = [birthi, deathi]` indicates the birth and death years of the `ith` person.
The **population** of some year `x` is the number of people alive during that year. The `ith` person is counted in year `x`'s population if `x` is in the **inclusive** range `[birthi, deathi - 1]`. Note that the person is **not** counted in the year that they die.
Return _the **earliest** year with the **maximum population**_.
**Example 1:**
**Input:** logs = \[\[1993,1999\],\[2000,2010\]\]
**Output:** 1993
**Explanation:** The maximum population is 1, and 1993 is the earliest year with this population.
**Example 2:**
**Input:** logs = \[\[1950,1961\],\[1960,1971\],\[1970,1981\]\]
**Output:** 1960
**Explanation:**
The maximum population is 2, and it had happened in years 1960 and 1970.
The earlier year between them is 1960.
**Constraints:**
* `1 <= logs.length <= 100`
* `1950 <= birthi < deathi <= 2050`
| null | null |
Easy
| null |
958 |
hey guys in this video we shall see another problem on the record check completeness of a binary tree so given the root of a binary it will determine if it is a concrete binary key or not in a complete binary tree every level except possibly the last is completely full and all nodes in the last level are as far as left as possible you can have between 1 and 2 power H nodes inclusive at the last level F so let's first understand what's up binary in a complete binary trick so mandatory means a tree having two nodes right so if this is a root node it should have two children so that's a minority three so what is what I mean by complete binary Electric that means if you have a tree like this all the levels this is the first level second level third level and fourth level one two three four so all the levels except the last one all this level except the last one must be full complete that means it's at every node so if in case there is a node like this then if You observe from the left to right left alone right till then empty this is null well it should be complete from the website so once you encounter a download all the notes further to that in the right side must also be null only then you can tell uh given to ESF complete binary trick so in the given question how do we find the whether a given tree is a complete tree or not so for the given question yeah I just pasted the diagram over here so if You observe uh all clothes except the last node that is this node and this node uh this all the levels sorry all the levels except the last level till here all the levels yeah all uh you can see it's a completely because both the children are present till the end but when you see the last level yeah you have to check from the left side it should be complete from the left side right so in the last little as for left as possible all the notes in the left uh last level must be present so left foot is present cycle is present if code is present and last one right code is not present yeah that is fine because it is complete from the left side and once you encounter no there is and coming to the second problem so yeah so all the levels except uh fit the last level you could see um yes and coming to the last and the substance and coming to the last level uh you can observe from left to right when you Traverse left row right now then here it is null it's not null so that means this is not a complete benedictory not a complete binary so how do we solve this problem logically what's the logic to solve this problem so for this you will be using BFS so BFS means if you take this example only let's consider this example uh in the BFS first level you consider so you will get one then in the second level you will get two and three and in third level if you will get four five for that six and coming to the right row it's null so this is nothing but that so this is one this is BFS for this tree and the other tree Here If You observe the first level you have one welcome to the second level two and three fine coming to the last level four five and here it is four five null and then self so Here If You observe the a welding wave first we will Traverse one we have five then two and then three five then four five six after that you will traversal so after this null are you encountering any normal node no yeah this is a binary complete manual but here in this case for this tree you Traverse like one then two three then four five and here we are encountering null so once you encounter null all the nodes further to this whatever you travel assume winner but you can see it's a seven is a non-level it's not an it's a seven is a non-level it's not an it's a seven is a non-level it's not an unload Twitter null node and this is not a complete binary trick and one other example I would like to give is like uh other scenario one two three four five then six there are no nothing seven okay eight nine tenth eleven but if you're observe in this example uh till here it's the all the notes except the last notice last level sorry all the levels except the last level so this is the last limit here all the levels Here If You observe this is one 0.23 456 after that here I'm sorry we 0.23 456 after that here I'm sorry we 0.23 456 after that here I'm sorry we are getting a decimal so this is not a complete parallel type so all else if this is a nth level all the N minus one levels should have two children compulsory two child nodes are must but for the last level it should be complete only from the website that means if you encounter a null somewhere in between then all the notes next to that in the right part of the last level should be that's one case so now for this as I said we'll be using BFS and we need a cube first which will follow first in first order so once you have q as I write the code will explain and later we'll Trace that same code with an example so let's move the implementation part first as I said we'll create a queue after a type or you know let's name it as q and new little cut list so we'll be using linked list implementation of the few interface in Java so linked list once you have this now you have to add the root row to the Q and one more we need a um Boolean value same as flag that is set equal to that is set to so why do we need this is required because if flag is sector false that means a node is not an unload once you encounter in the node you set the flag equal to true so that is where we refer to uh Boolean Valley flag now we shall start with the while loop while the queue is not empty what do we perform is when we create one more node three node we call node equal to Q dot School to remove the element from the queue because it's the first thing first so very first element which will be injected into that element will be removed now it's a header element and next after that you have to check if node equal to none if not equal to continue then your set flag equal to true so once this is done otherwise else part will be if flag equal to true the written false so what does this do is um at first you add a root or one into the Q right so once you do that you check out the Q simply or not no it's not empty because one is present in the queue then you check whether three node equal to Q Dot uh when you perform this operation so node will be equal to one you remove the element from the queue header element from the queue and that will be initialized to the node value so once you have node equal to 1 that means node is not technology you go to the else part so if in case if you get some remote element equal to null here you may get remote element equal to null right here in this case so if you get node equal to null and you set the flag equal to true then you go to the next loop again uh and after this here and Q dot add off root dot left and Q dot add off dot right okay so here you encounter what node equal to null line you set the slide equal to true no so next time we will encounter 7 as the header value pole value in the queue so that will be initialized to node so now in this case node is not equal to null but you are getting flag equal to true that means you have encounter null value somewhere between before only so at that time you will tell that the least uh I don't know whether you have caught it or not I'll explain this properly by addressing the code so yeah if this isn't if all the cases are passed that means you have not encountered any null values or you encounter that values and each time uh the flag was two only then you return just true if you do not come to this case once you encounter flag equal to then you return true now we'll run this or why is it telling time limit exceeded any mistake in the code um this is fine add a true then node it should be node value no dot left so whatever element you remove if you at first you'll encounter root as one you have to go for one uh and you remove that from the queue and you won't find that in the queue so you cannot do root dot left and root dot right because it will be empty by that time that one will initialize the normal so we have to load dot left right so now we'll trace this example I'll just uh copy this code okay I just pasted the code and the diagram now we'll start with the first so you'll initialize Q initially that will be empty and then Q dot through the uh add a root is nothing but one so you add one to this so once you add one next Bull uh flag will be set to false so once this flag is set to false you check whether queue is empty or not is it empty no certain so you go inside the while loop so once you go into the file Loop you create a new node where you initialize the value that is removed from the queue so Q dot pole will written so if you do perform Q dot pole then one will be removed and that will add it to the node value node will equal to one foreign so once you have node equal to one now if node equal to the only check node is not equal to null uh then else part you go if flag equal to true you check whether here if the flag equal to 2 is it true no so you check that part next you do Q dot add F no dot left what is node dot left add that to the queue so Q is equal to 4 dot left is suitable so and you will not have no dot track that is nothing but three so why am I doing this I am going in this order first thing first off so that next time when you perform Q dot Port 2 will be removed so this is the next again you go the while loop whether queue is empty no this is not empty NC go inside the while look so 2.2 will be removed so node will be so 2.2 will be removed so node will be so 2.2 will be removed so node will be equal to Uno and Q as you remove the two values you will continue only one element that is three so now that you check whether or not equal to the node is not equal to the hence you go next part if flag equal to true no one is not equal to it is equal to False only next U dot add of no dot left and node dot right so now for that queue you will add note dot left so 2 is left is 4 so 3 here or and Q load it does no dot right is 5. foreign so three dot left what do you have here this is null so Q equal to so once you remove three uh Cube will contains Pi comma four nothing else so now you have 4 here first by then load dot left that is none and no dot right that is 7. this is Q is containing so next you go again check while condition it is not empty you go inside now nobody call it you will not pull so naught will be equal to what is what is what is right so node equal to 9 and Q will be nothing but 11 null and Phi left nine uh sorry is it nine it's not nine it's four yeah it's four actually so this is four I misread this so this is four so four dot left and four dot right four dot left is so you just add uh them to the Q so Q will be equal to 5 null then 7 4 dot left decimal and four dot right also null so next again we perform while Q is not empty here it is not empty three node equal to node dot four so node will be final so once you remove Phi you will contain null seven and then so once you do this uh you check whether node equal to null node is not equal to null you go here whether slag equal to false uh flag equal to True is it true no there's no true so you return you will not check this condition check that out next you perform Q dot side of node dot left and node dot is node value five so Five Dot left and 5. so you just add them to the key much so you have this in the queue now you better you go inside the loop again with the Q is empty no it is not empty then again you perform a node equal to Q dot point so node equal to Q2 it is it's null so once you have this as null you check whether or not equal to Kernel s it is equal to NC flag will become true so flag equal to this important so once you apply equal to else part is not required next again you check whether uh okay once you remove this node you will have only these remaining elements now so is Q equal is not equal to null because it is not empty vertical one sorry it's is it empty or not no it's not empty so you're going to set the while loop foreign so you got this I hope what are we performing is we are inserting an element of the uh queue and we are popping that out and while popping that out we are checking if that value is null or not if that is null then you how about set the flag value equal to true if once you set the flag well you're going through all the flag values next to that must be true only because that you should get null value soon that means you should get every uh node value in SNL once you get a some no variation only then it can be a complete binary tree because in this case once you encode the null and you are encountering a not null value so in that case it won't be a complete binary trick if this was a null actually then it will be a complete binary so once you get uh node equal to you set flag equal to true so after setting flyer equal to if in some case node is not equal to null but you're getting Fair equal to true so once you set flag equal to true you are getting this node value is seven no and you are having flag equal to true that means it's somewhere before you have any confessional value and now we are equal to n containing a node which are not null value so that means that is not an upgrade binary trick this is how we praise this question I hope you guys have understood the problem if you have any doubts please drop them in the comment section will come up in another video in the next session and until then subscribe to the channel live like and share it thank you
|
Check Completeness of a Binary Tree
|
sort-array-by-parity-ii
|
Given the `root` of a binary tree, determine if it is a _complete binary tree_.
In a **[complete binary tree](http://en.wikipedia.org/wiki/Binary_tree#Types_of_binary_trees)**, every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between `1` and `2h` nodes inclusive at the last level `h`.
**Example 1:**
**Input:** root = \[1,2,3,4,5,6\]
**Output:** true
**Explanation:** Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
**Example 2:**
**Input:** root = \[1,2,3,4,5,null,7\]
**Output:** false
**Explanation:** The node with value 7 isn't as far left as possible.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 100]`.
* `1 <= Node.val <= 1000`
| null |
Array,Two Pointers,Sorting
|
Easy
|
2271,2283,2327
|
491 |
Hello friends today I'm going to saw with good problem number 491 non-decreasing subsequences so in this non-decreasing subsequences so in this non-decreasing subsequences so in this problem we are given an integer array numps and what we need to do is return all the possible non-decreasing subsequence of that array non-decreasing subsequence of that array non-decreasing subsequence of that array which has at least two elements so the things that we need to keep in mind is it should be non-decreasing and it should be non-decreasing and it should be non-decreasing and uh there should not be any repetition of the elements like let's see this example here so we have this array and we need to uh get the subsequence of this area so how are we going to start we start from the first element so from four we know that if the sequence first of all the sequence we start with an empty subsequence and then we add a 4 to that subsequence so now what do we have a 4 in our subsequence now um is this a flat 2 of course not our result array is empty so far and will only push those Elements which are at least of length two so the arrays would be of length to at least now what we need to do is we need to insert um another element right so we move on to the next element in this area and then we get the value 6. now we check is 6 greater than the previous the last element in the sequence well yes 6 is greater than 4 so we add a 6 to our sequence now we know this is at least of length 2 so this will be uh one sequence that we are going to append to our result array next um we will keep on continuing with this sequence so as we know we have 6 4 and 6 in our sequence um so far now we move on to the next element which is seven so E7 greater than the last element in our sequence it is so we add seven to our sequence and again here its length is greater than 2 so we add this to our result array and we keep continuing with the sequence the previous sequence we had so next we move on to the next element we have a seven again and 7 is greater than or equal it is actually equal to seven right equals to 7 means it's still non-decreasing right it is it's still non-decreasing right it is it's still non-decreasing right it is non-decreasing non-decreasing means it non-decreasing non-decreasing means it non-decreasing non-decreasing means it can be greater than or equal to so since 7 is equal to 7 so we can add this value to our sequence now we can again append this value to our result so far we have three uh arrays in our results three subsequences now what we do is uh we backtrack from our sequence so the last sequence we had was this one right so we backtrack from this subsequence so what we'll get is we pop our last value from the subsequent so we pop the last value and we get the value 7. and then um what we are trying to do here is we are trying to perform an iteration so for this subsequence that we have we added this element right to form this subsequence now what are we going to do is now we are looking for the next element after uh this one is there an X Element no there is not right so we just return back to our subsequence and backtrack again so since we do not have the next element we backtrack and then this is what we have in our subsequent so far so what is it that we have is four and six so we have 4 and 6 and we have already computed its next element right we have already iterated over the next element which is at position three now once we go to the next position which is okay this is position three uh two at index three so when we look at index 3 the value is equals to 7 right and we know that 7 is greater than 6 so since um adding seven to this subsequence would make still may keep it non-decreasing make still may keep it non-decreasing make still may keep it non-decreasing however we see that we already have that subsequence right we already have that subsequence even though this was from the second index and this is at index three this value is from index three however the values are same which is that we are actually creating a duplicate which we do not want to create so how do we avoid duplicates we are actually going to use unique asset set so we will be using a set uh where what we are going to do is so uh we'll assume that we have a subsequence four and six right so we have not moved so far so from 4 and 6 we have the subsequence this now we set a new um set every time we Define a new set on um and then what we do is now since we are iterating over seven we look at our set so our seat is right now set doesn't have any value 7 so far so what we do is we add seven to our set now in the next iteration uh what we do is we now backtrack and um so basically from this we moved on to this one that is our next subsequence was this and then we moved on to this one and then finally we backtracked where uh our subsequence was now this much only and then since we have already computed this value we move on to the next step so now here we see that we have uh a value 7 in our set already so since we already have the value 7 so we are not going to uh perform this operation um that is I'm not going to add to our set so that is um then we move on to the next element and since we do not have the next element then we backtrack again and then where do we reach is we reach the point where we only have one element in our array that is four right and since we already computed the it for the value 6 now we compute it for the value seven so next we'll have 4 comma seven in our subsequence and every time we uh like iterate like every time we are increasing our length of the subsequence we are actually creating a new set so for this subsequence we will have a new set which what want which doesn't have any value in it so far so when we then for this set um when we then move to the next value that is seven next index seven then um we do not find the value 7 here so that is when we can actually push the value 7 to this um subsequence in this way but when we backtrack again and then when our subsequence only has the value for that is at this point we create our new um a new set and now for each of the element that which Traverse for that state we are actually going to add it to the set so we'll add the value 6 to our set and then we'll get the subsequence we add our value 7 to get the subsequence with value for only four and seven and then when we move to the next element we see that we get the value 7 and we already have it in our set so we do not execute that Next Step so that is how we are going to avoid duplicates now let's dive into coding so what are the things that we need our result array and then we need to we need a subsequence array which will uh be which we will be using over each iterations uh to backtrack to move forward and then backtrack so our subsequence will keep on changing and we'll be using uh helper method for that so let me Define the value n is the nums length to result equals to our empty array and then our output function we will pass the index I and then our subsequence array and we are going to Define our unique set which is empty for every function new function call so now what we do is we iterate starting from the index I and J is less than equals to n j plus so why are we starting from index I so index I means our previous subsequence in our previous subsequence we have iterated up to index I so let me just complete it and then explain it to you again so what we'll do is we are going to check here if the set has the value at index J if it has the value then we are going to keep continuing to the next and also we are going to check if the next element is not decreasing or not so non-decreasing means we need to make non-decreasing means we need to make non-decreasing means we need to make sure that um the value at in the last index of sub array is less than our current value and for this to be valid we also need to check if the length is greater than zero so the length of the sub array should be greater than zero and the value should be less than our current element um if it's not less than equals to E that is if it's greater than greater which means it's not decreasing then we are going to continue that is we escape all the next steps that we have else what we do is uh we add to our sub array the value J and then we check if our length of the sub area is greater than or equals to 2 that is when we push this value this our sub array to our result and then we call our helper function um to perform the next iteration that is index J plus one and the sub array okay so we need to push the copy of our strawberry and then finally we are going to pop the last element from our Subaru that we pushed so and then finally we are going to call our helper function at index 0 and return our result now talking about starting from index I so let's see here we are calling at index 0 with an empty uh sub array right so index 0 is value four so right now our in unique error is empty unique state is empty so we start at index 0 since I is in the value is equals to zero so you start from index 0 unique doesn't have that value and also the length of sub array is less than zero so we move to the next step where we push our next our value at index 0 that is four two hours of array and then since its length is also not greater than equals to 2 so we move to the next step that is we make a call to our helper function with index 0 plus 1 which is equals to 1 and with our um sub area with value for init so we call our index I value is now equals to one okay so I'll just write it here and our sub array has the value 4. all right and then we Define our new unicarray and then we iterate starting from index one so now what we are doing is uh we are looking if 6 is um not in the array and is clear is less than or equal um I mean it's greater than or equal to the last element and it is so we push to our value at this uh our array and then since now the length is greater than or equals to 2 so we push to our result array and we call our helper function to the next element so what we are doing is we are we added four now we need to look for six so we add we are actually increasing the length of our subsequence here so four and then next we added six next in the next step We'll add seven given that it satisfies all the condition in the next step we are gonna add this 7 as well then we backtrack at this point at this step and then we move to we will only have this uh subsequence and then we again backtrack to this position and then from this for Loop right so these four Loop here it uh it's increasing the value of J is increasing right and at the position where we have our subsequence has the value four and six and the index value is equals to 2 right so we started from value two so J was equals to two um we backed tracked from Two and then now we will move on to the next element which is equals to seven so that is what we do so we for this subsequence J is equal to 2 then J is equals to 3 and so on so that is why we start from the next uh from because we have already evaluated these two so we are actually going to start from the elements after those after these to write which is at index 2 and Beyond so that is what it is now let's run our code oh no what's wrong oh my god there are a lot of undefined values all right okay so it's not equal to it's just less than n here okay I'm still getting wrong all right so I have this unique value so I defined it and I'm checking the value here but I'm never adding the value to it so I actually need to add it for The Unique value Unix set to work right so I'm adding numbers J here a lot of mistakes I make let's submit it so the time complexity of this solution is um
|
Non-decreasing Subsequences
|
increasing-subsequences
|
Given an integer array `nums`, return _all the different possible non-decreasing subsequences of the given array with at least two elements_. You may return the answer in **any order**.
**Example 1:**
**Input:** nums = \[4,6,7,7\]
**Output:** \[\[4,6\],\[4,6,7\],\[4,6,7,7\],\[4,7\],\[4,7,7\],\[6,7\],\[6,7,7\],\[7,7\]\]
**Example 2:**
**Input:** nums = \[4,4,3,2,1\]
**Output:** \[\[4,4\]\]
**Constraints:**
* `1 <= nums.length <= 15`
* `-100 <= nums[i] <= 100`
| null |
Array,Hash Table,Backtracking,Bit Manipulation
|
Medium
|
646
|
1,700 |
let's look at the problem 170 of lead code number of students unable to eat lunch so the question is long but you can I can summarize it as follows so they essentially saying that there are n number of students in the class okay and there are equal number of sandwiches that are there in the class right so students is equal to sandwiches as many students that many sandwiches but students sandwiches are of two types one is circular and one is box squar right so and these students every student has a preference so some want circular some want Square okay and if they don't get a sandwich which is circular if their preference is circular then they will not eat and if a say a student prefers a square sandwich and they don't get a square sandwich then they'll not eat okay so what you required to and the rules are like this so there is a sandwich stack okay which will be provided by the sandwich stack will be provided to our function okay so sandwich stack would look something like this so one stands for square and zero stands for circular a sandwich okay and similarly these students will be provided with their preference so the first student say has a preference of circular second student has a preference of say Square third students has a preference of square fourth student has a preference of circular fifth student has a preference of circular sixth student has a preference of square so something like this right and this is the Q so this is the sandwich stack and this is the student stack okay so the first student from the left will look at the top of the stack okay sandwich stack so the top would be from the left okay so if it doesn't match that the students preference is circular and the top of the stack is Square then the student will not take that sandwich instead go back at the line go back in the queue and wait for the students turn again okay then the next student will come in front they will check what is the first sandwich in the sandwich stack and if it matches their Preference they will take it and leave so this student takes that sandwiches sandwich and leaves the queue okay so the student has left the queue and went into the dining hall of something right and the sandwich they have taken the sandwich with them okay now the next student comes in front of the line and the next student looks at the uh the sandwich which is at the left of this array now and if it matches it takes it away if it doesn't it again goes back in the line so in this case it goes back in the line right then the next student checks if it matches their preference it takes it and goes to eat it okay then the next one checks it the next student checks if the preference matches it doesn't match so it doesn't take and goes back in the line and the next student sees it matches it takes the sandwich and leaves the queue and this goes on happening right now all the three will get their preference because zero is getting zero so it will take the sandwich and leave one will get one it will take the sandwich and leave circular will take circular it will take the sand and so here finally all students are able to get the sandwich so we will return that there was Zero students who were unable to eat lunch let say if I take another example right I take another example with which is as follows 1 0 1 these These are the sandwiches now these are the students okay and the sandwiches are as follows 1 0 1 okay so what happens here let's see so the First Student in the quebe checks for the sandwiches on the left it matches the preference takes it and leaves the queue second student checks the sandwiches sandwich on the left it doesn't match their preference it goes back into the line into the queue the next student who is now first checks the sandwich no it doesn't match the student goes back into the queue the next student they have preference matches they take the sandwich and leave the next student again the preference matches they take the sandwich and leave the next student the preference doesn't match and if you see now the students array all the students have preference one means square but the top sandwich is a circular one which means zero so this will never be taken away and this student will check the sandwich and go at the back of the queue the next student will check the sandwich go at the back of the queue the next student will take see the sandwich and go at the back at the Que at no point their preference will be matching with the top sandwich and that's why these students will never be able to get a sandwich so how many students are not able to get a sandwich three so our answer would be three so that's how we need to solve the question I cannot simply check the first thought that comes to the mind is check how many ones are there in sandwiches and how many ones are there in students so there are three ones in sandwiches and four ones in student so one student will not get a square sandwich and there are three circular sandwiches and two students having circular different so all the students preferring circular sandwich will get their sandwich but there will be one student who prefers Square will not get it that's our first intuition and so we'll return why but that's not the case there is another condition here that they will check only the top sandwich okay even though there are plent of sandwiches below it doesn't matter they are just bothered about with the top sandwich if that matches the preference then it's fine at that particular F so that makes it a little complex so how are we going to solve it what I can do is I can take count of students who prefer circular takes count of students who prefer Square okay how will I take count of that students. count Z and the rest of the students will be who prer Square so length of students minus students zero will give me number of students prefer that prefer Square okay and I'll check I'll keep on carrying this out so what I'll do is I Loop it so for I or sandwich in sandwiches so this is like same this is the current sandwich okay so all I'm saying is for sandwich and sandwiches if sandwich if there is if the sandwich is circular okay or Square and if there is a student who prefer Square okay then I will then that student will definitely get that sandwich right in some at some point or the other they can keep going back and back at some point or the other they will get that sandwich right so I could say students 1 minus 1 right and else means that the current sandwich is circular which is zero else if students Z is greater than zero then in that case students 0 - = to 1 case students 0 - = to 1 case students 0 - = to 1 right else say students one is zero right student one is zero in that case is all the other students which is students referring students one is zero so all the other students just student zero will not be able to get the sandwich right because there is nobody who will pick this up the current sandwich which is one since students one is zero which means there is no student who will prefer a square one and this will be stuck here so all the remaining students which are student zero those will never get svage so I'll return student zero similarly here if students zero these are the students that prefer circular sandwich the current sandwich is circular and there is no student left who prefers a circular sandwich which means that all the students who prefer Square remaining students who prefer Square will not get any sandwich so I'll return R then okay I reduce this Cod bet here and finally if this Loops Loop completes which means every student has got one sandwich so in that case I'll return zero so let's run this and see if this works that worked for these two cases let's submit it 13 milliseconds better than 95% of it 13 milliseconds better than 95% of it 13 milliseconds better than 95% of subm missions let's look at the best one here what they are doing is they are taking students and removing I from it oh so this will be a order of n Square solution every time to remove one value from students will make it make the program go through the entire array one more time so you'll be going through sandwiches once and for Every Sandwich you'll be going through students one so this is n Square solution not the best solution in terms of time complexity let's look at some other solution yeah they using DQ okay that's that could also be done but then making a DQ is uh itself is a long process so that will add to the time complexity this one looks like something that is someone who is doing something similar to what we are doing so that's how we solve the problem 1700 number of students unable to each eat lunch see in the next
|
Number of Students Unable to Eat Lunch
|
minimum-time-to-make-rope-colorful
|
The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers `0` and `1` respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.
The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a **stack**. At each step:
* If the student at the front of the queue **prefers** the sandwich on the top of the stack, they will **take it** and leave the queue.
* Otherwise, they will **leave it** and go to the queue's end.
This continues until none of the queue students want to take the top sandwich and are thus unable to eat.
You are given two integer arrays `students` and `sandwiches` where `sandwiches[i]` is the type of the `ith` sandwich in the stack (`i = 0` is the top of the stack) and `students[j]` is the preference of the `jth` student in the initial queue (`j = 0` is the front of the queue). Return _the number of students that are unable to eat._
**Example 1:**
**Input:** students = \[1,1,0,0\], sandwiches = \[0,1,0,1\]
**Output:** 0
**Explanation:**
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,0,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,0,1,1\].
- Front student takes the top sandwich and leaves the line making students = \[0,1,1\] and sandwiches = \[1,0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[1,1,0\].
- Front student takes the top sandwich and leaves the line making students = \[1,0\] and sandwiches = \[0,1\].
- Front student leaves the top sandwich and returns to the end of the line making students = \[0,1\].
- Front student takes the top sandwich and leaves the line making students = \[1\] and sandwiches = \[1\].
- Front student takes the top sandwich and leaves the line making students = \[\] and sandwiches = \[\].
Hence all students are able to eat.
**Example 2:**
**Input:** students = \[1,1,1,0,0,1\], sandwiches = \[1,0,0,0,1,1\]
**Output:** 3
**Constraints:**
* `1 <= students.length, sandwiches.length <= 100`
* `students.length == sandwiches.length`
* `sandwiches[i]` is `0` or `1`.
* `students[i]` is `0` or `1`.
|
Maintain the running sum and max value for repeated letters.
|
Array,String,Dynamic Programming,Greedy
|
Medium
| null |
1,413 |
hello everyone welcome to coderscam we are at 11th day of november record challenge and the problem we are going to see today is minimum value to get positive step by step so the input given here is an integer array with both positive and negative values and we have to return the minimum positive value as a start value such that the step-by-step a start value such that the step-by-step a start value such that the step-by-step sum is never less than one so let's understand this with an example so here is a given example in the problem statement so we have to return a minimum positive value to add with this array so that the step-by-step sum could array so that the step-by-step sum could array so that the step-by-step sum could never go less than zero so let's start considering the value as one so this is the minimum positive value so if we start adding one by one numbers at each step what would be the values so when we start with minus three the value would already be minus 2 so this is obviously less than 1 so in this case in the first step itself value 1 fails so it's time to increment our value to 2. so let's start and again at the first step the value would be minus 1 which is also less than 1 so we have to increase our value to 3 so let's start the value will be at the very first step 0 because we are adding with minus 3 which is also less than 1 so at this step as well this value fails so we have to increase our value to 4 so now adding 4 with minus 3 will give you 1 so which is actually not less than 1 so let's go and add the values ahead so adding uh with 2 will give you 3 at the next step and then the next value is -3 so here it becomes the next value is -3 so here it becomes the next value is -3 so here it becomes 0 again so in this case the value fails again at this step and 4 is actually a minimum value so in this case let's increment to one more value which is 5 so adding 5 with each step will give you 2 and then adding 2 plus 2 4 minus 3 is 1 then again these two values are positive values so it is going to be 5 and 7 so at no step the value becomes less than 1 so 5 is the minimum positive value you can actually written as an output so how are we going to approach this so what i explained here is the brute force way to solve this problem we are going to start with the minimum positive value and i trick till the max value it could possibly have and wherever we reach a stage to check uh the complete array passed without having a value which is less than one at all the steps and that is the value we are going to return so this is going to take n square m time where this is nothing but m is the maximum value so the maximum value they said this each number could be maximum of 100 so considering the worst case all the numbers are minus 100 then the minimum value we would need is length of the array into 100 would be the maximum value and plus 1 would be the minimum positive value we need to written as an output so considering this as our maximum value iterating from 1 to max would actually cost you n square m times so m is the maximum value and n square is nothing but we have to iterate the complete array to find the minimum sum every time for each m so how do we solve this in a better way so this brute force could also be considered as a binary search solution because we know the minimum value that is the lower bound and the maximum value which is the upper bound so we fix a mid value and every time we check whether we could pass with this mid value calculated so if we could pass then we shift our bound boundary values to lower and upper bound if not we keep our upper bound and lower bound as mid plus one to the right value so this is how we always solve a binary search problem this would also work in this problem but this is again going to take you big o of n into log m in solution because we use a binary search but how do we solve this in a constant space and linear time so let's see how we're going to approach that the third approach is pretty straightforward and simple so the problem statement itself says we have to get a positive number which should not make the step by step sum not less than one so here the step-by-step sum is nothing but a prefix step-by-step sum is nothing but a prefix step-by-step sum is nothing but a prefix sum so what are we going to do is we first going to calculate the prefix sum of the given array so once we calculated the prefix sum we are going to take the minimum out of all the prefix sums so that is the minimum value of minimum deep the array can actually go so that would be the value we have to compensate by putting a positive start value so plus one of that value would be our output so let's understand this by doing it step by step so let's start calculating the step by step sum at the first step minus three would be the step by step sum or prefix the next value would be minus 3 plus 2 which will be minus 1 and calculating it the same way it is minus 4 and then minus 4 plus 4 is 0 and then 2. so this is the prefix sum of this particular array so we have to search for the lowest value at any step in the prefix sum calculator so if you see minus 4 is the lowest value out of all so which actually means this is the least value or the deep value that the array could actually go so we have to compensate this deep value with the corresponding positive value to satisfy to not let it go less than 1 so if minus 4 is the least value then we have to need a plus 4 to make it 0 but the condition here is we should not make the array go less than 1 so 0 is also considered as less than 1 so we have to have 5 which is nothing but plus 4 plus 1 so minus 4 to compensate minus 4 to get it more than 1 we have to have a value 5 which is nothing but 4 plus 1 so this is the value we actually need to compensate it not to become less than 1 so this is going to be the minimum positive value we needed to make this array some not go less than one at each step this is going to be our output so we are simply going to i trade the array and calculate the prefix sum and that is going to take big o of n time and meanwhile we will get the minimum value at each step uh by iterating this array itself and this is not uh storing any extra space you can store the prefix sum in a separate array or you can make use of the existing array to calculate that so we can solve this in constant space so yes hope you are understanding this concept let us go to the code now so the code is also pretty simple we should have variables equal to 0 which is nothing but which is going to calculate the prefix sum of the array at each step we are not going to use a array for storing the value instead with a simple variable and minimum prefix sum is going to get the minimum value in the prefix sum calculated so let's i treat the array at each step we are going to calculate the sum and update our minimum prefix sum value with the least value or minimum value calculated so yes finally our minimum prefix sum will have the minimum prefix some calculated so we should have the positive side of this value plus 1 as a result so we can do absolute of this value plus 1 or we can simply return 1 minus that value which is also works same way as that of absolute plus one so yes let's run and try yes so let's submit yes a solution is accepted and runs in 0 millisecond and 100 faster than other solutions though this problem is a easy category problem a simple thinking process would make it even more efficient so 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
|
Minimum Value to Get Positive Step by Step Sum
|
maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold
|
Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.
**Example 1:**
**Input:** nums = \[-3,2,-3,4,2\]
**Output:** 5
**Explanation:** If you choose startValue = 4, in the third iteration your step by step sum is less than 1.
**step by step sum**
**startValue = 4 | startValue = 5 | nums**
(4 **\-3** ) = 1 | (5 **\-3** ) = 2 | -3
(1 **+2** ) = 3 | (2 **+2** ) = 4 | 2
(3 **\-3** ) = 0 | (4 **\-3** ) = 1 | -3
(0 **+4** ) = 4 | (1 **+4** ) = 5 | 4
(4 **+2** ) = 6 | (5 **+2** ) = 7 | 2
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 1
**Explanation:** Minimum start value should be positive.
**Example 3:**
**Input:** nums = \[1,-2,-3\]
**Output:** 5
**Constraints:**
* `1 <= nums.length <= 100`
* `-100 <= nums[i] <= 100`
|
Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.
|
Array,Binary Search,Matrix,Prefix Sum
|
Medium
| null |
1,649 |
hey everybody this is larry this is day 10 of the league code daily challenge uh hit the like button hit the subscribe button join me on discord let me know what you think about today's prom uh create it sorted away for instructions okay uh so yeah so i do usually read self and uh ex do the explanations live so let me know what you think so maybe a little bit slow uh but okay sorted away look the left right number of elements that's strictly less than instructions okay so i think i solved this problem during a contest not that long ago on legal context i suppose um there are a couple of ways to do it that um you can i'll probably put a link below so you could kind of see how i did it during the contest um so if you want to see myself that sell it live during the contest you can see that as well but i think for me um and your language may vary there are a lot of different ways to do this with different languages um you know maybe it's map or a tree map or something like that in different languages but the idea is just uh binary search um yeah uh you want to put in this data structure so that you could kind of do a binary search where you can do this count uh very effectively and log in time and once you are able to do that so it is a data structure problem um and once you do that then you can do it in a good way uh they're also you know you could always they also um you know alternate ways of doing it if you want to upself or you want to learn something new uh you could um yeah you can also do it with binary index tree or you can do it with um a segment tree as well so definitely look into those in directions but i'm going to try to do this live um yeah by using something called sorted list uh so basically sort of list is just a data structure that's in yeah in a library that's in python that lets me keep track of things in this sorted way so then now we can just look at um for instruction at a time uh strictly less than okay so then now um let's see yeah so for x in instructions now uh at that way and we want to insert it as well of course but before that we want to get the left side oops which is um so that we do binary search on the x um this is the number of elements that are less than uh x um because this is the first place to insert it on the left side um and then the right is just to go to the numbers that are um yeah strictly greater than x right let me look at the yeah strictly greater than x uh so to the right of that would be it so this is just n minus this where n is um i guess length of the uh sorted list so that now we of course um yeah we wanna the cost is the min of those two so yeah so now we do total zero total uh left right and of course we want to mod it by uh by the number 10 to the nine plus seven probably yeah and then at the very end we just return total uh this should be mostly right um i think during the contest i got this very quickly because well this is a if you look at it this way this is pretty straightforward um oh uh yeah from sorted containers imports sorted list and meanwhile let me copy and paste more of these cool let me give a quick submit yeah cool uh yeah so this is a data structure problem and of course in your library of choice it may be slower um uh but you know as long as you keep it logging it should be okay because and what is the complexity of this well um yeah the buy section it's going to be li uh log n device the second bisection is also going to be log n and the insertion is also going to be log n so and because we have n of these this is going to be n again in terms of space uh this will be of n times so yeah that's what i have for this problem um i don't know if i go to be honest i already did this explanation as a as part of the contest video so definitely i'll put a link below so you can kind of check me during it live so then you know you uh so you can see how that goes um let me look at some hints oh yeah uh yeah the inversion's in a way so you can also um yeah so from that you can obviously uh um you know do a binary index tree or a segment tree or something like that but yeah cool uh that's all i have for this prom let me know what you think and let me know how you solved it or let me know if you have any questions because for this one it's even though i remember this was a heart and i got this heart really quickly um but i so i don't know if there's like something i'm missing that uh makes this problem hard so let me know i will see you tomorrow and have a great night
|
Create Sorted Array through Instructions
|
maximum-number-of-non-overlapping-subarrays-with-sum-equals-target
|
Given an integer array `instructions`, you are asked to create a sorted array from the elements in `instructions`. You start with an empty container `nums`. For each element from **left to right** in `instructions`, insert it into `nums`. The **cost** of each insertion is the **minimum** of the following:
* The number of elements currently in `nums` that are **strictly less than** `instructions[i]`.
* The number of elements currently in `nums` that are **strictly greater than** `instructions[i]`.
For example, if inserting element `3` into `nums = [1,2,3,5]`, the **cost** of insertion is `min(2, 1)` (elements `1` and `2` are less than `3`, element `5` is greater than `3`) and `nums` will become `[1,2,3,3,5]`.
Return _the **total cost** to insert all elements from_ `instructions` _into_ `nums`. Since the answer may be large, return it **modulo** `109 + 7`
**Example 1:**
**Input:** instructions = \[1,5,6,2\]
**Output:** 1
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 5 with cost min(1, 0) = 0, now nums = \[1,5\].
Insert 6 with cost min(2, 0) = 0, now nums = \[1,5,6\].
Insert 2 with cost min(1, 2) = 1, now nums = \[1,2,5,6\].
The total cost is 0 + 0 + 0 + 1 = 1.
**Example 2:**
**Input:** instructions = \[1,2,3,6,5,4\]
**Output:** 3
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 2 with cost min(1, 0) = 0, now nums = \[1,2\].
Insert 3 with cost min(2, 0) = 0, now nums = \[1,2,3\].
Insert 6 with cost min(3, 0) = 0, now nums = \[1,2,3,6\].
Insert 5 with cost min(3, 1) = 1, now nums = \[1,2,3,5,6\].
Insert 4 with cost min(3, 2) = 2, now nums = \[1,2,3,4,5,6\].
The total cost is 0 + 0 + 0 + 0 + 1 + 2 = 3.
**Example 3:**
**Input:** instructions = \[1,3,3,3,2,4,2,1,2\]
**Output:** 4
**Explanation:** Begin with nums = \[\].
Insert 1 with cost min(0, 0) = 0, now nums = \[1\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3\].
Insert 3 with cost min(1, 0) = 0, now nums = \[1,3,3,3\].
Insert 2 with cost min(1, 3) = 1, now nums = \[1,2,3,3,3\].
Insert 4 with cost min(5, 0) = 0, now nums = \[1,2,3,3,3,4\].
Insert 2 with cost min(1, 4) = 1, now nums = \[1,2,2,3,3,3,4\].
Insert 1 with cost min(0, 6) = 0, now nums = \[1,1,2,2,3,3,3,4\].
Insert 2 with cost min(2, 4) = 2, now nums = \[1,1,2,2,2,3,3,3,4\].
The total cost is 0 + 0 + 0 + 0 + 1 + 0 + 1 + 0 + 2 = 4.
**Constraints:**
* `1 <= instructions.length <= 105`
* `1 <= instructions[i] <= 105`
|
Keep track of prefix sums to quickly look up what subarray that sums "target" can be formed at each step of scanning the input array. It can be proved that greedily forming valid subarrays as soon as one is found is optimal.
|
Array,Hash Table,Greedy,Prefix Sum
|
Medium
| null |
414 |
Hello everyone welcome back tu andar video site and today maximum number and return d third distance maximum number in this arrest if d third maximum number ok so like firstly i k u d input like three tu van so what is d third maximum number is first maximum Number is 3 seconds, you output this one, OK, example, OK, so I understand IAS very well, let me explain how you will solve it, okay, like, first of all, what have I done, I took number three here, you also took it here, one. I also took this, I keep a little distance, remove it, there is also a van, okay, I have number three, you have a van, three okay, and what do I do, first of all, what do I do, Max here, first of all, what do I do here, one here I will run a loop, what will I do in the loop, I will find you out, I will like the van, I will like examples and what I will do, I will compare with whom, if my three is bigger, then it will say, if my three is bigger, then what will I do, here, pay max What will I do in the van Max I will store three in the van Look at the time What will I do here Max What will I do in the van Next three in the max van Three in the van First of all what will happen to the max van Three will happen Okay, you understand this You must have gone and what will happen after this that you will be my max, what will be mine, understand that thing, it will become my maxi, what will become of my max van and my max van, what will become of me, it will become my maximum, understand that thing, see what I am trying to tell you. That this is yours, what is yours like an intake, it will become three, apne yahan pe tu pe aaye, understand this thing, then when apne comes to you again, then he will compare again, it is not a trick, it is simple, okay, see, first of all, what will you do? Here we will take ours, we will take the max, see, we will take it's okay, we will take it in any min, it's okay, now I'll take one, here, what will I return my next, okay, now see, the simple thing is, what do I have to return? Also, my max, I have taken input 321, then one will return here, okay, so here I take the next three, okay, I have written this okay, min value is okay here, I will raid that 321 has different numbers, so I have written here. I have put a loop, sorry, or I have put a loop here, N, and here I have written the name, okay, what is the name here, 321, now I look here, now let's check that if my N = my max 2K and equalas three. If this is an object then what to do then continue see why I did this thing you must not have understood see this like I take an example here pay like three you want to understand see if you have like this value Here pe again here repeats, man lo yahan pe kya hai, yahan pe van hota, yahan pe three happens, ok now see apna ko max return na see jab apna yahan pe van a has been done in maths three, you have to understand. Na, what is your van, if it is n, then it is already van, this is already van, so if another van comes, there is no need to update yours, just continue that is, shift the container forward. It means that whatever you consider as your own, you must be understanding that break means break and continue. You must be aware of this continuation which just like continue as your own means if that thing if condition becomes true then you continue it and stay there. Apna will not reduce it. Let's forward Apna loop to Apna. Okay, now Apna has written here Apna will do that if my max van is smaller than N then what is Apna N is smaller exactly Apna. It is big, if it happens then what to do is put Max 3 in Max Tu, okay, the Max will be free, Max Tu will be there and the Max Tu and the Max Van, what happened there, okay so what should I do, then what? Zero, this means min, that is, let's take zero man for our example and when what is the value of your one and max, what is max van, then max van, do you still have maximum also zero, let me comment out because I further. You also have to understand the process of ' If you don't understand my Max, take me now, take me, here you come, see, now you will come here, now here, how much is the value of Max van, what was yours, what was the next van, now Max van's. What is the value, if there is three, then it is 3 2 1, so what will happen here there is three, now first you will come, the condition will fail, then there is 3, here van will come, the condition will fail, meaning this once. If it will do, how will you update it? So what should I do? Now what will I do? Now I will put a NCP here, now I will do Max Tu from the end I will reduce one, let it be, okay, it is getting zero here, it is definitely happening. So what to do in Max 3, what is Dal Do in Max 3, give the value of Max Tu, if you don't understand what to do, it is okay to understand the value of Max 2, see what was there in Next Tu, give Dal Do in the next three, the value of Max 2, Tu is okay. If my max is 3, it is big. If it is big, then it is big and the minimum value is, look, the minimum value that is there is -22 to the power of minimum value that is there is -22 to the power of minimum value that is there is -22 to the power of 31 and the maximum is 31 - 1. It's a zero for the exam, maximum is 31 - 1. It's a zero for the exam, maximum is 31 - 1. It's a zero for the exam, so that you can understand it, and I don't go to the campus that much. Now he will check me here, now he will check me here, so what do you do? Max 3 Ko N Tell me what I said If you want to return here then I am simple Sa simple sa I will return it here Okay let's remove it from here Okay if people here dot min value if like this Understand okay Why am I doing this, understand that if D is the third note, understand this thing, now see how much is the max three, here is one, and if you had taken its input, then this would have happened, how does that happen because look here, there are two numbers here. If there are two numbers, then the max of one number becomes what comes in the van one, what comes in the van a goes, what comes in the max tu me means max van me tu a goes, that means 12 goes and the max of three becomes apna, here it is left blank which becomes equal. Its people are of dot min value, so now our condition is that our files are being created from this input and starting from this input, so first let us understand that if this is true or not but true. If it is there then what should you return? You are waiting for it to be returned. If you are taking your interior then you return the next van. If it is not like this then the maximum return is only in the third, so if it is not like this then you have to buy the third magazine number. So if this condition is not coming true then what should I do if the problem is coming, ok wait now let's see this thing now what will I return here Max 3 or if the condition is not coming true then I have to go for maxi i.e. not coming true then I have to go for maxi i.e. not coming true then I have to go for maxi i.e. van. What is the max, I have my own van, so what should I do, okay, now I will scope it once here, maybe there is no issue, I am okay with it, I hope my code will run properly, there should be no problem, it is taking a little timing. There is a network problem, let's see what is going on, okay, look here, where is the line coming from, maybe I did not write the integer here, that's what I was feeling, wait, okay, wait, a little timing is going on here. Look, what I am doing here is that here I have written the ID here, sorry ok, now run it, typing mistake, submit it to Congress, get your network corrected, one more here I have not taken Max 3 in the laptop. You have to write M3 there is some problem with the commission, so what should you do, you have to write M3=N there, it what should you do, you have to write M3=N there, it what should you do, you have to write M3=N there, it seems like a mistake to me, ok so thank you for watching this video.
|
Third Maximum Number
|
third-maximum-number
|
Given an integer array `nums`, return _the **third distinct maximum** number in this array. If the third maximum does not exist, return the **maximum** number_.
**Example 1:**
**Input:** nums = \[3,2,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.
**Example 2:**
**Input:** nums = \[1,2\]
**Output:** 2
**Explanation:**
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.
**Example 3:**
**Input:** nums = \[2,2,3,1\]
**Output:** 1
**Explanation:**
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.
**Constraints:**
* `1 <= nums.length <= 104`
* `-231 <= nums[i] <= 231 - 1`
**Follow up:** Can you find an `O(n)` solution?
| null |
Array,Sorting
|
Easy
|
215
|
393 |
hello everyone today I will solve the question number 393 and the question type is medium and the question is they will give us Vector integer and we need to return Boolean true or false after checking whether it is a valid UTF at encoding or not so first we need to know what is utf-8 so first we need to know what is utf-8 so first we need to know what is utf-8 in coding so the first rule is for one byte encoding first bit should be 0 and followed by its unique code so for the one byte we need to check on the first bit whether it is zero or not and for the N bytes it means other than one bytes we need to check first and bits whether it is one or not like here in three first three bit is one right yeah and after that n plus one bit is zero and plus 1 width is zero that is fourth bit is zero and followed by n minus 1 bytes n minus 1 is 2 4 n is equal to 3 right so two bytes one two these two bytes should be start from one zero the most significant two bits should be one zero so for n bytes first and width should be one after that n plus one bit should be zero and after that total n minus 1 bytes sequence like this should start from one zero so we need to check whether this condition is fulfilled by our input or not so in example one that is one nine seven one three zero and one 197 in binary is one two one triple zero one zero right and one three zero is one four times five times zero one zero like here that is it is one in binding so here in this 197 first two bit is one right and the third bit is zero so it is this first condition of the two bytes right but we need to check whether it has n minus 1 that is one bytes starting from one zero or not like here starting from one zero yes it has starting from one zero this one so it is two bytes encoding and for it is one bytes encoding because it is starting from zero so we have two bytes after one bytes encoding so it is true it is very important here in this example two three five one four zero and four two three five in binary is this one four zero is this one and four is this one now it has three one in the start right after that it is zero so it is sine of three bytes encoding right now we need to check n minus one that is two n minus 1 that is 2 whether it has two sequence or code which is starting from one zero or not yes it has one but it does not have another encoding or code which is starting from one zero so we need to return false so it is not three bit uh three bytes encoding it's one bytes encoding but it's not three bytes so we need to return false so our solution would be comprised of uh many things but the first thing we will do we will Traverse on each integers and we will check how many bytes uh of how many bytes encoding is there like first we will go on 235 and we will check its binary how we will check its binding we will do right CP you know after doing right shift like in this example triple one zero one after doing four right shift it will be one zero all these four digits uh bit integer will be remove right after doing four right shape this value will be after four right zip so we can check whether it is three bytes or two bytes or one bytes like here in this example after doing four bytes we can check it is one triple zero so we will do right shift and we will check whether it is two bytes or three bytes and after that if it is three Watts let's assume we will get it is three bytes and it will be three so we will uh we will run a loop for two times n minus 1 that is 2 I have to check whether after that whether all these two codes are starting from one or one zero or not so let's see the code first we will Traverse on each value and in the start we will initialize check with 0 because here we are not going to check I mean we don't know we do not have any previous uh codes we will start from the zero and after that we also know uh when we do right zip like N5 it is equal to n by 2 to the power 5 right so we are doing this only it is 2 to the power 5 it is 2 to the power 4 so we are doing right shape here and we are checking whether it is 1 0 or not like one zero after doing five right shift we will get 1 0 if it is one zero it means it is two bytes right two bytes encoding so we need to check n minus 1 that is one course whether it is starting from one zero or not when whether it starts from one zero no like similarly in this code after doing four right shift or you can say three write zip here in this example we will check whether it is three bytes or not if it is three bytes we will take next two codes whether it starts from one zero or no here it is the code of checking whether it starts from one zero or not after doing six right shift we will left with two bit integer only and we will check whether it is one zero or not if it is one zero then it's fine if it is not one zero we will return false so let's see the code again now run the code okay thank you
|
UTF-8 Validation
|
utf-8-validation
|
Given an integer array `data` representing the data, return whether it is a valid **UTF-8** encoding (i.e. it translates to a sequence of valid UTF-8 encoded characters).
A character in **UTF8** can be from **1 to 4 bytes** long, subjected to the following rules:
1. For a **1-byte** character, the first bit is a `0`, followed by its Unicode code.
2. For an **n-bytes** character, the first `n` bits are all one's, the `n + 1` bit is `0`, followed by `n - 1` bytes with the most significant `2` bits being `10`.
This is how the UTF-8 encoding would work:
Number of Bytes | UTF-8 Octet Sequence
| (binary)
--------------------+-----------------------------------------
1 | 0xxxxxxx
2 | 110xxxxx 10xxxxxx
3 | 1110xxxx 10xxxxxx 10xxxxxx
4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
`x` denotes a bit in the binary form of a byte that may be either `0` or `1`.
**Note:** The input is an array of integers. Only the **least significant 8 bits** of each integer is used to store the data. This means each integer represents only 1 byte of data.
**Example 1:**
**Input:** data = \[197,130,1\]
**Output:** true
**Explanation:** data represents the octet sequence: 11000101 10000010 00000001.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
**Example 2:**
**Input:** data = \[235,140,4\]
**Output:** false
**Explanation:** data represented the octet sequence: 11101011 10001100 00000100.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
**Constraints:**
* `1 <= data.length <= 2 * 104`
* `0 <= data[i] <= 255`
|
All you have to do is follow the rules. For a given integer, obtain its binary representation in the string form and work with the rules given in the problem. An integer can either represent the start of a UTF-8 character, or a part of an existing UTF-8 character. There are two separate rules for these two scenarios in the problem. If an integer is a part of an existing UTF-8 character, simply check the 2 most significant bits of in the binary representation string. They should be 10. If the integer represents the start of a UTF-8 character, then the first few bits would be 1 followed by a 0. The number of initial bits (most significant) bits determines the length of the UTF-8 character.
Note: The array can contain multiple valid UTF-8 characters. String manipulation will work fine here. But, it is too slow. Can we instead use bit manipulation to do the validations instead of string manipulations? We can use bit masking to check how many initial bits are set for a given number. We only need to work with the 8 least significant bits as mentioned in the problem.
mask = 1 << 7
while mask & num:
n_bytes += 1
mask = mask >> 1
Can you use bit-masking to perform the second validation as well i.e. checking if the most significant bit is 1 and the second most significant bit a 0? To check if the most significant bit is a 1 and the second most significant bit is a 0, we can make use of the following two masks.
mask1 = 1 << 7
mask2 = 1 << 6
if not (num & mask1 and not (num & mask2)):
return False
|
Array,Bit Manipulation
|
Medium
| null |
1,248 |
Hello everyone Hello well today I am going to solve the problem number lead in the name of problem number 12 4 account number of problem statement then we have to return the result to the account of total number of sub raise in which there will be more numbers then it is basic If we look at the first test case, we have given one in which the value of Andhak is created by some numbers [ Praise] and the second app is created with 121125 statements. Let's see how we can solve it. Problem number is 1248. Number of Nice Sub one which is the first test according to 112112 First of all how can we do this that we have to account so first of all we take a pointer which will arrowroot in it so first of all we need to account. It will be necessary to know how many out numbers, only then we will know that there are OD numbers, so first of all, let's take a variable which will be stored by someone else and how will this happen, there is a variable which will travel to the courier and that if count if. That will be the OD number, so here we will increment it, so as now we have come to know that here, first when the order is placed, one of the OTS near us can be made, but there can also be a case like this. That is, if there is another one before this van, then according to it our accounts will be changed because this one was made and this one also could have been made because in this also there are two a's and one here also. one here and one here also. And if it could be made, then we will introduce one more point for that, which will count, how many more are there before the start , , , we have okay, this is how many more are there before the first OD, sorry, we will keep going, okay, so here for now. We got one and I ours is also here so now what will we do that if this is this and if this is and then it will simply set this account again because this order is required exactly and if we index this one If we include K also then it will happen here that it will be wrong. According to the problem statement, we will increase K by one and then we will calculate that now it is possible for this, so first of all, if we write the code for this, then first of all and Whatever is there will increase them, okay and if our then and whatever I just said, if it becomes bigger than what it has done, then it will slice the account from the van, so the account will not be found, so that's why we We will always start the account with van and then when we check how many ands are there before it or not, then for that we are doing that, so first of all we will do one and that, if this and is there then We will create an account and then we will add this to whatever result we have, this is our basic surkot, if we have this and love then but if after this like van and no after this zero like till this So this is counted, but this also by mixing this and this, we do n't have to reduce the likes from there, because as a woman, we have four likes, if we have three, then I want one, but we can become some savers for this also. Then we can make them for this also, we can make them for this too and how many can be made, as many accounts as we have, we will keep increasing them as we get more and more, so for this we can do this is our first and check. If there is no app to do this then in this case we will do this that we will keep adding the same account in this result, we will not reset the account of the previous account, we will reset the account only when we get a new OD and hence we will do that. Because we need more exactly and if we do not reset then that previous OD will still be counted and a new one will be counted which will increase our number of arrests if we go to different cases. If it is possible then let's write its code and see if it works or not. So let's see if I am doing it. First of all, let's take the size for it. [ see if I am doing it. First of all, let's take the size for it. Let's make a blueprint of it. Before using the app, we need to give us another account. We need to do this and how it comes out Basically we have added another operator on the same thing which is not a pipe here And how did we get more equal If we are not recording this then submit it and let's see Color Answer Ram Sir So the code here is wrong answer OK or meaning how it is that here on the first index and A is there, then if our index is this one, we will not be able to do our movie further because it is inside the loop. In any case, you will not see that our entry will ever increase, so for this we can think that if this loop is either we give a value here and make it something like this that at least on the first run So there is an increase or we can do this by giving increment team here so that along with it the increase will also happen. Here our first and A is going so after the first order comes then as you can see that no more should come. And it should come and end only after the first order comes, otherwise it will go inside, otherwise first of all let's test it once. If I understand right, it is taking a lot of time. Okay, so the code has been submitted here. Okay, day bye. Thank you
|
Count Number of Nice Subarrays
|
binary-tree-coloring-game
|
Given an array of integers `nums` and an integer `k`. A continuous subarray is called **nice** if there are `k` odd numbers on it.
Return _the number of **nice** sub-arrays_.
**Example 1:**
**Input:** nums = \[1,1,2,1,1\], k = 3
**Output:** 2
**Explanation:** The only sub-arrays with 3 odd numbers are \[1,1,2,1\] and \[1,2,1,1\].
**Example 2:**
**Input:** nums = \[2,4,6\], k = 1
**Output:** 0
**Explanation:** There is no odd numbers in the array.
**Example 3:**
**Input:** nums = \[2,2,2,1,2,2,1,2,2,2\], k = 2
**Output:** 16
**Constraints:**
* `1 <= nums.length <= 50000`
* `1 <= nums[i] <= 10^5`
* `1 <= k <= nums.length`
|
The best move y must be immediately adjacent to x, since it locks out that subtree. Can you count each of (up to) 3 different subtrees neighboring x?
|
Tree,Depth-First Search,Binary Tree
|
Medium
| null |
792 |
hello everyone welcome to learn overflow in this video we'll discuss about today's liquid problem there is a number of matching substring okay so this is a medium level problem and understand what this question is asking us to do and how we should think on solving a question like this and what can be the multiple uh solutions or multiple thought processes behind solving this particular question so we'll look into one by one into all of those that ultimately will find an optimal solution a good solution rather for this particular system we write export for that and our dividend school so that will be the whole video all about also uh if you haven't subscribed this channel already make sure to subscribe to our channel for regular like code videos like this so let's start today's understanding today's question and let's see what this question is asking us to do so it's first this we give it a string s so this string is simply a string as given to us okay and an array of string squares so there's an array of strings called words so that's given to us there's two things and we need to return the number of words i so when it return a count of this words i that is a subsequence of s okay so number of words that is subsequence of s so there's a small thing when you say subsequence and when it says substring so there's a difference okay so say if there is a string something like this like written over here fine say there's a string over here and when it says subsequent subsequence can be it can be like this string with this character and the last character fine so that's a subsequence but when it says substring that means it should be a continuous flow of such strings so like really your one after another should be there so that's the substring but when you say subsequence you should make sure that it can be uh each character can be anywhere from the string so it you can pick it from you know jumble order as well so that's subsequence and the other one is substring so that's the small difference you should remember so uh let's understand further so here they have also explained what is the subsequences so it says like a subsequence of a string is a new string generated from the original string with some characters can be done as well so can be non characters as well also uh like delete is with some character deleted without changing the relative order of the uh remaining okay so they mentioned that i should it should be like the order shouldn't be changed over here okay so that will be our uh idea so it says like a c e is a word in that case what will happen a c is a word and uh if a subsequence like uh ac is a subsequence of this a b c d so a and c and e so all these are in the relative order in the same relative order and thus we see that uh this is how we are finding subsequence awesome so let's understand an example and see what the question exactly saying us to the question is like uh let's say like uh string is abcde that's a string is given to us and there's a word sorry what's that is five words uh four words one is a bb acd and ace so this uh five four words are given to us fine so and it says the output should be three and why is it so output is three because like there are three strings only uh like in the words array in the words that a there are only three strings that are subsequence of s how a is a subsequence we can find that a is there in uh yes then uh then ac d we can find a c and b are there in uh s without uh like changing the relative order right and then ac you can find a c and e is also there without changing the relative so there are like three words in our words array uh which are a subsequence of this fine so that's the question we have now uh we can easily understand what is this all about now after reading this the first uh type of solution or the first type of approach that comes to our mind is like wow we need to go through this so let's do something like take each of the words and do character by character check for the each character and find if uh like if any character matches with this like there's a uh b c d and then e fine so these are the five characters we have in s and uh we first take a like for the words array a we find that a is equals to a so we increment our count as one right then we find b so we uh start from the zero and travel to the next one we find a b over here okay then we uh like it's more like uh we got to be as our word okay so we fight the first character and they find a match to a perspective over here then we uh increment our this counter to the next character so we find another b and now we keep checking for the next characters till the end uh then what is another b if we don't find another b we break and like we go to the next one so this can be an approach and then we find uh words like a c and e again we start from the beginning fine we find a match then we uh increment it's a pointer to the next character it will respond to the next character we don't find a match with if we didn't find that match we increment it further we find a match okay once you find a match we increment both the character like put the pointers then you find it's not a match then we uh increment it further then we find a match and we come out of the particular loop okay and increment our account with that okay for two matches so this can be an approach uh but uh this may not be the best approach you can come up with five you need to think that what can be the other approaches that you can uh think of because if you go ahead like the other like if see in this particular next example there is a huge one and there are words like this unnecessary force you say that you need to search the whole length of string to find out what letter t and ultimately figuring out you don't have one fine so that will be the uh conservative you will end up traversing through the whole uh string and what is the string length like s dot length can go up to 5 into 10 to the fourth that's a huge value so it's that we use this waste of uh memory and time for us okay so how can we improve this scale moreover can we improve this so yes obviously we can improve this and we have to improve this to good too good in uh like interviews so what we can do exactly we uh can use a memorization how say you can use a hashmap map or something like that so what do you will even remember is that okay these are the characters we have at this is their order and this is a voice once you come across a word we should go ahead and check if we have a value like this and if it has a uh like if this question is less than this or not so what exactly we will do we will first get in uh as i said a hash number okay so in the hashtag say i'm just taking this particular example fine so that will be uh easier for us to understand so initially we had a b we had a c and a d fine and we had a uh c and e fine so that's the point we have fine now what we will do over here we will simply uh add the strings to our hash number how we'll do that we won't add the whole thing we'll add uh we'll add like first task for us will be to add this uh particular each of the characters of this string like maybe whatever characters we have we should add all these characters that a that's the characters uh we should add in the in our hashmap okay uh so this is the five characters given to us and we're adding this to a hashmap now what we'll do over here will uh we'll say we found a first word we'll not see how many characters are there in the world we found the word fine so we'll do the wall to carry zero so what does correct zero contains uh e so we'll do uh we'll use a like a linked list over here so uh i'll show you how we are doing this but yeah in the map we'll use the map to a link list so this is the key and the value will be the electrons fine and i find that a is over here and that's the uh and all or if there are other characters so that's over here fine so we added a that a is that this is a word that is starting with a that yeah zero dot carat zero is starting with a and we just i write it in our linked list uh at a okay pointing for a so that started with a uh any words starting with are pointed over here then you find b so we add it over b fine uh that's uh b and uh our b is pointing we are not bothered about the other characters of the particular word so with this first checking that we got our first character uh and we're mapping it to that first character only then you've got a c d so it's a linked list so the next word will be a c and d fine we are just putting it in a linked list and we find a being our first character we found then you got ace sorry for the proper right hand writing but yeah uh this is ace so we again got a c at a fine hey say we found that it starts with a and we should go ahead with it next in us for the steps let's just add it to all the words you know what now what we'll do we will simply uh we'll simply go ahead and make a size minus one how i will take one by one uh the one by one word from this uh linked list fine with us to a will remove this uh first character okay and whatever character is left out uh we'll remove this uh first so it's a linked list so you can understand that we can do remove first easily okay and then uh we'll simply check that if this character if this particular uh word length is one overland is one like double equals uh one that means it's a single character that's equals to this uh particular statement so we'll just increment counter uh plus right so that's the count plus now we'll go to the next word okay well over here we'll just uh take like what dot carrot type we don't uh make a link list over here like we so we remove this part first then we come to the next one right we remove this word first then we'll now check that if his length is one no it's length is not one this length is more than one fine now what we'll do uh we'll simply go ahead and uh we'll do a substring of the rest of the word right we'll do the substring of the rest of the word uh from the substring is lower we'll look into if we can find a better solution at last but let's understand the solution so we'll do a substring of the word fine now we got cd so we removed our uh first character and we do cd so cd is what cd is a falls in the string of first character c and we should find uh other characters later fine next we are going out with is the so ac is like we again uh remove the first character a and c is given to us so we can mark it as c at fine c and uh e fine so thus we can see is like we again check for the characters over here and we find that once we remove b the next vector is also in okay so we cannot go ahead in that why just because once we remove this particular uh like take this out and remove the first character b okay and then we try to like uh we try to like get a word out of it like try to uh find a character but like it's more like we are not going in random fashion okay we are rather going in uh like once we are in b it will have a checkpoint like we will uh go for each of the characters in s dot in s fine so we have we got a b c d e so first we went through all the a and anything added like if any word was there like a or bb so that would be added over here fine uh but we won't be looking into a further we understand that we won't be looking to a farther so whatever the values of a are there we got it initially and if there is a repetition that will be sitting over here so by our formula which is defining so we just removed b and b is added over here right ah that's clear next we'll go to c while we are moving ahead we are not going by all the stuffs that are being newly added and all we are not going about that we are rather going by each of the characters over here once we traverse each of the characters we are over with it anything being added to previous order we are not bothered with it if anything is farther they're in the town that will look into it but not in the previous order fine so that's more or less the idea now uh bv is not content next we've got c d so again cdc will uh which will remove c and 40 will add it to over here right so that's the d we added uh that's the bracket okay by saying uh then we found ce remove c and add uh e over here fine we'll add e over here fine next we come to the next two characters d we'll remove d and find that this equals one so we'll increment our counter uh next we move we find there's no more so we'll move to e and we if we find e okay with removing find this length is one and you remove individual so counter becomes three and we have traverse all the values only once in the particular sequence so once you get that so once we get that so we can be rest assured that we went through all the valves so that's more or less the whole idea behind this but um also just to note that we are using substring so substring is time consuming but you could use an array as a map to further improve the search okay so that's definitely possible we look into that but let's understand uh this particular concept that how we actually did this we simply went out with each of the characters in our uh string like yeah s given to us and in that we'll uh simply check for all the words given to us we kept checking the first character okay and removing the first character so that was the idea behind this okay so it's uh if you just look ahead so it's like oh order of s plus uh w into l so w being the number of words and it'll be the length of each word so w into l will go ahead and add it to s that will be s be the length of our string s so that will be the complexity for this question okay uh so next i will go ahead and write this code and then i will i hope you can understand this particular idea of what we are going at with a bit farther a bit better in this way okay fine so let's go ahead with that let's write this code and understand what uh this code is all about like how we can actually implement this using our idea or the idea which is thought of fine so as i say we'll use a map of our character and we'll use the queue of strings as its value okay so that will be the first thing that well let's write the whole thing and then i'll explain again all right so here you can see that this is an our solution on that which is accepted this is not the fastest solution we should think on finding a further faster solution but let's understand what exactly we need to go along with our particular solution okay so the first thing is uh we just took a map of characters and the key the one i was just showing you and then in that we just added all the characters in s that become each of the key in our map and it has a value added new link list fine and for each of the words uh we came across now what's the array we simply check the word carrick 0 and reject if the key is there already okay if the key is already there in our map we'll add that or if the key is not they say you know in the case of the second example there isn't any uh t starting with t right so the carrot zero is not there in our initial string so there's no point going ahead with this is already not in our possible solutions of the possible count cases right so we should just ignore that further what we'll do we'll simply uh like we added those words all these this and now we're going for each of the characters in the eyes so if there are like two times a being there so that case a being repeated like a and a because a being repeated so we can come across those solutions so that's the stuff we're going out with okay so and that was the case b uh so this b was not repeated any further so that's the reason we didn't come across the second b anytime and that was not counted in all solution f4 so that's the idea now we took a skew and in the queue we just take whatever the current value of a character we have whatever the current value we have just take it right and we just take the size of it now for 0 till the size we go through all the current elements in our street queue i don't know what we do we just um uh we just do q dot poll that is we take out one of the each of the elements from our uh queue okay now accurate poll is actually you know before like first it first just whatever element is insert first comes out first so uh there's no uh need for you pull first folder so like it's simply a queue not a dq okay so we uh took the string or the first string we got now actually in the string length is one we simply incremented our answer answering the final return also we got uh that is the counter and then if it's not one because there are more characters so we check if a map contains a key of character one okay say there's a word like this fine what uh like this no not this exactly um okay fine so when you look at this example find after a and h or inserted then what will happen we come across our character that b fine so b which if b is a key in our string or not if it's not a string we'll simply ignore this fine or it will not add it if it's not a string so if it has characters there as a key to our uh map so we just add our character like add a string with kara dye and we add it to like we do a substring over here so this is the one that takes the most of the time so if you want to improve the solution you need to improve this at this position because this improves our time complexity you can go ahead with uh using some kind of a string buffer or string builder kind of stuff and also you can do um like other initial one i was talking about like you can uh use an array as a map to further improve this solution so that can be possible to improve this kind of solution next up we simply what we did we simply added this uh rather part uh we just removed our first character and added rest of the characters with the particular value we got okay so that's the idea that's the whole idea behind this question and that's how we solve this question and as i said if you want to improve this solution you need to improve it on the substring part also if you have any further better solution which you think can i like complete this not solution rather a better thought person better uh approach to this question i would love to hear to that make sure you write that in the comments below so uh that's more or less about today's video i hope i can make you understand what uh how we can solve a question like this or what should i thought this would be answered by a question like this uh make sure you subscribe to our channel for regular lecture videos like this also like this video and comment down any of your thoughts or any of your doubts related to this question i'll be happy to help you out in the comments so thank you all for watching this video hope to see you soon in my next video as well thank you
|
Number of Matching Subsequences
|
binary-search
|
Given a string `s` and an array of strings `words`, return _the number of_ `words[i]` _that is a subsequence of_ `s`.
A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
* For example, `"ace "` is a subsequence of `"abcde "`.
**Example 1:**
**Input:** s = "abcde ", words = \[ "a ", "bb ", "acd ", "ace "\]
**Output:** 3
**Explanation:** There are three strings in words that are a subsequence of s: "a ", "acd ", "ace ".
**Example 2:**
**Input:** s = "dsahjpjauf ", words = \[ "ahjpjau ", "ja ", "ahbwzgqnuk ", "tnmlanowax "\]
**Output:** 2
**Constraints:**
* `1 <= s.length <= 5 * 104`
* `1 <= words.length <= 5000`
* `1 <= words[i].length <= 50`
* `s` and `words[i]` consist of only lowercase English letters.
| null |
Array,Binary Search
|
Easy
|
786
|
1,832 |
hey everybody this is Larry this is Daya let's click on the 17th of the late decode daily challenge hit the like button hit the Subscribe button join me on Discord let me know what you think about today's problem is it easy what are we doing 1832 check up the sentences pentagram okay I'm in San Francisco right now I'm not gonna lie it uh it's been a good night drank a little bit too much uh Soju is a dangerous thing for those of you at home uh that's what I would say um I am in the same room I just have a different lighting setup I don't know how I feel about that place my face a little I don't know anyway um yeah so let's get started if you and SF let me know uh maybe I don't know uh my schedule is actually kind of busy this week so we'll see but I am in Seattle next week I don't know how much time I have but I've let me know if you're around uh and anyway uh yeah join the Discord and all that stuff anyway okay so let's actually start to start this problem it is a Monday prom hope everyone's having a great week uh I had a great weekend and you know starting off the weekend Strong by doing nickel pumps we're halfway through let's get the other half you know on the world so yeah checkup sentences pangram what's a pan gram it's basically every letter of the English alphabet appears at least once okay uh if we turn okay so my question is whether there is um spaces but no so okay so I guess what I would do is just have a set of sentence and then just whether this is 26 right is that good enough I think that's good enough right oh this is wow why do I propose uh did I misunderstood something oh I'm dumb I meant of course I mean like this because you can't compare set to it ah I feel like given easy poems I'm being silly so I don't know uh hey something a little bit awkward about it I don't know but yeah um I don't know I don't to be honest I don't have much to say about this one I don't know if anyone's gonna watch this prom just because it is so silly uh it is a easy this is linear time or with a space where a is the size of the alphabet keeping in mind that basically this set cannot be greater than 26 elements for reasons that you can figure out homes I'm not going to get into that much so yeah so linear time of alpha space um that's pretty much all I have I mean you can write this in a number of different ways so I'm not going to even get into it but there really is not as much com there's no algorithms that I need to know of to explain so yeah um I don't know this is too easy for an interview question uh if someone asked me this then it would either be a smell meaning that it's like a flag that I should kind of raise or it's just like a warm-up raise or it's just like a warm-up raise or it's just like a warm-up question right because some places give you a warm-up question so you know you a warm-up question so you know you a warm-up question so you know you get your fingers warmed up if you will and your mind a little bit warmed up and then they ask you the real question right afterwards because they expect you to get this in 20 seconds um so yeah but that's all I have with this one I don't have much to say hope y'all have a great rest of the week we'll chat soon uh come to the Discord hit the like button and hit the Subscribe button with the little bell I don't know that's what I'll do YouTubers say so I don't know if that's something that makes sense hmm okay anyway stay good stay healthy to good mental health I'll see y'all later and take care at home bye
|
Check if the Sentence Is Pangram
|
minimum-operations-to-make-a-subsequence
|
A **pangram** is a sentence where every letter of the English alphabet appears at least once.
Given a string `sentence` containing only lowercase English letters, return `true` _if_ `sentence` _is a **pangram**, or_ `false` _otherwise._
**Example 1:**
**Input:** sentence = "thequickbrownfoxjumpsoverthelazydog "
**Output:** true
**Explanation:** sentence contains at least one of every letter of the English alphabet.
**Example 2:**
**Input:** sentence = "leetcode "
**Output:** false
**Constraints:**
* `1 <= sentence.length <= 1000`
* `sentence` consists of lowercase English letters.
|
The problem can be reduced to computing Longest Common Subsequence between both arrays. Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
|
Array,Hash Table,Binary Search,Greedy
|
Hard
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.